\n ";
var modal = $(html);
enableCopyable(modal);
var done = false;
$('body.main').append(modal);
return new Promise(function (resolve, reject) {
return modal.modal({
onHidden: function () {
modal.remove();
},
onHide: function () {
if (!done) {
done = true;
resolve(false);
}
},
}).modal("show");
});
}
exports.shareLinkAsync = shareLinkAsync;
function enableCopyable(modal) {
var btn = modal.find('.copybtn');
btn.click(function () {
try {
var inp = modal.find('.linkinput')[0];
inp.focus();
inp.setSelectionRange(0, inp.value.length);
document.execCommand("copy");
btn.popup({
on: "manual",
inline: true
});
btn.popup("show");
}
catch (e) {
}
});
}
function scrollIntoView(item, margin) {
if (margin === void 0) { margin = 0; }
if (!item.length)
return;
var parent = item.offsetParent();
var itemTop = Math.max(item.position().top - margin, 0);
var itemBottom = item.position().top + item.outerHeight(true) + margin;
var selfTop = $(parent).scrollTop();
var selfH = $(parent).height();
var newTop = selfTop;
if (itemTop < selfTop) {
newTop = itemTop;
}
else if (itemBottom > selfTop + selfH) {
newTop = itemBottom - selfH;
}
if (newTop != selfTop) {
parent.scrollTop(newTop);
}
}
exports.scrollIntoView = scrollIntoView;
// for JavaScript console
function apiAsync(path, data) {
return (data ?
Cloud.privatePostAsync(path, data) :
Cloud.privateGetAsync(path))
.then(function (resp) {
console.log("*");
console.log("*******", path, "--->");
console.log("*");
console.log(resp);
console.log("*");
return resp;
}, function (err) {
console.log(err.message);
});
}
exports.apiAsync = apiAsync;
},{"react-dom":135}],11:[function(require,module,exports){
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var core = require("./core");
var gallery = require("./gallery");
var Cloud = pxt.Cloud;
var Util = pxt.Util;
var virtualApis = {};
var targetConfig = undefined;
mountVirtualApi("cloud", {
getAsync: function (p) { return Cloud.privateGetAsync(stripProtocol(p)).catch(core.handleNetworkError); },
expirationTime: function (p) { return 60 * 1000; },
isOffline: function () { return !Cloud.isOnline(); },
});
mountVirtualApi("cloud-search", {
getAsync: function (p) { return Cloud.privateGetAsync(stripProtocol(p)).catch(function (e) { return core.handleNetworkError(e, [404]); }); },
expirationTime: function (p) { return 60 * 1000; },
isOffline: function () { return !Cloud.isOnline(); },
});
mountVirtualApi("gallery", {
getAsync: function (p) { return gallery.loadGalleryAsync(stripProtocol(p)).catch(core.handleNetworkError); },
expirationTime: function (p) { return 3600 * 1000; },
isOffline: function () { return !Cloud.isOnline(); }
});
mountVirtualApi("td-cloud", {
getAsync: function (p) {
return Util.httpGetJsonAsync("https://www.touchdevelop.com/api/" + stripProtocol(p))
.catch(core.handleNetworkError);
},
expirationTime: function (p) { return 60 * 1000; },
});
mountVirtualApi("gh-search", {
getAsync: function (query) { return pxt.targetConfigAsync()
.then(function (config) { return pxt.github.searchAsync(stripProtocol(query), config ? config.packages : undefined); })
.catch(core.handleNetworkError); },
expirationTime: function (p) { return 60 * 1000; },
isOffline: function () { return !Cloud.isOnline(); },
});
mountVirtualApi("gh-pkgcfg", {
getAsync: function (query) {
return pxt.github.pkgConfigAsync(stripProtocol(query)).catch(core.handleNetworkError);
},
expirationTime: function (p) { return 60 * 1000; },
isOffline: function () { return !Cloud.isOnline(); },
});
var cachedData = {};
function subscribe(component, path) {
var e = lookup(path);
var lst = e.components;
if (lst.indexOf(component) < 0) {
lst.push(component);
component.subscriptions.push(e);
}
}
function unsubscribe(component) {
var lst = component.subscriptions;
if (lst.length == 0)
return;
component.subscriptions = [];
lst.forEach(function (ce) {
var idx = ce.components.indexOf(component);
if (idx >= 0)
ce.components.splice(idx, 1);
});
}
function expired(ce) {
if (!ce.api.expirationTime)
return ce.data != null;
return ce.data == null || (Date.now() - ce.lastRefresh) > ce.api.expirationTime(ce.path);
}
function shouldCache(ce) {
if (!ce.data)
return false;
return /^cloud:(me\/settings|ptr-pkg-)/.test(ce.path);
}
function clearCache() {
cachedData = {};
saveCache();
}
exports.clearCache = clearCache;
function loadCache() {
JSON.parse(pxt.storage.getLocal("apiCache2") || "[]").forEach(function (e) {
var ce = lookup(e.path);
ce.data = e.data;
});
}
function saveCache() {
var obj = Util.values(cachedData).filter(function (e) { return shouldCache(e); }).map(function (e) {
return {
path: e.path,
data: e.data
};
});
pxt.storage.setLocal("apiCache2", JSON.stringify(obj));
}
function matches(ce, prefix) {
return ce.path.slice(0, prefix.length) == prefix;
}
function notify(ce) {
if (shouldCache(ce))
saveCache();
var lst = ce.callbackOnce;
if (lst.length > 0) {
ce.callbackOnce = [];
Util.nextTick(function () { return lst.forEach(function (f) { return f(); }); });
}
if (ce.components.length > 0)
Util.nextTick(function () { return ce.components.forEach(function (c) { return c.forceUpdate(); }); });
}
function getVirtualApi(path) {
var m = /^([\w\-]+):/.exec(path);
if (!m || !virtualApis[m[1]])
Util.oops("bad data protocol: " + path);
return virtualApis[m[1]];
}
function queue(ce) {
if (ce.queued)
return;
if (ce.api.isOffline && ce.api.isOffline())
return;
ce.queued = true;
var final = function (res) {
ce.data = res;
ce.lastRefresh = Date.now();
ce.queued = false;
notify(ce);
};
if (ce.api.isSync)
final(ce.api.getSync(ce.path));
else
ce.api.getAsync(ce.path).done(final);
}
function lookup(path) {
if (!cachedData.hasOwnProperty(path))
cachedData[path] = {
path: path,
data: null,
lastRefresh: 0,
queued: false,
callbackOnce: [],
components: [],
api: getVirtualApi(path)
};
return cachedData[path];
}
function getCached(component, path) {
subscribe(component, path);
var r = lookup(path);
if (r.api.isSync)
return r.api.getSync(r.path);
if (expired(r))
queue(r);
return r.data;
}
function mountVirtualApi(protocol, handler) {
Util.assert(!virtualApis[protocol]);
Util.assert(!!handler.getSync || !!handler.getAsync);
Util.assert(!!handler.getSync != !!handler.getAsync);
handler.isSync = !!handler.getSync;
virtualApis[protocol] = handler;
}
exports.mountVirtualApi = mountVirtualApi;
function stripProtocol(path) {
var m = /^([\w\-]+):(.*)/.exec(path);
if (m)
return m[2];
else
Util.oops("protocol missing in: " + path);
return path;
}
exports.stripProtocol = stripProtocol;
function invalidate(prefix) {
Util.values(cachedData).forEach(function (ce) {
if (matches(ce, prefix)) {
ce.lastRefresh = 0;
if (ce.components.length > 0)
queue(lookup(ce.path));
}
});
}
exports.invalidate = invalidate;
function getAsync(path) {
var ce = lookup(path);
if (ce.api.isSync)
return Promise.resolve(ce.api.getSync(ce.path));
if (!Cloud.isOnline() || !expired(ce))
return Promise.resolve(ce.data);
return new Promise(function (resolve, reject) {
ce.callbackOnce.push(function () {
resolve(ce.data);
});
queue(ce);
});
}
exports.getAsync = getAsync;
var Component = (function (_super) {
__extends(Component, _super);
function Component(props) {
_super.call(this, props);
this.subscriptions = [];
this.renderCoreOk = false;
this.state = {};
}
Component.prototype.getData = function (path) {
if (!this.renderCoreOk)
Util.oops("Override renderCore() not render()");
return getCached(this, path);
};
Component.prototype.componentWillUnmount = function () {
unsubscribe(this);
};
Component.prototype.child = function (selector) {
return core.findChild(this, selector);
};
Component.prototype.renderCore = function () {
return null;
};
Component.prototype.render = function () {
unsubscribe(this);
this.renderCoreOk = true;
return this.renderCore();
};
return Component;
}(React.Component));
exports.Component = Component;
loadCache();
},{"./core":10,"./gallery":18,"react":264}],12:[function(require,module,exports){
"use strict";
var Promise = require("bluebird");
window.Promise = Promise;
var PouchDB = require("pouchdb");
require('pouchdb/extras/memory');
Promise.config({
// Enables all warnings except forgotten return statements.
warnings: {
wForgottenReturn: false
}
});
var _db = undefined;
var inMemory = false;
function memoryDb() {
pxt.debug('db: in memory...');
inMemory = true;
_db = new PouchDB("pxt-" + pxt.storage.storageId(), {
adapter: 'memory'
});
return Promise.resolve(_db);
}
function getDbAsync() {
if (_db)
return Promise.resolve(_db);
if (pxt.shell.isSandboxMode() || pxt.shell.isReadOnly())
return memoryDb();
var temp = new PouchDB("pxt-" + pxt.storage.storageId(), { revs_limit: 2 });
return temp.get('pouchdbsupportabletest')
.catch(function (error) {
if (error && error.error && error.name == 'indexed_db_went_bad') {
return memoryDb();
}
else {
_db = temp;
return Promise.resolve(_db);
}
});
}
exports.getDbAsync = getDbAsync;
function destroyAsync() {
return !_db ? Promise.resolve() : _db.destroy();
}
exports.destroyAsync = destroyAsync;
var Table = (function () {
function Table(name) {
this.name = name;
}
Table.prototype.getAsync = function (id) {
var _this = this;
return getDbAsync().then(function (db) { return db.get(_this.name + "--" + id); }).then(function (v) {
v.id = id;
return v;
});
};
Table.prototype.getAllAsync = function () {
var _this = this;
return getDbAsync().then(function (db) { return db.allDocs({
include_docs: true,
startkey: _this.name + "--",
endkey: _this.name + "--\uffff"
}); }).then(function (resp) { return resp.rows.map(function (e) { return e.doc; }); });
};
Table.prototype.deleteAsync = function (obj) {
return getDbAsync().then(function (db) { return db.remove(obj); });
};
Table.prototype.forceSetAsync = function (obj) {
var _this = this;
return this.getAsync(obj.id)
.then(function (o) {
obj._rev = o._rev;
return _this.setAsync(obj);
}, function (e) { return _this.setAsync(obj); });
};
Table.prototype.setAsync = function (obj) {
if (obj.id && !obj._id)
obj._id = this.name + "--" + obj.id;
return getDbAsync().then(function (db) { return db.put(obj); }).then(function (resp) { return resp.rev; });
};
return Table;
}());
exports.Table = Table;
},{"bluebird":40,"pouchdb":120,"pouchdb/extras/memory":118}],13:[function(require,module,exports){
"use strict";
function setupDragAndDrop(r, filter, dragged) {
var dragAndDrop = document && document.createElement && 'draggable' in document.createElement('span');
r.addEventListener('paste', function (e) {
if (e.clipboardData) {
// has file?
var files = Util.toArray(e.clipboardData.files).filter(filter);
if (files.length > 0) {
e.stopPropagation(); // Stops some browsers from redirecting.
e.preventDefault();
dragged(files);
}
else if (e.clipboardData.items && e.clipboardData.items.length > 0) {
var f = e.clipboardData.items[0].getAsFile();
if (f) {
e.stopPropagation(); // Stops some browsers from redirecting.
e.preventDefault();
dragged([f]);
}
}
}
});
r.addEventListener('dragover', function (e) {
var types = e.dataTransfer.types;
var found = false;
for (var i = 0; i < types.length; ++i)
if (types[i] == "Files")
found = true;
if (found) {
if (e.preventDefault)
e.preventDefault(); // Necessary. Allows us to drop.
e.dataTransfer.dropEffect = 'copy'; // See the section on the DataTransfer object.
return false;
}
return true;
}, false);
r.addEventListener('drop', function (e) {
var files = Util.toArray(e.dataTransfer.files);
if (files.length > 0) {
e.stopPropagation(); // Stops some browsers from redirecting.
e.preventDefault();
dragged(files);
}
return false;
}, false);
r.addEventListener('dragend', function (e) {
return false;
}, false);
}
exports.setupDragAndDrop = setupDragAndDrop;
},{}],14:[function(require,module,exports){
///
///
///
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var data = require("./data");
var sui = require("./sui");
var EditorToolbar = (function (_super) {
__extends(EditorToolbar, _super);
function EditorToolbar(props) {
_super.call(this, props);
}
EditorToolbar.prototype.saveProjectName = function (name, view) {
pxt.tickEvent("editortools.projectrename", { view: view });
this.props.parent.updateHeaderName(name);
};
EditorToolbar.prototype.compile = function (view) {
pxt.tickEvent("editortools.download", { view: view, collapsed: this.getCollapsedState() });
this.props.parent.compile();
};
EditorToolbar.prototype.saveFile = function (view) {
pxt.tickEvent("editortools.save", { view: view, collapsed: this.getCollapsedState() });
this.props.parent.saveAndCompile();
};
EditorToolbar.prototype.undo = function (view) {
pxt.tickEvent("editortools.undo", { view: view, collapsed: this.getCollapsedState() });
this.props.parent.editor.undo();
};
EditorToolbar.prototype.redo = function (view) {
pxt.tickEvent("editortools.redo", { view: view, collapsed: this.getCollapsedState() });
this.props.parent.editor.redo();
};
EditorToolbar.prototype.zoomIn = function (view) {
pxt.tickEvent("editortools.zoomIn", { view: view, collapsed: this.getCollapsedState() });
this.props.parent.editor.zoomIn();
};
EditorToolbar.prototype.zoomOut = function (view) {
pxt.tickEvent("editortools.zoomOut", { view: view, collapsed: this.getCollapsedState() });
this.props.parent.editor.zoomOut();
};
EditorToolbar.prototype.startStopSimulator = function (view) {
pxt.tickEvent("editortools.startStopSimulator", { view: view, collapsed: this.getCollapsedState(), headless: this.getHeadlessState() });
this.props.parent.startStopSimulator();
};
EditorToolbar.prototype.restartSimulator = function (view) {
pxt.tickEvent("editortools.restart", { view: view, collapsed: this.getCollapsedState(), headless: this.getHeadlessState() });
this.props.parent.restartSimulator();
};
EditorToolbar.prototype.toggleCollapse = function (view) {
pxt.tickEvent("editortools.toggleCollapse", { view: view, collapsedTo: '' + !this.props.parent.state.collapseEditorTools });
this.props.parent.toggleSimulatorCollapse();
};
EditorToolbar.prototype.getCollapsedState = function () {
return '' + this.props.parent.state.collapseEditorTools;
};
EditorToolbar.prototype.getHeadlessState = function () {
return pxt.appTarget.simulator.headless ? "true" : "false";
};
EditorToolbar.prototype.render = function () {
var _this = this;
var state = this.props.parent.state;
var sandbox = pxt.shell.isSandboxMode();
var readOnly = pxt.shell.isReadOnly();
var hideEditorFloats = state.hideEditorFloats;
var collapsed = state.hideEditorFloats || state.collapseEditorTools;
var isEditor = this.props.parent.isBlocksEditor() || this.props.parent.isTextEditor();
if (!isEditor)
return React.createElement("div", null);
var targetTheme = pxt.appTarget.appTheme;
var compile = pxt.appTarget.compile;
var compileBtn = compile.hasHex;
var simOpts = pxt.appTarget.simulator;
var make = !sandbox && state.showParts && simOpts && (simOpts.instructions || (simOpts.parts && pxt.options.debug));
var compileTooltip = lf("Download your code to the {0}", targetTheme.boardName);
var compileLoading = !!state.compiling;
var runTooltip = state.running ? lf("Stop the simulator") : lf("Start the simulator");
var makeTooltip = lf("Open assembly instructions");
var restartTooltip = lf("Restart the simulator");
var collapseTooltip = collapsed ? lf("Show the simulator") : lf("Hide the simulator");
var headless = pxt.appTarget.simulator.headless;
var hasUndo = this.props.parent.editor.hasUndo();
var hasRedo = this.props.parent.editor.hasRedo();
var run = true;
var restart = run && !simOpts.hideRestart;
return React.createElement("div", {className: "ui equal width grid right aligned padded"}, React.createElement("div", {className: "column mobile only"}, collapsed ?
React.createElement("div", {className: "ui equal width grid"}, React.createElement("div", {className: "left aligned column"}, React.createElement("div", {className: "ui icon small buttons"}, React.createElement(sui.Button, {icon: "" + (collapsed ? 'toggle up' : 'toggle down'), class: "collapse-button " + (hideEditorFloats ? 'disabled' : ''), title: collapseTooltip, onClick: function () { return _this.toggleCollapse('mobile'); }}), headless && run ? React.createElement(sui.Button, {class: "", key: 'runmenubtn', icon: state.running ? "stop" : "play", title: runTooltip, onClick: function () { return _this.startStopSimulator('mobile'); }}) : undefined, headless && restart ? React.createElement(sui.Button, {key: 'restartbtn', class: "restart-button", icon: "refresh", title: restartTooltip, onClick: function () { return _this.restartSimulator('mobile'); }}) : undefined, compileBtn ? React.createElement(sui.Button, {class: "primary download-button download-button-full " + (compileLoading ? 'loading' : ''), icon: "download", title: compileTooltip, onClick: function () { return _this.compile('mobile'); }}) : undefined)), readOnly ? undefined :
React.createElement("div", {className: "right aligned column"}, React.createElement("div", {className: "ui icon small buttons"}, React.createElement(sui.Button, {icon: 'save', class: "editortools-btn save-editortools-btn", title: lf("Save"), onClick: function () { return _this.saveFile('mobile'); }}), React.createElement(sui.Button, {icon: 'undo', class: "editortools-btn undo-editortools-btn} " + (!hasUndo ? 'disabled' : ''), title: lf("Undo"), onClick: function () { return _this.undo('mobile'); }}))), React.createElement("div", {className: "right aligned column"}, React.createElement("div", {className: "ui icon small buttons"}, React.createElement(sui.Button, {icon: 'zoom', class: "editortools-btn zoomin-editortools-btn", title: lf("Zoom In"), onClick: function () { return _this.zoomIn('mobile'); }}), React.createElement(sui.Button, {icon: 'zoom out', class: "editortools-btn zoomout-editortools-btn", title: lf("Zoom Out"), onClick: function () { return _this.zoomOut('mobile'); }})))) :
React.createElement("div", {className: "ui equal width grid"}, React.createElement("div", {className: "left aligned two wide column"}, React.createElement("div", {className: "ui vertical icon small buttons"}, run ? React.createElement(sui.Button, {class: "", key: 'runmenubtn', icon: state.running ? "stop" : "play", title: runTooltip, onClick: function () { return _this.startStopSimulator('mobile'); }}) : undefined, restart ? React.createElement(sui.Button, {key: 'restartbtn', class: "restart-button", icon: "refresh", title: restartTooltip, onClick: function () { return _this.restartSimulator('mobile'); }}) : undefined), React.createElement("div", {className: "row", style: { paddingTop: "1rem" }}, React.createElement("div", {className: "ui vertical icon small buttons"}, React.createElement(sui.Button, {icon: "" + (collapsed ? 'toggle up' : 'toggle down'), class: "collapse-button", title: collapseTooltip, onClick: function () { return _this.toggleCollapse('mobile'); }})))), React.createElement("div", {className: "three wide column"}), React.createElement("div", {className: "ui grid column"}, readOnly ? undefined :
React.createElement("div", {className: "row"}, React.createElement("div", {className: "column"}, React.createElement("div", {className: "ui icon large buttons"}, React.createElement(sui.Button, {icon: 'undo', class: "editortools-btn undo-editortools-btn} " + (!hasUndo ? 'disabled' : ''), title: lf("Undo"), onClick: function () { return _this.undo('mobile'); }})))), React.createElement("div", {className: "row", style: readOnly ? undefined : { paddingTop: 0 }}, React.createElement("div", {className: "column"}, React.createElement("div", {className: "ui icon large buttons"}, compileBtn ? React.createElement(sui.Button, {class: "primary download-button download-button-full " + (compileLoading ? 'loading' : ''), icon: "download", title: compileTooltip, onClick: function () { return _this.compile('mobile'); }}) : undefined)))))), React.createElement("div", {className: "column tablet only"}, collapsed ?
React.createElement("div", {className: "ui grid seven column"}, headless ?
React.createElement("div", {className: "left aligned six wide column"}, React.createElement("div", {className: "ui icon large buttons"}, React.createElement(sui.Button, {icon: "" + (collapsed ? 'toggle up' : 'toggle down'), class: "large collapse-button " + (hideEditorFloats ? 'disabled' : ''), title: collapseTooltip, onClick: function () { return _this.toggleCollapse('tablet'); }}), run ? React.createElement(sui.Button, {role: "menuitem", class: "large", key: 'runmenubtn', icon: state.running ? "stop" : "play", title: runTooltip, onClick: function () { return _this.startStopSimulator('tablet'); }}) : undefined, restart ? React.createElement(sui.Button, {key: 'restartbtn', class: "large restart-button", icon: "refresh", title: restartTooltip, onClick: function () { return _this.restartSimulator('tablet'); }}) : undefined, compileBtn ? React.createElement(sui.Button, {class: "primary large download-button download-button-full " + (compileLoading ? 'loading' : ''), icon: "download", title: compileTooltip, onClick: function () { return _this.compile('tablet'); }}) : undefined)) :
React.createElement("div", {className: "left aligned six wide column"}, React.createElement(sui.Button, {icon: "" + (collapsed ? 'toggle up' : 'toggle down'), class: "large collapse-button " + (hideEditorFloats ? 'disabled' : ''), title: collapseTooltip, onClick: function () { return _this.toggleCollapse('tablet'); }}), compileBtn ? React.createElement(sui.Button, {class: "primary large download-button download-button-full " + (compileLoading ? 'loading' : ''), icon: "download", text: lf("Download"), title: compileTooltip, onClick: function () { return _this.compile('tablet'); }}) : undefined), readOnly ? undefined :
React.createElement("div", {className: "column four wide"}, React.createElement(sui.Button, {icon: 'save', class: "large editortools-btn save-editortools-btn", title: lf("Save"), onClick: function () { return _this.saveFile('tablet'); }})), React.createElement("div", {className: "column six wide right aligned"}, readOnly ? undefined :
React.createElement("div", {className: "ui icon large buttons"}, React.createElement(sui.Button, {icon: 'undo', class: "editortools-btn undo-editortools-btn} " + (!hasUndo ? 'disabled' : ''), title: lf("Undo"), onClick: function () { return _this.undo('tablet'); }}), React.createElement(sui.Button, {icon: 'repeat', class: "editortools-btn redo-editortools-btn} " + (!hasRedo ? 'disabled' : ''), title: lf("Redo"), onClick: function () { return _this.redo('tablet'); }})), React.createElement("div", {className: "ui icon large buttons"}, React.createElement(sui.Button, {icon: 'zoom', class: "editortools-btn zoomin-editortools-btn", title: lf("Zoom In"), onClick: function () { return _this.zoomIn('tablet'); }}), React.createElement(sui.Button, {icon: 'zoom out', class: "editortools-btn zoomout-editortools-btn", title: lf("Zoom Out"), onClick: function () { return _this.zoomOut('tablet'); }}))))
: React.createElement("div", {className: "ui grid"}, React.createElement("div", {className: "left aligned two wide column"}, React.createElement("div", {className: "ui vertical icon small buttons"}, run ? React.createElement(sui.Button, {role: "menuitem", class: "", key: 'runmenubtn', icon: state.running ? "stop" : "play", title: runTooltip, onClick: function () { return _this.startStopSimulator('tablet'); }}) : undefined, restart ? React.createElement(sui.Button, {key: 'restartbtn', class: "restart-button", icon: "refresh", title: restartTooltip, onClick: function () { return _this.restartSimulator('tablet'); }}) : undefined), React.createElement("div", {className: "row", style: { paddingTop: "1rem" }}, React.createElement("div", {className: "ui vertical icon small buttons"}, React.createElement(sui.Button, {icon: "" + (collapsed ? 'toggle up' : 'toggle down'), class: "collapse-button", title: collapseTooltip, onClick: function () { return _this.toggleCollapse('tablet'); }})))), React.createElement("div", {className: "three wide column"}), React.createElement("div", {className: "five wide column"}, React.createElement("div", {className: "ui grid right aligned"}, compileBtn ? React.createElement("div", {className: "row"}, React.createElement("div", {className: "column"}, React.createElement(sui.Button, {role: "menuitem", class: "primary large fluid download-button download-button-full " + (compileLoading ? 'loading' : ''), icon: "download", text: lf("Download"), title: compileTooltip, onClick: function () { return _this.compile('tablet'); }}))) : undefined, readOnly ? undefined :
React.createElement("div", {className: "row", style: compileBtn ? { paddingTop: 0 } : {}}, React.createElement("div", {className: "column"}, React.createElement("div", {className: "ui item large right labeled fluid input projectname-input projectname-tablet", title: lf("Pick a name for your project")}, React.createElement("input", {id: "fileNameInput", type: "text", placeholder: lf("Pick a name..."), value: state.projectName || '', onChange: function (e) { return _this.saveProjectName(e.target.value, 'tablet'); }}), React.createElement(sui.Button, {icon: 'save', class: "large right attached editortools-btn save-editortools-btn", title: lf("Save"), onClick: function () { return _this.saveFile('tablet'); }})))))), React.createElement("div", {className: "six wide column right aligned"}, readOnly ? undefined :
React.createElement("div", {className: "ui icon large buttons"}, React.createElement(sui.Button, {icon: 'undo', class: "editortools-btn undo-editortools-btn} " + (!hasUndo ? 'disabled' : ''), title: lf("Undo"), onClick: function () { return _this.undo(); }}), React.createElement(sui.Button, {icon: 'repeat', class: "editortools-btn redo-editortools-btn} " + (!hasRedo ? 'disabled' : ''), title: lf("Redo"), onClick: function () { return _this.redo(); }})), React.createElement("div", {className: "ui icon large buttons"}, React.createElement(sui.Button, {icon: 'zoom', class: "editortools-btn zoomin-editortools-btn", title: lf("Zoom In"), onClick: function () { return _this.zoomIn(); }}), React.createElement(sui.Button, {icon: 'zoom out', class: "editortools-btn zoomout-editortools-btn", title: lf("Zoom Out"), onClick: function () { return _this.zoomOut(); }}))))), React.createElement("div", {className: "column computer only"}, React.createElement("div", {className: "ui grid equal width"}, React.createElement("div", {id: "downloadArea", className: "ui column items"}, headless && collapsed ?
React.createElement("div", {className: "ui item"}, React.createElement("div", {className: "ui icon large buttons"}, React.createElement(sui.Button, {icon: "" + (state.collapseEditorTools ? 'toggle right' : 'toggle left'), class: "large collapse-button", title: collapseTooltip, onClick: function () { return _this.toggleCollapse('computer'); }}), run ? React.createElement(sui.Button, {role: "menuitem", class: "large", key: 'runmenubtn', icon: state.running ? "stop" : "play", title: runTooltip, onClick: function () { return _this.startStopSimulator('tablet'); }}) : undefined, restart ? React.createElement(sui.Button, {key: 'restartbtn', class: "large restart-button", icon: "refresh", title: restartTooltip, onClick: function () { return _this.restartSimulator('tablet'); }}) : undefined, compileBtn ? React.createElement(sui.Button, {icon: 'icon download', class: "primary large download-button " + (compileLoading ? 'loading' : ''), title: compileTooltip, onClick: function () { return _this.compile('computer'); }}) : undefined)) :
React.createElement("div", {className: "ui item"}, React.createElement(sui.Button, {icon: "" + (state.collapseEditorTools ? 'toggle right' : 'toggle left'), class: "large collapse-button", title: collapseTooltip, onClick: function () { return _this.toggleCollapse('computer'); }}), compileBtn ? React.createElement(sui.Button, {icon: 'icon download', class: "primary huge fluid download-button " + (compileLoading ? 'loading' : ''), text: lf("Download"), title: compileTooltip, onClick: function () { return _this.compile('computer'); }}) : undefined)), readOnly ? undefined :
React.createElement("div", {className: "column left aligned"}, React.createElement("div", {className: "ui large right labeled input projectname-input projectname-computer", title: lf("Pick a name for your project")}, React.createElement("input", {id: "fileNameInput", type: "text", placeholder: lf("Pick a name..."), value: state.projectName || '', onChange: function (e) { return _this.saveProjectName(e.target.value, 'computer'); }}), React.createElement(sui.Button, {icon: 'save', class: "small right attached editortools-btn save-editortools-btn", title: lf("Save"), onClick: function () { return _this.saveFile('computer'); }}))), React.createElement("div", {className: "column right aligned"}, readOnly ? undefined :
React.createElement("div", {className: "ui icon small buttons"}, React.createElement(sui.Button, {icon: 'undo', class: "editortools-btn undo-editortools-btn} " + (!hasUndo ? 'disabled' : ''), title: lf("Undo"), onClick: function () { return _this.undo('computer'); }}), React.createElement(sui.Button, {icon: 'repeat', class: "editortools-btn redo-editortools-btn} " + (!hasRedo ? 'disabled' : ''), title: lf("Redo"), onClick: function () { return _this.redo('computer'); }})), React.createElement("div", {className: "ui icon small buttons"}, React.createElement(sui.Button, {icon: 'zoom', class: "editortools-btn zoomin-editortools-btn", title: lf("Zoom In"), onClick: function () { return _this.zoomIn('computer'); }}), React.createElement(sui.Button, {icon: 'zoom out', class: "editortools-btn zoomout-editortools-btn", title: lf("Zoom Out"), onClick: function () { return _this.zoomOut('computer'); }}))))));
};
return EditorToolbar;
}(data.Component));
exports.EditorToolbar = EditorToolbar;
},{"./data":11,"./sui":32,"react":264}],15:[function(require,module,exports){
"use strict";
var core = require("./core");
var Cloud = pxt.Cloud;
var UpdateEventType;
(function (UpdateEventType) {
UpdateEventType[UpdateEventType["Critical"] = 1] = "Critical";
UpdateEventType[UpdateEventType["Notification"] = 2] = "Notification";
UpdateEventType[UpdateEventType["Prompt"] = 3] = "Prompt";
})(UpdateEventType || (UpdateEventType = {}));
var electronSocket = null;
exports.isElectron = /[?&]electron=1/.test(window.location.href);
function init() {
if (!exports.isElectron || !Cloud.isLocalHost() || !Cloud.localToken) {
return;
}
function onCriticalUpdate(args) {
var isUrl = /^https:\/\//.test(args.targetVersion);
var body = lf("To continue using {0}, you must install an update.", args.appName || lf("this application"));
var agreeLbl = lf("Update");
if (isUrl) {
body = lf("To continue using {0}, you must install an update from the website.", args.appName || lf("this application"));
agreeLbl = lf("Go to website");
}
core.confirmAsync({
header: lf("Critical update required"),
body: body,
agreeLbl: agreeLbl,
disagreeLbl: lf("Quit"),
disagreeClass: "red",
size: "medium"
}).then(function (b) {
if (!b) {
pxt.tickEvent("update.refusedCritical");
sendMessage("quit");
}
else {
pxt.tickEvent("update.acceptedCritical");
core.showLoading(lf("Downloading update..."));
sendMessage("update", {
targetVersion: args.targetVersion,
type: args.type
});
}
});
}
function onUpdateAvailable(args) {
var isUrl = /^https:\/\//.test(args.targetVersion);
var header = lf("Version {0} available", args.targetVersion);
var body = lf("A new version of {0} is ready to download and install. The app will restart during the update. Update now?", args.appName || lf("this application"));
var agreeLbl = lf("Update");
if (isUrl) {
header = lf("Update available from website");
body = lf("A new version of {0} is available from the website.", args.appName || lf("this application"));
agreeLbl = lf("Go to website");
}
if (args.type === UpdateEventType.Notification) {
core.infoNotification(lf("A new version is available. Select 'Check for updates...' in the menu.", args.targetVersion));
}
else if (args.type === UpdateEventType.Prompt) {
core.confirmAsync({
header: header,
body: body,
agreeLbl: agreeLbl,
disagreeLbl: lf("Not now"),
size: "medium"
}).then(function (b) {
if (!b) {
if (args.isInitialCheck) {
pxt.tickEvent("update.refusedInitial");
}
else {
pxt.tickEvent("update.refused");
}
}
else {
if (args.isInitialCheck) {
pxt.tickEvent("update.acceptedInitial");
}
else {
pxt.tickEvent("update.accepted");
}
if (!isUrl) {
core.showLoading(lf("Downloading update..."));
}
sendMessage("update", {
targetVersion: args.targetVersion,
type: args.type
});
}
});
}
}
function onUpdateNotAvailable() {
core.confirmAsync({
body: lf("You are using the latest version available."),
header: lf("Good to go!"),
agreeLbl: lf("Ok"),
hideCancel: true
});
}
function onUpdateCheckError() {
displayUpdateError(lf("Unable to check for updates"), lf("Ok"));
}
function onUpdateDownloadError(args) {
var isCritical = args && args.type === UpdateEventType.Critical;
core.hideLoading();
displayUpdateError(lf("There was an error downloading the update"), isCritical ? lf("Quit") : lf("Ok"))
.finally(function () {
if (isCritical) {
sendMessage("quit");
}
});
}
function displayUpdateError(header, btnLabel) {
return core.confirmAsync({
header: header,
body: lf("Please ensure you are connected to the Internet and try again later."),
agreeClass: "red",
agreeIcon: "cancel",
agreeLbl: btnLabel,
hideCancel: true
});
}
pxt.log('initializing electron socket');
electronSocket = new WebSocket("ws://localhost:" + pxt.options.wsPort + "/" + Cloud.localToken + "/electron");
electronSocket.onopen = function (ev) {
pxt.log('electron: socket opened');
sendMessage("ready");
};
electronSocket.onclose = function (ev) {
pxt.log('electron: socket closed');
electronSocket = null;
};
electronSocket.onmessage = function (ev) {
try {
var msg = JSON.parse(ev.data);
switch (msg.type) {
case "critical-update":
onCriticalUpdate(msg.args);
break;
case "update-available":
onUpdateAvailable(msg.args);
break;
case "update-not-available":
onUpdateNotAvailable();
break;
case "update-check-error":
onUpdateCheckError();
break;
case "update-download-error":
onUpdateDownloadError(msg.args);
break;
case "telemetry":
var telemetryInfo = msg.args;
if (!telemetryInfo) {
pxt.debug('invalid telemetry message: ' + ev.data);
return;
}
pxt.tickEvent(telemetryInfo.event, telemetryInfo.data);
default:
pxt.debug('unknown electron message: ' + ev.data);
break;
}
}
catch (e) {
pxt.debug('unknown electron message: ' + ev.data);
}
};
}
exports.init = init;
function sendMessage(type, args) {
if (!electronSocket) {
return;
}
var message = {
type: type,
args: args
};
// Sending messages to the web socket sometimes hangs the app briefly; use setTimeout to smoothen the UI animations a bit
setTimeout(function () {
electronSocket.send(JSON.stringify(message));
}, 150);
}
exports.sendMessage = sendMessage;
function checkForUpdate() {
pxt.tickEvent("menu.electronupdate");
sendMessage("check-for-update");
}
exports.checkForUpdate = checkForUpdate;
},{"./core":10}],16:[function(require,module,exports){
///
///
///
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var data = require("./data");
var sui = require("./sui");
var pkg = require("./package");
var core = require("./core");
var FileList = (function (_super) {
__extends(FileList, _super);
function FileList(props) {
_super.call(this, props);
this.state = {
expands: {}
};
}
FileList.prototype.removePkg = function (e, p) {
var _this = this;
e.stopPropagation();
core.confirmAsync({
header: lf("Remove {0} package", p.getPkgId()),
body: lf("You are about to remove a package from your project. Are you sure?"),
agreeClass: "red",
agreeIcon: "trash",
agreeLbl: lf("Remove it"),
}).done(function (res) {
if (res) {
pkg.mainEditorPkg().removeDepAsync(p.getPkgId())
.then(function () { return _this.props.parent.reloadHeaderAsync(); })
.done();
}
});
};
FileList.prototype.removeFile = function (e, f) {
e.stopPropagation();
this.props.parent.removeFile(f);
};
FileList.prototype.updatePkg = function (e, p) {
var _this = this;
e.stopPropagation();
pkg.mainEditorPkg().updateDepAsync(p.getPkgId())
.then(function () { return _this.props.parent.reloadHeaderAsync(); })
.done();
};
FileList.prototype.filesOf = function (pkg) {
var _this = this;
var deleteFiles = pkg.getPkgId() == "this";
var parent = this.props.parent;
return pkg.sortedFiles().map(function (file) {
var meta = _this.getData("open-meta:" + file.getName());
return (React.createElement("a", {key: file.getName(), onClick: function () { return parent.setSideFile(file); }, className: (parent.state.currFile == file ? "active " : "") + (pkg.isTopLevel() ? "" : "nested ") + "item"}, file.name, " ", meta.isSaved ? "" : "*", /\.ts$/.test(file.name) ? React.createElement("i", {className: "align left icon"}) : /\.blocks$/.test(file.name) ? React.createElement("i", {className: "puzzle icon"}) : undefined, meta.isReadonly ? React.createElement("i", {className: "lock icon"}) : null, !meta.numErrors ? null : React.createElement("span", {className: 'ui label red'}, meta.numErrors), deleteFiles && /\.blocks$/i.test(file.getName()) ? React.createElement(sui.Button, {class: "primary label", icon: "trash", onClick: function (e) { return _this.removeFile(e, file); }}) : ''));
});
};
FileList.prototype.packageOf = function (p) {
var _this = this;
var expands = this.state.expands;
var del = p.getPkgId() != pxt.appTarget.id && p.getPkgId() != "built";
var upd = p.getKsPkg() && p.getKsPkg().verProtocol() == "github";
return [React.createElement("div", {key: "hd-" + p.getPkgId(), className: "header link item", onClick: function () { return _this.togglePkg(p); }}, React.createElement("i", {className: "chevron " + (expands[p.getPkgId()] ? "down" : "right") + " icon"}), upd ? React.createElement(sui.Button, {class: "primary label", icon: "refresh", onClick: function (e) { return _this.updatePkg(e, p); }}) : '', del ? React.createElement(sui.Button, {class: "primary label", icon: "trash", onClick: function (e) { return _this.removePkg(e, p); }}) : '', p.getPkgId())
].concat(expands[p.getPkgId()] ? this.filesOf(p) : []);
};
FileList.prototype.togglePkg = function (p) {
var expands = this.state.expands;
expands[p.getPkgId()] = !expands[p.getPkgId()];
this.forceUpdate();
};
FileList.prototype.filesWithHeader = function (p) {
return p.isTopLevel() ? this.filesOf(p) : this.packageOf(p);
};
FileList.prototype.toggleVisibility = function () {
this.props.parent.setState({ showFiles: !this.props.parent.state.showFiles });
};
FileList.prototype.renderCore = function () {
var _this = this;
var show = !!this.props.parent.state.showFiles;
var targetTheme = pxt.appTarget.appTheme;
return React.createElement("div", {className: "ui tiny vertical " + (targetTheme.invertedMenu ? "inverted" : '') + " menu filemenu landscape only"}, React.createElement("div", {key: "projectheader", className: "link item", onClick: function () { return _this.toggleVisibility(); }}, lf("Explorer"), React.createElement("i", {className: "chevron " + (show ? "down" : "right") + " icon"})), show ? Util.concat(pkg.allEditorPkgs().map(function (p) { return _this.filesWithHeader(p); })) : undefined);
};
return FileList;
}(data.Component));
exports.FileList = FileList;
},{"./core":10,"./data":11,"./package":24,"./sui":32,"react":264}],17:[function(require,module,exports){
"use strict";
var db = require("./db");
var core = require("./core");
var data = require("./data");
var U = pxt.Util;
var Cloud = pxt.Cloud;
var lf = U.lf;
var allScripts = [];
var currentTarget;
function lookup(id) {
return allScripts.filter(function (x) { return x.id == id; })[0];
}
function getHeaders() {
return allScripts.map(function (e) { return e.header; });
}
function getHeader(id) {
var e = lookup(id);
if (e && !e.header.isDeleted)
return e.header;
return null;
}
function apiAsync(path, data) {
return U.requestAsync({
url: "/api/" + path,
headers: { "Authorization": Cloud.localToken },
method: data ? "POST" : "GET",
data: data || undefined
}).then(function (r) { return r.json; }).catch(core.handleNetworkError);
}
function mergeFsPkg(pkg) {
var e = lookup(pkg.path);
if (!e) {
e = {
id: pkg.path,
header: null,
text: null,
fsText: null
};
allScripts.push(e);
}
var time = pkg.files.map(function (f) { return f.mtime; });
time.sort(function (a, b) { return b - a; });
var modTime = Math.round(time[0] / 1000) || U.nowSeconds();
var hd = {
target: currentTarget,
name: pkg.config.name,
meta: {},
editor: pxt.JAVASCRIPT_PROJECT_NAME,
pubId: pkg.config.installedVersion,
pubCurrent: false,
_rev: null,
id: pkg.path,
recentUse: modTime,
modificationTime: modTime,
blobId: null,
blobCurrent: false,
isDeleted: false,
icon: pkg.icon
};
if (!e.header) {
e.header = hd;
}
else {
var eh = e.header;
eh.name = hd.name;
eh.pubId = hd.pubId;
eh.modificationTime = hd.modificationTime;
eh.isDeleted = hd.isDeleted;
eh.icon = hd.icon;
}
}
function initAsync(target) {
allScripts = [];
currentTarget = target;
// TODO check that target is correct.
return syncAsync();
}
function fetchTextAsync(e) {
return apiAsync("pkg/" + e.id)
.then(function (resp) {
if (!e.text) {
// otherwise we were beaten to it
e.text = {};
e.mtime = 0;
for (var _i = 0, _a = resp.files; _i < _a.length; _i++) {
var f = _a[_i];
e.text[f.name] = f.content;
e.mtime = Math.max(e.mtime, f.mtime);
}
e.fsText = U.flatClone(e.text);
}
return e.text;
});
}
var headerQ = new U.PromiseQueue();
function getTextAsync(id) {
var e = lookup(id);
if (!e)
return Promise.resolve(null);
if (e.text)
return Promise.resolve(e.text);
return headerQ.enqueue(id, function () { return fetchTextAsync(e); });
}
function saveCoreAsync(h, text) {
if (h.temporary)
return Promise.resolve();
var e = lookup(h.id);
U.assert(e.header === h);
if (!text)
return Promise.resolve();
h.saveId = null;
e.textNeedsSave = true;
e.text = text;
return headerQ.enqueue(h.id, function () {
U.assert(!!e.fsText);
var pkg = {
files: [],
config: null,
path: h.id,
};
for (var _i = 0, _a = Object.keys(e.text); _i < _a.length; _i++) {
var fn = _a[_i];
if (e.text[fn] !== e.fsText[fn])
pkg.files.push({
name: fn,
mtime: null,
content: e.text[fn],
prevContent: e.fsText[fn]
});
}
var savedText = U.flatClone(e.text);
if (pkg.files.length == 0)
return Promise.resolve();
return apiAsync("pkg/" + h.id, pkg)
.then(function (pkg) {
e.fsText = savedText;
mergeFsPkg(pkg);
data.invalidate("header:" + h.id);
data.invalidate("header:*");
if (text) {
data.invalidate("text:" + h.id);
h.saveId = null;
}
})
.catch(function (e) { return core.errorNotification(lf("Save failed!")); });
});
}
function saveAsync(h, text) {
return saveCoreAsync(h, text);
}
function installAsync(h0, text) {
var h = h0;
var path = h.name.replace(/[^a-zA-Z0-9]+/g, " ").trim().replace(/ /g, "-");
if (lookup(path)) {
var n = 2;
while (lookup(path + "-" + n))
n++;
path += "-" + n;
h.name += " " + n;
}
h.id = path;
h.recentUse = U.nowSeconds();
h.modificationTime = h.recentUse;
h.target = currentTarget;
var e = {
id: h.id,
header: h,
text: text,
fsText: {}
};
allScripts.push(e);
return saveCoreAsync(h, text)
.then(function () { return h; });
}
function saveToCloudAsync(h) {
return Promise.resolve();
}
function syncAsync() {
return apiAsync("list").then(function (h) {
h.pkgs.forEach(mergeFsPkg);
})
.then(function () {
data.invalidate("header:");
data.invalidate("text:");
});
}
function saveScreenshotAsync(h, screenshot, icon) {
return apiAsync("screenshot/" + h.id, { screenshot: screenshot, icon: icon });
}
function resetAsync() {
return db.destroyAsync()
.then(function () {
allScripts = [];
pxt.storage.clearLocal();
data.clearCache();
});
}
exports.provider = {
getHeaders: getHeaders,
getHeader: getHeader,
getTextAsync: getTextAsync,
initAsync: initAsync,
saveAsync: saveAsync,
installAsync: installAsync,
saveToCloudAsync: saveToCloudAsync,
syncAsync: syncAsync,
resetAsync: resetAsync,
saveScreenshotAsync: saveScreenshotAsync
};
},{"./core":10,"./data":11,"./db":12}],18:[function(require,module,exports){
"use strict";
function parseExampleMarkdown(name, md) {
if (!md)
return undefined;
var m = /```blocks\s*((.|\s)+?)\s*```/i.exec(md);
if (!m)
return undefined;
return {
name: name,
filesOverride: {
"main.blocks": "",
"main.ts": m[1]
}
};
}
function parseGalleryMardown(md) {
if (!md)
return [];
// second level titles are categories
// ## foo bar
// fenced code ```cards are sections of cards
var galleries = [];
var incard = false;
var name = undefined;
var cards = "";
md.split(/\r?\n/).forEach(function (line) {
// new category
if (/^##/.test(line)) {
name = line.substr(2).trim();
}
else if (/^```codecard$/.test(line)) {
incard = true;
}
else if (/^```$/.test(line)) {
incard = false;
if (name && cards) {
try {
var cardsJSON = JSON.parse(cards);
if (cardsJSON && cardsJSON.length > 0)
galleries.push({ name: name, cards: cardsJSON });
}
catch (e) {
pxt.log('invalid card format in gallery');
}
}
cards = "";
name = undefined;
}
else if (incard)
cards += line + '\n';
});
return galleries;
}
function loadGalleryAsync(name) {
return pxt.Cloud.downloadMarkdownAsync(name, pxt.Util.userLanguage(), pxt.Util.localizeLive)
.then(function (md) { return parseGalleryMardown(md); });
}
exports.loadGalleryAsync = loadGalleryAsync;
function loadExampleAsync(name, path) {
return pxt.Cloud.downloadMarkdownAsync(path, pxt.Util.userLanguage(), pxt.Util.localizeLive)
.then(function (md) { return parseExampleMarkdown(name, md); });
}
exports.loadExampleAsync = loadExampleAsync;
},{}],19:[function(require,module,exports){
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var workeriface = require("./workeriface");
var Cloud = pxt.Cloud;
var U = pxt.Util;
var iface;
var devPath;
var HIDError = (function (_super) {
__extends(HIDError, _super);
function HIDError(msg) {
_super.call(this, msg);
this.message = msg;
}
return HIDError;
}(Error));
exports.HIDError = HIDError;
var bridgeByPath = {};
function onOOB(v) {
var b = U.lookup(bridgeByPath, v.result.path);
if (b) {
b.onOOB(v);
}
else {
console.error("Dropping data for " + v.result.path);
}
}
function init() {
if (!iface) {
if (!Cloud.isLocalHost() || !Cloud.localToken)
return;
pxt.debug('initializing hid pipe');
iface = workeriface.makeWebSocket("ws://localhost:" + pxt.options.wsPort + "/" + Cloud.localToken + "/hid", onOOB);
}
}
function shouldUse() {
return pxt.appTarget.serial && pxt.appTarget.serial.useHF2 && Cloud.isLocalHost() && !!Cloud.localToken;
}
exports.shouldUse = shouldUse;
function mkBridgeAsync() {
init();
return iface.opAsync("list", {})
.then(function (devs) {
var d0 = devs.devices.filter(function (d) { return (d.release & 0xff00) == 0x4200; })[0];
if (d0)
return new BridgeIO(d0);
else
throw new Error("No device connected");
})
.then(function (b) { return b.initAsync().then(function () { return b; }); });
}
exports.mkBridgeAsync = mkBridgeAsync;
var BridgeIO = (function () {
function BridgeIO(dev) {
this.dev = dev;
this.onData = function (v) { };
this.onError = function (e) { };
this.onSerial = function (v, isErr) { };
}
BridgeIO.prototype.onOOB = function (v) {
if (v.op == "serial") {
this.onSerial(U.fromHex(v.result.data), v.result.isError);
}
};
BridgeIO.prototype.talksAsync = function (cmds) {
return iface.opAsync("talk", {
path: this.dev.path,
cmds: cmds.map(function (c) { return ({ cmd: c.cmd, data: c.data ? U.toHex(c.data) : "" }); })
})
.then(function (resp) {
return resp.map(function (v) { return U.fromHex(v.data); });
});
};
BridgeIO.prototype.error = function (msg) {
throw new HIDError(U.lf("USB/HID error on device {0} ({1})", this.dev.product, msg));
};
BridgeIO.prototype.reconnectAsync = function () {
return this.initAsync();
};
BridgeIO.prototype.sendPacketAsync = function (pkt) {
throw new Error("should use talksAsync()!");
};
BridgeIO.prototype.sendSerialAsync = function (buf, useStdErr) {
return iface.opAsync("sendserial", {
path: this.dev.path,
data: U.toHex(buf),
isError: useStdErr
});
};
BridgeIO.prototype.initAsync = function () {
bridgeByPath[this.dev.path] = this;
return iface.opAsync("init", {
path: this.dev.path
});
};
return BridgeIO;
}());
function hf2Async() {
return mkBridgeAsync()
.then(function (h) {
var w = new pxt.HF2.Wrapper(h);
return w.reconnectAsync(true)
.then(function () { return w; });
});
}
var initPromise;
function initAsync() {
if (!initPromise)
initPromise = hf2Async()
.catch(function (err) {
initPromise = null;
return Promise.reject(err);
});
return initPromise;
}
exports.initAsync = initAsync;
},{"./workeriface":36}],20:[function(require,module,exports){
"use strict";
var compiler = require("./compiler");
var workeriface = require("./workeriface");
var Cloud = pxt.Cloud;
var U = pxt.Util;
var iface;
var isHalted = false;
var lastCompileResult;
var haltCheckRunning = false;
var onHalted = Promise.resolve();
var haltHandler;
var cachedStateInfo;
var nextBreakpoints = [];
var currBreakpoint;
var lastDebugStatus;
var callInfos;
function init() {
if (!iface) {
if (!Cloud.isLocalHost() || !Cloud.localToken)
return;
pxt.debug('initializing debug pipe');
iface = workeriface.makeWebSocket("ws://localhost:" + pxt.options.wsPort + "/" + Cloud.localToken + "/debug");
}
}
function readMemAsync(addr, numwords) {
return workerOpAsync("mem", { addr: addr, words: numwords })
.then(function (resp) { return resp.data; });
}
exports.readMemAsync = readMemAsync;
function writeMemAsync(addr, words) {
return workerOpAsync("wrmem", { addr: addr, words: words })
.then(function () { });
}
exports.writeMemAsync = writeMemAsync;
var asm = "";
function callAndPush(prc) {
var idx = asm.length;
asm += "\n ldr r4, .proc" + idx + "\n blx r4\n push {r0}\n b .next" + idx + "\n .balign 4\n.proc" + idx + ":\n .word " + prc + "|1\n.next" + idx + ":\n";
}
var stateProcs = [
"pxt::getNumGlobals/numGlobals",
"pxtrt::getGlobalsPtr/globalsPtr",
];
function callForStateAsync(st) {
if (cachedStateInfo)
return Promise.resolve(cachedStateInfo);
asm = "";
for (var _i = 0, stateProcs_1 = stateProcs; _i < stateProcs_1.length; _i++) {
var p = stateProcs_1[_i];
callAndPush(p.replace(/\/.*/, ""));
}
asm += "\n bkpt 42\n @nostackcheck\n";
return compiler.assembleAsync(asm)
.then(function (res) { return workerOpAsync("exec", { code: res.words, args: [] }); })
.then(function () { return snapshotAsync(); })
.then(function (st) {
var fields = stateProcs.map(function (s) { return s.replace(/.*\//, ""); });
fields.reverse();
var r = {};
fields.forEach(function (f, i) {
r[f] = st.stack[i];
});
cachedStateInfo = r;
})
.then(function () { return restoreAsync(st); })
.then(function () { return cachedStateInfo; });
}
function clearAsync() {
isHalted = false;
lastCompileResult = null;
cachedStateInfo = null;
lastDebugStatus = null;
return Promise.resolve();
}
function coreHalted() {
return getHwStateAsync()
.then(function (st) {
nextBreakpoints = [];
var globals = {};
st.globals.slice(1).forEach(function (v, i) {
var loc = lastCompileResult.procDebugInfo[0].locals[i];
if (loc)
globals[loc.name] = v;
else
globals["?" + i] = v;
});
var pc = st.machineState.registers[15];
var final = function () { return Promise.resolve(); };
var stepInBkp = lastCompileResult.procDebugInfo.filter(function (p) { return p.bkptLoc == pc; })[0];
if (stepInBkp) {
pc = stepInBkp.codeStartLoc;
st.machineState.registers[15] = pc;
final = function () { return restoreAsync(st.machineState); };
}
var bb = lastCompileResult.breakpoints;
var brkMatch = bb[0];
var bestDelta = Infinity;
for (var _i = 0, bb_1 = bb; _i < bb_1.length; _i++) {
var b = bb_1[_i];
var delta = pc - b.binAddr;
if (delta >= 0 && delta < bestDelta) {
bestDelta = delta;
brkMatch = b;
}
}
currBreakpoint = brkMatch;
var msg = {
type: 'debugger',
subtype: 'breakpoint',
breakpointId: brkMatch.id,
globals: globals,
stackframes: []
};
exports.postMessage(msg);
return final();
})
.then(haltHandler);
}
function haltCheckAsync() {
if (isHalted)
return Promise.delay(100).then(haltCheckAsync);
return workerOpAsync("status")
.then(function (res) {
if (res.isHalted) {
isHalted = true;
coreHalted();
}
return Promise.delay(300);
})
.then(haltCheckAsync);
}
function clearHalted() {
isHalted = false;
onHalted = new Promise(function (resolve, reject) {
haltHandler = resolve;
});
if (!haltCheckRunning) {
haltCheckRunning = true;
haltCheckAsync();
}
}
function writeDebugStatusAsync(v) {
if (v === lastDebugStatus)
return Promise.resolve();
lastDebugStatus = v;
return writeMemAsync(cachedStateInfo.globalsPtr, [v]);
}
function setBreakpointsAsync(addrs) {
return workerOpAsync("breakpoints", { addrs: addrs });
}
function startDebugAsync() {
return clearAsync()
.then(function () { return compiler.compileAsync({ native: true }); })
.then(function (res) {
lastCompileResult = res;
callInfos = {};
var procLookup = [];
for (var _i = 0, _a = res.procDebugInfo; _i < _a.length; _i++) {
var pdi = _a[_i];
procLookup[pdi.idx] = pdi;
}
for (var _b = 0, _c = res.procDebugInfo; _b < _c.length; _b++) {
var pdi = _c[_b];
for (var _d = 0, _e = pdi.calls; _d < _e.length; _d++) {
var ci = _e[_d];
callInfos[ci.addr + ""] = {
from: pdi,
to: procLookup[ci.procIndex],
stack: ci.stack
};
}
}
var bb = lastCompileResult.breakpoints;
var entry = bb[1];
for (var _f = 0, bb_2 = bb; _f < bb_2.length; _f++) {
var b = bb_2[_f];
if (b.binAddr && b.binAddr < entry.binAddr)
entry = b;
}
return setBreakpointsAsync([entry.binAddr]);
})
.then(function () { return workerOpAsync("reset"); })
.then(clearHalted)
.then(waitForHaltAsync)
.then(function (res) { return writeDebugStatusAsync(1).then(function () { return res; }); });
}
exports.startDebugAsync = startDebugAsync;
function handleMessage(msg) {
console.log("HWDBGMSG", msg);
if (msg.type != "debugger")
return;
var stepInto = false;
switch (msg.subtype) {
case 'stepinto':
stepInto = true;
case 'stepover':
nextBreakpoints = currBreakpoint.successors.map(function (id) { return lastCompileResult.breakpoints[id].binAddr; });
resumeAsync(stepInto);
break;
}
}
exports.handleMessage = handleMessage;
function snapshotAsync() {
return workerOpAsync("snapshot")
.then(function (r) { return r.state; });
}
exports.snapshotAsync = snapshotAsync;
function restoreAsync(st) {
return workerOpAsync("restore", { state: st })
.then(function () { });
}
exports.restoreAsync = restoreAsync;
function resumeAsync(into) {
if (into === void 0) { into = false; }
return Promise.resolve()
.then(function () { return writeDebugStatusAsync(into ? 3 : 1); })
.then(function () { return setBreakpointsAsync(nextBreakpoints); })
.then(function () { return workerOpAsync("resume"); })
.then(clearHalted);
}
exports.resumeAsync = resumeAsync;
function waitForHaltAsync() {
U.assert(haltCheckRunning);
return onHalted;
}
exports.waitForHaltAsync = waitForHaltAsync;
function getHwStateAsync() {
var res = {
machineState: null,
globals: []
};
return snapshotAsync()
.then(function (v) {
res.machineState = v;
return callForStateAsync(v);
})
.then(function (info) { return readMemAsync(info.globalsPtr, info.numGlobals); })
.then(function (g) {
res.globals = g;
return res;
});
}
exports.getHwStateAsync = getHwStateAsync;
var devPath;
function workerOpAsync(op, arg) {
if (arg === void 0) { arg = {}; }
init();
if (!devPath)
devPath = iface.opAsync("list", {})
.then(function (devs) {
var d0 = devs.devices[0];
if (d0)
return d0.path;
else
throw new Error("No device connected");
});
return devPath
.then(function (path) {
arg["path"] = path;
return iface.opAsync(op, arg);
});
}
exports.workerOpAsync = workerOpAsync;
function flashDeviceAsync(startAddr, words) {
var cfg = {
flashWords: words,
flashCode: [],
bufferAddr: 0x20000400,
numBuffers: 2,
flashAddr: startAddr
};
return compiler.assembleAsync(nrfFlashAsm)
.then(function (res) { cfg.flashCode = res.words; })
.then(function (res) { return workerOpAsync("wrpages", cfg); });
}
exports.flashDeviceAsync = flashDeviceAsync;
/*
#define PAGE_SIZE 0x400
#define SIZE_IN_WORDS (PAGE_SIZE/4)
void setConfig(uint32_t v) {
NRF_NVMC->CONFIG = v;
while (NRF_NVMC->READY == NVMC_READY_READY_Busy);
}
void overwriteFlashPage(uint32_t* to, uint32_t* from)
{
// Turn on flash erase enable and wait until the NVMC is ready:
setConfig(NVMC_CONFIG_WEN_Een << NVMC_CONFIG_WEN_Pos);
// Erase page:
NRF_NVMC->ERASEPAGE = (uint32_t)to;
while (NRF_NVMC->READY == NVMC_READY_READY_Busy);
// Turn off flash erase enable and wait until the NVMC is ready:
setConfig(NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);
// Turn on flash write enable and wait until the NVMC is ready:
setConfig(NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos);
for(int i = 0; i <= (SIZE_IN_WORDS - 1); i++) {
*(to + i) = *(from + i);
while (NRF_NVMC->READY == NVMC_READY_READY_Busy);
}
// Turn off flash write enable and wait until the NVMC is ready:
setConfig(NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);
}
*/
var nrfFlashAsm = "\noverwriteFlashPage:\n cpsid i\n push {r4, r5, r6, lr}\n movs r5, r0\n movs r0, #2\n movs r6, r1\n bl .setConfig\n movs r3, #161 ; 0xa1\n movs r2, #128 ; 0x80\n ldr r4, .NRF_NVMC\n lsls r3, r3, #3\n str r5, [r4, r3]\n lsls r2, r2, #3\n.overLoop:\n ldr r3, [r4, r2]\n cmp r3, #0\n beq .overLoop\n movs r0, #0\n bl .setConfig\n movs r0, #1\n bl .setConfig\n movs r2, #128\n lsls r2, r2, #3\n movs r3, #0\n movs r1, r2\n.overOuterLoop:\n ldr r0, [r6, r3]\n str r0, [r5, r3]\n.overLoop2:\n ldr r0, [r4, r2]\n cmp r0, #0\n beq .overLoop2\n adds r3, #4\n cmp r3, r1\n bne .overOuterLoop\n movs r0, #0\n bl .setConfig\n pop {r4, r5, r6, pc}\n\n.setConfig:\n movs r1, #128\n ldr r3, .NRF_NVMC\n ldr r2, .v504\n lsls r1, r1, #3\n str r0, [r3, r2]\n.cfgLoop:\n ldr r2, [r3, r1]\n cmp r2, #0\n beq .cfgLoop\n bx lr\n\n\n .balign 4\n.NRF_NVMC: .word 0x4001e000\n.v504: .word 0x504\n";
},{"./compiler":8,"./workeriface":36}],21:[function(require,module,exports){
///
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var ReactDOM = require("react-dom");
var core = require("./core");
var STREAM_INTERVAL = 30000;
var LogView = (function (_super) {
__extends(LogView, _super);
function LogView(props) {
var _this = this;
_super.call(this, props);
this.lastStreamUploadTime = 0;
this.streamUploadTimeout = 0;
this.view = new pxsim.logs.LogViewElement({
maxEntries: 80,
maxAccValues: 500,
onClick: function (es) { return _this.onClick(es); },
onTrendChartChanged: function () { return _this.setState({ trends: _this.view.hasTrends() }); }
});
this.state = {};
}
LogView.prototype.componentDidMount = function () {
var node = ReactDOM.findDOMNode(this);
node.appendChild(this.view.element);
};
LogView.prototype.clear = function () {
this.view.clear();
};
LogView.prototype.render = function () {
return React.createElement("div", null);
};
LogView.prototype.componentDidUpdate = function () {
var streams = pxt.appTarget.simulator && !!pxt.appTarget.simulator.streams;
if (streams && this.state.stream)
this.view.setLabel(lf("streaming to cloud"), "green cloudflash");
else if (streams && this.state.trends)
this.view.setLabel(lf("streaming off"), "gray");
else
this.view.setLabel(undefined);
if (this.state.stream)
this.scheduleStreamData();
};
LogView.prototype.cancelStreamData = function () {
if (this.streamUploadTimeout) {
clearTimeout(this.streamUploadTimeout);
this.streamUploadTimeout = 0;
}
};
LogView.prototype.scheduleStreamData = function () {
var _this = this;
this.cancelStreamData();
var towait = Math.max(100, STREAM_INTERVAL - (Util.now() - this.lastStreamUploadTime));
this.streamUploadTimeout = setTimeout(function () { return _this.streamData(); }, towait);
};
LogView.prototype.streamData = function () {
var _this = this;
var stream = this.state.stream;
if (!stream) {
if (this.streamUploadTimeout) {
clearTimeout(this.streamUploadTimeout);
this.streamUploadTimeout = 0;
}
return;
}
if (!pxt.Cloud.isOnline()) {
this.scheduleStreamData();
return;
}
pxt.debug('streaming payload...');
var data = this.view.streamPayload(this.lastStreamUploadTime);
this.lastStreamUploadTime = Util.now();
if (!data) {
this.scheduleStreamData();
return;
}
pxt.streams.postPayloadAsync(stream, data)
.catch(function (e) {
core.warningNotification(lf("Oops, we could not upload your data..."));
_this.scheduleStreamData();
}).done(function () { return _this.scheduleStreamData(); });
};
LogView.prototype.setStream = function (stream) {
this.setState({ stream: stream });
};
LogView.prototype.onClick = function (entries) {
this.showStreamDialog(entries);
};
LogView.prototype.showStreamDialog = function (entries) {
var _this = this;
var targetTheme = pxt.appTarget.appTheme;
var streaming = pxt.appTarget.simulator && !!pxt.appTarget.simulator.streams;
var rootUrl = targetTheme.embedUrl;
if (!rootUrl) {
pxt.commands.browserDownloadAsync(pxsim.logs.entriesToCSV(entries), "data.csv", 'text/csv');
return;
}
if (!/\/$/.test(rootUrl))
rootUrl += '/';
var streamUrl = this.state.stream ? rootUrl + this.state.stream.id : undefined;
core.confirmAsync({
logos: streaming ? ["https://az851932.vo.msecnd.net/pub/hjlxsmaf"] : undefined,
header: pxt.appTarget.title + ' - ' + lf("Analyze Data"),
hideAgree: true,
disagreeLbl: lf("Close"),
onLoaded: function (_) {
_.find('#datasavelocalfile').click(function () {
_.modal('hide');
pxt.commands.browserDownloadAsync(pxsim.logs.entriesToCSV(entries), "data.csv", 'text/csv');
}),
_.find('#datastreamstart').click(function () {
_.modal('hide');
core.showLoading(lf("creating stream in Microsoft Azure..."));
pxt.streams.createStreamAsync(pxt.appTarget.id)
.then(function (stream) {
core.hideLoading();
_this.setStream(stream);
}).catch(function (e) {
pxt.reportException(e, {});
core.hideLoading();
core.warningNotification(lf("Oops, we could not create the stream. Please try again later."));
}).done();
});
_.find('#datastreamstop').click(function () {
_.modal('hide');
_this.setStream(null);
});
},
htmlBody: "\n
\n
\n
\n
" + lf("Local File") + "
\n
\n " + lf("Save the data to your 'Downloads' folder.") + "\n
\n
\n
\n \n " + lf("Download data") + "\n
\n
\n " + (streaming ?
"
\n
\n
" + lf("Stream to Cloud") + "
\n
\n " + (streamUrl ? lf("We are uploading your data to Microsoft Azure every minute.")
: lf("Upload your data to Microsoft Azure to analyze it.")) + "\n
"
}).done();
};
return LogView;
}(React.Component));
exports.LogView = LogView;
},{"./core":10,"react":264,"react-dom":135}],22:[function(require,module,exports){
"use strict";
var U = pxt.Util;
var projects = {};
var target = "";
function getHeaders() {
return Util.values(projects).map(function (p) { return p.header; });
}
function getHeader(id) {
var p = projects[id];
return p ? p.header : undefined;
}
function getTextAsync(id) {
var p = projects[id];
return Promise.resolve(p ? p.text : undefined);
}
function initAsync(trg) {
target = target;
return Promise.resolve();
}
function saveAsync(h, text) {
projects[h.id] = {
header: h,
text: text
};
return Promise.resolve();
}
function installAsync(h0, text) {
var h = h0;
h.id = U.guidGen();
h.recentUse = U.nowSeconds();
h.modificationTime = h.recentUse;
h.target = pxt.appTarget.id;
return saveAsync(h, text).then(function () { return h; });
}
function saveToCloudAsync(h) {
return Promise.resolve();
}
function syncAsync() {
return Promise.resolve();
}
function resetAsync() {
projects = {};
target = "";
return Promise.resolve();
}
exports.provider = {
getHeaders: getHeaders,
getHeader: getHeader,
getTextAsync: getTextAsync,
initAsync: initAsync,
saveAsync: saveAsync,
installAsync: installAsync,
saveToCloudAsync: saveToCloudAsync,
syncAsync: syncAsync,
resetAsync: resetAsync
};
},{}],23:[function(require,module,exports){
///
///
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var pkg = require("./package");
var core = require("./core");
var srceditor = require("./srceditor");
var compiler = require("./compiler");
var Util = pxt.Util;
var lf = Util.lf;
var MIN_EDITOR_FONT_SIZE = 10;
var MAX_EDITOR_FONT_SIZE = 40;
var FileType;
(function (FileType) {
FileType[FileType["Unknown"] = 0] = "Unknown";
FileType[FileType["TypeScript"] = 1] = "TypeScript";
FileType[FileType["Markdown"] = 2] = "Markdown";
})(FileType || (FileType = {}));
var Editor = (function (_super) {
__extends(Editor, _super);
function Editor() {
_super.apply(this, arguments);
this.fileType = FileType.Unknown;
this.highlightDecorations = [];
}
Editor.prototype.hasBlocks = function () {
if (!this.currFile)
return true;
var blockFile = this.currFile.getVirtualFileName();
return (blockFile && pkg.mainEditorPkg().files[blockFile] != null);
};
Editor.prototype.openBlocks = function () {
var _this = this;
pxt.tickEvent("typescript.showBlocks");
var header = this.parent.state.header;
if (header) {
header.editor = pxt.BLOCKS_PROJECT_NAME;
header.pubCurrent = false;
}
var promise = Promise.resolve().then(function () {
if (!_this.hasBlocks())
return;
var blockFile = _this.currFile.getVirtualFileName();
if (!blockFile) {
var mainPkg_1 = pkg.mainEditorPkg();
if (!mainPkg_1 || !mainPkg_1.files["main.blocks"]) {
if (mainPkg_1) {
_this.parent.setFile(mainPkg_1.files["main.ts"]);
}
return;
}
_this.currFile = mainPkg_1.files["main.ts"];
blockFile = _this.currFile.getVirtualFileName();
}
var failedAsync = function (file) {
core.cancelAsyncLoading();
_this.forceDiagnosticsUpdate();
return _this.showConversionFailedDialog(file);
};
// might be undefined
var mainPkg = pkg.mainEditorPkg();
var xml;
// it's a bit for a wild round trip:
// 1) convert blocks to js to see if any changes happened, otherwise, just reload blocks
// 2) decompile js -> blocks then take the decompiled blocks -> js
// 3) check that decompiled js == current js % white space
var blocksInfo;
return _this.parent.saveFileAsync()
.then(function () { return compiler.getBlocksAsync(); })
.then(function (bi) {
blocksInfo = bi;
pxt.blocks.initBlocks(blocksInfo);
var oldWorkspace = pxt.blocks.loadWorkspaceXml(mainPkg.files[blockFile].content);
if (oldWorkspace) {
var oldJs = pxt.blocks.compile(oldWorkspace, blocksInfo).source;
if (pxtc.format(oldJs, 0).formatted == pxtc.format(_this.editor.getValue(), 0).formatted) {
pxt.debug('js not changed, skipping decompile');
pxt.tickEvent("typescript.noChanges");
return _this.parent.setFile(mainPkg.files[blockFile]);
}
}
return compiler.decompileAsync(_this.currFile.name, blocksInfo, oldWorkspace, blockFile)
.then(function (resp) {
if (!resp.success) {
_this.currFile.diagnostics = resp.diagnostics;
return failedAsync(blockFile);
}
xml = resp.outfiles[blockFile];
Util.assert(!!xml);
return mainPkg.setContentAsync(blockFile, xml)
.then(function () { return _this.parent.setFile(mainPkg.files[blockFile]); });
});
}).catch(function (e) {
pxt.reportException(e);
core.errorNotification(lf("Oops, something went wrong trying to convert your code."));
});
});
core.showLoadingAsync(lf("switching to blocks..."), promise).done();
};
Editor.prototype.showConversionFailedDialog = function (blockFile) {
var _this = this;
var bf = pkg.mainEditorPkg().files[blockFile];
return core.confirmAsync({
header: lf("Oops, there is a problem converting your code."),
body: lf("We are unable to convert your JavaScript code back to blocks. You can keep working in JavaScript or discard your changes and go back to the previous Blocks version."),
agreeLbl: lf("Discard and go to Blocks"),
agreeClass: "cancel",
agreeIcon: "cancel",
disagreeLbl: lf("Stay in JavaScript"),
disagreeClass: "positive",
disagreeIcon: "checkmark",
size: "medium",
hideCancel: !bf
}).then(function (b) {
// discard
if (!b) {
pxt.tickEvent("typescript.keepText");
}
else {
pxt.tickEvent("typescript.discardText");
_this.overrideFile(_this.parent.saveBlocksToTypeScript());
_this.parent.setFile(bf);
}
});
};
Editor.prototype.decompileAsync = function (blockFile) {
return compiler.decompileAsync(blockFile)
.then(function (resp) { return resp.success; });
};
Editor.prototype.display = function () {
return (React.createElement("div", {className: 'full-abs', id: "monacoEditorArea"}, React.createElement("div", {id: 'monacoEditorToolbox', className: 'injectionDiv'}), React.createElement("div", {id: 'monacoEditorInner'})));
};
Editor.prototype.defineEditorTheme = function () {
var inverted = pxt.appTarget.appTheme.invertedMonaco;
var invertedColorluminosityMultipler = 0.6;
var fnDict = this.definitions;
var rules = [];
Object.keys(fnDict).forEach(function (ns) {
var element = fnDict[ns];
if (element.metaData && element.metaData.color && element.fns) {
var hexcolor_1 = pxt.blocks.convertColour(element.metaData.color);
hexcolor_1 = (inverted ? Blockly.PXTUtils.fadeColour(hexcolor_1, invertedColorluminosityMultipler, true) : hexcolor_1).replace('#', '');
Object.keys(element.fns).forEach(function (fn) {
rules.push({ token: "identifier.ts " + fn, foreground: hexcolor_1 });
});
rules.push({ token: "identifier.ts " + ns, foreground: hexcolor_1 });
}
});
rules.push({ token: "identifier.ts if", foreground: '5B80A5', });
rules.push({ token: "identifier.ts else", foreground: '5B80A5', });
rules.push({ token: "identifier.ts while", foreground: '5BA55B', });
rules.push({ token: "identifier.ts for", foreground: '5BA55B', });
monaco.editor.defineTheme('pxtTheme', {
base: inverted ? 'vs-dark' : 'vs',
inherit: true,
rules: rules
});
this.editor.updateOptions({ theme: 'pxtTheme' });
};
Editor.prototype.beforeCompile = function () {
if (this.editor)
this.formatCode();
};
Editor.prototype.formatCode = function (isAutomatic) {
if (isAutomatic === void 0) { isAutomatic = false; }
Util.assert(this.editor != undefined); // Guarded
if (this.fileType != FileType.TypeScript)
return;
function spliceStr(big, idx, deleteCount, injection) {
if (injection === void 0) { injection = ""; }
return big.slice(0, idx) + injection + big.slice(idx + deleteCount);
}
var position = this.editor.getPosition();
var data = this.textAndPosition(position);
var cursorOverride = this.editor.getModel().getOffsetAt(position);
if (cursorOverride >= 0) {
isAutomatic = false;
data.charNo = cursorOverride;
}
var tmp = pxtc.format(data.programText, data.charNo);
if (isAutomatic && tmp.formatted == data.programText)
return;
var formatted = tmp.formatted;
var line = 1;
var col = 0;
//console.log(data.charNo, tmp.pos)
for (var i = 0; i < formatted.length; ++i) {
var c = formatted.charCodeAt(i);
col++;
if (i >= tmp.pos)
break;
if (c == 10) {
line++;
col = 0;
}
}
this.editor.setValue(formatted);
this.editor.setScrollPosition(line);
this.editor.setPosition(position);
return formatted;
};
Editor.prototype.textAndPosition = function (pos) {
var programText = this.editor.getValue();
var lines = pos.lineNumber;
var chars = pos.column;
var charNo = 0;
for (; charNo < programText.length; ++charNo) {
if (lines == 0) {
if (chars-- == 0)
break;
}
else if (programText[charNo] == '\n')
lines--;
}
return { programText: programText, charNo: charNo };
};
Editor.prototype.isIncomplete = function () {
return this.editor && this.editor._view ?
this.editor._view.contentWidgets._widgets["editor.widget.suggestWidget"].isVisible :
false;
};
Editor.prototype.resize = function (e) {
var monacoArea = document.getElementById('monacoEditorArea');
var monacoToolbox = document.getElementById('monacoEditorToolbox');
if (monacoArea && monacoToolbox && this.editor)
this.editor.layout({ width: monacoArea.offsetWidth - monacoToolbox.offsetWidth - 1, height: monacoArea.offsetHeight });
};
Editor.prototype.prepare = function () {
this.isReady = true;
};
Editor.prototype.loadMonacoAsync = function () {
var _this = this;
if (this.editor || this.loadingMonaco)
return Promise.resolve();
this.loadingMonaco = true;
this.extraLibs = Object.create(null);
var editorArea = document.getElementById("monacoEditorArea");
var editorElement = document.getElementById("monacoEditorInner");
return pxt.vs.initMonacoAsync(editorElement).then(function (editor) {
_this.editor = editor;
_this.loadingMonaco = false;
_this.editor.updateOptions({ fontSize: _this.parent.settings.editorFontSize });
_this.editor.getActions().filter(function (action) { return action.id == "editor.action.formatDocument"; })[0]
.run = function () { return Promise.resolve(_this.beforeCompile()); };
_this.editor.addAction({
id: "save",
label: lf("Save"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S],
keybindingContext: "!editorReadonly",
precondition: "!editorReadonly",
contextMenuGroupId: "0_pxtnavigation",
contextMenuOrder: 0.2,
run: function () { return Promise.resolve(_this.parent.typecheckNow()); }
});
_this.editor.addAction({
id: "runSimulator",
label: lf("Run Simulator"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],
keybindingContext: "!editorReadonly",
precondition: "!editorReadonly",
contextMenuGroupId: "0_pxtnavigation",
contextMenuOrder: 0.21,
run: function () { return Promise.resolve(_this.parent.runSimulator()); }
});
if (pxt.appTarget.compile && pxt.appTarget.compile.hasHex) {
_this.editor.addAction({
id: "compileHex",
label: lf("Download"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Alt | monaco.KeyCode.Enter],
keybindingContext: "!editorReadonly",
precondition: "!editorReadonly",
contextMenuGroupId: "0_pxtnavigation",
contextMenuOrder: 0.22,
run: function () { return Promise.resolve(_this.parent.compile()); }
});
}
_this.editor.addAction({
id: "zoomIn",
label: lf("Zoom In"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.NUMPAD_ADD, monaco.KeyMod.CtrlCmd | monaco.KeyCode.US_EQUAL],
run: function () { return Promise.resolve(_this.zoomIn()); }
});
_this.editor.addAction({
id: "zoomOut",
label: lf("Zoom Out"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.NUMPAD_SUBTRACT, monaco.KeyMod.CtrlCmd | monaco.KeyCode.US_MINUS],
run: function () { return Promise.resolve(_this.zoomOut()); }
});
_this.editor.onDidBlurEditorText(function () {
if (_this.isIncomplete()) {
monaco.languages.typescript.typescriptDefaults._diagnosticsOptions = ({ noSyntaxValidation: true, noSemanticValidation: true });
}
else {
monaco.languages.typescript.typescriptDefaults._diagnosticsOptions = ({ noSyntaxValidation: false, noSemanticValidation: false });
}
});
if (pxt.appTarget.appTheme.hasReferenceDocs) {
var referenceContextKey_1 = _this.editor.createContextKey("editorHasReference", false);
_this.editor.addAction({
id: "reference",
label: lf("Help"),
keybindingContext: "!editorReadonly && editorHasReference",
precondition: "!editorReadonly && editorHasReference",
contextMenuGroupId: "navigation",
contextMenuOrder: 0.1,
run: function () { return Promise.resolve(_this.loadReference()); }
});
_this.editor.onDidChangeCursorPosition(function (e) {
var word = _this.editor.getModel().getWordUntilPosition(e.position);
if (word && word.word != "") {
referenceContextKey_1.set(true);
}
else {
referenceContextKey_1.reset();
}
});
}
_this.editor.onDidLayoutChange(function (e) {
// Update editor font size in settings after a ctrl+scroll zoom
var currentFont = _this.editor.getConfiguration().fontInfo.fontSize;
if (_this.parent.settings.editorFontSize != currentFont) {
_this.parent.settings.editorFontSize = currentFont;
_this.forceDiagnosticsUpdate();
}
// Update widgets
var toolbox = document.getElementById('monacoEditorToolbox');
toolbox.style.height = _this.editor.getLayoutInfo().contentHeight + "px";
var flyout = document.getElementById('monacoFlyoutWidget');
flyout.style.height = _this.editor.getLayoutInfo().contentHeight + "px";
});
var monacoEditorInner = document.getElementById('monacoEditorInner');
monacoEditorInner.ondragenter = (function (ev) {
ev.preventDefault();
ev.stopPropagation();
});
monacoEditorInner.ondragover = (function (ev) {
ev.preventDefault();
ev.stopPropagation();
var mouseTarget = _this.editor.getTargetAtClientPoint(ev.clientX, ev.clientY);
var position = mouseTarget.position;
if (position && _this.editor.getPosition() != position)
_this.editor.setPosition(position);
_this.editor.focus();
});
monacoEditorInner.ondrop = (function (ev) {
var insertText = ev.dataTransfer.getData('text'); // IE11 only support "text"
if (!insertText)
return;
ev.preventDefault();
ev.stopPropagation();
var mouseTarget = _this.editor.getTargetAtClientPoint(ev.clientX, ev.clientY);
var position = mouseTarget.position;
var model = _this.editor.getModel();
var currPos = _this.editor.getPosition();
var cursor = model.getOffsetAt(currPos);
if (!position)
position = currPos;
insertText = (currPos.column > 1) ? '\n' + insertText :
model.getWordUntilPosition(currPos) != undefined && model.getWordUntilPosition(currPos).word != '' ?
insertText + '\n' : insertText;
if (insertText.indexOf('{{}}') > -1) {
cursor += (insertText.indexOf('{{}}'));
insertText = insertText.replace('{{}}', '');
}
else
cursor += (insertText.length);
_this.editor.pushUndoStop();
_this.editor.executeEdits("", [
{
identifier: { major: 0, minor: 0 },
range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column),
text: insertText,
forceMoveMarkers: false
}
]);
_this.editor.pushUndoStop();
var endPos = model.getPositionAt(cursor);
_this.editor.setPosition(endPos);
_this.editor.focus();
});
_this.editor.onDidFocusEditorText(function () {
_this.resetFlyout(true);
});
_this.editorViewZones = [];
_this.setupToolbox(editorArea);
});
};
Editor.prototype.undo = function () {
if (!this.editor)
return;
this.editor.trigger('keyboard', monaco.editor.Handler.Undo, null);
};
Editor.prototype.redo = function () {
if (!this.editor)
return;
this.editor.trigger('keyboard', monaco.editor.Handler.Redo, null);
};
Editor.prototype.zoomIn = function () {
if (!this.editor)
return;
if (this.parent.settings.editorFontSize >= MAX_EDITOR_FONT_SIZE)
return;
var currentFont = this.editor.getConfiguration().fontInfo.fontSize;
this.parent.settings.editorFontSize = currentFont + 1;
this.editor.updateOptions({ fontSize: this.parent.settings.editorFontSize });
this.forceDiagnosticsUpdate();
};
Editor.prototype.zoomOut = function () {
if (!this.editor)
return;
if (this.parent.settings.editorFontSize <= MIN_EDITOR_FONT_SIZE)
return;
var currentFont = this.editor.getConfiguration().fontInfo.fontSize;
this.parent.settings.editorFontSize = currentFont - 1;
this.editor.updateOptions({ fontSize: this.parent.settings.editorFontSize });
this.forceDiagnosticsUpdate();
};
Editor.prototype.loadReference = function () {
Util.assert(this.editor != undefined); // Guarded
var currentPosition = this.editor.getPosition();
var wordInfo = this.editor.getModel().getWordAtPosition(currentPosition);
if (!wordInfo)
return;
var prevWordInfo = this.editor.getModel().getWordUntilPosition(new monaco.Position(currentPosition.lineNumber, wordInfo.startColumn - 1));
if (prevWordInfo && wordInfo) {
var namespaceName = prevWordInfo.word.replace(/([A-Z]+)/g, "-$1");
var methodName = wordInfo.word.replace(/([A-Z]+)/g, "-$1");
this.parent.setSideDoc("/reference/" + namespaceName + "/" + methodName);
}
else if (wordInfo) {
var methodName = wordInfo.word.replace(/([A-Z]+)/g, "-$1");
this.parent.setSideDoc("/reference/" + methodName);
}
};
Editor.prototype.setupToolbox = function (editorElement) {
// Monaco flyout widget
var flyoutWidget = {
getId: function () {
return 'pxt.flyout.widget';
},
getDomNode: function () {
if (!this.domNode) {
this.domNode = document.createElement('div');
this.domNode.id = 'monacoFlyoutWidget';
this.domNode.style.top = "0";
this.domNode.className = 'monacoFlyout';
// Hide by default
this.domNode.style.display = 'none';
this.domNode.innerText = 'Flyout';
}
return this.domNode;
},
getPosition: function () {
return null;
}
};
this.editor.addOverlayWidget(flyoutWidget);
};
Editor.prototype.resetFlyout = function (clear) {
// Hide the flyout
var flyout = document.getElementById('monacoFlyoutWidget');
flyout.innerHTML = '';
flyout.style.display = 'none';
// Hide the currnet toolbox category
if (this.selectedCategoryRow) {
this.selectedCategoryRow.style.background = "" + this.selectedCategoryBackgroundColor;
this.selectedCategoryRow.style.color = "" + this.selectedCategoryColor;
this.selectedCategoryRow.className = 'blocklyTreeRow';
}
if (clear) {
this.selectedCategoryRow = null;
}
};
Editor.prototype.updateToolbox = function () {
var _this = this;
var appTheme = pxt.appTarget.appTheme;
if (!appTheme.monacoToolbox || pxt.shell.isReadOnly())
return;
// Toolbox div
var toolbox = document.getElementById('monacoEditorToolbox');
// Move the monaco editor to make room for the toolbox div
this.editor.getLayoutInfo().glyphMarginLeft = 200;
this.editor.layout();
var monacoEditor = this;
// clear the toolbox
toolbox.innerHTML = '';
// Add an overlay widget for the toolbox
toolbox.style.height = monacoEditor.editor.getLayoutInfo().contentHeight + "px";
var root = document.createElement('div');
root.className = 'blocklyTreeRoot';
toolbox.appendChild(root);
var group = document.createElement('div');
group.setAttribute('role', 'group');
root.appendChild(group);
var fnDef = this.definitions;
Object.keys(fnDef).sort(function (f1, f2) {
// sort by fn weight
var fn1 = fnDef[f1];
var fn2 = fnDef[f2];
var w2 = (fn2.metaData ? fn2.metaData.weight || 50 : 50)
+ (fn2.metaData && fn2.metaData.advanced ? 0 : 1000);
+(fn2.metaData && fn2.metaData.blockId ? 10000 : 0);
var w1 = (fn1.metaData ? fn1.metaData.weight || 50 : 50)
+ (fn1.metaData && fn1.metaData.advanced ? 0 : 1000);
+(fn1.metaData && fn1.metaData.blockId ? 10000 : 0);
return w2 - w1;
}).filter(function (ns) { return fnDef[ns].metaData != null && fnDef[ns].metaData.color != null; }).forEach(function (ns) {
var metaElement = fnDef[ns];
var fnElement = fnDef[ns];
monacoEditor.addToolboxCategory(group, ns, metaElement.metaData.color, metaElement.metaData.icon, true, fnElement.fns);
});
Editor.addBuiltinCategories(group, monacoEditor);
// Add the toolbox buttons
if (pxt.appTarget.cloud && pxt.appTarget.cloud.packages) {
this.addToolboxCategory(group, "", "#717171", "addpackage", false, null, function () {
_this.resetFlyout();
_this.parent.addPackage();
}, lf("{id:category}Add Package"));
}
// Inject toolbox icon css
pxt.blocks.injectToolboxIconCss();
};
Editor.addBuiltinCategories = function (group, monacoEditor) {
monacoEditor.addToolboxCategory(group, "", pxt.blocks.blockColors["logic"].toString(), "logic", false, {
"if": {
sig: "",
snippet: "if (true) {\n\n}",
comment: lf("Runs code if the condition is true"),
metaData: {
callingConvention: ts.pxtc.ir.CallingConvention.Plain,
paramDefl: {}
}
}, "if ": {
sig: "",
snippet: "if (true) {\n\n} else {\n\n}",
comment: lf("Runs code if the condition is true; else run other code"),
metaData: {
callingConvention: ts.pxtc.ir.CallingConvention.Plain,
paramDefl: {}
}
}, "switch": {
sig: "",
snippet: "switch(item) {\n case 0:\n break;\n case 1:\n break;\n}",
comment: lf("Runs different code based on a value"),
metaData: {
callingConvention: ts.pxtc.ir.CallingConvention.Plain,
paramDefl: {}
}
}
}, null, lf("{id:category}Logic"));
monacoEditor.addToolboxCategory(group, "", pxt.blocks.blockColors["loops"].toString(), "loops", false, {
"while": {
sig: "while(...)",
snippet: "while(true) {\n\n}",
comment: lf("Repeat code while condition is true"),
metaData: {
callingConvention: ts.pxtc.ir.CallingConvention.Plain,
paramDefl: {}
}
},
"for": {
sig: "",
snippet: "for(let i = 0; i < 5; i++) {\n\n}",
comment: lf("Repeat code a number of times in a loop"),
metaData: {
callingConvention: ts.pxtc.ir.CallingConvention.Plain,
paramDefl: {}
}
}
}, null, lf("{id:category}Loops"));
};
Editor.prototype.addToolboxCategory = function (group, ns, metaColor, icon, injectIconClass, fns, onClick, category) {
if (injectIconClass === void 0) { injectIconClass = true; }
var appTheme = pxt.appTarget.appTheme;
var monacoEditor = this;
// Create a tree item
var treeitem = document.createElement('div');
var treerow = document.createElement('div');
treeitem.setAttribute('role', 'treeitem');
var color = pxt.blocks.convertColour(metaColor);
treeitem.onclick = function (ev) {
pxt.tickEvent("monaco.toolbox.click");
var monacoFlyout = document.getElementById('monacoFlyoutWidget');
monacoEditor.resetFlyout(false);
// Hide the toolbox if the current category is clicked twice
if (monacoEditor.selectedCategoryRow == treerow) {
monacoEditor.selectedCategoryRow = null;
monacoFlyout.style.display = 'none';
treerow.className = 'blocklyTreeRow';
return;
}
else {
// Selected category
treerow.style.background = appTheme.invertedToolbox ?
"" + Blockly.PXTUtils.fadeColour(color, Blockly.Options.invertedMultiplier, false) :
"" + color;
treerow.style.color = '#fff';
treerow.className += ' blocklyTreeSelected';
monacoEditor.selectedCategoryRow = treerow;
if (appTheme.invertedToolbox) {
// Inverted toolbox
monacoEditor.selectedCategoryColor = '#fff';
monacoEditor.selectedCategoryBackgroundColor = color;
}
else {
monacoEditor.selectedCategoryColor = color;
monacoEditor.selectedCategoryBackgroundColor = 'none';
}
}
monacoFlyout.style.left = monacoEditor.editor.getLayoutInfo().lineNumbersLeft + "px";
monacoFlyout.style.height = monacoEditor.editor.getLayoutInfo().contentHeight + "px";
monacoFlyout.style.display = 'block';
monacoFlyout.className = 'monacoFlyout';
monacoFlyout.style.transform = 'none';
if (onClick) {
// No flyout
onClick();
}
else {
// Create a flyout and add the category methods in there
Object.keys(fns).sort(function (f1, f2) {
// sort by fn weight
var fn1 = fns[f1];
var fn2 = fns[f2];
var w2 = (fn2.metaData ? fn2.metaData.weight || 50 : 50)
+ (fn2.metaData && fn2.metaData.advanced ? 0 : 1000);
+(fn2.metaData && fn2.metaData.blockId ? 10000 : 0);
var w1 = (fn1.metaData ? fn1.metaData.weight || 50 : 50)
+ (fn1.metaData && fn1.metaData.advanced ? 0 : 1000);
+(fn1.metaData && fn1.metaData.blockId ? 10000 : 0);
return w2 - w1;
}).forEach(function (fn) {
var monacoBlock = document.createElement('div');
monacoBlock.className = 'monacoDraggableBlock';
monacoBlock.style.fontSize = monacoEditor.parent.settings.editorFontSize + "px";
monacoBlock.style.backgroundColor = "" + color;
monacoBlock.style.borderColor = "" + color;
monacoBlock.draggable = true;
var elem = fns[fn];
var snippet = elem.snippet;
var comment = elem.comment;
var metaData = elem.metaData;
var methodToken = document.createElement('span');
methodToken.innerText = fn;
var sigToken = document.createElement('span');
sigToken.className = 'sig';
// completion is a bit busted but looks better
sigToken.innerText = snippet
.replace(/^[^(]*\(/, '(')
.replace(/^\s*\{\{\}\}\n/gm, '')
.replace(/\{\n\}/g, '{}')
.replace(/(?:\{\{)|(?:\}\})/g, '');
monacoBlock.title = comment;
monacoBlock.onclick = function (ev2) {
pxt.tickEvent("monaco.toolbox.itemclick");
monacoEditor.resetFlyout(true);
var model = monacoEditor.editor.getModel();
var currPos = monacoEditor.editor.getPosition();
var cursor = model.getOffsetAt(currPos);
var insertText = ns ? ns + "." + snippet : snippet;
insertText = (currPos.column > 1) ? '\n' + insertText :
model.getWordUntilPosition(currPos) != undefined && model.getWordUntilPosition(currPos).word != '' ?
insertText + '\n' : insertText;
if (insertText.indexOf('{{}}') > -1) {
cursor += (insertText.indexOf('{{}}'));
insertText = insertText.replace('{{}}', '');
}
else
cursor += (insertText.length);
insertText = insertText.replace(/(?:\{\{)|(?:\}\})/g, '');
monacoEditor.editor.pushUndoStop();
monacoEditor.editor.executeEdits("", [
{
identifier: { major: 0, minor: 0 },
range: new monaco.Range(currPos.lineNumber, currPos.column, currPos.lineNumber, currPos.column),
text: insertText,
forceMoveMarkers: false
}
]);
monacoEditor.editor.pushUndoStop();
var endPos = model.getPositionAt(cursor);
monacoEditor.editor.setPosition(endPos);
monacoEditor.editor.focus();
//monacoEditor.editor.setSelection(new monaco.Range(currPos.lineNumber, currPos.column, endPos.lineNumber, endPos.column));
};
monacoBlock.ondragstart = function (ev2) {
pxt.tickEvent("monaco.toolbox.itemdrag");
var clone = monacoBlock.cloneNode(true);
setTimeout(function () {
monacoFlyout.style.transform = "translateX(-9999px)";
});
var insertText = ns ? ns + "." + snippet : snippet;
ev2.dataTransfer.setData('text', insertText); // IE11 only supports text
};
monacoBlock.ondragend = function (ev2) {
monacoFlyout.style.transform = "none";
monacoEditor.resetFlyout(true);
};
monacoBlock.appendChild(methodToken);
monacoBlock.appendChild(sigToken);
monacoFlyout.appendChild(monacoBlock);
});
}
};
group.appendChild(treeitem);
treerow.className = 'blocklyTreeRow';
treeitem.appendChild(treerow);
var iconBlank = document.createElement('span');
var iconNone = document.createElement('span');
var label = document.createElement('span');
var iconClass = ("blocklyTreeIcon" + (icon ? (ns || icon).toLowerCase() : 'Default')).replace(/\s/g, '');
iconBlank.className = 'blocklyTreeIcon';
iconBlank.setAttribute('role', 'presentation');
iconNone.className = "blocklyTreeIcon " + iconClass;
iconNone.setAttribute('role', 'presentation');
iconNone.style.display = 'inline-block';
label.className = 'blocklyTreeLabel';
treerow.appendChild(iconBlank);
treerow.appendChild(iconNone);
treerow.appendChild(label);
if (appTheme.coloredToolbox) {
// Colored toolbox
treerow.style.color = "" + color;
treerow.style.borderLeft = "8px solid " + color;
}
else if (appTheme.invertedToolbox) {
// Inverted toolbox
treerow.style.color = '#fff';
treerow.style.background = (color || '#ddd');
treerow.onmouseenter = function () {
if (treerow != monacoEditor.selectedCategoryRow) {
treerow.style.background = Blockly.PXTUtils.fadeColour(color || '#ddd', Blockly.Options.invertedMultiplier, false);
}
};
treerow.onmouseleave = function () {
if (treerow != monacoEditor.selectedCategoryRow) {
treerow.style.background = (color || '#ddd');
}
};
}
else {
// Standard toolbox
treerow.style.borderLeft = "8px solid " + color;
}
if (icon && injectIconClass) {
pxt.blocks.appendToolboxIconCss(iconClass, icon);
}
treerow.style.paddingLeft = '0px';
label.innerText = "" + Util.capitalize(category || ns);
};
Editor.prototype.getId = function () {
return "monacoEditor";
};
Editor.prototype.getViewState = function () {
return this.editor ? this.editor.getPosition() : {};
};
Editor.prototype.getCurrentSource = function () {
return this.editor ? this.editor.getValue() : this.currSource;
};
Editor.prototype.acceptsFile = function (file) {
return true;
};
Editor.prototype.setValue = function (v) {
this.editor.setValue(v);
};
Editor.prototype.overrideFile = function (content) {
Util.assert(this.editor != undefined); // Guarded
this.editor.setValue(content);
};
Editor.prototype.loadFileAsync = function (file) {
var _this = this;
var mode = "text";
this.currSource = file.content;
var loading = document.createElement("div");
loading.className = "ui inverted loading dimmer active";
var editorArea = document.getElementById("monacoEditorArea");
var editorDiv = document.getElementById("monacoEditorInner");
editorArea.insertBefore(loading, editorDiv);
return this.loadMonacoAsync()
.then(function () {
if (!_this.editor)
return;
var toolbox = document.getElementById('monacoEditorToolbox');
var ext = file.getExtension();
var modeMap = {
"cpp": "cpp",
"h": "cpp",
"json": "json",
"md": "text",
"ts": "typescript",
"js": "javascript",
"svg": "xml",
"blocks": "xml",
"asm": "asm"
};
if (modeMap.hasOwnProperty(ext))
mode = modeMap[ext];
var readOnly = file.isReadonly() || pxt.shell.isReadOnly();
_this.editor.updateOptions({ readOnly: readOnly });
var proto = "pkg:" + file.getName();
var model = monaco.editor.getModels().filter(function (model) { return model.uri.toString() == proto; })[0];
if (!model)
model = monaco.editor.createModel(pkg.mainPkg.readFile(file.getName()), mode, monaco.Uri.parse(proto));
if (model)
_this.editor.setModel(model);
if (mode == "typescript") {
toolbox.innerHTML = '';
_this.beginLoadToolbox(file);
}
// Set the current file
_this.currFile = file;
_this.setValue(file.content);
_this.setDiagnostics(file, _this.snapshotState());
_this.fileType = mode == "typescript" ? FileType.TypeScript : ext == "md" ? FileType.Markdown : FileType.Unknown;
if (_this.fileType == FileType.Markdown)
_this.parent.setSideMarkdown(file.content);
_this.currFile.setForceChangeCallback(function (from, to) {
if (from != to) {
pxt.debug("File changed (from " + from + ", to " + to + "). Reloading editor");
_this.loadFileAsync(_this.currFile);
}
});
if (!file.isReadonly()) {
model.onDidChangeContent(function (e) {
// Remove any Highlighted lines
if (_this.highlightDecorations)
_this.editor.deltaDecorations(_this.highlightDecorations, []);
// Remove any current error shown, as a change has been made.
var viewZones = _this.editorViewZones || [];
_this.editor.changeViewZones(function (changeAccessor) {
viewZones.forEach(function (id) {
changeAccessor.removeZone(id);
});
});
_this.editorViewZones = [];
if (!e.isRedoing && !e.isUndoing && !_this.editor.getValue()) {
_this.editor.setValue(" ");
}
_this.updateDiagnostics();
_this.changeCallback();
});
}
if (mode == "typescript" && !file.isReadonly()) {
toolbox.className = 'monacoToolboxDiv';
}
else {
toolbox.className = 'monacoToolboxDiv hide';
}
_this.resize();
_this.resetFlyout(true);
}).finally(function () {
editorArea.removeChild(loading);
});
};
Editor.prototype.beginLoadToolbox = function (file) {
var _this = this;
pxt.vs.syncModels(pkg.mainPkg, this.extraLibs, file.getName(), file.isReadonly())
.then(function (definitions) {
_this.definitions = definitions;
_this.defineEditorTheme();
_this.updateToolbox();
_this.resize();
});
};
Editor.prototype.unloadFileAsync = function () {
if (this.currFile && this.currFile.getName() == "this/" + pxt.CONFIG_NAME) {
// Reload the header if a change was made to the config file: pxt.json
return this.parent.reloadHeaderAsync();
}
return Promise.resolve();
};
Editor.prototype.snapshotState = function () {
return this.editor && this.editor.getModel() ? this.editor.getModel().getLinesContent() : null;
};
Editor.prototype.setViewState = function (pos) {
if (!this.editor)
return;
if (!pos || Object.keys(pos).length === 0)
return;
this.editor.setPosition(pos);
this.editor.setScrollPosition(pos);
};
Editor.prototype.setDiagnostics = function (file, snapshot) {
Util.assert(this.editor != undefined); // Guarded
Util.assert(this.currFile == file);
this.diagSnapshot = snapshot;
this.forceDiagnosticsUpdate();
};
Editor.prototype.updateDiagnostics = function () {
if (this.needsDiagUpdate())
this.forceDiagnosticsUpdate();
};
Editor.prototype.needsDiagUpdate = function () {
if (!this.annotationLines)
return false;
var lines = this.editor.getModel().getLinesContent();
for (var _i = 0, _a = this.annotationLines; _i < _a.length; _i++) {
var line = _a[_i];
if (this.diagSnapshot[line] !== lines[line])
return true;
}
return false;
};
Editor.prototype.forceDiagnosticsUpdate = function () {
if (this.fileType != FileType.TypeScript)
return;
var file = this.currFile;
var lines = this.editor.getModel().getLinesContent();
var fontSize = this.parent.settings.editorFontSize - 3;
var lineHeight = this.editor.getConfiguration().lineHeight;
var borderSize = lineHeight / 10;
var viewZones = this.editorViewZones || [];
this.annotationLines = [];
this.editor.changeViewZones(function (changeAccessor) {
viewZones.forEach(function (id) {
changeAccessor.removeZone(id);
});
});
this.editorViewZones = [];
this.errorLines = [];
if (file && file.diagnostics) {
var _loop_1 = function(d) {
if (this_1.errorLines.filter(function (lineNumber) { return lineNumber == d.line; }).length > 0 || this_1.errorLines.length > 0)
return "continue";
var viewZoneId = null;
this_1.editor.changeViewZones(function (changeAccessor) {
var wrapper = document.createElement('div');
wrapper.className = "zone-widget error-view-zone";
var container = document.createElement('div');
container.className = "zone-widget-container marker-widget";
container.setAttribute('role', 'tooltip');
container.style.setProperty("border", "solid " + borderSize + "px rgb(255, 90, 90)");
container.style.setProperty("border", "solid " + borderSize + "px rgb(255, 90, 90)");
container.style.setProperty("top", "" + lineHeight / 4);
var domNode = document.createElement('div');
domNode.className = "block descriptioncontainer";
domNode.style.setProperty("font-size", fontSize.toString() + "px");
domNode.style.setProperty("line-height", lineHeight.toString() + "px");
domNode.innerText = ts.flattenDiagnosticMessageText(d.messageText, "\n");
container.appendChild(domNode);
wrapper.appendChild(container);
viewZoneId = changeAccessor.addZone({
afterLineNumber: d.line + 1,
heightInLines: 1,
domNode: wrapper
});
});
this_1.editorViewZones.push(viewZoneId);
this_1.errorLines.push(d.line);
if (lines[d.line] === this_1.diagSnapshot[d.line]) {
this_1.annotationLines.push(d.line);
}
};
var this_1 = this;
for (var _i = 0, _a = file.diagnostics; _i < _a.length; _i++) {
var d = _a[_i];
var state_1 = _loop_1(d);
if (state_1 === "continue") continue;
}
}
};
Editor.prototype.highlightStatement = function (brk) {
if (!brk || !this.currFile || this.currFile.name != brk.fileName || !this.editor)
return;
var position = this.editor.getModel().getPositionAt(brk.start);
if (!position)
return;
this.highlightDecorations = this.editor.deltaDecorations(this.highlightDecorations, [
{
range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column + brk.length),
options: { inlineClassName: 'highlight-statement' }
},
]);
};
return Editor;
}(srceditor.Editor));
exports.Editor = Editor;
},{"./compiler":8,"./core":10,"./package":24,"./srceditor":31,"react":264}],24:[function(require,module,exports){
"use strict";
var workspace = require("./workspace");
var data = require("./data");
var core = require("./core");
var db = require("./db");
var Util = pxt.Util;
var lf = Util.lf;
var hostCache = new db.Table("hostcache");
var extWeight = {
"ts": 10,
"blocks": 20,
"json": 30,
"md": 40,
};
function setupAppTarget(trgbundle) {
//if (!trgbundle.appTheme) trgbundle.appTheme = {};
pxt.setAppTarget(trgbundle);
}
exports.setupAppTarget = setupAppTarget;
var File = (function () {
function File(epkg, name, content) {
this.epkg = epkg;
this.name = name;
this.content = content;
this.inSyncWithEditor = true;
this.inSyncWithDisk = true;
}
File.prototype.isReadonly = function () {
return !this.epkg.header;
};
File.prototype.getName = function () {
return this.epkg.getPkgId() + "/" + this.name;
};
File.prototype.getTypeScriptName = function () {
if (this.epkg.isTopLevel())
return this.name;
else
return "pxt_modules/" + this.epkg.getPkgId() + "/" + this.name;
};
File.prototype.getExtension = function () {
var m = /\.([^\.]+)$/.exec(this.name);
if (m)
return m[1];
return "";
};
File.prototype.getVirtualFileName = function () {
if (File.blocksFileNameRx.test(this.name))
return this.name.replace(File.blocksFileNameRx, '.ts');
if (File.tsFileNameRx.test(this.name))
return this.name.replace(File.tsFileNameRx, '.blocks');
return undefined;
};
File.prototype.weight = function () {
if (/^main\./.test(this.name))
return 5;
if (extWeight.hasOwnProperty(this.getExtension()))
return extWeight[this.getExtension()];
return 60;
};
File.prototype.markDirty = function () {
this.inSyncWithEditor = false;
this.updateStatus();
};
File.prototype.updateStatus = function () {
data.invalidate("open-meta:" + this.getName());
};
File.prototype.setContentAsync = function (newContent, force) {
var _this = this;
Util.assert(newContent !== undefined);
this.inSyncWithEditor = true;
if (newContent != this.content) {
var prevContent_1 = this.content;
this.inSyncWithDisk = false;
this.content = newContent;
this.updateStatus();
return this.epkg.saveFilesAsync()
.then(function () {
if (_this.content == newContent) {
_this.inSyncWithDisk = true;
_this.updateStatus();
}
if (force && _this.forceChangeCallback)
_this.forceChangeCallback(prevContent_1, newContent);
});
}
else {
this.updateStatus();
return Promise.resolve();
}
};
File.prototype.setForceChangeCallback = function (callback) {
this.forceChangeCallback = callback;
};
File.tsFileNameRx = /\.ts$/;
File.blocksFileNameRx = /\.blocks$/;
return File;
}());
exports.File = File;
var EditorPackage = (function () {
function EditorPackage(ksPkg, topPkg) {
this.ksPkg = ksPkg;
this.topPkg = topPkg;
this.files = {};
this.onupdate = function () { };
this.saveScheduled = false;
this.savingNow = 0;
if (ksPkg && ksPkg.verProtocol() == "workspace")
this.header = workspace.getHeader(ksPkg.verArgument());
}
EditorPackage.prototype.getTopHeader = function () {
return this.topPkg.header;
};
EditorPackage.prototype.makeTopLevel = function () {
this.topPkg = this;
this.outputPkg = new EditorPackage(null, this);
this.outputPkg.id = "built";
};
EditorPackage.prototype.updateConfigAsync = function (update) {
var cfgFile = this.files[pxt.CONFIG_NAME];
if (cfgFile) {
try {
var cfg = JSON.parse(cfgFile.content);
update(cfg);
return cfgFile.setContentAsync(JSON.stringify(cfg, null, 4) + "\n");
}
catch (e) { }
}
return null;
};
EditorPackage.prototype.updateDepAsync = function (pkgid) {
var _this = this;
var p = this.ksPkg.resolveDep(pkgid);
if (!p || p.verProtocol() != "github")
return Promise.resolve();
var parsed = pxt.github.parseRepoId(p.verArgument());
return pxt.packagesConfigAsync()
.then(function (config) { return pxt.github.latestVersionAsync(parsed.fullName, config); })
.then(function (tag) { parsed.tag = tag; })
.then(function () { return pxt.github.pkgConfigAsync(parsed.fullName, parsed.tag); })
.catch(core.handleNetworkError)
.then(function (cfg) { return _this.addDepAsync(cfg.name, pxt.github.stringifyRepo(parsed)); });
};
EditorPackage.prototype.removeDepAsync = function (pkgid) {
var _this = this;
return this.updateConfigAsync(function (cfg) { return delete cfg.dependencies[pkgid]; })
.then(function () { return _this.saveFilesAsync(true); });
};
EditorPackage.prototype.addDepAsync = function (pkgid, pkgversion) {
var _this = this;
return this.updateConfigAsync(function (cfg) { return cfg.dependencies[pkgid] = pkgversion; })
.then(function () { return _this.saveFilesAsync(true); });
};
EditorPackage.prototype.getKsPkg = function () {
return this.ksPkg;
};
EditorPackage.prototype.getPkgId = function () {
return this.ksPkg ? this.ksPkg.id : this.id;
};
EditorPackage.prototype.isTopLevel = function () {
return this.ksPkg && this.ksPkg.level == 0;
};
EditorPackage.prototype.setFile = function (n, v) {
var f = new File(this, n, v);
this.files[n] = f;
data.invalidate("open-meta:");
return f;
};
EditorPackage.prototype.removeFileAsync = function (n) {
delete this.files[n];
data.invalidate("open-meta:");
return this.updateConfigAsync(function (cfg) { return cfg.files = cfg.files.filter(function (f) { return f != n; }); });
};
EditorPackage.prototype.setContentAsync = function (n, v) {
var f = this.files[n];
if (!f)
f = this.setFile(n, v);
return f.setContentAsync(v);
};
EditorPackage.prototype.setFiles = function (files) {
var _this = this;
this.files = Util.mapMap(files, function (k, v) { return new File(_this, k, v); });
data.invalidate("open-meta:");
};
EditorPackage.prototype.updateStatus = function () {
data.invalidate("pkg-status:" + this.header.id);
};
EditorPackage.prototype.savePkgAsync = function () {
var _this = this;
if (this.header.blobCurrent)
return Promise.resolve();
this.savingNow++;
this.updateStatus();
return workspace.saveToCloudAsync(this.header)
.then(function () {
_this.savingNow--;
_this.updateStatus();
if (!_this.header.blobCurrent)
_this.scheduleSave();
});
};
EditorPackage.prototype.scheduleSave = function () {
var _this = this;
if (this.saveScheduled)
return;
this.saveScheduled = true;
setTimeout(function () {
_this.saveScheduled = false;
_this.savePkgAsync().done();
}, 5000);
};
EditorPackage.prototype.getAllFiles = function () {
return Util.mapMap(this.files, function (k, f) { return f.content; });
};
EditorPackage.prototype.saveFilesAsync = function (immediate) {
var _this = this;
if (!this.header)
return Promise.resolve();
var cfgFile = this.files[pxt.CONFIG_NAME];
if (cfgFile) {
try {
var cfg = JSON.parse(cfgFile.content);
this.header.name = cfg.name;
}
catch (e) {
}
}
return workspace.saveAsync(this.header, this.getAllFiles())
.then(function () { return immediate ? _this.savePkgAsync() : _this.scheduleSave(); });
};
EditorPackage.prototype.sortedFiles = function () {
var lst = Util.values(this.files);
lst.sort(function (a, b) { return a.weight() - b.weight() || Util.strcmp(a.name, b.name); });
return lst;
};
EditorPackage.prototype.forEachFile = function (cb) {
this.pkgAndDeps().forEach(function (p) {
Util.values(p.files).forEach(cb);
});
};
EditorPackage.prototype.getMainFile = function () {
return this.sortedFiles()[0];
};
EditorPackage.prototype.pkgAndDeps = function () {
if (this.topPkg != this)
return this.topPkg.pkgAndDeps();
return Util.values(this.ksPkg.deps).map(getEditorPkg).concat([this.outputPkg]);
};
EditorPackage.prototype.filterFiles = function (cond) {
return Util.concat(this.pkgAndDeps().map(function (e) { return Util.values(e.files).filter(cond); }));
};
EditorPackage.prototype.lookupFile = function (name) {
return this.filterFiles(function (f) { return f.getName() == name; })[0];
};
return EditorPackage;
}());
exports.EditorPackage = EditorPackage;
var Host = (function () {
function Host() {
}
Host.prototype.readFile = function (module, filename) {
var epkg = getEditorPkg(module);
var file = epkg.files[filename];
return file ? file.content : null;
};
Host.prototype.writeFile = function (module, filename, contents, force) {
if (filename == pxt.CONFIG_NAME || force) {
// only write config writes
var epkg = getEditorPkg(module);
var file = epkg.files[filename];
file.setContentAsync(contents, force).done();
return;
}
throw Util.oops("trying to write " + module + " / " + filename);
};
Host.prototype.getHexInfoAsync = function (extInfo) {
return pxt.hex.getHexInfoAsync(this, extInfo).catch(core.handleNetworkError);
};
Host.prototype.cacheStoreAsync = function (id, val) {
return hostCache.forceSetAsync({
id: id,
val: val
}).then(function () { }, function (e) {
pxt.tickEvent('cache.store.failed', { error: e.name });
pxt.log("cache store failed for " + id + ": " + e.name);
});
};
Host.prototype.cacheGetAsync = function (id) {
return hostCache.getAsync(id)
.then(function (v) { return v.val; }, function (e) { return null; });
};
Host.prototype.downloadPackageAsync = function (pkg) {
var proto = pkg.verProtocol();
var epkg = getEditorPkg(pkg);
if (proto == "pub") {
// make sure it sits in cache
return workspace.getPublishedScriptAsync(pkg.verArgument())
.then(function (files) { return epkg.setFiles(files); });
}
else if (proto == "github") {
return workspace.getPublishedScriptAsync(pkg.version())
.then(function (files) { return epkg.setFiles(files); });
}
else if (proto == "workspace") {
return workspace.getTextAsync(pkg.verArgument())
.then(function (scr) { return epkg.setFiles(scr); });
}
else if (proto == "file") {
var arg = pkg.verArgument();
if (arg[0] == ".")
arg = resolvePath(pkg.parent.verArgument() + "/" + arg);
return workspace.getTextAsync(arg)
.then(function (scr) { return epkg.setFiles(scr); });
}
else if (proto == "embed") {
epkg.setFiles(pxt.getEmbeddedScript(pkg.verArgument()));
return Promise.resolve();
}
else {
return Promise.reject("Cannot download " + pkg.version() + "; unknown protocol");
}
};
return Host;
}());
function resolvePath(p) {
return p.replace(/\/+/g, "/").replace(/[^\/]+\/\.\.\//g, "").replace(/\/\.\//g, "/");
}
var theHost = new Host();
exports.mainPkg = new pxt.MainPackage(theHost);
function getEditorPkg(p) {
var r = p._editorPkg;
if (r)
return r;
var top = null;
if (p != exports.mainPkg)
top = getEditorPkg(exports.mainPkg);
var newOne = new EditorPackage(p, top);
if (p == exports.mainPkg)
newOne.makeTopLevel();
p._editorPkg = newOne;
return newOne;
}
exports.getEditorPkg = getEditorPkg;
function mainEditorPkg() {
return getEditorPkg(exports.mainPkg);
}
exports.mainEditorPkg = mainEditorPkg;
function genFileName(extension) {
var sanitizedName = mainEditorPkg().header.name.replace(/[\\\/.?*^:<>|"\x00-\x1F ]/g, "-");
var fn = (pxt.appTarget.nickname || pxt.appTarget.id) + "-" + sanitizedName + extension;
return fn;
}
exports.genFileName = genFileName;
function allEditorPkgs() {
return getEditorPkg(exports.mainPkg).pkgAndDeps();
}
exports.allEditorPkgs = allEditorPkgs;
function notifySyncDone(updated) {
var newOnes = Util.values(exports.mainPkg.deps).filter(function (d) { return d.verProtocol() == "workspace" && updated.hasOwnProperty(d.verArgument()); });
if (newOnes.length > 0) {
getEditorPkg(exports.mainPkg).onupdate();
}
}
exports.notifySyncDone = notifySyncDone;
function loadPkgAsync(id) {
exports.mainPkg = new pxt.MainPackage(theHost);
exports.mainPkg._verspec = "workspace:" + id;
return theHost.downloadPackageAsync(exports.mainPkg)
.catch(core.handleNetworkError)
.then(function () { return theHost.readFile(exports.mainPkg, pxt.CONFIG_NAME); })
.then(function (str) {
if (!str)
return Promise.resolve();
return exports.mainPkg.installAllAsync()
.catch(function (e) {
core.errorNotification(lf("Cannot load package: {0}", e.message));
});
});
}
exports.loadPkgAsync = loadPkgAsync;
/*
open-meta:/ - readonly/saved/unsaved + number of errors
*/
data.mountVirtualApi("open-meta", {
getSync: function (p) {
p = data.stripProtocol(p);
var f = getEditorPkg(exports.mainPkg).lookupFile(p);
if (!f)
return {};
var fs = {
isReadonly: f.isReadonly(),
isSaved: f.inSyncWithEditor && f.inSyncWithDisk,
numErrors: f.numDiagnosticsOverride
};
if (fs.numErrors == null)
fs.numErrors = f.diagnostics ? f.diagnostics.length : 0;
return fs;
},
});
// pkg-status:
data.mountVirtualApi("pkg-status", {
getSync: function (p) {
p = data.stripProtocol(p);
var ep = allEditorPkgs().filter(function (pkg) { return pkg.header && pkg.header.id == p; })[0];
if (ep)
return ep.savingNow ? "saving" : "";
return "";
},
});
},{"./core":10,"./data":11,"./db":12,"./workspace":37}],25:[function(require,module,exports){
///
///
///
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var ReactDOM = require("react-dom");
var workspace = require("./workspace");
var data = require("./data");
var sui = require("./sui");
var pkg = require("./package");
var core = require("./core");
var codecard = require("./codecard");
var gallery = require("./gallery");
var ProjectsTab;
(function (ProjectsTab) {
ProjectsTab[ProjectsTab["MyStuff"] = 0] = "MyStuff";
ProjectsTab[ProjectsTab["Make"] = 1] = "Make";
ProjectsTab[ProjectsTab["Code"] = 2] = "Code";
})(ProjectsTab || (ProjectsTab = {}));
var Projects = (function (_super) {
__extends(Projects, _super);
function Projects(props) {
_super.call(this, props);
this.prevGhData = [];
this.prevUrlData = [];
this.prevMakes = [];
this.prevCodes = [];
this.state = {
visible: false,
tab: ProjectsTab.MyStuff
};
}
Projects.prototype.hide = function () {
this.setState({ visible: false });
};
Projects.prototype.showOpenProject = function () {
this.setState({ visible: true, tab: ProjectsTab.MyStuff });
};
Projects.prototype.fetchMakes = function () {
if (this.state.tab != ProjectsTab.Make)
return [];
var res = this.getData("gallery:" + encodeURIComponent(pxt.appTarget.appTheme.projectGallery));
if (res)
this.prevMakes = Util.concat(res.map(function (g) { return g.cards; }));
return this.prevMakes;
};
Projects.prototype.fetchCodes = function () {
if (this.state.tab != ProjectsTab.Code)
return [];
var res = this.getData("gallery:" + encodeURIComponent(pxt.appTarget.appTheme.exampleGallery));
if (res)
this.prevCodes = Util.concat(res.map(function (g) { return g.cards; }));
return this.prevCodes;
};
Projects.prototype.fetchUrlData = function () {
var scriptid = pxt.Cloud.parseScriptId(this.state.searchFor);
if (scriptid) {
var res = this.getData("cloud-search:" + scriptid);
if (res) {
if (res.statusCode !== 404) {
if (!this.prevUrlData)
this.prevUrlData = [res];
else
this.prevUrlData.push(res);
}
}
}
return this.prevUrlData;
};
Projects.prototype.fetchLocalData = function () {
var _this = this;
if (this.state.tab != ProjectsTab.MyStuff)
return [];
var headers = this.getData("header:*");
if (this.state.searchFor)
headers = headers.filter(function (hdr) { return hdr.name.toLowerCase().indexOf(_this.state.searchFor.toLowerCase()) > -1; });
return headers;
};
Projects.prototype.shouldComponentUpdate = function (nextProps, nextState, nextContext) {
return this.state.visible != nextState.visible
|| this.state.tab != nextState.tab
|| this.state.searchFor != nextState.searchFor;
};
Projects.prototype.numDaysOld = function (d1) {
var diff = Math.abs((Date.now() / 1000) - d1);
return Math.floor(diff / (60 * 60 * 24));
};
Projects.prototype.renderCore = function () {
var _this = this;
var _a = this.state, visible = _a.visible, tab = _a.tab;
var tabNames = [
lf("My Stuff"),
lf("Make"),
lf("Code")
];
var headers = this.fetchLocalData();
var urldata = this.fetchUrlData();
var makes = this.fetchMakes();
var codes = this.fetchCodes();
var chgHeader = function (hdr) {
pxt.tickEvent("projects.header");
_this.hide();
_this.props.parent.loadHeaderAsync(hdr);
};
var chgMake = function (scr) {
pxt.tickEvent("projects.gallery", { name: scr.name });
_this.hide();
_this.props.parent.newEmptyProject(scr.name.toLowerCase(), scr.url);
};
var chgCode = function (scr) {
pxt.tickEvent("projects.example", { name: scr.name });
_this.hide();
core.showLoading(lf("Loading..."));
gallery.loadExampleAsync(scr.name.toLowerCase(), scr.url)
.done(function (opts) {
core.hideLoading();
if (opts)
_this.props.parent.newProject(opts);
});
};
var upd = function (v) {
var str = ReactDOM.findDOMNode(_this.refs["searchInput"]).value;
_this.setState({ searchFor: str });
};
var kupd = function (ev) {
if (ev.keyCode == 13)
upd(ev);
};
var installScript = function (scr) {
_this.hide();
core.showLoading(lf("loading project..."));
workspace.installByIdAsync(scr.id)
.then(function (r) { return _this.props.parent.loadHeaderAsync(r); })
.done(function () { return core.hideLoading(); });
};
var importHex = function () {
pxt.tickEvent("projects.import");
_this.hide();
_this.props.parent.importFileDialog();
};
var importUrl = function () {
pxt.tickEvent("projects.importurl");
_this.hide();
_this.props.parent.importUrlDialog();
};
var newProject = function () {
pxt.tickEvent("projects.new");
_this.hide();
_this.props.parent.newProject();
};
var saveProject = function () {
pxt.tickEvent("projects.save");
_this.hide();
_this.props.parent.saveAndCompile();
};
var renameProject = function () {
pxt.tickEvent("projects.rename");
_this.hide();
_this.props.parent.setFile(pkg.mainEditorPkg().files[pxt.CONFIG_NAME]);
};
var isEmpty = function () {
if (_this.state.searchFor) {
if (headers.length > 0
|| urldata.length > 0)
return false;
return true;
}
return false;
};
var targetTheme = pxt.appTarget.appTheme;
var tabs = [ProjectsTab.MyStuff];
if (pxt.appTarget.appTheme.projectGallery)
tabs.push(ProjectsTab.Make);
if (pxt.appTarget.appTheme.exampleGallery)
tabs.push(ProjectsTab.Code);
var headersToday = headers.filter(function (h) { var days = _this.numDaysOld(h.modificationTime); return days == 0; });
var headersYesterday = headers.filter(function (h) { var days = _this.numDaysOld(h.modificationTime); return days == 1; });
var headersThisWeek = headers.filter(function (h) { var days = _this.numDaysOld(h.modificationTime); return days > 1 && days <= 7; });
var headersLastWeek = headers.filter(function (h) { var days = _this.numDaysOld(h.modificationTime); return days > 7 && days <= 14; });
var headersThisMonth = headers.filter(function (h) { var days = _this.numDaysOld(h.modificationTime); return days > 14 && days <= 30; });
var headersOlder = headers.filter(function (h) { var days = _this.numDaysOld(h.modificationTime); return days > 30; });
var headersGrouped = [
{ name: lf("Today"), headers: headersToday },
{ name: lf("Yesterday"), headers: headersYesterday },
{ name: lf("This Week"), headers: headersThisWeek },
{ name: lf("Last Week"), headers: headersLastWeek },
{ name: lf("This Month"), headers: headersThisMonth },
{ name: lf("Older"), headers: headersOlder },
];
var isLoading = (tab == ProjectsTab.Make && makes.length == 0) ||
(tab == ProjectsTab.Code && codes.length == 0);
var tabClasses = sui.cx([
isLoading ? 'loading' : '',
'ui segment bottom attached tab active tabsegment'
]);
return (React.createElement(sui.Modal, {open: visible, className: "projectsdialog", size: "fullscreen", closeIcon: true, onClose: function () { return _this.setState({ visible: false }); }, dimmer: true, closeOnDimmerClick: true, closeOnDocumentClick: true}, React.createElement(sui.Segment, {inverted: targetTheme.invertedMenu, attached: "top"}, React.createElement(sui.Menu, {inverted: targetTheme.invertedMenu, secondary: true}, tabs.map(function (t) {
return React.createElement(sui.MenuItem, {key: "tab" + t, active: tab == t, name: tabNames[t], onClick: function () { return _this.setState({ tab: t }); }});
}), React.createElement("div", {className: "right menu"}, React.createElement(sui.Button, {icon: 'close', class: "clear " + (targetTheme.invertedMenu ? 'inverted' : ''), onClick: function () { return _this.setState({ visible: false }); }})))), tab == ProjectsTab.MyStuff ? React.createElement("div", {className: tabClasses}, React.createElement("div", {className: "group"}, React.createElement("div", {className: "ui cards"}, React.createElement(codecard.CodeCardView, {key: 'newproject', icon: "file outline", iconColor: "primary", name: lf("New Project..."), description: lf("Creates a new empty project"), onClick: function () { return newProject(); }}), pxt.appTarget.compile ?
React.createElement(codecard.CodeCardView, {key: 'import', icon: "upload", iconColor: "secondary", name: lf("Import File..."), description: lf("Open files from your computer"), onClick: function () { return importHex(); }}) : undefined, pxt.appTarget.cloud && pxt.appTarget.cloud.sharing && pxt.appTarget.cloud.publishing && pxt.appTarget.cloud.importing ?
React.createElement(codecard.CodeCardView, {key: 'importurl', icon: "upload", iconColor: "secondary", name: lf("Import URL..."), description: lf("Open a shared project URL"), onClick: function () { return importUrl(); }}) : undefined)), headersGrouped.filter(function (g) { return g.headers.length != 0; }).map(function (headerGroup) {
return React.createElement("div", {key: 'localgroup' + headerGroup.name, className: "group"}, React.createElement("h3", {className: "ui dividing header disabled"}, headerGroup.name), React.createElement("div", {className: "ui cards"}, headerGroup.headers.map(function (scr) {
return React.createElement(codecard.CodeCardView, {key: 'local' + scr.id, name: scr.name, time: scr.recentUse, imageUrl: scr.icon, url: scr.pubId && scr.pubCurrent ? "/" + scr.pubId : "", onClick: function () { return chgHeader(scr); }});
})));
}), React.createElement("div", {className: "group"}, React.createElement("div", {className: "ui cards"}, urldata.map(function (scr) {
return React.createElement(codecard.CodeCardView, {name: scr.name, time: scr.time, header: '/' + scr.id, description: scr.description, key: 'cloud' + scr.id, onClick: function () { return installScript(scr); }, url: '/' + scr.id, color: "blue"});
})))) : undefined, tab == ProjectsTab.Make ? React.createElement("div", {className: tabClasses}, React.createElement("div", {className: "ui cards"}, makes.map(function (scr) { return React.createElement(codecard.CodeCardView, {key: 'make' + scr.name, name: scr.name, description: scr.description, url: scr.url, imageUrl: scr.imageUrl, onClick: function () { return chgMake(scr); }}); }))) : undefined, tab == ProjectsTab.Code ? React.createElement("div", {className: tabClasses}, React.createElement("div", {className: "ui cards"}, codes.map(function (scr) { return React.createElement(codecard.CodeCardView, {key: 'code' + scr.name, name: scr.name, description: scr.description, url: scr.url, imageUrl: scr.imageUrl, onClick: function () { return chgCode(scr); }}); }))) : undefined, isEmpty() ?
React.createElement("div", {className: "ui items"}, React.createElement("div", {className: "ui item"}, lf("We couldn't find any projects matching '{0}'", this.state.searchFor)))
: undefined));
};
return Projects;
}(data.Component));
exports.Projects = Projects;
},{"./codecard":7,"./core":10,"./data":11,"./gallery":18,"./package":24,"./sui":32,"./workspace":37,"react":264,"react-dom":135}],26:[function(require,module,exports){
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var pkg = require("./package");
var srceditor = require("./srceditor");
var sui = require("./sui");
var Util = pxt.Util;
var lf = Util.lf;
var Editor = (function (_super) {
__extends(Editor, _super);
function Editor() {
_super.apply(this, arguments);
this.config = {};
this.changeMade = false;
}
Editor.prototype.prepare = function () {
this.isReady = true;
};
Editor.prototype.getId = function () {
return "pxtJsonEditor";
};
Editor.prototype.display = function () {
var _this = this;
var c = this.config;
var save = function () {
_this.isSaving = true;
var f = pkg.mainEditorPkg().lookupFile("this/" + pxt.CONFIG_NAME);
f.setContentAsync(JSON.stringify(_this.config, null, 4) + "\n").then(function () {
pkg.mainPkg.config.name = c.name;
_this.parent.setState({ projectName: c.name });
_this.parent.forceUpdate();
Util.nextTick(_this.changeCallback);
_this.isSaving = false;
_this.changeMade = true;
});
};
var setFileName = function (v) {
c.name = v;
_this.parent.forceUpdate();
};
var deleteProject = function () {
_this.parent.removeProject();
};
var initCard = function () {
if (!c.card)
c.card = {};
};
var card = c.card || {};
var userConfigs = [];
pkg.allEditorPkgs().map(function (ep) { return ep.getKsPkg(); })
.filter(function (dep) { return !!dep && dep.isLoaded && !!dep.config && !!dep.config.yotta && !!dep.config.yotta.userConfigs; })
.forEach(function (dep) { return userConfigs = userConfigs.concat(dep.config.yotta.userConfigs); });
var isUserConfigActive = function (uc) {
var cfg = Util.jsonFlatten(_this.config.yotta ? _this.config.yotta.config : {});
var ucfg = Util.jsonFlatten(uc.config);
return !Object.keys(ucfg).some(function (k) { return ucfg[k] === null ? !!cfg[k] : cfg[k] !== ucfg[k]; });
};
var applyUserConfig = function (uc) {
var cfg = Util.jsonFlatten(_this.config.yotta ? _this.config.yotta.config : {});
var ucfg = Util.jsonFlatten(uc.config);
if (isUserConfigActive(uc)) {
Object.keys(ucfg).forEach(function (k) { return delete cfg[k]; });
}
else {
Object.keys(ucfg).forEach(function (k) { return cfg[k] = ucfg[k]; });
}
// update cfg
if (Object.keys(cfg).length) {
if (!_this.config.yotta)
_this.config.yotta = {};
Object.keys(cfg).filter(function (k) { return cfg[k] === null; }).forEach(function (k) { return delete cfg[k]; });
_this.config.yotta.config = Util.jsonUnFlatten(cfg);
}
else {
if (_this.config.yotta) {
delete _this.config.yotta.config;
if (!Object.keys(_this.config.yotta).length)
delete _this.config.yotta;
}
}
// trigger update
save();
};
return (React.createElement("div", {className: "ui content"}, React.createElement("div", {className: "ui segment form text", style: { backgroundColor: "white" }}, React.createElement(sui.Input, {label: lf("Name"), value: c.name, onChange: setFileName}), userConfigs.map(function (uc) {
return React.createElement(sui.Checkbox, {key: "userconfig-" + uc.description, inputLabel: uc.description, checked: isUserConfigActive(uc), onChange: function () { return applyUserConfig(uc); }});
}), React.createElement(sui.Field, null, React.createElement(sui.Button, {text: lf("Save"), class: "green " + (this.isSaving ? 'disabled' : ''), onClick: function () { return save(); }}), React.createElement(sui.Button, {text: lf("Edit Settings As text"), onClick: function () { return _this.editSettingsText(); }})))));
};
Editor.prototype.editSettingsText = function () {
this.changeMade = false;
this.parent.editText();
};
Editor.prototype.getCurrentSource = function () {
return JSON.stringify(this.config, null, 4) + "\n";
};
Editor.prototype.acceptsFile = function (file) {
if (file.name != pxt.CONFIG_NAME)
return false;
if (file.isReadonly()) {
// TODO add read-only support
return false;
}
try {
var cfg = JSON.parse(file.content);
// TODO validate?
return true;
}
catch (e) {
return false;
}
};
Editor.prototype.loadFileAsync = function (file) {
this.config = JSON.parse(file.content);
this.setDiagnostics(file, this.snapshotState());
this.changeMade = false;
return Promise.resolve();
};
Editor.prototype.unloadFileAsync = function () {
if (this.changeMade) {
return this.parent.reloadHeaderAsync();
}
return Promise.resolve();
};
return Editor;
}(srceditor.Editor));
exports.Editor = Editor;
},{"./package":24,"./srceditor":31,"./sui":32,"react":264}],27:[function(require,module,exports){
"use strict";
var workspace = require("./workspace");
var data = require("./data");
function loadImageAsync(data) {
var img = document.createElement("img");
return new Promise(function (resolve, reject) {
img.onload = function () { return resolve(img); };
img.onerror = function () { return resolve(undefined); };
img.src = data;
});
}
function renderIcon(img) {
var icon = null;
if (img && img.width > 0 && img.height > 0) {
var cvs = document.createElement("canvas");
cvs.width = 305;
cvs.height = 200;
var ox = 0;
var oy = 0;
var iw = 0;
var ih = 0;
if (img.height > img.width) {
ox = 0;
iw = img.width;
ih = iw / cvs.width * cvs.height;
oy = (img.height - ih) / 2;
}
else {
oy = 0;
ih = img.height;
iw = ih / cvs.height * cvs.width;
ox = (img.width - iw) / 2;
}
var ctx = cvs.getContext("2d");
ctx.drawImage(img, ox, oy, iw, ih, 0, 0, cvs.width, cvs.height);
icon = cvs.toDataURL('image/jpeg', 85);
}
return icon;
}
function saveAsync(header, screenshot) {
return loadImageAsync(screenshot)
.then(function (img) {
var icon = renderIcon(img);
return workspace.saveScreenshotAsync(header, screenshot, icon)
.then(function () {
data.invalidate("header:" + header.id);
data.invalidate("header:*");
});
});
}
exports.saveAsync = saveAsync;
},{"./data":11,"./workspace":37}],28:[function(require,module,exports){
///
///
///
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var ReactDOM = require("react-dom");
var data = require("./data");
var sui = require("./sui");
var pkg = require("./package");
var core = require("./core");
var codecard = require("./codecard");
var ScriptSearch = (function (_super) {
__extends(ScriptSearch, _super);
function ScriptSearch(props) {
_super.call(this, props);
this.prevGhData = [];
this.prevUrlData = [];
this.prevGalleries = [];
this.state = {
searchFor: '',
visible: false
};
}
ScriptSearch.prototype.hide = function () {
this.setState({ visible: false });
};
ScriptSearch.prototype.showAddPackages = function () {
this.setState({ visible: true, searchFor: '' });
};
ScriptSearch.prototype.fetchGhData = function () {
var cloud = pxt.appTarget.cloud || {};
if (!cloud.packages)
return [];
var searchFor = cloud.githubPackages ? this.state.searchFor : undefined;
var res = searchFor || cloud.preferredPackages
? this.getData("gh-search:" + (searchFor || cloud.preferredPackages.join('|')))
: null;
if (res)
this.prevGhData = res;
return this.prevGhData || [];
};
ScriptSearch.prototype.fetchBundled = function () {
if (!!this.state.searchFor)
return [];
var bundled = pxt.appTarget.bundledpkgs;
return Object.keys(bundled).filter(function (k) { return !/prj$/.test(k); })
.map(function (k) { return JSON.parse(bundled[k]["pxt.json"]); });
};
ScriptSearch.prototype.shouldComponentUpdate = function (nextProps, nextState, nextContext) {
return this.state.visible != nextState.visible
|| this.state.searchFor != nextState.searchFor;
};
ScriptSearch.prototype.renderCore = function () {
var _this = this;
var bundles = this.fetchBundled();
var ghdata = this.fetchGhData();
var chgHeader = function (hdr) {
pxt.tickEvent("projects.header");
_this.hide();
_this.props.parent.loadHeaderAsync(hdr);
};
var chgBundle = function (scr) {
pxt.tickEvent("packages.bundled", { name: scr.name });
_this.hide();
addDepIfNoConflict(scr, "*")
.done();
};
var chgGallery = function (scr) {
pxt.tickEvent("projects.gallery", { name: scr.name });
_this.hide();
_this.props.parent.newEmptyProject(scr.name.toLowerCase(), scr.url);
};
var upd = function (v) {
var str = ReactDOM.findDOMNode(_this.refs["searchInput"]).value;
_this.setState({ searchFor: str });
};
var kupd = function (ev) {
if (ev.keyCode == 13)
upd(ev);
};
var installGh = function (scr) {
pxt.tickEvent("packages.github");
_this.hide();
var p = pkg.mainEditorPkg();
core.showLoading(lf("downloading package..."));
pxt.packagesConfigAsync()
.then(function (config) { return pxt.github.latestVersionAsync(scr.fullName, config); })
.then(function (tag) { return pxt.github.pkgConfigAsync(scr.fullName, tag)
.then(function (cfg) { return addDepIfNoConflict(cfg, "github:" + scr.fullName + "#" + tag); }); })
.catch(core.handleNetworkError)
.finally(function () { return core.hideLoading(); });
};
var addDepIfNoConflict = function (config, version) {
return pkg.mainPkg.findConflictsAsync(config, version)
.then(function (conflicts) {
var inUse = conflicts.filter(function (c) { return pkg.mainPkg.isPackageInUse(c.pkg0.id); });
var addDependencyPromise = Promise.resolve(true);
if (inUse.length) {
addDependencyPromise = addDependencyPromise
.then(function () { return core.confirmAsync({
header: lf("Cannot add {0} package", config.name),
hideCancel: true,
agreeLbl: lf("Ok"),
body: lf("Remove all the blocks from the {0} package and try again.", inUse[0].pkg0.id)
}); })
.then(function () {
return false;
});
}
else if (conflicts.length) {
var body_1 = conflicts.length === 1 ?
// Single conflict: "Package a is..."
lf("Package {0} is incompatible with {1}. Remove {0} and add {1}?", conflicts[0].pkg0.id, config.name) :
// 2 conflicts: "Packages A and B are..."; 3+ conflicts: "Packages A, B, C and D are..."
lf("Packages {0} and {1} are incompatible with {2}. Remove them and add {2}?", conflicts.slice(0, -1).map(function (c) { return c.pkg0.id; }).join(","), conflicts.slice(-1)[0].pkg0.id, config.name);
addDependencyPromise = addDependencyPromise
.then(function () { return core.confirmAsync({
header: lf("Some packages will be removed"),
agreeLbl: lf("Remove package(s) and add {0}", config.name),
agreeClass: "pink",
body: body_1
}); })
.then(function (buttonPressed) {
if (buttonPressed !== 0) {
var p_1 = pkg.mainEditorPkg();
return Promise.all(conflicts.map(function (c) {
return p_1.removeDepAsync(c.pkg0.id);
}))
.then(function () { return true; });
}
return Promise.resolve(false);
});
}
return addDependencyPromise
.then(function (shouldAdd) {
if (shouldAdd) {
var p = pkg.mainEditorPkg();
return p.addDepAsync(config.name, version)
.then(function () { return _this.props.parent.reloadHeaderAsync(); });
}
return Promise.resolve();
});
});
};
var isEmpty = function () {
if (_this.state.searchFor) {
if (bundles.length > 0
|| ghdata.length > 0)
return false;
return true;
}
return false;
};
var headerText = lf("Add Package...");
return (React.createElement(sui.Modal, {open: this.state.visible, dimmer: true, header: headerText, className: "searchdialog", size: "large", onClose: function () { return _this.setState({ visible: false }); }, closeIcon: true, closeOnDimmerClick: true}, React.createElement("div", {className: "ui vertical segment"}, React.createElement("div", {className: "ui search"}, React.createElement("div", {className: "ui fluid action input", role: "search"}, React.createElement("input", {ref: "searchInput", type: "text", placeholder: lf("Search..."), onKeyUp: kupd}), React.createElement("button", {title: lf("Search"), className: "ui right icon button", onClick: upd}, React.createElement("i", {className: "search icon"})))), React.createElement("div", {className: "ui cards"}, bundles.map(function (scr) {
return React.createElement(codecard.CodeCardView, {key: 'bundled' + scr.name, name: scr.name, description: scr.description, url: "/" + scr.installedVersion, onClick: function () { return chgBundle(scr); }});
}), ghdata.filter(function (repo) { return repo.status == pxt.github.GitRepoStatus.Approved; }).map(function (scr) {
return React.createElement(codecard.CodeCardView, {name: scr.name.replace(/^pxt-/, ""), header: scr.fullName, description: scr.description, key: 'gh' + scr.fullName, onClick: function () { return installGh(scr); }, url: 'github:' + scr.fullName, color: "blue"});
}), ghdata.filter(function (repo) { return repo.status != pxt.github.GitRepoStatus.Approved; }).map(function (scr) {
return React.createElement(codecard.CodeCardView, {name: scr.name.replace(/^pxt-/, ""), header: scr.fullName, description: scr.description, key: 'gh' + scr.fullName, onClick: function () { return installGh(scr); }, url: 'github:' + scr.fullName, color: "red"});
})), isEmpty() ?
React.createElement("div", {className: "ui items"}, React.createElement("div", {className: "ui item"}, lf("We couldn't find any packages matching '{0}'", this.state.searchFor)))
: undefined)));
};
return ScriptSearch;
}(data.Component));
exports.ScriptSearch = ScriptSearch;
},{"./codecard":7,"./core":10,"./data":11,"./package":24,"./sui":32,"react":264,"react-dom":135}],29:[function(require,module,exports){
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var data = require("./data");
var sui = require("./sui");
var pkg = require("./package");
(function (ShareMode) {
ShareMode[ShareMode["Screenshot"] = 0] = "Screenshot";
ShareMode[ShareMode["Url"] = 1] = "Url";
ShareMode[ShareMode["Editor"] = 2] = "Editor";
ShareMode[ShareMode["Simulator"] = 3] = "Simulator";
ShareMode[ShareMode["Cli"] = 4] = "Cli";
})(exports.ShareMode || (exports.ShareMode = {}));
var ShareMode = exports.ShareMode;
var ShareEditor = (function (_super) {
__extends(ShareEditor, _super);
function ShareEditor(props) {
_super.call(this, props);
this.state = {
currentPubId: undefined,
pubCurrent: false,
visible: false,
advancedMenu: false
};
}
ShareEditor.prototype.hide = function () {
this.setState({ visible: false });
};
ShareEditor.prototype.show = function (header) {
this.setState({ visible: true, mode: ShareMode.Screenshot, pubCurrent: header.pubCurrent });
};
ShareEditor.prototype.shouldComponentUpdate = function (nextProps, nextState, nextContext) {
return this.state.visible != nextState.visible
|| this.state.advancedMenu != nextState.advancedMenu
|| this.state.mode != nextState.mode
|| this.state.pubCurrent != nextState.pubCurrent
|| this.state.screenshotId != nextState.screenshotId
|| this.state.currentPubId != nextState.currentPubId;
};
ShareEditor.prototype.renderCore = function () {
var _this = this;
var visible = this.state.visible;
var cloud = pxt.appTarget.cloud || {};
var embedding = !!cloud.embedding;
var header = this.props.parent.state.header;
var advancedMenu = !!this.state.advancedMenu;
var ready = false;
var mode = this.state.mode;
var url = '';
var embed = '';
var help = lf("Copy this HTML to your website or blog.");
if (header) {
var rootUrl = pxt.appTarget.appTheme.embedUrl;
if (!/\/$/.test(rootUrl))
rootUrl += '/';
var isBlocks = this.props.parent.getPreferredEditor() == pxt.BLOCKS_PROJECT_NAME;
var pubCurrent = header ? header.pubCurrent : false;
var currentPubId_1 = (header ? header.pubId : undefined) || this.state.currentPubId;
ready = (!!currentPubId_1 && header.pubCurrent);
if (ready) {
url = "" + rootUrl + header.pubId;
var editUrl = rootUrl + "#pub:" + currentPubId_1;
switch (mode) {
case ShareMode.Cli:
embed = "pxt target " + pxt.appTarget.id + "\npxt extract " + url;
help = lf("Run this command from a shell.");
break;
case ShareMode.Editor:
embed = pxt.docs.embedUrl(rootUrl, "pub", header.pubId);
break;
case ShareMode.Simulator:
var padding = '81.97%';
// TODO: parts aspect ratio
if (pxt.appTarget.simulator)
padding = (100 / pxt.appTarget.simulator.aspectRatio).toPrecision(4) + '%';
var runUrl = rootUrl + (pxt.webConfig.runUrl || "--run").replace(/^\//, '');
embed = pxt.docs.runUrl(runUrl, padding, header.pubId);
break;
case ShareMode.Url:
embed = editUrl;
break;
default:
if (isBlocks) {
// Render screenshot
if (this.state.screenshotId == currentPubId_1) {
if (this.state.screenshotUri)
embed = "";
else
embed = lf("Ooops, no screenshot available.");
}
else {
pxt.debug("rendering share-editor screenshot png");
embed = lf("rendering...");
pxt.blocks.layout.toPngAsync(this.props.parent.editor.editor)
.done(function (uri) { return _this.setState({ screenshotId: currentPubId_1, screenshotUri: uri }); });
}
}
else {
// Render javascript code
pxt.debug("rendering share-editor javascript markdown");
embed = lf("rendering...");
var main = pkg.getEditorPkg(pkg.mainPkg);
var file = main.getMainFile();
if (pkg.File.blocksFileNameRx.test(file.getName()) && file.getVirtualFileName())
file = main.lookupFile("this/" + file.getVirtualFileName()) || file;
if (pkg.File.tsFileNameRx.test(file.getName())) {
var fileContents = file.content;
var mdContent = pxt.docs.renderMarkdown("@body@", "```javascript\n" + fileContents + "\n```");
embed = "" + mdContent + "";
}
}
break;
}
}
}
var publish = function () {
pxt.tickEvent("menu.embed.publish");
_this.props.parent.anonymousPublishAsync().done(function () {
_this.setState({ pubCurrent: true });
});
_this.forceUpdate();
};
var formats = [{ mode: ShareMode.Screenshot, label: lf("Screenshot") },
{ mode: ShareMode.Editor, label: lf("Editor") },
{ mode: ShareMode.Simulator, label: lf("Simulator") },
{ mode: ShareMode.Cli, label: lf("Command line") }
];
var action = !ready ? lf("Publish project") : undefined;
var actionLoading = this.props.parent.state.publishing;
return (React.createElement(sui.Modal, {open: this.state.visible, className: "sharedialog", header: lf("Share Project"), size: "small", onClose: function () { return _this.setState({ visible: false }); }, dimmer: true, action: action, actionClick: publish, actionLoading: actionLoading, closeIcon: true, closeOnDimmerClick: true, closeOnDocumentClick: true}, React.createElement("div", {className: "ui form"}, action ?
React.createElement("p", null, lf("You need to publish your project to share it or embed it in other web pages.") +
lf("You acknowledge having consent to publish this project."))
: undefined, url && ready ? React.createElement("div", null, React.createElement("p", null, lf("Your project is ready! Use the address below to share your projects.")), React.createElement(sui.Input, {class: "mini", readOnly: true, lines: 1, value: url, copy: true}))
: undefined, ready ? React.createElement("div", null, React.createElement("div", {className: "ui divider"}), React.createElement(sui.Button, {class: "labeled", icon: "chevron " + (advancedMenu ? "down" : "right"), text: lf("Embed"), onClick: function () { return _this.setState({ advancedMenu: !advancedMenu }); }}), advancedMenu ?
React.createElement(sui.Menu, {pointing: true, secondary: true}, formats.map(function (f) {
return React.createElement(sui.MenuItem, {key: "tab" + f.label, active: mode == f.mode, name: f.label, onClick: function () { return _this.setState({ mode: f.mode }); }});
})) : undefined, advancedMenu ?
React.createElement(sui.Field, null, React.createElement(sui.Input, {class: "mini", readOnly: true, lines: 4, value: embed, copy: ready, disabled: !ready})) : null) : undefined)));
};
return ShareEditor;
}(data.Component));
exports.ShareEditor = ShareEditor;
},{"./data":11,"./package":24,"./sui":32,"react":264}],30:[function(require,module,exports){
///
///
"use strict";
var core = require("./core");
var U = pxt.U;
var nextFrameId = 0;
var themes = ["blue", "red", "green", "yellow"];
var config;
var lastCompileResult;
var $debugger;
function init(root, cfg) {
$(root).html("\n
\n
\n
\n
\n ");
$debugger = $('#debugger');
var options = {
revealElement: function (el) {
$(el).transition({
animation: pxt.appTarget.appTheme.simAnimationEnter || 'fly right in',
duration: '0.5s',
});
},
removeElement: function (el, completeHandler) {
if (pxt.appTarget.simulator.headless) {
$(el).addClass('simHeadless');
completeHandler();
}
else {
$(el).transition({
animation: pxt.appTarget.appTheme.simAnimationExit || 'fly right out',
duration: '0.5s',
onComplete: function () {
if (completeHandler)
completeHandler();
$(el).remove();
}
}).error(function () {
// Problem with animation, still complete
if (completeHandler)
completeHandler();
$(el).remove();
});
}
},
unhideElement: function (el) {
$(el).removeClass("simHeadless");
},
onDebuggerBreakpoint: function (brk) {
updateDebuggerButtons(brk);
var brkInfo = lastCompileResult.breakpoints[brk.breakpointId];
config.highlightStatement(brkInfo);
if (brk.exceptionMessage) {
core.errorNotification(lf("Program Error: {0}", brk.exceptionMessage));
}
},
onDebuggerWarning: function (wrn) {
for (var _i = 0, _a = wrn.breakpointIds; _i < _a.length; _i++) {
var id = _a[_i];
var brkInfo = lastCompileResult.breakpoints[id];
if (brkInfo) {
if (!U.startsWith("pxt_modules/", brkInfo.fileName)) {
config.highlightStatement(brkInfo);
break;
}
}
}
},
onDebuggerResume: function () {
config.highlightStatement(null);
updateDebuggerButtons();
},
onStateChanged: function (state) {
updateDebuggerButtons();
},
onSimulatorCommand: function (msg) {
switch (msg.command) {
case "restart":
cfg.restartSimulator();
break;
case "modal":
stop();
core.confirmAsync({
header: msg.header,
body: msg.body,
size: "large",
copyable: msg.copyable,
hideAgree: true,
disagreeLbl: lf("Close")
}).done();
break;
}
}
};
exports.driver = new pxsim.SimulatorDriver($('#simulators')[0], options);
config = cfg;
updateDebuggerButtons();
}
exports.init = init;
function setState(editor) {
if (config.editor != editor) {
config.editor = editor;
config.highlightStatement(null);
updateDebuggerButtons();
}
}
exports.setState = setState;
function makeDirty() {
pxsim.U.addClass(exports.driver.container, "sepia");
}
exports.makeDirty = makeDirty;
function isDirty() {
return /sepia/.test(exports.driver.container.className);
}
exports.isDirty = isDirty;
function run(pkg, debug, res, mute) {
pxsim.U.removeClass(exports.driver.container, "sepia");
var js = res.outfiles[pxtc.BINARY_JS];
var boardDefinition = pxt.appTarget.simulator.boardDefinition;
var parts = pxtc.computeUsedParts(res, true);
var fnArgs = res.usedArguments;
lastCompileResult = res;
var opts = {
boardDefinition: boardDefinition,
mute: mute,
parts: parts,
debug: debug,
fnArgs: fnArgs,
aspectRatio: parts.length ? pxt.appTarget.simulator.partsAspectRatio : pxt.appTarget.simulator.aspectRatio,
partDefinitions: pkg.computePartDefinitions(parts)
};
exports.driver.run(js, opts);
}
exports.run = run;
function mute(mute) {
exports.driver.mute(mute);
$debugger.empty();
}
exports.mute = mute;
function stop(unload) {
if (!exports.driver)
return;
pxsim.U.removeClass(exports.driver.container, "sepia");
exports.driver.stop(unload);
$debugger.empty();
}
exports.stop = stop;
function hide(completeHandler) {
if (!pxt.appTarget.simulator.headless) {
pxsim.U.addClass(exports.driver.container, "sepia");
}
exports.driver.hide(completeHandler);
$debugger.empty();
}
exports.hide = hide;
function unhide() {
exports.driver.unhide();
}
exports.unhide = unhide;
function proxy(message) {
if (!exports.driver)
return;
exports.driver.postMessage(message);
$debugger.empty();
}
exports.proxy = proxy;
function updateDebuggerButtons(brk) {
if (brk === void 0) { brk = null; }
function btn(icon, name, label, click) {
var b = $("");
if (icon)
b.addClass("icon").append("");
if (name)
b.append(Util.htmlEscape(name));
return b.click(click);
}
$debugger.empty();
if (!exports.driver.runOptions.debug)
return;
var advanced = config.editor == 'tsprj';
if (exports.driver.state == pxsim.SimulatorState.Paused) {
var $resume = btn("play", lf("Resume"), lf("Resume execution"), function () { return exports.driver.resume(pxsim.SimulatorDebuggerCommand.Resume); });
var $stepOver = btn("xicon stepover", lf("Step over"), lf("Step over next function call"), function () { return exports.driver.resume(pxsim.SimulatorDebuggerCommand.StepOver); });
var $stepInto = btn("xicon stepinto", lf("Step into"), lf("Step into next function call"), function () { return exports.driver.resume(pxsim.SimulatorDebuggerCommand.StepInto); });
$debugger.append($resume).append($stepOver);
if (advanced)
$debugger.append($stepInto);
}
else if (exports.driver.state == pxsim.SimulatorState.Running) {
var $pause = btn("pause", lf("Pause"), lf("Pause execution on the next instruction"), function () { return exports.driver.resume(pxsim.SimulatorDebuggerCommand.Pause); });
$debugger.append($pause);
}
if (!brk || !advanced)
return;
function vars(hd, frame) {
var frameView = $("
" + U.htmlEscape(hd) + "
");
for (var _i = 0, _a = Object.keys(frame); _i < _a.length; _i++) {
var k = _a[_i];
var v = frame[k];
var sv = "";
switch (typeof (v)) {
case "number":
sv = v + "";
break;
case "string":
sv = JSON.stringify(v);
break;
case "object":
if (v == null)
sv = "null";
else if (v.id !== undefined)
sv = "(object)";
else if (v.text)
sv = v.text;
else
sv = "(unknown)";
break;
default: U.oops();
}
var n = k.replace(/___\d+$/, "");
frameView.append("
" + U.htmlEscape(n) + ": " + U.htmlEscape(sv) + "
");
}
return frameView;
}
var dbgView = $("");
dbgView.append(vars(U.lf("globals"), brk.globals));
brk.stackframes.forEach(function (sf) {
var info = sf.funcInfo;
dbgView.append(vars(info.functionName, sf.locals));
});
$('#debugger').append(dbgView);
}
},{"./core":10}],31:[function(require,module,exports){
"use strict";
var React = require("react");
var Editor = (function () {
function Editor(parent) {
this.parent = parent;
this.isVisible = false;
this.changeCallback = function () { };
this.isReady = false;
}
Editor.prototype.setVisible = function (v) {
this.isVisible = v;
};
/*******************************
Methods called before loadFile
this.editor may be undefined
Always check that this.editor exists
*******************************/
Editor.prototype.acceptsFile = function (file) {
return false;
};
Editor.prototype.getViewState = function () {
return {};
};
Editor.prototype.getCurrentSource = function () {
return this.currSource;
};
Editor.prototype.getId = function () {
return "editor";
};
Editor.prototype.displayOuter = function () {
return (React.createElement("div", {className: 'full-abs', key: this.getId(), id: this.getId(), style: { display: this.isVisible ? "block" : "none" }}, this.display()));
};
Editor.prototype.display = function () {
return null;
};
Editor.prototype.beforeCompile = function () { };
Editor.prototype.prepare = function () {
this.isReady = true;
};
Editor.prototype.resize = function (e) { };
Editor.prototype.snapshotState = function () {
return null;
};
Editor.prototype.unloadFileAsync = function () { return Promise.resolve(); };
Editor.prototype.isIncomplete = function () {
return false;
};
Editor.prototype.hasUndo = function () { return true; };
Editor.prototype.hasRedo = function () { return true; };
Editor.prototype.undo = function () { };
Editor.prototype.redo = function () { };
Editor.prototype.zoomIn = function () { };
Editor.prototype.zoomOut = function () { };
/*******************************
loadFile
*******************************/
Editor.prototype.loadFileAsync = function (file) {
this.currSource = file.content;
this.setDiagnostics(file, this.snapshotState());
return Promise.resolve();
};
/*******************************
Methods called after loadFile
this.editor != undefined
*******************************/
Editor.prototype.domUpdate = function () { };
Editor.prototype.setDiagnostics = function (file, snapshot) { };
Editor.prototype.setViewState = function (view) { };
Editor.prototype.saveToTypeScript = function () {
return null;
};
Editor.prototype.highlightStatement = function (brk) { };
Editor.prototype.filterToolbox = function (blockSubset, showCategories, showToolboxButtons) {
if (showCategories === void 0) { showCategories = true; }
if (showToolboxButtons === void 0) { showToolboxButtons = true; }
return null;
};
return Editor;
}());
exports.Editor = Editor;
},{"react":264}],32:[function(require,module,exports){
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var ReactDOM = require("react-dom");
var data = require("./data");
function cx(classes) {
return classes.filter(function (c) { return c && c.length !== 0 && c.trim() != ''; }).join(' ');
}
exports.cx = cx;
function genericClassName(cls, props, ignoreIcon) {
if (ignoreIcon === void 0) { ignoreIcon = false; }
return cls + " " + (ignoreIcon ? '' : props.icon && props.text ? 'icon-and-text' : props.icon ? 'icon' : "") + " " + (props.class || "");
}
function genericContent(props) {
return [
props.icon ? (React.createElement("i", {key: 'iconkey', className: props.icon + " icon " + (props.text ? " icon-and-text " : "") + (props.iconClass ? " " + props.iconClass : '')})) : null,
props.text ? (React.createElement("span", {key: 'textkey', className: 'ui text' + (props.textClass ? ' ' + props.textClass : '')}, props.text)) : null,
];
}
var UiElement = (function (_super) {
__extends(UiElement, _super);
function UiElement() {
_super.apply(this, arguments);
}
UiElement.prototype.popup = function () {
if (this.props.popup) {
var ch_1 = this.child("");
ch_1.popup({
content: this.props.popup
});
if (!ch_1.data("hasPopupHide")) {
ch_1.data("hasPopupHide", "yes");
ch_1.on("click", function () {
ch_1.popup("hide");
});
}
}
};
UiElement.prototype.componentDidMount = function () {
this.popup();
};
UiElement.prototype.componentDidUpdate = function () {
this.popup();
};
return UiElement;
}(data.Component));
exports.UiElement = UiElement;
var DropdownMenuItem = (function (_super) {
__extends(DropdownMenuItem, _super);
function DropdownMenuItem() {
_super.apply(this, arguments);
}
DropdownMenuItem.prototype.componentDidMount = function () {
var _this = this;
this.popup();
this.child("").dropdown({
action: "hide",
fullTextSearch: true,
onChange: function (v) {
if (_this.props.onChange && v != _this.props.value) {
_this.props.onChange(v);
}
}
});
};
DropdownMenuItem.prototype.componentDidUpdate = function () {
this.child("").dropdown("refresh");
this.popup();
};
DropdownMenuItem.prototype.renderCore = function () {
return (React.createElement("div", {className: genericClassName("ui dropdown item", this.props), role: this.props.role, title: this.props.title}, genericContent(this.props), React.createElement("div", {className: "menu"}, this.props.children)));
};
return DropdownMenuItem;
}(UiElement));
exports.DropdownMenuItem = DropdownMenuItem;
var Item = (function (_super) {
__extends(Item, _super);
function Item() {
_super.apply(this, arguments);
}
Item.prototype.renderCore = function () {
return (React.createElement("div", {className: genericClassName("ui item link", this.props, true) + (" " + (this.props.active ? 'active' : '')), role: this.props.role, title: this.props.title, key: this.props.value, "data-value": this.props.value, onClick: this.props.onClick}, genericContent(this.props), this.props.children));
};
return Item;
}(data.Component));
exports.Item = Item;
var Button = (function (_super) {
__extends(Button, _super);
function Button() {
_super.apply(this, arguments);
}
Button.prototype.renderCore = function () {
return (React.createElement("button", {className: genericClassName("ui button", this.props) + " " + (this.props.disabled ? "disabled" : ""), role: this.props.role, title: this.props.title, onClick: this.props.onClick}, genericContent(this.props), this.props.children));
};
return Button;
}(UiElement));
exports.Button = Button;
var Popup = (function (_super) {
__extends(Popup, _super);
function Popup() {
_super.apply(this, arguments);
}
Popup.prototype.componentDidMount = function () {
this.child(".popup-button").popup({
position: "bottom right",
on: "click",
hoverable: true,
delay: {
show: 50,
hide: 1000
}
});
};
Popup.prototype.componentDidUpdate = function () {
this.child(".popup-button").popup('refresh');
};
Popup.prototype.renderCore = function () {
return (React.createElement("div", {role: this.props.role}, React.createElement("div", {className: genericClassName("ui button popup-button", this.props)}, genericContent(this.props)), React.createElement("div", {className: "ui popup transition hidden"}, this.props.children)));
};
return Popup;
}(data.Component));
exports.Popup = Popup;
var Field = (function (_super) {
__extends(Field, _super);
function Field() {
_super.apply(this, arguments);
}
Field.prototype.renderCore = function () {
return (React.createElement("div", {className: "field"}, this.props.label ? React.createElement("label", null, this.props.label) : null, this.props.children));
};
return Field;
}(data.Component));
exports.Field = Field;
var Input = (function (_super) {
__extends(Input, _super);
function Input() {
_super.apply(this, arguments);
}
Input.prototype.copy = function () {
var p = this.props;
var el = ReactDOM.findDOMNode(this);
if (!p.lines || p.lines == 1) {
var inp = el.getElementsByTagName("input")[0];
inp.select();
}
else {
var inp = el.getElementsByTagName("textarea")[0];
inp.select();
}
try {
var success = document.execCommand("copy");
pxt.debug('copy: ' + success);
}
catch (e) {
}
};
Input.prototype.renderCore = function () {
var _this = this;
var p = this.props;
var copyBtn = p.copy && document.queryCommandSupported('copy')
? React.createElement(Button, {class: "ui right labeled primary icon button", text: lf("Copy"), icon: "copy", onClick: function () { return _this.copy(); }})
: null;
return (React.createElement(Field, {label: p.label}, React.createElement("div", {className: "ui input" + (p.inputLabel ? " labelled" : "") + (p.copy ? " action fluid" : "") + (p.disabled ? " disabled" : "")}, p.inputLabel ? (React.createElement("div", {className: "ui label"}, p.inputLabel)) : "", !p.lines || p.lines == 1 ? React.createElement("input", {className: p.class || "", type: p.type || "text", placeholder: p.placeholder, value: p.value, readOnly: !!p.readOnly, onChange: function (v) { return p.onChange(v.target.value); }})
: React.createElement("textarea", {className: "ui input " + (p.class || "") + (p.inputLabel ? " labelled" : ""), rows: p.lines, placeholder: p.placeholder, value: p.value, readOnly: !!p.readOnly, onChange: function (v) { return p.onChange(v.target.value); }}), copyBtn)));
};
return Input;
}(data.Component));
exports.Input = Input;
var Checkbox = (function (_super) {
__extends(Checkbox, _super);
function Checkbox() {
_super.apply(this, arguments);
}
Checkbox.prototype.renderCore = function () {
var p = this.props;
return React.createElement(Field, {label: p.label}, React.createElement("div", {className: "ui toggle checkbox"}, React.createElement("input", {type: "checkbox", checked: p.checked, onChange: function (v) { return p.onChange(v.target.value); }}), p.inputLabel ? React.createElement("label", null, p.inputLabel) : undefined));
};
return Checkbox;
}(data.Component));
exports.Checkbox = Checkbox;
var Segment = (function (_super) {
__extends(Segment, _super);
function Segment() {
_super.apply(this, arguments);
}
Segment.prototype.renderCore = function () {
var _a = this.props, attached = _a.attached, basic = _a.basic, children = _a.children, circular = _a.circular, className = _a.className, clearing = _a.clearing, color = _a.color, compact = _a.compact, disabled = _a.disabled, floated = _a.floated, inverted = _a.inverted, loading = _a.loading, padded = _a.padded, piled = _a.piled, raised = _a.raised, secondary = _a.secondary, size = _a.size, stacked = _a.stacked, tertiary = _a.tertiary, textAlign = _a.textAlign, vertical = _a.vertical;
var classes = cx([
'ui',
color,
size,
basic ? 'basic' : '',
circular ? 'circular' : '',
clearing ? 'clearing' : '',
compact ? 'compact' : '',
disabled ? 'disabled' : '',
inverted ? 'inverted' : '',
loading ? 'loading' : '',
piled ? 'piled' : '',
raised ? 'raised' : '',
secondary ? 'secondary' : '',
stacked ? 'stacked' : '',
tertiary ? 'tertiary' : '',
vertical ? 'vertical' : '',
attached ? attached + " attached" : '',
padded ? padded + " padded" : '',
textAlign ? (textAlign == 'justified' ? 'justified' : textAlign + " aligned") : '',
floated ? floated + " floated" : '',
'segment',
className,
]);
return (React.createElement("div", {className: classes}, children));
};
return Segment;
}(data.Component));
exports.Segment = Segment;
var MenuItem = (function (_super) {
__extends(MenuItem, _super);
function MenuItem(props) {
var _this = this;
_super.call(this, props);
this.handleClick = function (e) {
var onClick = _this.props.onClick;
if (onClick)
onClick(e, _this.props);
};
}
MenuItem.prototype.renderCore = function () {
var _a = this.props, active = _a.active, children = _a.children, className = _a.className, color = _a.color, content = _a.content, fitted = _a.fitted, header = _a.header, icon = _a.icon, link = _a.link, name = _a.name, onClick = _a.onClick, position = _a.position;
var classes = cx([
color,
position,
active ? 'active' : '',
icon === true || icon && !(name || content) ? 'icon' : '',
header ? 'header' : '',
link || onClick ? 'link' : '',
fitted ? (fitted == true ? "" + fitted : "fitted " + fitted) : '',
'item',
className
]);
if (children) {
return React.createElement("div", {className: classes, onClick: this.handleClick}, children);
}
return (React.createElement("div", {className: classes, onClick: this.handleClick}, icon ? React.createElement("i", {className: "icon " + icon}) : undefined, content || name));
};
return MenuItem;
}(data.Component));
exports.MenuItem = MenuItem;
var Menu = (function (_super) {
__extends(Menu, _super);
function Menu(props) {
_super.call(this, props);
}
Menu.prototype.renderCore = function () {
var _a = this.props, attached = _a.attached, borderless = _a.borderless, children = _a.children, className = _a.className, color = _a.color, compact = _a.compact, fixed = _a.fixed, floated = _a.floated, fluid = _a.fluid, icon = _a.icon, inverted = _a.inverted, pagination = _a.pagination, pointing = _a.pointing, secondary = _a.secondary, size = _a.size, stackable = _a.stackable, tabular = _a.tabular, text = _a.text, vertical = _a.vertical;
var classes = cx([
'ui',
color,
size,
borderless ? 'borderless' : '',
compact ? 'compact' : '',
fluid ? 'fluid' : '',
inverted ? 'inverted' : '',
pagination ? 'pagination' : '',
pointing ? 'pointing' : '',
secondary ? 'secondary' : '',
stackable ? 'stackable' : '',
text ? 'text' : '',
vertical ? 'vertical' : '',
attached ? (attached == true ? 'attached' : attached + " attached ") : '',
floated ? (floated == true ? 'floated' : floated + " floated") : '',
icon ? (icon == true ? 'icon' : icon + " icon") : '',
tabular ? (tabular == true ? 'tabular' : tabular + " tabular") : '',
fixed ? "tabular " + tabular : '',
className,
'menu'
]);
return (React.createElement("div", {className: classes}, children));
};
return Menu;
}(data.Component));
exports.Menu = Menu;
var Modal = (function (_super) {
__extends(Modal, _super);
function Modal(props) {
var _this = this;
_super.call(this, props);
this.getMountNode = function () { return _this.props.mountNode || document.body; };
this.handleClose = function (e) {
var onClose = _this.props.onClose;
if (onClose)
onClose(e, _this.props);
if (_this.state.open != false)
_this.setState({ open: false });
};
this.handleOpen = function (e) {
var onOpen = _this.props.onOpen;
if (onOpen)
onOpen(e, _this.props);
if (_this.state.open != true)
_this.setState({ open: true });
};
this.setPosition = function () {
if (_this.ref) {
var mountNode = _this.getMountNode();
var height = _this.ref.getBoundingClientRect().height;
var marginTop = -Math.round(height / 2);
var scrolling = height >= window.innerHeight;
var newState = {};
if (_this.state.marginTop !== marginTop) {
newState.marginTop = marginTop;
}
if (_this.state.scrolling !== scrolling) {
newState.scrolling = scrolling;
if (scrolling) {
mountNode.classList.add('scrolling');
}
else {
mountNode.classList.remove('scrolling');
}
}
if (Object.keys(newState).length > 0)
_this.setState(newState);
}
_this.animationId = requestAnimationFrame(_this.setPosition);
};
this.handlePortalMount = function () {
var dimmer = _this.props.dimmer;
var mountNode = _this.getMountNode();
if (dimmer) {
mountNode.classList.add('dimmable', 'dimmed');
if (dimmer === 'blurring' && !pxt.options.light) {
mountNode.classList.add('blurring');
}
}
_this.setPosition();
};
this.handleRef = function (c) { return (_this.ref = c); };
this.handlePortalUnmount = function () {
var mountNode = _this.getMountNode();
mountNode.classList.remove('blurring', 'dimmable', 'dimmed', 'scrollable');
if (_this.animationId)
cancelAnimationFrame(_this.animationId);
};
this.id = Util.guidGen();
this.state = {
open: this.props.open
};
}
Modal.prototype.componentWillUnmount = function () {
this.handlePortalUnmount();
};
Modal.prototype.componentWillMount = function () {
var open = this.props.open;
this.state = { open: open };
};
Modal.prototype.componentWillReceiveProps = function (nextProps) {
var newState = {};
if (nextProps.open != undefined) {
newState.open = nextProps.open;
}
if (Object.keys(newState).length > 0)
this.setState(newState);
};
Modal.prototype.renderCore = function () {
var _this = this;
var open = this.state.open;
var _a = this.props, basic = _a.basic, children = _a.children, className = _a.className, closeIcon = _a.closeIcon, closeOnDimmerClick = _a.closeOnDimmerClick, closeOnDocumentClick = _a.closeOnDocumentClick, dimmer = _a.dimmer, dimmerClassName = _a.dimmerClassName, size = _a.size;
var _b = this.state, marginTop = _b.marginTop, scrolling = _b.scrolling;
var classes = cx([
'ui',
size,
basic ? 'basic' : '',
scrolling ? 'scrolling' : '',
'modal transition visible active',
className,
]);
var closeIconName = closeIcon === true ? 'close' : closeIcon;
var modalJSX = (React.createElement("div", {className: classes, style: { marginTop: marginTop }, ref: this.handleRef, role: "dialog", "aria-labelledby": this.id + 'title', "aria-describedby": this.id + 'desc'}, this.props.header ? React.createElement("div", {id: this.id + 'title', className: "header " + (this.props.headerClass || "")}, this.props.header, this.props.closeIcon ? React.createElement(Button, {icon: closeIconName, class: "clear right floated", onClick: function () { return _this.handleClose(null); }}) : undefined, this.props.helpUrl ?
React.createElement("a", {className: "ui button icon-and-text right floated labeled", href: this.props.helpUrl, target: "_docs"}, React.createElement("i", {className: "help icon"}), lf("Help"))
: undefined) : undefined, React.createElement("div", {id: this.id + 'desc', className: "content"}, children), this.props.action && this.props.actionClick ?
React.createElement("div", {className: "actions"}, React.createElement(Button, {text: this.props.action, class: "approve primary " + (this.props.actionLoading ? "loading" : ""), onClick: function () {
_this.props.actionClick();
}})) : undefined));
var dimmerClasses = !dimmer
? null
: cx([
'ui',
dimmer === 'inverted' ? 'inverted' : '',
pxt.options.light ? '' : "transition",
'page modals dimmer visible active',
dimmerClassName
]);
var blurring = dimmer === 'blurring';
return (React.createElement(Portal, {closeOnRootNodeClick: closeOnDimmerClick, closeOnDocumentClick: closeOnDocumentClick, className: dimmerClasses, mountNode: this.getMountNode(), onMount: this.handlePortalMount, onUnmount: this.handlePortalUnmount, onClose: this.handleClose, onOpen: this.handleOpen, open: open}, modalJSX));
};
return Modal;
}(data.Component));
exports.Modal = Modal;
var Portal = (function (_super) {
__extends(Portal, _super);
function Portal(props) {
var _this = this;
_super.call(this, props);
this.handleDocumentClick = function (e) {
var _a = _this.props, closeOnDocumentClick = _a.closeOnDocumentClick, closeOnRootNodeClick = _a.closeOnRootNodeClick;
if (!_this.rootNode || !_this.portalNode || _this.portalNode.contains(e.target))
return;
var didClickInRootNode = _this.rootNode.contains(e.target);
if (closeOnDocumentClick && !didClickInRootNode || closeOnRootNodeClick && didClickInRootNode) {
_this.close(e);
}
};
this.close = function (e) {
var onClose = _this.props.onClose;
if (onClose)
onClose(e);
if (_this.state.open != false)
_this.setState({ open: false });
};
this.open = function (e) {
var onOpen = _this.props.onOpen;
if (onOpen)
onOpen(e);
if (_this.state.open != true)
_this.setState({ open: true });
};
this.mountPortal = function () {
if (_this.rootNode)
return;
var _a = _this.props.mountNode, mountNode = _a === void 0 ? document.body : _a;
_this.rootNode = document.createElement('div');
mountNode.appendChild(_this.rootNode);
document.addEventListener('click', _this.handleDocumentClick);
var onMount = _this.props.onMount;
if (onMount)
onMount();
};
this.unmountPortal = function () {
if (!_this.rootNode)
return;
ReactDOM.unmountComponentAtNode(_this.rootNode);
_this.rootNode.parentNode.removeChild(_this.rootNode);
_this.rootNode = null;
_this.portalNode = null;
document.removeEventListener('click', _this.handleDocumentClick);
var onUnmount = _this.props.onUnmount;
if (onUnmount)
onUnmount();
};
}
Portal.prototype.componentDidMount = function () {
if (this.state.open) {
this.renderPortal();
}
};
Portal.prototype.componentDidUpdate = function (prevProps, prevState) {
if (this.state.open) {
this.renderPortal();
}
if (prevState.open && !this.state.open) {
this.unmountPortal();
}
};
Portal.prototype.componentWillUnmount = function () {
this.unmountPortal();
};
Portal.prototype.componentWillMount = function () {
var open = this.props.open;
this.state = { open: open };
};
Portal.prototype.componentWillReceiveProps = function (nextProps) {
var newState = {};
if (nextProps.open != undefined) {
newState.open = nextProps.open;
}
if (Object.keys(newState).length > 0)
this.setState(newState);
};
Portal.prototype.renderPortal = function () {
var _a = this.props, children = _a.children, className = _a.className, open = _a.open;
this.mountPortal();
this.rootNode.className = className || '';
ReactDOM.unstable_renderSubtreeIntoContainer(this, React.Children.only(children), this.rootNode);
this.portalNode = this.rootNode.firstElementChild;
};
Portal.prototype.renderCore = function () {
return React.createElement("div", null);
};
return Portal;
}(data.Component));
exports.Portal = Portal;
},{"./data":11,"react":264,"react-dom":135}],33:[function(require,module,exports){
"use strict";
var workeriface = require("./workeriface");
var pkg = require("./package");
var iface;
function td2tsAsync(td) {
if (!iface)
iface = workeriface.makeWebWorker(pxt.webConfig.tdworkerjs);
return pkg.mainPkg.getCompileOptionsAsync()
.then(function (opts) {
opts.ast = true;
var res = pxtc.compile(opts);
var apiinfo = pxtc.getApiInfo(res.ast, true);
var arg = {
text: td,
useExtensions: true,
apiInfo: apiinfo
};
return iface.opAsync("td2ts", arg);
})
.then(function (resp) {
pxt.debug(resp);
return resp.text;
});
}
exports.td2tsAsync = td2tsAsync;
},{"./package":24,"./workeriface":36}],34:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = new DOMParser().parseFromString("\n \n \n \n \n 4\n \n \n \n \n \n \n \n \n \n \n \n 4\n \n \n \n \n \n \n \n \n TRUE\n \n \n \n \n \n \n \n TRUE\n \n \n \n \n \n \n 0\n \n \n \n \n 0\n \n \n \n \n LT\n \n \n 0\n \n \n \n \n 0\n \n \n \n \n \n OR\n \n \n \n \n FALSE\n \n \n \n \n \n \n \n \n 0\n \n \n \n \n 0\n \n \n \n \n \n \n 0\n \n \n \n \n 0\n \n \n MINUS\n \n \n \n \n 0\n \n \n \n \n 0\n \n \n MULTIPLY\n \n \n \n \n 0\n \n \n \n \n 0\n \n \n DIVIDE\n \n \n 0\n \n \n \n \n 4\n \n \n \n \n \n \n \n 0\n \n \n \n \n 1\n \n \n \n \n \n \n 0\n \n \n \n \n 0\n \n \n \n \n \n \n 0\n \n \n \n \n 0\n \n \n max\n \n \n \n \n 0\n \n \n \n \n \n \n \n \n \n \n \n 0\n \n \n \n \n \n \n \n \n \n \n abc\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ", "text/xml");
},{}],35:[function(require,module,exports){
///
///
///
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var data = require("./data");
var sui = require("./sui");
var TutorialMenuItem = (function (_super) {
__extends(TutorialMenuItem, _super);
function TutorialMenuItem(props) {
_super.call(this, props);
}
TutorialMenuItem.prototype.openTutorialStep = function (step) {
pxt.tickEvent("tutorial.step", { tutorial: this.props.parent.state.tutorial, step: step });
this.props.parent.setState({ tutorialStep: step, tutorialReady: false });
this.props.parent.setTutorialStep(step);
};
TutorialMenuItem.prototype.render = function () {
var _this = this;
var state = this.props.parent.state;
var tutorialReady = state.tutorialReady;
var targetTheme = pxt.appTarget.appTheme;
var tutorialSteps = state.tutorialSteps;
var currentStep = state.tutorialStep;
var tutorialName = state.tutorialName;
return React.createElement("div", {className: "ui item"}, React.createElement("div", {className: "ui item tutorial-menuitem"}, tutorialSteps.map(function (step, index) {
return React.createElement(sui.Button, {key: 'tutorialStep' + index, class: "icon circular " + (currentStep == index ? 'red selected' : 'inverted') + " " + (!tutorialReady ? 'disabled' : ''), text: " " + (index + 1) + " ", onClick: function () { return _this.openTutorialStep(index); }});
})));
};
return TutorialMenuItem;
}(data.Component));
exports.TutorialMenuItem = TutorialMenuItem;
var TutorialContent = (function (_super) {
__extends(TutorialContent, _super);
function TutorialContent(props) {
_super.call(this, props);
}
TutorialContent.notify = function (message) {
var tc = document.getElementById("tutorialcontent");
if (tc && tc.contentWindow)
tc.contentWindow.postMessage(message, "*");
};
TutorialContent.prototype.setPath = function (path) {
var docsUrl = pxt.webConfig.docsUrl || '/--docs';
var mode = this.props.parent.isBlocksEditor() ? "blocks" : "js";
var url = docsUrl + "#tutorial:" + path + ":" + mode + ":" + pxt.Util.localeInfo();
this.setUrl(url);
};
TutorialContent.prototype.setUrl = function (url) {
var el = document.getElementById("tutorialcontent");
if (el)
el.src = url;
else
this.props.parent.setState({ tutorialUrl: url });
};
TutorialContent.refresh = function () {
var el = document.getElementById("tutorialcontent");
if (el && el.contentWindow) {
el.parentElement.style.height = "";
el.parentElement.style.height = el.contentWindow.document.body.scrollHeight + "px";
}
};
TutorialContent.prototype.renderCore = function () {
var state = this.props.parent.state;
var docsUrl = state.tutorialUrl;
if (!docsUrl)
return null;
return React.createElement("iframe", {id: "tutorialcontent", onLoad: function () { return TutorialContent.refresh(); }, src: docsUrl, role: "complementary", sandbox: "allow-scripts allow-same-origin allow-popups"});
};
return TutorialContent;
}(data.Component));
exports.TutorialContent = TutorialContent;
var TutorialCard = (function (_super) {
__extends(TutorialCard, _super);
function TutorialCard(props) {
_super.call(this, props);
}
TutorialCard.prototype.previousTutorialStep = function () {
var currentStep = this.props.parent.state.tutorialStep;
var previousStep = currentStep - 1;
pxt.tickEvent("tutorial.previous", { tutorial: this.props.parent.state.tutorial, step: previousStep });
this.props.parent.setState({ tutorialStep: previousStep, tutorialReady: false });
this.props.parent.setTutorialStep(previousStep);
};
TutorialCard.prototype.nextTutorialStep = function () {
var currentStep = this.props.parent.state.tutorialStep;
var nextStep = currentStep + 1;
pxt.tickEvent("tutorial.next", { tutorial: this.props.parent.state.tutorial, step: nextStep });
this.props.parent.setState({ tutorialStep: nextStep, tutorialReady: false });
this.props.parent.setTutorialStep(nextStep);
};
TutorialCard.prototype.finishTutorial = function () {
this.props.parent.exitTutorial();
};
TutorialCard.prototype.setPath = function (path) {
var tc = this.refs["tutorialcontent"];
if (!tc)
return;
tc.setPath(path);
};
TutorialCard.prototype.render = function () {
var _this = this;
var state = this.props.parent.state;
var tutorialReady = state.tutorialReady;
var currentStep = state.tutorialStep;
var cardLocation = state.tutorialCardLocation || 'bottom';
var maxSteps = state.tutorialSteps.length;
var hasPrevious = currentStep != 0;
var hasNext = currentStep != maxSteps - 1;
var hasFinish = currentStep == maxSteps - 1;
return React.createElement("div", {id: "tutorialcard", className: "ui " + (pxt.options.light ? "" : "transition fly in") + " " + cardLocation + " visible active"}, React.createElement("div", {className: "ui raised fluid card"}, React.createElement("div", {className: "ui"}, React.createElement(TutorialContent, {ref: "tutorialcontent", parent: this.props.parent})), React.createElement("div", {className: "extra content"}, React.createElement("div", {className: "ui two buttons"}, hasPrevious ? React.createElement(sui.Button, {icon: "left chevron", class: "ui icon red button " + (!tutorialReady ? 'disabled' : ''), text: lf("Back"), onClick: function () { return _this.previousTutorialStep(); }}) : undefined, hasNext ? React.createElement(sui.Button, {icon: "right chevron", class: "ui icon green button " + (!tutorialReady ? 'disabled' : ''), text: lf("Next"), onClick: function () { return _this.nextTutorialStep(); }}) : undefined, hasFinish ? React.createElement(sui.Button, {icon: "left checkmark", class: "ui icon orange button " + (!tutorialReady ? 'disabled' : ''), text: lf("Finish"), onClick: function () { return _this.finishTutorial(); }}) : undefined))));
};
return TutorialCard;
}(data.Component));
exports.TutorialCard = TutorialCard;
},{"./data":11,"./sui":32,"react":264}],36:[function(require,module,exports){
"use strict";
var U = pxt.Util;
function wrap(send) {
var pendingMsgs = {};
var msgId = 0;
var q = new U.PromiseQueue();
var initPromise = new Promise(function (resolve, reject) {
pendingMsgs["ready"] = resolve;
});
q.enqueue("main", function () { return initPromise; });
var recvHandler = function (data) {
if (pendingMsgs.hasOwnProperty(data.id)) {
var cb = pendingMsgs[data.id];
delete pendingMsgs[data.id];
cb(data.result);
}
};
function opAsync(op, arg) {
return q.enqueue("main", function () { return new Promise(function (resolve, reject) {
var id = "" + msgId++;
pendingMsgs[id] = function (v) {
if (!v) {
//pxt.reportError("worker", "no response")
reject(new Error("no response"));
}
else if (v.errorMessage) {
//pxt.reportError("worker", v.errorMessage)
reject(new Error(v.errorMessage));
}
else {
resolve(v);
}
};
send({ id: id, op: op, arg: arg });
}); });
}
return { opAsync: opAsync, recvHandler: recvHandler };
}
exports.wrap = wrap;
function makeWebWorker(workerFile) {
var worker = new Worker(workerFile);
var iface = wrap(function (v) { return worker.postMessage(v); });
worker.onmessage = function (ev) {
iface.recvHandler(ev.data);
};
return iface;
}
exports.makeWebWorker = makeWebWorker;
function makeWebSocket(url, onOOB) {
if (onOOB === void 0) { onOOB = null; }
var ws = new WebSocket(url);
var sendq = [];
var iface = wrap(function (v) {
var s = JSON.stringify(v);
if (sendq)
sendq.push(s);
else
ws.send(s);
});
ws.onmessage = function (ev) {
var js = JSON.parse(ev.data);
if (onOOB && js.id == null) {
onOOB(js);
}
else {
iface.recvHandler(js);
}
};
ws.onopen = function (ev) {
pxt.debug('socket opened');
for (var _i = 0, sendq_1 = sendq; _i < sendq_1.length; _i++) {
var m = sendq_1[_i];
ws.send(m);
}
sendq = null;
};
ws.onclose = function (ev) {
pxt.debug('socket closed');
};
return iface;
}
exports.makeWebSocket = makeWebSocket;
},{}],37:[function(require,module,exports){
///
///
"use strict";
var db = require("./db");
var core = require("./core");
var data = require("./data");
var cloudworkspace = require("./cloudworkspace");
var fileworkspace = require("./fileworkspace");
var memoryworkspace = require("./memoryworkspace");
var scripts = new db.Table("script");
var U = pxt.Util;
var Cloud = pxt.Cloud;
var lf = U.lf;
var impl;
function setupWorkspace(id) {
U.assert(!impl, "workspace set twice");
pxt.debug("workspace: " + id);
switch (id) {
case "fs":
case "file":
impl = fileworkspace.provider;
break;
case "mem":
case "memory":
impl = memoryworkspace.provider;
break;
case "cloud":
default:
impl = cloudworkspace.provider;
break;
}
}
exports.setupWorkspace = setupWorkspace;
function getHeaders(withDeleted) {
if (withDeleted === void 0) { withDeleted = false; }
checkSession();
var r = impl.getHeaders();
if (!withDeleted)
r = r.filter(function (r) { return !r.isDeleted; });
r.sort(function (a, b) { return b.recentUse - a.recentUse; });
return r;
}
exports.getHeaders = getHeaders;
function getHeader(id) {
checkSession();
var hd = impl.getHeader(id);
if (hd && !hd.isDeleted)
return hd;
return null;
}
exports.getHeader = getHeader;
var sessionID;
function isSessionOutdated() {
return pxt.storage.getLocal('pxt_workspace_session_id') != sessionID;
}
exports.isSessionOutdated = isSessionOutdated;
function checkSession() {
if (isSessionOutdated()) {
Util.assert(false, "trying to access outdated session");
}
}
function initAsync() {
if (!impl)
impl = cloudworkspace.provider;
// generate new workspace session id to avoid races with other tabs
sessionID = Util.guidGen();
pxt.storage.setLocal('pxt_workspace_session_id', sessionID);
pxt.debug("workspace session: " + sessionID);
return impl.initAsync(pxt.appTarget.id);
}
exports.initAsync = initAsync;
function getTextAsync(id) {
checkSession();
return impl.getTextAsync(id);
}
exports.getTextAsync = getTextAsync;
// https://github.com/Microsoft/pxt-backend/blob/master/docs/sharing.md#anonymous-publishing
function anonymousPublishAsync(h, text, meta) {
var saveId = {};
h.saveId = saveId;
var stext = JSON.stringify(text, null, 2) + "\n";
var scrReq = {
name: h.name,
target: h.target,
description: meta.description,
editor: h.editor,
text: text,
meta: {
versions: pxt.appTarget.versions,
blocksHeight: meta.blocksHeight,
blocksWidth: meta.blocksWidth
}
};
pxt.debug("publishing script; " + stext.length + " bytes");
return Cloud.privatePostAsync("scripts", scrReq)
.then(function (inf) {
h.pubId = inf.id;
h.pubCurrent = h.saveId === saveId;
h.meta = inf.meta;
pxt.debug("published; id /" + inf.id);
return saveAsync(h)
.then(function () { return inf; });
});
}
exports.anonymousPublishAsync = anonymousPublishAsync;
function saveAsync(h, text) {
checkSession();
if (text || h.isDeleted) {
h.pubCurrent = false;
h.blobCurrent = false;
h.modificationTime = U.nowSeconds();
}
h.recentUse = U.nowSeconds();
return impl.saveAsync(h, text);
}
exports.saveAsync = saveAsync;
function installAsync(h0, text) {
checkSession();
return impl.installAsync(h0, text);
}
exports.installAsync = installAsync;
function saveScreenshotAsync(h, data, icon) {
checkSession();
return impl.saveScreenshotAsync
? impl.saveScreenshotAsync(h, data, icon)
: Promise.resolve();
}
exports.saveScreenshotAsync = saveScreenshotAsync;
function fixupFileNames(txt) {
if (!txt)
return txt;
for (var oldName in ["kind.json", "yelm.json"]) {
if (!txt[pxt.CONFIG_NAME] && txt[oldName]) {
txt[pxt.CONFIG_NAME] = txt[oldName];
delete txt[oldName];
}
}
return txt;
}
exports.fixupFileNames = fixupFileNames;
var scriptDlQ = new U.PromiseQueue();
//let scriptCache:any = {}
function getPublishedScriptAsync(id) {
checkSession();
//if (scriptCache.hasOwnProperty(id)) return Promise.resolve(scriptCache[id])
if (pxt.github.isGithubId(id))
id = pxt.github.noramlizeRepoId(id);
var eid = encodeURIComponent(id);
return pxt.packagesConfigAsync()
.then(function (config) { return scriptDlQ.enqueue(id, function () { return scripts.getAsync(eid)
.then(function (v) { return v.files; }, function (e) {
return (pxt.github.isGithubId(id) ?
pxt.github.downloadPackageAsync(id, config).then(function (v) { return v.files; }) :
Cloud.downloadScriptFilesAsync(id))
.catch(core.handleNetworkError)
.then(function (files) { return scripts.setAsync({ id: eid, files: files })
.then(function () {
//return (scriptCache[id] = files)
return files;
}); });
})
.then(fixupFileNames); }); });
}
exports.getPublishedScriptAsync = getPublishedScriptAsync;
function installByIdAsync(id) {
return Cloud.privateGetAsync(id)
.then(function (scr) {
return getPublishedScriptAsync(scr.id)
.then(function (files) { return installAsync({
name: scr.name,
pubId: id,
pubCurrent: true,
meta: scr.meta,
editor: scr.editor,
target: scr.target,
}, files); });
});
}
exports.installByIdAsync = installByIdAsync;
function saveToCloudAsync(h) {
checkSession();
return impl.saveToCloudAsync(h);
}
exports.saveToCloudAsync = saveToCloudAsync;
function syncAsync() {
checkSession();
return impl.syncAsync();
}
exports.syncAsync = syncAsync;
function resetAsync() {
checkSession();
return impl.resetAsync();
}
exports.resetAsync = resetAsync;
/*
header: - one header
header:* - all headers
*/
data.mountVirtualApi("header", {
getSync: function (p) {
p = data.stripProtocol(p);
if (p == "*")
return getHeaders();
return getHeader(p);
},
});
/*
text: - all files
text:/ - one file
*/
data.mountVirtualApi("text", {
getAsync: function (p) {
var m = /^[\w\-]+:([^\/]+)(\/(.*))?/.exec(p);
return getTextAsync(m[1])
.then(function (files) {
if (m[3])
return files[m[3]];
else
return files;
});
},
});
},{"./cloudworkspace":5,"./core":10,"./data":11,"./db":12,"./fileworkspace":17,"./memoryworkspace":22}],38:[function(require,module,exports){
'use strict';
module.exports = argsArray;
function argsArray(fun) {
return function () {
var len = arguments.length;
if (len) {
var args = [];
var i = -1;
while (++i < len) {
args[i] = arguments[i];
}
return fun.call(this, args);
} else {
return fun.call(this, []);
}
};
}
},{}],39:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr(len * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],40:[function(require,module,exports){
(function (process,global){
/* @preserve
* The MIT License (MIT)
*
* Copyright (c) 2013-2015 Petka Antonov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/**
* bluebird build version 3.4.7
* Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
this._reset();
this._haveDrainedQueues = true;
this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
if (!this._isTickUsed) {
this._isTickUsed = true;
this._schedule(this.drainQueues);
}
};
Async.prototype._reset = function () {
this._isTickUsed = false;
};
module.exports = Async;
module.exports.firstLineError = firstLineError;
},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
var calledBind = false;
var rejectThis = function(_, e) {
this._reject(e);
};
var targetRejected = function(e, context) {
context.promiseRejectionQueued = true;
context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function(thisArg, context) {
if (((this._bitField & 50397184) === 0)) {
this._resolveCallback(context.target);
}
};
var bindingRejected = function(e, context) {
if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
if (!calledBind) {
calledBind = true;
Promise.prototype._propagateFrom = debug.propagateFromFunction();
Promise.prototype._boundValue = debug.boundValueFunction();
}
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, undefined, ret, context);
maybePromise._then(
bindingResolved, bindingRejected, undefined, ret, context);
ret._setOnCancel(maybePromise);
} else {
ret._resolveCallback(target);
}
return ret;
};
Promise.prototype._setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 2097152;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~2097152);
}
};
Promise.prototype._isBound = function () {
return (this._bitField & 2097152) === 2097152;
};
Promise.bind = function (thisArg, value) {
return Promise.resolve(value).bind(thisArg);
};
};
},{}],4:[function(_dereq_,module,exports){
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict() {
try { if (Promise === bluebird) Promise = old; }
catch (e) {}
return bluebird;
}
var bluebird = _dereq_("./promise")();
bluebird.noConflict = noConflict;
module.exports = bluebird;
},{"./promise":22}],5:[function(_dereq_,module,exports){
"use strict";
var cr = Object.create;
if (cr) {
var callerCache = cr(null);
var getterCache = cr(null);
callerCache[" size"] = getterCache[" size"] = 0;
}
module.exports = function(Promise) {
var util = _dereq_("./util");
var canEvaluate = util.canEvaluate;
var isIdentifier = util.isIdentifier;
var getMethodCaller;
var getGetter;
if (!true) {
var makeMethodCaller = function (methodName) {
return new Function("ensureMethod", " \n\
return function(obj) { \n\
'use strict' \n\
var len = this.length; \n\
ensureMethod(obj, 'methodName'); \n\
switch(len) { \n\
case 1: return obj.methodName(this[0]); \n\
case 2: return obj.methodName(this[0], this[1]); \n\
case 3: return obj.methodName(this[0], this[1], this[2]); \n\
case 0: return obj.methodName(); \n\
default: \n\
return obj.methodName.apply(obj, this); \n\
} \n\
}; \n\
".replace(/methodName/g, methodName))(ensureMethod);
};
var makeGetter = function (propertyName) {
return new Function("obj", " \n\
'use strict'; \n\
return obj.propertyName; \n\
".replace("propertyName", propertyName));
};
var getCompiled = function(name, compiler, cache) {
var ret = cache[name];
if (typeof ret !== "function") {
if (!isIdentifier(name)) {
return null;
}
ret = compiler(name);
cache[name] = ret;
cache[" size"]++;
if (cache[" size"] > 512) {
var keys = Object.keys(cache);
for (var i = 0; i < 256; ++i) delete cache[keys[i]];
cache[" size"] = keys.length - 256;
}
}
return ret;
};
getMethodCaller = function(name) {
return getCompiled(name, makeMethodCaller, callerCache);
};
getGetter = function(name) {
return getCompiled(name, makeGetter, getterCache);
};
}
function ensureMethod(obj, methodName) {
var fn;
if (obj != null) fn = obj[methodName];
if (typeof fn !== "function") {
var message = "Object " + util.classString(obj) + " has no method '" +
util.toString(methodName) + "'";
throw new Promise.TypeError(message);
}
return fn;
}
function caller(obj) {
var methodName = this.pop();
var fn = ensureMethod(obj, methodName);
return fn.apply(obj, this);
}
Promise.prototype.call = function (methodName) {
var args = [].slice.call(arguments, 1);;
if (!true) {
if (canEvaluate) {
var maybeCaller = getMethodCaller(methodName);
if (maybeCaller !== null) {
return this._then(
maybeCaller, undefined, undefined, args, undefined);
}
}
}
args.push(methodName);
return this._then(caller, undefined, undefined, args, undefined);
};
function namedGetter(obj) {
return obj[this];
}
function indexedGetter(obj) {
var index = +this;
if (index < 0) index = Math.max(0, index + obj.length);
return obj[index];
}
Promise.prototype.get = function (propertyName) {
var isIndex = (typeof propertyName === "number");
var getter;
if (!isIndex) {
if (canEvaluate) {
var maybeGetter = getGetter(propertyName);
getter = maybeGetter !== null ? maybeGetter : namedGetter;
} else {
getter = namedGetter;
}
} else {
getter = indexedGetter;
}
return this._then(getter, undefined, undefined, propertyName, undefined);
};
};
},{"./util":36}],6:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, PromiseArray, apiRejection, debug) {
var util = _dereq_("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
Promise.prototype["break"] = Promise.prototype.cancel = function() {
if (!debug.cancellation()) return this._warn("cancellation is disabled");
var promise = this;
var child = promise;
while (promise._isCancellable()) {
if (!promise._cancelBy(child)) {
if (child._isFollowing()) {
child._followee().cancel();
} else {
child._cancelBranched();
}
break;
}
var parent = promise._cancellationParent;
if (parent == null || !parent._isCancellable()) {
if (promise._isFollowing()) {
promise._followee().cancel();
} else {
promise._cancelBranched();
}
break;
} else {
if (promise._isFollowing()) promise._followee().cancel();
promise._setWillBeCancelled();
child = promise;
promise = parent;
}
}
};
Promise.prototype._branchHasCancelled = function() {
this._branchesRemainingToCancel--;
};
Promise.prototype._enoughBranchesHaveCancelled = function() {
return this._branchesRemainingToCancel === undefined ||
this._branchesRemainingToCancel <= 0;
};
Promise.prototype._cancelBy = function(canceller) {
if (canceller === this) {
this._branchesRemainingToCancel = 0;
this._invokeOnCancel();
return true;
} else {
this._branchHasCancelled();
if (this._enoughBranchesHaveCancelled()) {
this._invokeOnCancel();
return true;
}
}
return false;
};
Promise.prototype._cancelBranched = function() {
if (this._enoughBranchesHaveCancelled()) {
this._cancel();
}
};
Promise.prototype._cancel = function() {
if (!this._isCancellable()) return;
this._setCancelled();
async.invoke(this._cancelPromises, this, undefined);
};
Promise.prototype._cancelPromises = function() {
if (this._length() > 0) this._settlePromises();
};
Promise.prototype._unsetOnCancel = function() {
this._onCancelField = undefined;
};
Promise.prototype._isCancellable = function() {
return this.isPending() && !this._isCancelled();
};
Promise.prototype.isCancellable = function() {
return this.isPending() && !this.isCancelled();
};
Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
if (util.isArray(onCancelCallback)) {
for (var i = 0; i < onCancelCallback.length; ++i) {
this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
}
} else if (onCancelCallback !== undefined) {
if (typeof onCancelCallback === "function") {
if (!internalOnly) {
var e = tryCatch(onCancelCallback).call(this._boundValue());
if (e === errorObj) {
this._attachExtraTrace(e.e);
async.throwLater(e.e);
}
}
} else {
onCancelCallback._resultCancelled(this);
}
}
};
Promise.prototype._invokeOnCancel = function() {
var onCancelCallback = this._onCancel();
this._unsetOnCancel();
async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
};
Promise.prototype._invokeInternalOnCancel = function() {
if (this._isCancellable()) {
this._doInvokeOnCancel(this._onCancel(), true);
this._unsetOnCancel();
}
};
Promise.prototype._resultCancelled = function() {
this.cancel();
};
};
},{"./util":36}],7:[function(_dereq_,module,exports){
"use strict";
module.exports = function(NEXT_FILTER) {
var util = _dereq_("./util");
var getKeys = _dereq_("./es5").keys;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function catchFilter(instances, cb, promise) {
return function(e) {
var boundTo = promise._boundValue();
predicateLoop: for (var i = 0; i < instances.length; ++i) {
var item = instances[i];
if (item === Error ||
(item != null && item.prototype instanceof Error)) {
if (e instanceof item) {
return tryCatch(cb).call(boundTo, e);
}
} else if (typeof item === "function") {
var matchesPredicate = tryCatch(item).call(boundTo, e);
if (matchesPredicate === errorObj) {
return matchesPredicate;
} else if (matchesPredicate) {
return tryCatch(cb).call(boundTo, e);
}
} else if (util.isObject(e)) {
var keys = getKeys(item);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
if (item[key] != e[key]) {
continue predicateLoop;
}
}
return tryCatch(cb).call(boundTo, e);
}
}
return NEXT_FILTER;
};
}
return catchFilter;
};
},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var longStackTraces = false;
var contextStack = [];
Promise.prototype._promiseCreated = function() {};
Promise.prototype._pushContext = function() {};
Promise.prototype._popContext = function() {return null;};
Promise._peekContext = Promise.prototype._peekContext = function() {};
function Context() {
this._trace = new Context.CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
if (this._trace !== undefined) {
this._trace._promiseCreated = null;
contextStack.push(this._trace);
}
};
Context.prototype._popContext = function () {
if (this._trace !== undefined) {
var trace = contextStack.pop();
var ret = trace._promiseCreated;
trace._promiseCreated = null;
return ret;
}
return null;
};
function createContext() {
if (longStackTraces) return new Context();
}
function peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return undefined;
}
Context.CapturedTrace = null;
Context.create = createContext;
Context.deactivateLongStackTraces = function() {};
Context.activateLongStackTraces = function() {
var Promise_pushContext = Promise.prototype._pushContext;
var Promise_popContext = Promise.prototype._popContext;
var Promise_PeekContext = Promise._peekContext;
var Promise_peekContext = Promise.prototype._peekContext;
var Promise_promiseCreated = Promise.prototype._promiseCreated;
Context.deactivateLongStackTraces = function() {
Promise.prototype._pushContext = Promise_pushContext;
Promise.prototype._popContext = Promise_popContext;
Promise._peekContext = Promise_PeekContext;
Promise.prototype._peekContext = Promise_peekContext;
Promise.prototype._promiseCreated = Promise_promiseCreated;
longStackTraces = false;
};
longStackTraces = true;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;
Promise._peekContext = Promise.prototype._peekContext = peekContext;
Promise.prototype._promiseCreated = function() {
var ctx = this._peekContext();
if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
};
};
return Context;
};
},{}],9:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, Context) {
var getDomain = Promise._getDomain;
var async = Promise._async;
var Warning = _dereq_("./errors").Warning;
var util = _dereq_("./util");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var bluebirdFramePattern =
/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var printWarning;
var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
(true ||
util.env("BLUEBIRD_DEBUG") ||
util.env("NODE_ENV") === "development"));
var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
(debugging || util.env("BLUEBIRD_WARNINGS")));
var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
(debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
(warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target();
target._bitField = ((target._bitField & (~1048576)) |
524288);
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
};
Promise.prototype._setReturnedNonUndefined = function() {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._returnedNonUndefined = function() {
return (this._bitField & 268435456) !== 0;
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue();
this._setUnhandledRejectionIsNotified();
fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 262144;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~262144);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 1048576;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~1048576);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
return warn(message, shouldUseOwnTrace, promise || this);
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
};
var disableLongStackTraces = function() {};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
config.longStackTraces = true;
disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
};
var fireDomEvent = (function() {
try {
if (typeof CustomEvent === "function") {
var event = new CustomEvent("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new CustomEvent(name.toLowerCase(), {
detail: event,
cancelable: true
});
return !util.global.dispatchEvent(domEvent);
};
} else if (typeof Event === "function") {
var event = new Event("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new Event(name.toLowerCase(), {
cancelable: true
});
domEvent.detail = event;
return !util.global.dispatchEvent(domEvent);
};
} else {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = document.createEvent("CustomEvent");
domEvent.initCustomEvent(name.toLowerCase(), false, true,
event);
return !util.global.dispatchEvent(domEvent);
};
}
} catch (e) {}
return function() {
return false;
};
})();
var fireGlobalEvent = (function() {
if (util.isNode) {
return function() {
return process.emit.apply(process, arguments);
};
} else {
if (!util.global) {
return function() {
return false;
};
}
return function(name) {
var methodName = "on" + name.toLowerCase();
var method = util.global[methodName];
if (!method) return false;
method.apply(util.global, [].slice.call(arguments, 1));
return true;
};
}
})();
function generatePromiseLifecycleEventObject(name, promise) {
return {promise: promise};
}
var eventToObjectGenerator = {
promiseCreated: generatePromiseLifecycleEventObject,
promiseFulfilled: generatePromiseLifecycleEventObject,
promiseRejected: generatePromiseLifecycleEventObject,
promiseResolved: generatePromiseLifecycleEventObject,
promiseCancelled: generatePromiseLifecycleEventObject,
promiseChained: function(name, promise, child) {
return {promise: promise, child: child};
},
warning: function(name, warning) {
return {warning: warning};
},
unhandledRejection: function (name, reason, promise) {
return {reason: reason, promise: promise};
},
rejectionHandled: generatePromiseLifecycleEventObject
};
var activeFireEvent = function (name) {
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent.apply(null, arguments);
} catch (e) {
async.throwLater(e);
globalEventFired = true;
}
var domEventFired = false;
try {
domEventFired = fireDomEvent(name,
eventToObjectGenerator[name].apply(null, arguments));
} catch (e) {
async.throwLater(e);
domEventFired = true;
}
return domEventFired || globalEventFired;
};
Promise.config = function(opts) {
opts = Object(opts);
if ("longStackTraces" in opts) {
if (opts.longStackTraces) {
Promise.longStackTraces();
} else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
disableLongStackTraces();
}
}
if ("warnings" in opts) {
var warningsOption = opts.warnings;
config.warnings = !!warningsOption;
wForgottenReturn = config.warnings;
if (util.isObject(warningsOption)) {
if ("wForgottenReturn" in warningsOption) {
wForgottenReturn = !!warningsOption.wForgottenReturn;
}
}
}
if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
if (async.haveItemsQueued()) {
throw new Error(
"cannot enable cancellation after promises are in use");
}
Promise.prototype._clearCancellationData =
cancellationClearCancellationData;
Promise.prototype._propagateFrom = cancellationPropagateFrom;
Promise.prototype._onCancel = cancellationOnCancel;
Promise.prototype._setOnCancel = cancellationSetOnCancel;
Promise.prototype._attachCancellationCallback =
cancellationAttachCancellationCallback;
Promise.prototype._execute = cancellationExecute;
propagateFromFunction = cancellationPropagateFrom;
config.cancellation = true;
}
if ("monitoring" in opts) {
if (opts.monitoring && !config.monitoring) {
config.monitoring = true;
Promise.prototype._fireEvent = activeFireEvent;
} else if (!opts.monitoring && config.monitoring) {
config.monitoring = false;
Promise.prototype._fireEvent = defaultFireEvent;
}
}
return Promise;
};
function defaultFireEvent() { return false; }
Promise.prototype._fireEvent = defaultFireEvent;
Promise.prototype._execute = function(executor, resolve, reject) {
try {
executor(resolve, reject);
} catch (e) {
return e;
}
};
Promise.prototype._onCancel = function () {};
Promise.prototype._setOnCancel = function (handler) { ; };
Promise.prototype._attachCancellationCallback = function(onCancel) {
;
};
Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) {
;
;
};
function cancellationExecute(executor, resolve, reject) {
var promise = this;
try {
executor(resolve, reject, function(onCancel) {
if (typeof onCancel !== "function") {
throw new TypeError("onCancel must be a function, got: " +
util.toString(onCancel));
}
promise._attachCancellationCallback(onCancel);
});
} catch (e) {
return e;
}
}
function cancellationAttachCancellationCallback(onCancel) {
if (!this._isCancellable()) return this;
var previousOnCancel = this._onCancel();
if (previousOnCancel !== undefined) {
if (util.isArray(previousOnCancel)) {
previousOnCancel.push(onCancel);
} else {
this._setOnCancel([previousOnCancel, onCancel]);
}
} else {
this._setOnCancel(onCancel);
}
}
function cancellationOnCancel() {
return this._onCancelField;
}
function cancellationSetOnCancel(onCancel) {
this._onCancelField = onCancel;
}
function cancellationClearCancellationData() {
this._cancellationParent = undefined;
this._onCancelField = undefined;
}
function cancellationPropagateFrom(parent, flags) {
if ((flags & 1) !== 0) {
this._cancellationParent = parent;
var branchesRemainingToCancel = parent._branchesRemainingToCancel;
if (branchesRemainingToCancel === undefined) {
branchesRemainingToCancel = 0;
}
parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
}
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
function bindingPropagateFrom(parent, flags) {
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
var propagateFromFunction = bindingPropagateFrom;
function boundValueFunction() {
var ret = this._boundTo;
if (ret !== undefined) {
if (ret instanceof Promise) {
if (ret.isFulfilled()) {
return ret.value();
} else {
return undefined;
}
}
}
return ret;
}
function longStackTracesCaptureStackTrace() {
this._trace = new CapturedTrace(this._peekContext());
}
function longStackTracesAttachExtraTrace(error, ignoreSelf) {
if (canAttachTrace(error)) {
var trace = this._trace;
if (trace !== undefined) {
if (ignoreSelf) trace = trace._parent;
}
if (trace !== undefined) {
trace.attachExtraTrace(error);
} else if (!error.__stackCleaned__) {
var parsed = parseStackAndMessage(error);
util.notEnumerableProp(error, "stack",
parsed.message + "\n" + parsed.stack.join("\n"));
util.notEnumerableProp(error, "__stackCleaned__", true);
}
}
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise,
parent) {
if (returnValue === undefined && promiseCreated !== null &&
wForgottenReturn) {
if (parent !== undefined && parent._returnedNonUndefined()) return;
if ((promise._bitField & 65535) === 0) return;
if (name) name = name + " ";
var handlerLine = "";
var creatorLine = "";
if (promiseCreated._trace) {
var traceLines = promiseCreated._trace.stack.split("\n");
var stack = cleanStack(traceLines);
for (var i = stack.length - 1; i >= 0; --i) {
var line = stack[i];
if (!nodeFramePattern.test(line)) {
var lineMatches = line.match(parseLinePattern);
if (lineMatches) {
handlerLine = "at " + lineMatches[1] +
":" + lineMatches[2] + ":" + lineMatches[3] + " ";
}
break;
}
}
if (stack.length > 0) {
var firstUserLine = stack[0];
for (var i = 0; i < traceLines.length; ++i) {
if (traceLines[i] === firstUserLine) {
if (i > 0) {
creatorLine = "\n" + traceLines[i - 1];
}
break;
}
}
}
}
var msg = "a promise was created in a " + name +
"handler " + handlerLine + "but was not returned from it, " +
"see http://goo.gl/rRqMUw" +
creatorLine;
promise._warn(msg, true, promiseCreated);
}
}
function deprecated(name, replacement) {
var message = name +
" is deprecated and will be removed in a future version.";
if (replacement) message += " Use " + replacement + " instead.";
return warn(message);
}
function warn(message, shouldUseOwnTrace, promise) {
if (!config.warnings) return;
var warning = new Warning(message);
var ctx;
if (shouldUseOwnTrace) {
promise._attachExtraTrace(warning);
} else if (config.longStackTraces && (ctx = Promise._peekContext())) {
ctx.attachExtraTrace(warning);
} else {
var parsed = parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
if (!activeFireEvent("warning", warning)) {
formatAndLogError(warning, "", true);
}
}
function reconstructStack(message, stacks) {
for (var i = 0; i < stacks.length - 1; ++i) {
stacks[i].push("From previous event:");
stacks[i] = stacks[i].join("\n");
}
if (i < stacks.length) {
stacks[i] = stacks[i].join("\n");
}
return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
for (var i = 0; i < stacks.length; ++i) {
if (stacks[i].length === 0 ||
((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
stacks.splice(i, 1);
i--;
}
}
}
function removeCommonRoots(stacks) {
var current = stacks[0];
for (var i = 1; i < stacks.length; ++i) {
var prev = stacks[i];
var currentLastIndex = current.length - 1;
var currentLastLine = current[currentLastIndex];
var commonRootMeetPoint = -1;
for (var j = prev.length - 1; j >= 0; --j) {
if (prev[j] === currentLastLine) {
commonRootMeetPoint = j;
break;
}
}
for (var j = commonRootMeetPoint; j >= 0; --j) {
var line = prev[j];
if (current[currentLastIndex] === line) {
current.pop();
currentLastIndex--;
} else {
break;
}
}
current = prev;
}
}
function cleanStack(stack) {
var ret = [];
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
var isTraceLine = " (No stack trace)" === line ||
stackFramePattern.test(line);
var isInternalFrame = isTraceLine && shouldIgnore(line);
if (isTraceLine && !isInternalFrame) {
if (indentStackFrames && line.charAt(0) !== " ") {
line = " " + line;
}
ret.push(line);
}
}
return ret;
}
function stackFramesAsArray(error) {
var stack = error.stack.replace(/\s+$/g, "").split("\n");
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
if (" (No stack trace)" === line || stackFramePattern.test(line)) {
break;
}
}
if (i > 0 && error.name != "SyntaxError") {
stack = stack.slice(i);
}
return stack;
}
function parseStackAndMessage(error) {
var stack = error.stack;
var message = error.toString();
stack = typeof stack === "string" && stack.length > 0
? stackFramesAsArray(error) : [" (No stack trace)"];
return {
message: message,
stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
};
}
function formatAndLogError(error, title, isSoft) {
if (typeof console !== "undefined") {
var message;
if (util.isObject(error)) {
var stack = error.stack;
message = title + formatStack(stack, error);
} else {
message = title + String(error);
}
if (typeof printWarning === "function") {
printWarning(message, isSoft);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
}
function fireRejectionEvent(name, localHandler, reason, promise) {
var localEventFired = false;
try {
if (typeof localHandler === "function") {
localEventFired = true;
if (name === "rejectionHandled") {
localHandler(promise);
} else {
localHandler(reason, promise);
}
}
} catch (e) {
async.throwLater(e);
}
if (name === "unhandledRejection") {
if (!activeFireEvent(name, reason, promise) && !localEventFired) {
formatAndLogError(reason, "Unhandled rejection ");
}
} else {
activeFireEvent(name, promise);
}
}
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj && typeof obj.toString === "function"
? obj.toString() : util.toString(obj);
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
function longStackTracesIsSupported() {
return typeof captureStackTrace === "function";
}
var shouldIgnore = function() { return false; };
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
var matches = line.match(parseLineInfoRegex);
if (matches) {
return {
fileName: matches[1],
line: parseInt(matches[2], 10)
};
}
}
function setBounds(firstLineError, lastLineError) {
if (!longStackTracesIsSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
var lastFileName;
for (var i = 0; i < firstStackLines.length; ++i) {
var result = parseLineInfo(firstStackLines[i]);
if (result) {
firstFileName = result.fileName;
firstIndex = result.line;
break;
}
}
for (var i = 0; i < lastStackLines.length; ++i) {
var result = parseLineInfo(lastStackLines[i]);
if (result) {
lastFileName = result.fileName;
lastIndex = result.line;
break;
}
}
if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
firstFileName !== lastFileName || firstIndex >= lastIndex) {
return;
}
shouldIgnore = function(line) {
if (bluebirdFramePattern.test(line)) return true;
var info = parseLineInfo(line);
if (info) {
if (info.fileName === firstFileName &&
(firstIndex <= info.line && info.line <= lastIndex)) {
return true;
}
}
return false;
};
}
function CapturedTrace(parent) {
this._parent = parent;
this._promisesCreated = 0;
var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
captureStackTrace(this, CapturedTrace);
if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
Context.CapturedTrace = CapturedTrace;
CapturedTrace.prototype.uncycle = function() {
var length = this._length;
if (length < 2) return;
var nodes = [];
var stackToIndex = {};
for (var i = 0, node = this; node !== undefined; ++i) {
nodes.push(node);
node = node._parent;
}
length = this._length = i;
for (var i = length - 1; i >= 0; --i) {
var stack = nodes[i].stack;
if (stackToIndex[stack] === undefined) {
stackToIndex[stack] = i;
}
}
for (var i = 0; i < length; ++i) {
var currentStack = nodes[i].stack;
var index = stackToIndex[currentStack];
if (index !== undefined && index !== i) {
if (index > 0) {
nodes[index - 1]._parent = undefined;
nodes[index - 1]._length = 1;
}
nodes[i]._parent = undefined;
nodes[i]._length = 1;
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
if (index < length - 1) {
cycleEdgeNode._parent = nodes[index + 1];
cycleEdgeNode._parent.uncycle();
cycleEdgeNode._length =
cycleEdgeNode._parent._length + 1;
} else {
cycleEdgeNode._parent = undefined;
cycleEdgeNode._length = 1;
}
var currentChildLength = cycleEdgeNode._length + 1;
for (var j = i - 2; j >= 0; --j) {
nodes[j]._length = currentChildLength;
currentChildLength++;
}
return;
}
}
};
CapturedTrace.prototype.attachExtraTrace = function(error) {
if (error.__stackCleaned__) return;
this.uncycle();
var parsed = parseStackAndMessage(error);
var message = parsed.message;
var stacks = [parsed.stack];
var trace = this;
while (trace !== undefined) {
stacks.push(cleanStack(trace.stack.split("\n")));
trace = trace._parent;
}
removeCommonRoots(stacks);
removeDuplicateOrEmptyJumps(stacks);
util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
util.notEnumerableProp(error, "__stackCleaned__", true);
};
var captureStackTrace = (function stackDetection() {
var v8stackFramePattern = /^\s*at\s*/;
var v8stackFormatter = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
if (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
Error.stackTraceLimit += 6;
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
var captureStackTrace = Error.captureStackTrace;
shouldIgnore = function(line) {
return bluebirdFramePattern.test(line);
};
return function(receiver, ignoreUntil) {
Error.stackTraceLimit += 6;
captureStackTrace(receiver, ignoreUntil);
Error.stackTraceLimit -= 6;
};
}
var err = new Error();
if (typeof err.stack === "string" &&
err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
stackFramePattern = /@/;
formatStack = v8stackFormatter;
indentStackFrames = true;
return function captureStackTrace(o) {
o.stack = new Error().stack;
};
}
var hasStackAfterThrow;
try { throw new Error(); }
catch(e) {
hasStackAfterThrow = ("stack" in e);
}
if (!("stack" in err) && hasStackAfterThrow &&
typeof Error.stackTraceLimit === "number") {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {
Error.stackTraceLimit += 6;
try { throw new Error(); }
catch(e) { o.stack = e.stack; }
Error.stackTraceLimit -= 6;
};
}
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
return null;
})([]);
if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
printWarning = function (message) {
console.warn(message);
};
if (util.isNode && process.stderr.isTTY) {
printWarning = function(message, isSoft) {
var color = isSoft ? "\u001b[33m" : "\u001b[31m";
console.warn(color + message + "\u001b[0m\n");
};
} else if (!util.isNode && typeof (new Error().stack) === "string") {
printWarning = function(message, isSoft) {
console.warn("%c" + message,
isSoft ? "color: darkorange" : "color: red");
};
}
}
var config = {
warnings: warnings,
longStackTraces: false,
cancellation: false,
monitoring: false
};
if (longStackTraces) Promise.longStackTraces();
return {
longStackTraces: function() {
return config.longStackTraces;
},
warnings: function() {
return config.warnings;
},
cancellation: function() {
return config.cancellation;
},
monitoring: function() {
return config.monitoring;
},
propagateFromFunction: function() {
return propagateFromFunction;
},
boundValueFunction: function() {
return boundValueFunction;
},
checkForgottenReturns: checkForgottenReturns,
setBounds: setBounds,
warn: warn,
deprecated: deprecated,
CapturedTrace: CapturedTrace,
fireDomEvent: fireDomEvent,
fireGlobalEvent: fireGlobalEvent
};
};
},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
function returner() {
return this.value;
}
function thrower() {
throw this.reason;
}
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
returner, undefined, undefined, {value: value}, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
return this._then(
thrower, undefined, undefined, {reason: reason}, undefined);
};
Promise.prototype.catchThrow = function (reason) {
if (arguments.length <= 1) {
return this._then(
undefined, thrower, undefined, {reason: reason}, undefined);
} else {
var _reason = arguments[1];
var handler = function() {throw _reason;};
return this.caught(reason, handler);
}
};
Promise.prototype.catchReturn = function (value) {
if (arguments.length <= 1) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
undefined, returner, undefined, {value: value}, undefined);
} else {
var _value = arguments[1];
if (_value instanceof Promise) _value.suppressUnhandledRejections();
var handler = function() {return _value;};
return this.caught(value, handler);
}
};
};
},{}],11:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
var PromiseAll = Promise.all;
function promiseAllThis() {
return PromiseAll(this);
}
function PromiseMapSeries(promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
}
Promise.prototype.each = function (fn) {
return PromiseReduce(this, fn, INTERNAL, 0)
._then(promiseAllThis, undefined, undefined, this, undefined);
};
Promise.prototype.mapSeries = function (fn) {
return PromiseReduce(this, fn, INTERNAL, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, 0)
._then(promiseAllThis, undefined, undefined, promises, undefined);
};
Promise.mapSeries = PromiseMapSeries;
};
},{}],12:[function(_dereq_,module,exports){
"use strict";
var es5 = _dereq_("./es5");
var Objectfreeze = es5.freeze;
var util = _dereq_("./util");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
es5.defineProperty(AggregateError.prototype, "length", {
value: 0,
configurable: false,
writable: true,
enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
es5.defineProperty(Error, "__BluebirdErrorTypes__", {
value: errorTypes,
writable: false,
enumerable: false,
configurable: false
});
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};
},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
var isES5 = (function(){
"use strict";
return this === undefined;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
getDescriptor: Object.getOwnPropertyDescriptor,
keys: Object.keys,
names: Object.getOwnPropertyNames,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5,
propertyIsWritable: function(obj, prop) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return !!(!descriptor || descriptor.writable || descriptor.set);
}
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function (o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
};
var ObjectGetDescriptor = function(o, key) {
return {value: o[key]};
};
var ObjectDefineProperty = function (o, key, desc) {
o[key] = desc.value;
return o;
};
var ObjectFreeze = function (obj) {
return obj;
};
var ObjectGetPrototypeOf = function (obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
};
var ArrayIsArray = function (obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
};
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
names: ObjectKeys,
defineProperty: ObjectDefineProperty,
getDescriptor: ObjectGetDescriptor,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5,
propertyIsWritable: function() {
return true;
}
};
}
},{}],14:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseMap = Promise.map;
Promise.prototype.filter = function (fn, options) {
return PromiseMap(this, fn, options, INTERNAL);
};
Promise.filter = function (promises, fn, options) {
return PromiseMap(promises, fn, options, INTERNAL);
};
};
},{}],15:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, tryConvertToPromise) {
var util = _dereq_("./util");
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
function PassThroughHandlerContext(promise, type, handler) {
this.promise = promise;
this.type = type;
this.handler = handler;
this.called = false;
this.cancelPromise = null;
}
PassThroughHandlerContext.prototype.isFinallyHandler = function() {
return this.type === 0;
};
function FinallyHandlerCancelReaction(finallyHandler) {
this.finallyHandler = finallyHandler;
}
FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
checkCancel(this.finallyHandler);
};
function checkCancel(ctx, reason) {
if (ctx.cancelPromise != null) {
if (arguments.length > 1) {
ctx.cancelPromise._reject(reason);
} else {
ctx.cancelPromise._cancel();
}
ctx.cancelPromise = null;
return true;
}
return false;
}
function succeed() {
return finallyHandler.call(this, this.promise._target()._settledValue());
}
function fail(reason) {
if (checkCancel(this, reason)) return;
errorObj.e = reason;
return errorObj;
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
if (!this.called) {
this.called = true;
var ret = this.isFinallyHandler()
? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue);
if (ret !== undefined) {
promise._setReturnedNonUndefined();
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
if (this.cancelPromise != null) {
if (maybePromise._isCancelled()) {
var reason =
new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
errorObj.e = reason;
return errorObj;
} else if (maybePromise.isPending()) {
maybePromise._attachCancellationCallback(
new FinallyHandlerCancelReaction(this));
}
}
return maybePromise._then(
succeed, fail, undefined, this, undefined);
}
}
}
if (promise.isRejected()) {
checkCancel(this);
errorObj.e = reasonOrValue;
return errorObj;
} else {
checkCancel(this);
return reasonOrValue;
}
}
Promise.prototype._passThrough = function(handler, type, success, fail) {
if (typeof handler !== "function") return this.then();
return this._then(success,
fail,
undefined,
new PassThroughHandlerContext(this, type, handler),
undefined);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function (handler) {
return this._passThrough(handler,
0,
finallyHandler,
finallyHandler);
};
Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler);
};
return PassThroughHandlerContext;
};
},{"./util":36}],16:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
apiRejection,
INTERNAL,
tryConvertToPromise,
Proxyable,
debug) {
var errors = _dereq_("./errors");
var TypeError = errors.TypeError;
var util = _dereq_("./util");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var yieldHandlers = [];
function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
for (var i = 0; i < yieldHandlers.length; ++i) {
traceParent._pushContext();
var result = tryCatch(yieldHandlers[i])(value);
traceParent._popContext();
if (result === errorObj) {
traceParent._pushContext();
var ret = Promise.reject(errorObj.e);
traceParent._popContext();
return ret;
}
var maybePromise = tryConvertToPromise(result, traceParent);
if (maybePromise instanceof Promise) return maybePromise;
}
return null;
}
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
if (debug.cancellation()) {
var internal = new Promise(INTERNAL);
var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
this._promise = internal.lastly(function() {
return _finallyPromise;
});
internal._captureStackTrace();
internal._setOnCancel(this);
} else {
var promise = this._promise = new Promise(INTERNAL);
promise._captureStackTrace();
}
this._stack = stack;
this._generatorFunction = generatorFunction;
this._receiver = receiver;
this._generator = undefined;
this._yieldHandlers = typeof yieldHandler === "function"
? [yieldHandler].concat(yieldHandlers)
: yieldHandlers;
this._yieldedPromise = null;
this._cancellationPhase = false;
}
util.inherits(PromiseSpawn, Proxyable);
PromiseSpawn.prototype._isResolved = function() {
return this._promise === null;
};
PromiseSpawn.prototype._cleanup = function() {
this._promise = this._generator = null;
if (debug.cancellation() && this._finallyPromise !== null) {
this._finallyPromise._fulfill();
this._finallyPromise = null;
}
};
PromiseSpawn.prototype._promiseCancelled = function() {
if (this._isResolved()) return;
var implementsReturn = typeof this._generator["return"] !== "undefined";
var result;
if (!implementsReturn) {
var reason = new Promise.CancellationError(
"generator .return() sentinel");
Promise.coroutine.returnSentinel = reason;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
result = tryCatch(this._generator["throw"]).call(this._generator,
reason);
this._promise._popContext();
} else {
this._promise._pushContext();
result = tryCatch(this._generator["return"]).call(this._generator,
undefined);
this._promise._popContext();
}
this._cancellationPhase = true;
this._yieldedPromise = null;
this._continue(result);
};
PromiseSpawn.prototype._promiseFulfilled = function(value) {
this._yieldedPromise = null;
this._promise._pushContext();
var result = tryCatch(this._generator.next).call(this._generator, value);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._promiseRejected = function(reason) {
this._yieldedPromise = null;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
var result = tryCatch(this._generator["throw"])
.call(this._generator, reason);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._resultCancelled = function() {
if (this._yieldedPromise instanceof Promise) {
var promise = this._yieldedPromise;
this._yieldedPromise = null;
promise.cancel();
}
};
PromiseSpawn.prototype.promise = function () {
return this._promise;
};
PromiseSpawn.prototype._run = function () {
this._generator = this._generatorFunction.call(this._receiver);
this._receiver =
this._generatorFunction = undefined;
this._promiseFulfilled(undefined);
};
PromiseSpawn.prototype._continue = function (result) {
var promise = this._promise;
if (result === errorObj) {
this._cleanup();
if (this._cancellationPhase) {
return promise.cancel();
} else {
return promise._rejectCallback(result.e, false);
}
}
var value = result.value;
if (result.done === true) {
this._cleanup();
if (this._cancellationPhase) {
return promise.cancel();
} else {
return promise._resolveCallback(value);
}
} else {
var maybePromise = tryConvertToPromise(value, this._promise);
if (!(maybePromise instanceof Promise)) {
maybePromise =
promiseFromYieldHandler(maybePromise,
this._yieldHandlers,
this._promise);
if (maybePromise === null) {
this._promiseRejected(
new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
"From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n")
)
);
return;
}
}
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
this._yieldedPromise = maybePromise;
maybePromise._proxy(this, null);
} else if (((bitField & 33554432) !== 0)) {
Promise._async.invoke(
this._promiseFulfilled, this, maybePromise._value()
);
} else if (((bitField & 16777216) !== 0)) {
Promise._async.invoke(
this._promiseRejected, this, maybePromise._reason()
);
} else {
this._promiseCancelled();
}
}
};
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
var ret = spawn.promise();
spawn._generator = generator;
spawn._promiseFulfilled(undefined);
return ret;
};
};
Promise.coroutine.addYieldHandler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
debug.deprecated("Promise.spawn()", "Promise.coroutine()");
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
};
};
},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
getDomain) {
var util = _dereq_("./util");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
if (!true) {
if (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var promiseSetter = function(i) {
return new Function("promise", "holder", " \n\
'use strict'; \n\
holder.pIndex = promise; \n\
".replace(/Index/g, i));
};
var generateHolderClass = function(total) {
var props = new Array(total);
for (var i = 0; i < props.length; ++i) {
props[i] = "this.p" + (i+1);
}
var assignment = props.join(" = ") + " = null;";
var cancellationCode= "var promise;\n" + props.map(function(prop) {
return " \n\
promise = " + prop + "; \n\
if (promise instanceof Promise) { \n\
promise.cancel(); \n\
} \n\
";
}).join("\n");
var passedArguments = props.join(", ");
var name = "Holder$" + total;
var code = "return function(tryCatch, errorObj, Promise, async) { \n\
'use strict'; \n\
function [TheName](fn) { \n\
[TheProperties] \n\
this.fn = fn; \n\
this.asyncNeeded = true; \n\
this.now = 0; \n\
} \n\
\n\
[TheName].prototype._callFunction = function(promise) { \n\
promise._pushContext(); \n\
var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
promise._popContext(); \n\
if (ret === errorObj) { \n\
promise._rejectCallback(ret.e, false); \n\
} else { \n\
promise._resolveCallback(ret); \n\
} \n\
}; \n\
\n\
[TheName].prototype.checkFulfillment = function(promise) { \n\
var now = ++this.now; \n\
if (now === [TheTotal]) { \n\
if (this.asyncNeeded) { \n\
async.invoke(this._callFunction, this, promise); \n\
} else { \n\
this._callFunction(promise); \n\
} \n\
\n\
} \n\
}; \n\
\n\
[TheName].prototype._resultCancelled = function() { \n\
[CancellationCode] \n\
}; \n\
\n\
return [TheName]; \n\
}(tryCatch, errorObj, Promise, async); \n\
";
code = code.replace(/\[TheName\]/g, name)
.replace(/\[TheTotal\]/g, total)
.replace(/\[ThePassedArguments\]/g, passedArguments)
.replace(/\[TheProperties\]/g, assignment)
.replace(/\[CancellationCode\]/g, cancellationCode);
return new Function("tryCatch", "errorObj", "Promise", "async", code)
(tryCatch, errorObj, Promise, async);
};
var holderClasses = [];
var thenCallbacks = [];
var promiseSetters = [];
for (var i = 0; i < 8; ++i) {
holderClasses.push(generateHolderClass(i + 1));
thenCallbacks.push(thenCallback(i + 1));
promiseSetters.push(promiseSetter(i + 1));
}
reject = function (reason) {
this._reject(reason);
};
}}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!true) {
if (last <= 8 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var HolderClass = holderClasses[last - 1];
var holder = new HolderClass(fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
maybePromise._then(callbacks[i], reject,
undefined, ret, holder);
promiseSetters[i](maybePromise, holder);
holder.asyncNeeded = false;
} else if (((bitField & 33554432) !== 0)) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else if (((bitField & 16777216) !== 0)) {
ret._reject(maybePromise._reason());
} else {
ret._cancel();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
if (!ret._isFateSealed()) {
if (holder.asyncNeeded) {
var domain = getDomain();
if (domain !== null) {
holder.fn = util.domainBind(domain, holder.fn);
}
}
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
}
return ret;
}
}
}
var args = [].slice.call(arguments);;
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
};
};
},{"./util":36}],18:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = _dereq_("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var domain = getDomain();
this._callback = domain === null ? fn : util.domainBind(domain, fn);
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
this._limit = limit;
this._inFlight = 0;
this._queue = [];
async.invoke(this._asyncInit, this, undefined);
}
util.inherits(MappingPromiseArray, PromiseArray);
MappingPromiseArray.prototype._asyncInit = function() {
this._init$(undefined, -2);
};
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (index < 0) {
index = (index * -1) - 1;
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return true;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return false;
}
if (preservedValues !== null) preservedValues[index] = value;
var promise = this._promise;
var callback = this._callback;
var receiver = promise._boundValue();
promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
preservedValues !== null ? "Promise.filter" : "Promise.map",
promise
);
if (ret === errorObj) {
this._reject(ret.e);
return true;
}
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
if (limit >= 1) this._inFlight++;
values[index] = maybePromise;
maybePromise._proxy(this, (index + 1) * -1);
return false;
} else if (((bitField & 33554432) !== 0)) {
ret = maybePromise._value();
} else if (((bitField & 16777216) !== 0)) {
this._reject(maybePromise._reason());
return true;
} else {
this._cancel();
return true;
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
return true;
}
return false;
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var limit = 0;
if (options !== undefined) {
if (typeof options === "object" && options !== null) {
if (typeof options.concurrency !== "number") {
return Promise.reject(
new TypeError("'concurrency' must be a number but it is " +
util.classString(options.concurrency)));
}
limit = options.concurrency;
} else {
return Promise.reject(new TypeError(
"options argument must be an object but it is " +
util.classString(options)));
}
}
limit = typeof limit === "number" &&
isFinite(limit) && limit >= 1 ? limit : 0;
return new MappingPromiseArray(promises, fn, limit, _filter).promise();
}
Promise.prototype.map = function (fn, options) {
return map(this, fn, options, null);
};
Promise.map = function (promises, fn, options, _filter) {
return map(promises, fn, options, _filter);
};
};
},{"./util":36}],19:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
var util = _dereq_("./util");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.method", ret);
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value;
if (arguments.length > 1) {
debug.deprecated("calling Promise.try with more than 1 argument");
var arg = arguments[1];
var ctx = arguments[2];
value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
: tryCatch(fn).call(ctx, arg);
} else {
value = tryCatch(fn)();
}
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.try", ret);
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false);
} else {
this._resolveCallback(value, true);
}
};
};
},{"./util":36}],20:[function(_dereq_,module,exports){
"use strict";
var util = _dereq_("./util");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = _dereq_("./errors");
var OperationalError = errors.OperationalError;
var es5 = _dereq_("./es5");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
ret.name = obj.name;
ret.message = obj.message;
ret.stack = obj.stack;
var keys = es5.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!rErrorKey.test(key)) {
ret[key] = obj[key];
}
}
return ret;
}
util.markAsOriginatingFromRejection(obj);
return obj;
}
function nodebackForPromise(promise, multiArgs) {
return function(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (!multiArgs) {
promise._fulfill(value);
} else {
var args = [].slice.call(arguments, 1);;
promise._fulfill(args);
}
promise = null;
};
}
module.exports = nodebackForPromise;
},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var util = _dereq_("./util");
var async = Promise._async;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function spreadAdapter(val, nodeback) {
var promise = this;
if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
var ret =
tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function successAdapter(val, nodeback) {
var promise = this;
var receiver = promise._boundValue();
var ret = val === undefined
? tryCatch(nodeback).call(receiver, null)
: tryCatch(nodeback).call(receiver, null, val);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function errorAdapter(reason, nodeback) {
var promise = this;
if (!reason) {
var newReason = new Error(reason + "");
newReason.cause = reason;
reason = newReason;
}
var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(
adapter,
errorAdapter,
undefined,
this,
nodeback
);
}
return this;
};
};
},{"./util":36}],22:[function(_dereq_,module,exports){
"use strict";
module.exports = function() {
var makeSelfResolutionError = function () {
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var reflectHandler = function() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
return Promise.reject(new TypeError(msg));
};
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = _dereq_("./util");
var getDomain;
if (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
return null;
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var es5 = _dereq_("./es5");
var Async = _dereq_("./async");
var async = new Async();
es5.defineProperty(Promise, "_async", {value: async});
var errors = _dereq_("./errors");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
var CancellationError = Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {};
var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
var PromiseArray =
_dereq_("./promise_array")(Promise, INTERNAL,
tryConvertToPromise, apiRejection, Proxyable);
var Context = _dereq_("./context")(Promise);
/*jshint unused:false*/
var createContext = Context.create;
var debug = _dereq_("./debuggability")(Promise, Context);
var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext =
_dereq_("./finally")(Promise, tryConvertToPromise);
var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = _dereq_("./nodeback");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor));
}
if (self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
}
function Promise(executor) {
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
if (executor !== INTERNAL) {
check(this, executor);
this._resolveFromExecutor(executor);
}
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("expecting an object but got " +
"A catch statement predicate " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
};
Promise.prototype.reflect = function () {
return this._then(reflectHandler,
reflectHandler, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject) {
if (debug.warnings() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, undefined, undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject) {
var promise =
this._then(didFulfill, didReject, undefined, undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
return this.all()._then(fn, undefined, undefined, APPLY, undefined);
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
if (arguments.length > 0) {
this._warn(".all() was passed arguments but it does not take any");
}
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.getNewLibraryCopy = module.exports;
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = Promise.fromCallback = function(fn) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
: false;
var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
if (result === errorObj) {
ret._rejectCallback(result.e, true);
}
if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
return ret;
};
Promise.all = function (promises) {
return new PromiseArray(promises).promise();
};
Promise.cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._setFulfilled();
ret._rejectionHandler0 = obj;
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
return async.setScheduler(fn);
};
Promise.prototype._then = function (
didFulfill,
didReject,
_, receiver,
internalData
) {
var haveInternalData = internalData !== undefined;
var promise = haveInternalData ? internalData : new Promise(INTERNAL);
var target = this._target();
var bitField = target._bitField;
if (!haveInternalData) {
promise._propagateFrom(this, 3);
promise._captureStackTrace();
if (receiver === undefined &&
((this._bitField & 2097152) !== 0)) {
if (!((bitField & 50397184) === 0)) {
receiver = this._boundValue();
} else {
receiver = target === this ? undefined : this._boundTo;
}
}
this._fireEvent("promiseChained", this, promise);
}
var domain = getDomain();
if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) {
value = target._rejectionHandler0;
handler = didFulfill;
} else if (((bitField & 16777216) !== 0)) {
value = target._fulfillmentHandler0;
handler = didReject;
target._unsetRejectionIsUnhandled();
} else {
settler = target._settlePromiseLateCancellationObserver;
value = new CancellationError("late cancellation observer");
target._attachExtraTrace(value);
handler = didReject;
}
async.invoke(settler, target, {
handler: domain === null ? handler
: (typeof handler === "function" &&
util.domainBind(domain, handler)),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
}
return promise;
};
Promise.prototype._length = function () {
return this._bitField & 65535;
};
Promise.prototype._isFateSealed = function () {
return (this._bitField & 117506048) !== 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 67108864) === 67108864;
};
Promise.prototype._setLength = function (len) {
this._bitField = (this._bitField & -65536) |
(len & 65535);
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 33554432;
this._fireEvent("promiseFulfilled", this);
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 16777216;
this._fireEvent("promiseRejected", this);
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 67108864;
this._fireEvent("promiseResolved", this);
};
Promise.prototype._setIsFinal = function () {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._isFinal = function () {
return (this._bitField & 4194304) > 0;
};
Promise.prototype._unsetCancelled = function() {
this._bitField = this._bitField & (~65536);
};
Promise.prototype._setCancelled = function() {
this._bitField = this._bitField | 65536;
this._fireEvent("promiseCancelled", this);
};
Promise.prototype._setWillBeCancelled = function() {
this._bitField = this._bitField | 8388608;
};
Promise.prototype._setAsyncGuaranteed = function() {
if (async.hasCustomScheduler()) return;
this._bitField = this._bitField | 134217728;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0 ? this._receiver0 : this[
index * 4 - 4 + 3];
if (ret === UNDEFINED_BINDING) {
return undefined;
} else if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return this[
index * 4 - 4 + 2];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return this[
index * 4 - 4 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return this[
index * 4 - 4 + 1];
};
Promise.prototype._boundValue = function() {};
Promise.prototype._migrateCallback0 = function (follower) {
var bitField = follower._bitField;
var fulfill = follower._fulfillmentHandler0;
var reject = follower._rejectionHandler0;
var promise = follower._promise0;
var receiver = follower._receiverAt(0);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._migrateCallbackAt = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (
fulfill,
reject,
promise,
receiver,
domain
) {
var index = this._length();
if (index >= 65535 - 4) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 =
domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : util.domainBind(domain, reject);
}
} else {
var base = index * 4 - 4;
this[base + 2] = promise;
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : util.domainBind(domain, reject);
}
}
this._setLength(index + 1);
return index;
};
Promise.prototype._proxy = function (proxyable, arg) {
this._addCallbacks(undefined, undefined, arg, proxyable, null);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
if (((this._bitField & 117506048) !== 0)) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
if (promise === this) {
this._reject(makeSelfResolutionError());
return;
}
var bitField = promise._bitField;
if (((bitField & 50397184) === 0)) {
var len = this._length();
if (len > 0) promise._migrateCallback0(this);
for (var i = 1; i < len; ++i) {
promise._migrateCallbackAt(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) {
this._reject(promise._reason());
} else {
var reason = new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
this._reject(reason);
}
};
Promise.prototype._rejectCallback =
function(reason, synchronous, ignoreNonErrorWarnings) {
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
var message = "a promise was rejected with a non-error: " +
util.classString(reason);
this._warn(message, true);
}
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason);
};
Promise.prototype._resolveFromExecutor = function (executor) {
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = this._execute(executor, function(value) {
promise._resolveCallback(value);
}, function (reason) {
promise._rejectCallback(reason, synchronous);
});
synchronous = false;
this._popContext();
if (r !== undefined) {
promise._rejectCallback(r, true);
}
};
Promise.prototype._settlePromiseFromHandler = function (
handler, receiver, value, promise
) {
var bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
promise._pushContext();
var x;
if (receiver === APPLY) {
if (!value || typeof value.length !== "number") {
x = errorObj;
x.e = new TypeError("cannot .spread() a non-array: " +
util.classString(value));
} else {
x = tryCatch(handler).apply(this._boundValue(), value);
}
} else {
x = tryCatch(handler).call(receiver, value);
}
var promiseCreated = promise._popContext();
bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
if (x === NEXT_FILTER) {
promise._reject(value);
} else if (x === errorObj) {
promise._rejectCallback(x.e, false);
} else {
debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
promise._resolveCallback(x);
}
};
Promise.prototype._target = function() {
var ret = this;
while (ret._isFollowing()) ret = ret._followee();
return ret;
};
Promise.prototype._followee = function() {
return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function(promise) {
this._rejectionHandler0 = promise;
};
Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
var isPromise = promise instanceof Promise;
var bitField = this._bitField;
var asyncGuaranteed = ((bitField & 134217728) !== 0);
if (((bitField & 65536) !== 0)) {
if (isPromise) promise._invokeInternalOnCancel();
if (receiver instanceof PassThroughHandlerContext &&
receiver.isFinallyHandler()) {
receiver.cancelPromise = promise;
if (tryCatch(handler).call(receiver, value) === errorObj) {
promise._reject(errorObj.e);
}
} else if (handler === reflectHandler) {
promise._fulfill(reflectHandler.call(receiver));
} else if (receiver instanceof Proxyable) {
receiver._promiseCancelled(promise);
} else if (isPromise || promise instanceof PromiseArray) {
promise._cancel();
} else {
receiver.cancel();
}
} else if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof Proxyable) {
if (!receiver._isResolved()) {
if (((bitField & 33554432) !== 0)) {
receiver._promiseFulfilled(value, promise);
} else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
if (((bitField & 33554432) !== 0)) {
promise._fulfill(value);
} else {
promise._reject(value);
}
}
};
Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
var handler = ctx.handler;
var promise = ctx.promise;
var receiver = ctx.receiver;
var value = ctx.value;
if (typeof handler === "function") {
if (!(promise instanceof Promise)) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (promise instanceof Promise) {
promise._reject(value);
}
};
Promise.prototype._settlePromiseCtx = function(ctx) {
this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
};
Promise.prototype._settlePromise0 = function(handler, value, bitField) {
var promise = this._promise0;
var receiver = this._receiverAt(0);
this._promise0 = undefined;
this._receiver0 = undefined;
this._settlePromise(promise, handler, receiver, value);
};
Promise.prototype._clearCallbackDataAtIndex = function(index) {
var base = index * 4 - 4;
this[base + 2] =
this[base + 3] =
this[base + 0] =
this[base + 1] = undefined;
};
Promise.prototype._fulfill = function (value) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._reject(err);
}
this._setFulfilled();
this._rejectionHandler0 = value;
if ((bitField & 65535) > 0) {
if (((bitField & 134217728) !== 0)) {
this._settlePromises();
} else {
async.settlePromises(this);
}
}
};
Promise.prototype._reject = function (reason) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
this._setRejected();
this._fulfillmentHandler0 = reason;
if (this._isFinal()) {
return async.fatalError(reason, util.isNode);
}
if ((bitField & 65535) > 0) {
async.settlePromises(this);
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._fulfillPromises = function (len, value) {
for (var i = 1; i < len; i++) {
var handler = this._fulfillmentHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, value);
}
};
Promise.prototype._rejectPromises = function (len, reason) {
for (var i = 1; i < len; i++) {
var handler = this._rejectionHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, reason);
}
};
Promise.prototype._settlePromises = function () {
var bitField = this._bitField;
var len = (bitField & 65535);
if (len > 0) {
if (((bitField & 16842752) !== 0)) {
var reason = this._fulfillmentHandler0;
this._settlePromise0(this._rejectionHandler0, reason, bitField);
this._rejectPromises(len, reason);
} else {
var value = this._rejectionHandler0;
this._settlePromise0(this._fulfillmentHandler0, value, bitField);
this._fulfillPromises(len, value);
}
this._setLength(0);
}
this._clearCancellationData();
};
Promise.prototype._settledValue = function() {
var bitField = this._bitField;
if (((bitField & 33554432) !== 0)) {
return this._rejectionHandler0;
} else if (((bitField & 16777216) !== 0)) {
return this._fulfillmentHandler0;
}
};
function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);}
Promise.defer = Promise.pending = function() {
debug.deprecated("Promise.defer", "new Promise");
var promise = new Promise(INTERNAL);
return {
promise: promise,
resolve: deferResolve,
reject: deferReject
};
};
util.notEnumerableProp(Promise,
"_makeSelfResolutionError",
makeSelfResolutionError);
_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
debug);
_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
_dereq_("./direct_resolve")(Promise);
_dereq_("./synchronous_inspection")(Promise);
_dereq_("./join")(
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
Promise.Promise = Promise;
Promise.version = "3.4.7";
_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
_dereq_('./call_get.js')(Promise);
_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
_dereq_('./timers.js')(Promise, INTERNAL, debug);
_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
_dereq_('./nodeify.js')(Promise);
_dereq_('./promisify.js')(Promise, INTERNAL);
_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
_dereq_('./settle.js')(Promise, PromiseArray, debug);
_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
_dereq_('./filter.js')(Promise, INTERNAL);
_dereq_('./each.js')(Promise, INTERNAL);
_dereq_('./any.js')(Promise);
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
function fillTypes(value) {
var p = new Promise(INTERNAL);
p._fulfillmentHandler0 = value;
p._rejectionHandler0 = value;
p._promise0 = value;
p._receiver0 = value;
}
// Complete slack tracking, opt out of field-type tracking and
// stabilize map
fillTypes({a: 1});
fillTypes({b: 2});
fillTypes({c: 3});
fillTypes(1);
fillTypes(function(){});
fillTypes(undefined);
fillTypes(false);
fillTypes(new Promise(INTERNAL));
debug.setBounds(Async.firstLineError, util.lastLineError);
return Promise;
};
},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection, Proxyable) {
var util = _dereq_("./util");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) {
promise._propagateFrom(values, 3);
}
promise._setOnCancel(this);
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(undefined, -2);
}
util.inherits(PromiseArray, Proxyable);
PromiseArray.prototype.length = function () {
return this._length;
};
PromiseArray.prototype.promise = function () {
return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
var values = tryConvertToPromise(this._values, this._promise);
if (values instanceof Promise) {
values = values._target();
var bitField = values._bitField;
;
this._values = values;
if (((bitField & 50397184) === 0)) {
this._promise._setAsyncGuaranteed();
return values._then(
init,
this._reject,
undefined,
this,
resolveValueIfEmpty
);
} else if (((bitField & 33554432) !== 0)) {
values = values._value();
} else if (((bitField & 16777216) !== 0)) {
return this._reject(values._reason());
} else {
return this._cancel();
}
}
values = util.asArray(values);
if (values === null) {
var err = apiRejection(
"expecting an array or an iterable object but got " + util.classString(values)).reason();
this._promise._rejectCallback(err, false);
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
this._iterate(values);
};
PromiseArray.prototype._iterate = function(values) {
var len = this.getActualLength(values.length);
this._length = len;
this._values = this.shouldCopyValues() ? new Array(len) : this._values;
var result = this._promise;
var isResolved = false;
var bitField = null;
for (var i = 0; i < len; ++i) {
var maybePromise = tryConvertToPromise(values[i], result);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
bitField = maybePromise._bitField;
} else {
bitField = null;
}
if (isResolved) {
if (bitField !== null) {
maybePromise.suppressUnhandledRejections();
}
} else if (bitField !== null) {
if (((bitField & 50397184) === 0)) {
maybePromise._proxy(this, i);
this._values[i] = maybePromise;
} else if (((bitField & 33554432) !== 0)) {
isResolved = this._promiseFulfilled(maybePromise._value(), i);
} else if (((bitField & 16777216) !== 0)) {
isResolved = this._promiseRejected(maybePromise._reason(), i);
} else {
isResolved = this._promiseCancelled(i);
}
} else {
isResolved = this._promiseFulfilled(maybePromise, i);
}
}
if (!isResolved) result._setAsyncGuaranteed();
};
PromiseArray.prototype._isResolved = function () {
return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype._cancel = function() {
if (this._isResolved() || !this._promise._isCancellable()) return;
this._values = null;
this._promise._cancel();
};
PromiseArray.prototype._reject = function (reason) {
this._values = null;
this._promise._rejectCallback(reason, false);
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
PromiseArray.prototype._promiseCancelled = function() {
this._cancel();
return true;
};
PromiseArray.prototype._promiseRejected = function (reason) {
this._totalResolved++;
this._reject(reason);
return true;
};
PromiseArray.prototype._resultCancelled = function() {
if (this._isResolved()) return;
var values = this._values;
this._cancel();
if (values instanceof Promise) {
values.cancel();
} else {
for (var i = 0; i < values.length; ++i) {
if (values[i] instanceof Promise) {
values[i].cancel();
}
}
}
};
PromiseArray.prototype.shouldCopyValues = function () {
return true;
};
PromiseArray.prototype.getActualLength = function (len) {
return len;
};
return PromiseArray;
};
},{"./util":36}],24:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var THIS = {};
var util = _dereq_("./util");
var nodebackForPromise = _dereq_("./nodeback");
var withAppended = util.withAppended;
var maybeWrapAsError = util.maybeWrapAsError;
var canEvaluate = util.canEvaluate;
var TypeError = _dereq_("./errors").TypeError;
var defaultSuffix = "Async";
var defaultPromisified = {__isPromisified__: true};
var noCopyProps = [
"arity", "length",
"name",
"arguments",
"caller",
"callee",
"prototype",
"__isPromisified__"
];
var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
var defaultFilter = function(name) {
return util.isIdentifier(name) &&
name.charAt(0) !== "_" &&
name !== "constructor";
};
function propsFilter(key) {
return !noCopyPropsPattern.test(key);
}
function isPromisified(fn) {
try {
return fn.__isPromisified__ === true;
}
catch (e) {
return false;
}
}
function hasPromisified(obj, key, suffix) {
var val = util.getDataPropertyOrDefault(obj, key + suffix,
defaultPromisified);
return val ? isPromisified(val) : false;
}
function checkValid(ret, suffix, suffixRegexp) {
for (var i = 0; i < ret.length; i += 2) {
var key = ret[i];
if (suffixRegexp.test(key)) {
var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
for (var j = 0; j < ret.length; j += 2) {
if (ret[j] === keyWithoutAsyncSuffix) {
throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
.replace("%s", suffix));
}
}
}
}
}
function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
var keys = util.inheritedDataKeys(obj);
var ret = [];
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = obj[key];
var passesDefaultFilter = filter === defaultFilter
? true : defaultFilter(key, value, obj);
if (typeof value === "function" &&
!isPromisified(value) &&
!hasPromisified(obj, key, suffix) &&
filter(key, value, obj, passesDefaultFilter)) {
ret.push(key, value);
}
}
checkValid(ret, suffix, suffixRegexp);
return ret;
}
var escapeIdentRegex = function(str) {
return str.replace(/([$])/, "\\$");
};
var makeNodePromisifiedEval;
if (!true) {
var switchCaseArgumentOrder = function(likelyArgumentCount) {
var ret = [likelyArgumentCount];
var min = Math.max(0, likelyArgumentCount - 1 - 3);
for(var i = likelyArgumentCount - 1; i >= min; --i) {
ret.push(i);
}
for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
ret.push(i);
}
return ret;
};
var argumentSequence = function(argumentCount) {
return util.filledRange(argumentCount, "_arg", "");
};
var parameterDeclaration = function(parameterCount) {
return util.filledRange(
Math.max(parameterCount, 3), "_arg", "");
};
var parameterCount = function(fn) {
if (typeof fn.length === "number") {
return Math.max(Math.min(fn.length, 1023 + 1), 0);
}
return 0;
};
makeNodePromisifiedEval =
function(callback, receiver, originalName, fn, _, multiArgs) {
var newParameterCount = Math.max(0, parameterCount(fn) - 1);
var argumentOrder = switchCaseArgumentOrder(newParameterCount);
var shouldProxyThis = typeof callback === "string" || receiver === THIS;
function generateCallForArgumentCount(count) {
var args = argumentSequence(count).join(", ");
var comma = count > 0 ? ", " : "";
var ret;
if (shouldProxyThis) {
ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
} else {
ret = receiver === undefined
? "ret = callback({{args}}, nodeback); break;\n"
: "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
}
return ret.replace("{{args}}", args).replace(", ", comma);
}
function generateArgumentSwitchCase() {
var ret = "";
for (var i = 0; i < argumentOrder.length; ++i) {
ret += "case " + argumentOrder[i] +":" +
generateCallForArgumentCount(argumentOrder[i]);
}
ret += " \n\
default: \n\
var args = new Array(len + 1); \n\
var i = 0; \n\
for (var i = 0; i < len; ++i) { \n\
args[i] = arguments[i]; \n\
} \n\
args[i] = nodeback; \n\
[CodeForCall] \n\
break; \n\
".replace("[CodeForCall]", (shouldProxyThis
? "ret = callback.apply(this, args);\n"
: "ret = callback.apply(receiver, args);\n"));
return ret;
}
var getFunctionCode = typeof callback === "string"
? ("this != null ? this['"+callback+"'] : fn")
: "fn";
var body = "'use strict'; \n\
var ret = function (Parameters) { \n\
'use strict'; \n\
var len = arguments.length; \n\
var promise = new Promise(INTERNAL); \n\
promise._captureStackTrace(); \n\
var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
var ret; \n\
var callback = tryCatch([GetFunctionCode]); \n\
switch(len) { \n\
[CodeForSwitchCase] \n\
} \n\
if (ret === errorObj) { \n\
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
} \n\
if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
return promise; \n\
}; \n\
notEnumerableProp(ret, '__isPromisified__', true); \n\
return ret; \n\
".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
.replace("[GetFunctionCode]", getFunctionCode);
body = body.replace("Parameters", parameterDeclaration(newParameterCount));
return new Function("Promise",
"fn",
"receiver",
"withAppended",
"maybeWrapAsError",
"nodebackForPromise",
"tryCatch",
"errorObj",
"notEnumerableProp",
"INTERNAL",
body)(
Promise,
fn,
receiver,
withAppended,
maybeWrapAsError,
nodebackForPromise,
util.tryCatch,
util.errorObj,
util.notEnumerableProp,
INTERNAL);
};
}
function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
var defaultThis = (function() {return this;})();
var method = callback;
if (typeof method === "string") {
callback = fn;
}
function promisified() {
var _receiver = receiver;
if (receiver === THIS) _receiver = this;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var cb = typeof method === "string" && this !== defaultThis
? this[method] : callback;
var fn = nodebackForPromise(promise, multiArgs);
try {
cb.apply(_receiver, withAppended(arguments, fn));
} catch(e) {
promise._rejectCallback(maybeWrapAsError(e), true, true);
}
if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
return promise;
}
util.notEnumerableProp(promisified, "__isPromisified__", true);
return promisified;
}
var makeNodePromisified = canEvaluate
? makeNodePromisifiedEval
: makeNodePromisifiedClosure;
function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
var methods =
promisifiableMethods(obj, suffix, suffixRegexp, filter);
for (var i = 0, len = methods.length; i < len; i+= 2) {
var key = methods[i];
var fn = methods[i+1];
var promisifiedKey = key + suffix;
if (promisifier === makeNodePromisified) {
obj[promisifiedKey] =
makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
} else {
var promisified = promisifier(fn, function() {
return makeNodePromisified(key, THIS, key,
fn, suffix, multiArgs);
});
util.notEnumerableProp(promisified, "__isPromisified__", true);
obj[promisifiedKey] = promisified;
}
}
util.toFastProperties(obj);
return obj;
}
function promisify(callback, receiver, multiArgs) {
return makeNodePromisified(callback, receiver, undefined,
callback, null, multiArgs);
}
Promise.promisify = function (fn, options) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
if (isPromisified(fn)) {
return fn;
}
options = Object(options);
var receiver = options.context === undefined ? THIS : options.context;
var multiArgs = !!options.multiArgs;
var ret = promisify(fn, receiver, multiArgs);
util.copyDescriptors(fn, ret, propsFilter);
return ret;
};
Promise.promisifyAll = function (target, options) {
if (typeof target !== "function" && typeof target !== "object") {
throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
options = Object(options);
var multiArgs = !!options.multiArgs;
var suffix = options.suffix;
if (typeof suffix !== "string") suffix = defaultSuffix;
var filter = options.filter;
if (typeof filter !== "function") filter = defaultFilter;
var promisifier = options.promisifier;
if (typeof promisifier !== "function") promisifier = makeNodePromisified;
if (!util.isIdentifier(suffix)) {
throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var keys = util.inheritedDataKeys(target);
for (var i = 0; i < keys.length; ++i) {
var value = target[keys[i]];
if (keys[i] !== "constructor" &&
util.isClass(value)) {
promisifyAll(value.prototype, suffix, filter, promisifier,
multiArgs);
promisifyAll(value, suffix, filter, promisifier, multiArgs);
}
}
return promisifyAll(target, suffix, filter, promisifier, multiArgs);
};
};
},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
"use strict";
module.exports = function(
Promise, PromiseArray, tryConvertToPromise, apiRejection) {
var util = _dereq_("./util");
var isObject = util.isObject;
var es5 = _dereq_("./es5");
var Es6Map;
if (typeof Map === "function") Es6Map = Map;
var mapToEntries = (function() {
var index = 0;
var size = 0;
function extractEntry(value, key) {
this[index] = value;
this[index + size] = key;
index++;
}
return function mapToEntries(map) {
size = map.size;
index = 0;
var ret = new Array(map.size * 2);
map.forEach(extractEntry, ret);
return ret;
};
})();
var entriesToMap = function(entries) {
var ret = new Es6Map();
var length = entries.length / 2 | 0;
for (var i = 0; i < length; ++i) {
var key = entries[length + i];
var value = entries[i];
ret.set(key, value);
}
return ret;
};
function PropertiesPromiseArray(obj) {
var isMap = false;
var entries;
if (Es6Map !== undefined && obj instanceof Es6Map) {
entries = mapToEntries(obj);
isMap = true;
} else {
var keys = es5.keys(obj);
var len = keys.length;
entries = new Array(len * 2);
for (var i = 0; i < len; ++i) {
var key = keys[i];
entries[i] = obj[key];
entries[i + len] = key;
}
}
this.constructor$(entries);
this._isMap = isMap;
this._init$(undefined, -3);
}
util.inherits(PropertiesPromiseArray, PromiseArray);
PropertiesPromiseArray.prototype._init = function () {};
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
var val;
if (this._isMap) {
val = entriesToMap(this._values);
} else {
val = {};
var keyOffset = this.length();
for (var i = 0, len = this.length(); i < len; ++i) {
val[this._values[i + keyOffset]] = this._values[i];
}
}
this._resolve(val);
return true;
}
return false;
};
PropertiesPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
PropertiesPromiseArray.prototype.getActualLength = function (len) {
return len >> 1;
};
function props(promises) {
var ret;
var castValue = tryConvertToPromise(promises);
if (!isObject(castValue)) {
return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
} else if (castValue instanceof Promise) {
ret = castValue._then(
Promise.props, undefined, undefined, undefined, undefined);
} else {
ret = new PropertiesPromiseArray(castValue).promise();
}
if (castValue instanceof Promise) {
ret._propagateFrom(castValue, 2);
}
return ret;
}
Promise.prototype.props = function () {
return props(this);
};
Promise.props = function (promises) {
return props(promises);
};
};
},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
"use strict";
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
}
Queue.prototype._willBeOverCapacity = function (size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = arg;
this._length = length + 1;
};
Queue.prototype.push = function (fn, receiver, arg) {
var length = this.length() + 3;
if (this._willBeOverCapacity(length)) {
this._pushOne(fn);
this._pushOne(receiver);
this._pushOne(arg);
return;
}
var j = this._front + length - 3;
this._checkCapacity(length);
var wrapMask = this._capacity - 1;
this[(j + 0) & wrapMask] = fn;
this[(j + 1) & wrapMask] = receiver;
this[(j + 2) & wrapMask] = arg;
this._length = length;
};
Queue.prototype.shift = function () {
var front = this._front,
ret = this[front];
this[front] = undefined;
this._front = (front + 1) & (this._capacity - 1);
this._length--;
return ret;
};
Queue.prototype.length = function () {
return this._length;
};
Queue.prototype._checkCapacity = function (size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 1);
}
};
Queue.prototype._resizeTo = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
var length = this._length;
var moveItemsCount = (front + length) & (oldCapacity - 1);
arrayMove(this, 0, this, oldCapacity, moveItemsCount);
};
module.exports = Queue;
},{}],27:[function(_dereq_,module,exports){
"use strict";
module.exports = function(
Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = _dereq_("./util");
var raceLater = function (promise) {
return promise.then(function(array) {
return race(array, promise);
});
};
function race(promises, parent) {
var maybePromise = tryConvertToPromise(promises);
if (maybePromise instanceof Promise) {
return raceLater(maybePromise);
} else {
promises = util.asArray(promises);
if (promises === null)
return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
}
var ret = new Promise(INTERNAL);
if (parent !== undefined) {
ret._propagateFrom(parent, 3);
}
var fulfill = ret._fulfill;
var reject = ret._reject;
for (var i = 0, len = promises.length; i < len; ++i) {
var val = promises[i];
if (val === undefined && !(i in promises)) {
continue;
}
Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
}
return ret;
}
Promise.race = function (promises) {
return race(promises, undefined);
};
Promise.prototype.race = function () {
return race(this, undefined);
};
};
},{"./util":36}],28:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = _dereq_("./util");
var tryCatch = util.tryCatch;
function ReductionPromiseArray(promises, fn, initialValue, _each) {
this.constructor$(promises);
var domain = getDomain();
this._fn = domain === null ? fn : util.domainBind(domain, fn);
if (initialValue !== undefined) {
initialValue = Promise.resolve(initialValue);
initialValue._attachCancellationCallback(this);
}
this._initialValue = initialValue;
this._currentCancellable = null;
if(_each === INTERNAL) {
this._eachValues = Array(this._length);
} else if (_each === 0) {
this._eachValues = null;
} else {
this._eachValues = undefined;
}
this._promise._captureStackTrace();
this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._gotAccum = function(accum) {
if (this._eachValues !== undefined &&
this._eachValues !== null &&
accum !== INTERNAL) {
this._eachValues.push(accum);
}
};
ReductionPromiseArray.prototype._eachComplete = function(value) {
if (this._eachValues !== null) {
this._eachValues.push(value);
}
return this._eachValues;
};
ReductionPromiseArray.prototype._init = function() {};
ReductionPromiseArray.prototype._resolveEmptyArray = function() {
this._resolve(this._eachValues !== undefined ? this._eachValues
: this._initialValue);
};
ReductionPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
ReductionPromiseArray.prototype._resolve = function(value) {
this._promise._resolveCallback(value);
this._values = null;
};
ReductionPromiseArray.prototype._resultCancelled = function(sender) {
if (sender === this._initialValue) return this._cancel();
if (this._isResolved()) return;
this._resultCancelled$();
if (this._currentCancellable instanceof Promise) {
this._currentCancellable.cancel();
}
if (this._initialValue instanceof Promise) {
this._initialValue.cancel();
}
};
ReductionPromiseArray.prototype._iterate = function (values) {
this._values = values;
var value;
var i;
var length = values.length;
if (this._initialValue !== undefined) {
value = this._initialValue;
i = 0;
} else {
value = Promise.resolve(values[0]);
i = 1;
}
this._currentCancellable = value;
if (!value.isRejected()) {
for (; i < length; ++i) {
var ctx = {
accum: null,
value: values[i],
index: i,
length: length,
array: this
};
value = value._then(gotAccum, undefined, undefined, ctx, undefined);
}
}
if (this._eachValues !== undefined) {
value = value
._then(this._eachComplete, undefined, undefined, this, undefined);
}
value._then(completed, completed, undefined, value, this);
};
Promise.prototype.reduce = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
};
function completed(valueOrReason, array) {
if (this.isFulfilled()) {
array._resolve(valueOrReason);
} else {
array._reject(valueOrReason);
}
}
function reduce(promises, fn, initialValue, _each) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
return array.promise();
}
function gotAccum(accum) {
this.accum = accum;
this.array._gotAccum(accum);
var value = tryConvertToPromise(this.value, this.array._promise);
if (value instanceof Promise) {
this.array._currentCancellable = value;
return value._then(gotValue, undefined, undefined, this, undefined);
} else {
return gotValue.call(this, value);
}
}
function gotValue(value) {
var array = this.array;
var promise = array._promise;
var fn = tryCatch(array._fn);
promise._pushContext();
var ret;
if (array._eachValues !== undefined) {
ret = fn.call(promise._boundValue(), value, this.index, this.length);
} else {
ret = fn.call(promise._boundValue(),
this.accum, value, this.index, this.length);
}
if (ret instanceof Promise) {
array._currentCancellable = ret;
}
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
promise
);
return ret;
}
};
},{"./util":36}],29:[function(_dereq_,module,exports){
"use strict";
var util = _dereq_("./util");
var schedule;
var noAsyncScheduler = function() {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var NativePromise = util.getNativePromise();
if (util.isNode && typeof MutationObserver === "undefined") {
var GlobalSetImmediate = global.setImmediate;
var ProcessNextTick = process.nextTick;
schedule = util.isRecentNode
? function(fn) { GlobalSetImmediate.call(global, fn); }
: function(fn) { ProcessNextTick.call(process, fn); };
} else if (typeof NativePromise === "function" &&
typeof NativePromise.resolve === "function") {
var nativePromise = NativePromise.resolve();
schedule = function(fn) {
nativePromise.then(fn);
};
} else if ((typeof MutationObserver !== "undefined") &&
!(typeof window !== "undefined" &&
window.navigator &&
(window.navigator.standalone || window.cordova))) {
schedule = (function() {
var div = document.createElement("div");
var opts = {attributes: true};
var toggleScheduled = false;
var div2 = document.createElement("div");
var o2 = new MutationObserver(function() {
div.classList.toggle("foo");
toggleScheduled = false;
});
o2.observe(div2, opts);
var scheduleToggle = function() {
if (toggleScheduled) return;
toggleScheduled = true;
div2.classList.toggle("foo");
};
return function schedule(fn) {
var o = new MutationObserver(function() {
o.disconnect();
fn();
});
o.observe(div, opts);
scheduleToggle();
};
})();
} else if (typeof setImmediate !== "undefined") {
schedule = function (fn) {
setImmediate(fn);
};
} else if (typeof setTimeout !== "undefined") {
schedule = function (fn) {
setTimeout(fn, 0);
};
} else {
schedule = noAsyncScheduler;
}
module.exports = schedule;
},{"./util":36}],30:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, debug) {
var PromiseInspection = Promise.PromiseInspection;
var util = _dereq_("./util");
function SettledPromiseArray(values) {
this.constructor$(values);
}
util.inherits(SettledPromiseArray, PromiseArray);
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
this._values[index] = inspection;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
var ret = new PromiseInspection();
ret._bitField = 33554432;
ret._settledValueField = value;
return this._promiseResolved(index, ret);
};
SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
var ret = new PromiseInspection();
ret._bitField = 16777216;
ret._settledValueField = reason;
return this._promiseResolved(index, ret);
};
Promise.settle = function (promises) {
debug.deprecated(".settle()", ".reflect()");
return new SettledPromiseArray(promises).promise();
};
Promise.prototype.settle = function () {
return Promise.settle(this);
};
};
},{"./util":36}],31:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, apiRejection) {
var util = _dereq_("./util");
var RangeError = _dereq_("./errors").RangeError;
var AggregateError = _dereq_("./errors").AggregateError;
var isArray = util.isArray;
var CANCELLATION = {};
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}
util.inherits(SomePromiseArray, PromiseArray);
SomePromiseArray.prototype._init = function () {
if (!this._initialized) {
return;
}
if (this._howMany === 0) {
this._resolve([]);
return;
}
this._init$(undefined, -5);
var isArrayResolved = isArray(this._values);
if (!this._isResolved() &&
isArrayResolved &&
this._howMany > this._canPossiblyFulfill()) {
this._reject(this._getRangeError(this.length()));
}
};
SomePromiseArray.prototype.init = function () {
this._initialized = true;
this._init();
};
SomePromiseArray.prototype.setUnwrap = function () {
this._unwrap = true;
};
SomePromiseArray.prototype.howMany = function () {
return this._howMany;
};
SomePromiseArray.prototype.setHowMany = function (count) {
this._howMany = count;
};
SomePromiseArray.prototype._promiseFulfilled = function (value) {
this._addFulfilled(value);
if (this._fulfilled() === this.howMany()) {
this._values.length = this.howMany();
if (this.howMany() === 1 && this._unwrap) {
this._resolve(this._values[0]);
} else {
this._resolve(this._values);
}
return true;
}
return false;
};
SomePromiseArray.prototype._promiseRejected = function (reason) {
this._addRejected(reason);
return this._checkOutcome();
};
SomePromiseArray.prototype._promiseCancelled = function () {
if (this._values instanceof Promise || this._values == null) {
return this._cancel();
}
this._addRejected(CANCELLATION);
return this._checkOutcome();
};
SomePromiseArray.prototype._checkOutcome = function() {
if (this.howMany() > this._canPossiblyFulfill()) {
var e = new AggregateError();
for (var i = this.length(); i < this._values.length; ++i) {
if (this._values[i] !== CANCELLATION) {
e.push(this._values[i]);
}
}
if (e.length > 0) {
this._reject(e);
} else {
this._cancel();
}
return true;
}
return false;
};
SomePromiseArray.prototype._fulfilled = function () {
return this._totalResolved;
};
SomePromiseArray.prototype._rejected = function () {
return this._values.length - this.length();
};
SomePromiseArray.prototype._addRejected = function (reason) {
this._values.push(reason);
};
SomePromiseArray.prototype._addFulfilled = function (value) {
this._values[this._totalResolved++] = value;
};
SomePromiseArray.prototype._canPossiblyFulfill = function () {
return this.length() - this._rejected();
};
SomePromiseArray.prototype._getRangeError = function (count) {
var message = "Input array must contain at least " +
this._howMany + " items but contains only " + count + " items";
return new RangeError(message);
};
SomePromiseArray.prototype._resolveEmptyArray = function () {
this._reject(this._getRangeError(0));
};
function some(promises, howMany) {
if ((howMany | 0) !== howMany || howMany < 0) {
return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(howMany);
ret.init();
return promise;
}
Promise.some = function (promises, howMany) {
return some(promises, howMany);
};
Promise.prototype.some = function (howMany) {
return some(this, howMany);
};
Promise._SomePromiseArray = SomePromiseArray;
};
},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed()
? promise._settledValue() : undefined;
}
else {
this._bitField = 0;
this._settledValueField = undefined;
}
}
PromiseInspection.prototype._settledValue = function() {
return this._settledValueField;
};
var value = PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var reason = PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
return (this._bitField & 33554432) !== 0;
};
var isRejected = PromiseInspection.prototype.isRejected = function () {
return (this._bitField & 16777216) !== 0;
};
var isPending = PromiseInspection.prototype.isPending = function () {
return (this._bitField & 50397184) === 0;
};
var isResolved = PromiseInspection.prototype.isResolved = function () {
return (this._bitField & 50331648) !== 0;
};
PromiseInspection.prototype.isCancelled = function() {
return (this._bitField & 8454144) !== 0;
};
Promise.prototype.__isCancelled = function() {
return (this._bitField & 65536) === 65536;
};
Promise.prototype._isCancelled = function() {
return this._target().__isCancelled();
};
Promise.prototype.isCancelled = function() {
return (this._target()._bitField & 8454144) !== 0;
};
Promise.prototype.isPending = function() {
return isPending.call(this._target());
};
Promise.prototype.isRejected = function() {
return isRejected.call(this._target());
};
Promise.prototype.isFulfilled = function() {
return isFulfilled.call(this._target());
};
Promise.prototype.isResolved = function() {
return isResolved.call(this._target());
};
Promise.prototype.value = function() {
return value.call(this._target());
};
Promise.prototype.reason = function() {
var target = this._target();
target._unsetRejectionIsUnhandled();
return reason.call(target);
};
Promise.prototype._value = function() {
return this._settledValue();
};
Promise.prototype._reason = function() {
this._unsetRejectionIsUnhandled();
return this._settledValue();
};
Promise.PromiseInspection = PromiseInspection;
};
},{}],33:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = _dereq_("./util");
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
if (obj instanceof Promise) return obj;
var then = getThen(obj);
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(
ret._fulfill,
ret._reject,
undefined,
ret,
null
);
return ret;
}
return doThenable(obj, then, context);
}
}
return obj;
}
function doGetThen(obj) {
return obj.then;
}
function getThen(obj) {
try {
return doGetThen(obj);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
try {
return hasProp.call(obj, "_promise0");
} catch (e) {
return false;
}
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
var result = util.tryCatch(then).call(x, resolve, reject);
synchronous = false;
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
function resolve(value) {
if (!promise) return;
promise._resolveCallback(value);
promise = null;
}
function reject(reason) {
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
return ret;
}
return tryConvertToPromise;
};
},{"./util":36}],34:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, debug) {
var util = _dereq_("./util");
var TimeoutError = Promise.TimeoutError;
function HandleWrapper(handle) {
this.handle = handle;
}
HandleWrapper.prototype._resultCancelled = function() {
clearTimeout(this.handle);
};
var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (ms, value) {
var ret;
var handle;
if (value !== undefined) {
ret = Promise.resolve(value)
._then(afterValue, null, null, ms, undefined);
if (debug.cancellation() && value instanceof Promise) {
ret._setOnCancel(value);
}
} else {
ret = new Promise(INTERNAL);
handle = setTimeout(function() { ret._fulfill(); }, +ms);
if (debug.cancellation()) {
ret._setOnCancel(new HandleWrapper(handle));
}
ret._captureStackTrace();
}
ret._setAsyncGuaranteed();
return ret;
};
Promise.prototype.delay = function (ms) {
return delay(ms, this);
};
var afterTimeout = function (promise, message, parent) {
var err;
if (typeof message !== "string") {
if (message instanceof Error) {
err = message;
} else {
err = new TimeoutError("operation timed out");
}
} else {
err = new TimeoutError(message);
}
util.markAsOriginatingFromRejection(err);
promise._attachExtraTrace(err);
promise._reject(err);
if (parent != null) {
parent.cancel();
}
};
function successClear(value) {
clearTimeout(this.handle);
return value;
}
function failureClear(reason) {
clearTimeout(this.handle);
throw reason;
}
Promise.prototype.timeout = function (ms, message) {
ms = +ms;
var ret, parent;
var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
if (ret.isPending()) {
afterTimeout(ret, message, parent);
}
}, ms));
if (debug.cancellation()) {
parent = this.then();
ret = parent._then(successClear, failureClear,
undefined, handleWrapper, undefined);
ret._setOnCancel(handleWrapper);
} else {
ret = this._then(successClear, failureClear,
undefined, handleWrapper, undefined);
}
return ret;
};
};
},{"./util":36}],35:[function(_dereq_,module,exports){
"use strict";
module.exports = function (Promise, apiRejection, tryConvertToPromise,
createContext, INTERNAL, debug) {
var util = _dereq_("./util");
var TypeError = _dereq_("./errors").TypeError;
var inherits = _dereq_("./util").inherits;
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var NULL = {};
function thrower(e) {
setTimeout(function(){throw e;}, 0);
}
function castPreservingDisposable(thenable) {
var maybePromise = tryConvertToPromise(thenable);
if (maybePromise !== thenable &&
typeof thenable._isDisposable === "function" &&
typeof thenable._getDisposer === "function" &&
thenable._isDisposable()) {
maybePromise._setDisposable(thenable._getDisposer());
}
return maybePromise;
}
function dispose(resources, inspection) {
var i = 0;
var len = resources.length;
var ret = new Promise(INTERNAL);
function iterator() {
if (i >= len) return ret._fulfill();
var maybePromise = castPreservingDisposable(resources[i++]);
if (maybePromise instanceof Promise &&
maybePromise._isDisposable()) {
try {
maybePromise = tryConvertToPromise(
maybePromise._getDisposer().tryDispose(inspection),
resources.promise);
} catch (e) {
return thrower(e);
}
if (maybePromise instanceof Promise) {
return maybePromise._then(iterator, thrower,
null, null, null);
}
}
iterator();
}
iterator();
return ret;
}
function Disposer(data, promise, context) {
this._data = data;
this._promise = promise;
this._context = context;
}
Disposer.prototype.data = function () {
return this._data;
};
Disposer.prototype.promise = function () {
return this._promise;
};
Disposer.prototype.resource = function () {
if (this.promise().isFulfilled()) {
return this.promise().value();
}
return NULL;
};
Disposer.prototype.tryDispose = function(inspection) {
var resource = this.resource();
var context = this._context;
if (context !== undefined) context._pushContext();
var ret = resource !== NULL
? this.doDispose(resource, inspection) : null;
if (context !== undefined) context._popContext();
this._promise._unsetDisposable();
this._data = null;
return ret;
};
Disposer.isDisposer = function (d) {
return (d != null &&
typeof d.resource === "function" &&
typeof d.tryDispose === "function");
};
function FunctionDisposer(fn, promise, context) {
this.constructor$(fn, promise, context);
}
inherits(FunctionDisposer, Disposer);
FunctionDisposer.prototype.doDispose = function (resource, inspection) {
var fn = this.data();
return fn.call(resource, resource, inspection);
};
function maybeUnwrapDisposer(value) {
if (Disposer.isDisposer(value)) {
this.resources[this.index]._setDisposable(value);
return value.promise();
}
return value;
}
function ResourceList(length) {
this.length = length;
this.promise = null;
this[length-1] = null;
}
ResourceList.prototype._resultCancelled = function() {
var len = this.length;
for (var i = 0; i < len; ++i) {
var item = this[i];
if (item instanceof Promise) {
item.cancel();
}
}
};
Promise.using = function () {
var len = arguments.length;
if (len < 2) return apiRejection(
"you must pass at least 2 arguments to Promise.using");
var fn = arguments[len - 1];
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var input;
var spreadArgs = true;
if (len === 2 && Array.isArray(arguments[0])) {
input = arguments[0];
len = input.length;
spreadArgs = false;
} else {
input = arguments;
len--;
}
var resources = new ResourceList(len);
for (var i = 0; i < len; ++i) {
var resource = input[i];
if (Disposer.isDisposer(resource)) {
var disposer = resource;
resource = resource.promise();
resource._setDisposable(disposer);
} else {
var maybePromise = tryConvertToPromise(resource);
if (maybePromise instanceof Promise) {
resource =
maybePromise._then(maybeUnwrapDisposer, null, null, {
resources: resources,
index: i
}, undefined);
}
}
resources[i] = resource;
}
var reflectedResources = new Array(resources.length);
for (var i = 0; i < reflectedResources.length; ++i) {
reflectedResources[i] = Promise.resolve(resources[i]).reflect();
}
var resultPromise = Promise.all(reflectedResources)
.then(function(inspections) {
for (var i = 0; i < inspections.length; ++i) {
var inspection = inspections[i];
if (inspection.isRejected()) {
errorObj.e = inspection.error();
return errorObj;
} else if (!inspection.isFulfilled()) {
resultPromise.cancel();
return;
}
inspections[i] = inspection.value();
}
promise._pushContext();
fn = tryCatch(fn);
var ret = spreadArgs
? fn.apply(undefined, inspections) : fn(inspections);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret, promiseCreated, "Promise.using", promise);
return ret;
});
var promise = resultPromise.lastly(function() {
var inspection = new Promise.PromiseInspection(resultPromise);
return dispose(resources, inspection);
});
resources.promise = promise;
promise._setOnCancel(resources);
return promise;
};
Promise.prototype._setDisposable = function (disposer) {
this._bitField = this._bitField | 131072;
this._disposer = disposer;
};
Promise.prototype._isDisposable = function () {
return (this._bitField & 131072) > 0;
};
Promise.prototype._getDisposer = function () {
return this._disposer;
};
Promise.prototype._unsetDisposable = function () {
this._bitField = this._bitField & (~131072);
this._disposer = undefined;
};
Promise.prototype.disposer = function (fn) {
if (typeof fn === "function") {
return new FunctionDisposer(fn, this, createContext());
}
throw new TypeError();
};
};
},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
"use strict";
var es5 = _dereq_("./es5");
var canEvaluate = typeof navigator == "undefined";
var errorObj = {e: {}};
var tryCatchTarget;
var globalObject = typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
typeof global !== "undefined" ? global :
this !== undefined ? this : null;
function tryCatcher() {
try {
var target = tryCatchTarget;
tryCatchTarget = null;
return target.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return typeof value === "function" ||
typeof value === "object" && value !== null;
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
var excludedPrototypes = [
Array.prototype,
Object.prototype,
Function.prototype
];
var isExcludedProto = function(val) {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (excludedPrototypes[i] === val) {
return true;
}
}
return false;
};
if (es5.isES5) {
var getKeys = Object.getOwnPropertyNames;
return function(obj) {
var ret = [];
var visitedKeys = Object.create(null);
while (obj != null && !isExcludedProto(obj)) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
var hasProp = {}.hasOwnProperty;
return function(obj) {
if (isExcludedProto(obj)) return [];
var ret = [];
/*jshint forin:false */
enumeration: for (var key in obj) {
if (hasProp.call(obj, key)) {
ret.push(key);
} else {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (hasProp.call(excludedPrototypes[i], key)) {
continue enumeration;
}
}
ret.push(key);
}
}
return ret;
};
}
})();
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.names(fn.prototype);
var hasMethods = es5.isES5 && keys.length > 1;
var hasMethodsOtherThanConstructor = keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
var hasThisAssignmentAndStaticMethods =
thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
if (hasMethods || hasMethodsOtherThanConstructor ||
hasThisAssignmentAndStaticMethods) {
return true;
}
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/
function FakeConstructor() {}
FakeConstructor.prototype = obj;
var l = 8;
while (l--) new FakeConstructor();
return obj;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
function safeToString(obj) {
try {
return obj + "";
} catch (e) {
return "[no string representation]";
}
}
function isError(obj) {
return obj !== null &&
typeof obj === "object" &&
typeof obj.message === "string" &&
typeof obj.name === "string";
}
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
e["isOperational"] === true);
}
function canAttachTrace(obj) {
return isError(obj) && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = (function() {
if (!("stack" in new Error())) {
return function(value) {
if (canAttachTrace(value)) return value;
try {throw new Error(safeToString(value));}
catch(err) {return err;}
};
} else {
return function(value) {
if (canAttachTrace(value)) return value;
return new Error(safeToString(value));
};
}
})();
function classString(obj) {
return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
var keys = es5.names(from);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (filter(key)) {
try {
es5.defineProperty(to, key, es5.getDescriptor(from, key));
} catch (ignore) {}
}
}
}
var asArray = function(v) {
if (es5.isArray(v)) {
return v;
}
return null;
};
if (typeof Symbol !== "undefined" && Symbol.iterator) {
var ArrayFrom = typeof Array.from === "function" ? function(v) {
return Array.from(v);
} : function(v) {
var ret = [];
var it = v[Symbol.iterator]();
var itResult;
while (!((itResult = it.next()).done)) {
ret.push(itResult.value);
}
return ret;
};
asArray = function(v) {
if (es5.isArray(v)) {
return v;
} else if (v != null && typeof v[Symbol.iterator] === "function") {
return ArrayFrom(v);
}
return null;
};
}
var isNode = typeof process !== "undefined" &&
classString(process).toLowerCase() === "[object process]";
var hasEnvVariables = typeof process !== "undefined" &&
typeof process.env !== "undefined";
function env(key) {
return hasEnvVariables ? process.env[key] : undefined;
}
function getNativePromise() {
if (typeof Promise === "function") {
try {
var promise = new Promise(function(){});
if ({}.toString.call(promise) === "[object Promise]") {
return Promise;
}
} catch (e) {}
}
}
function domainBind(self, cb) {
return self.bind(cb);
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
asArray: asArray,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
isError: isError,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch: tryCatch,
inherits: inherits,
withAppended: withAppended,
maybeWrapAsError: maybeWrapAsError,
toFastProperties: toFastProperties,
filledRange: filledRange,
toString: safeToString,
canAttachTrace: canAttachTrace,
ensureErrorObject: ensureErrorObject,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: isNode,
hasEnvVariables: hasEnvVariables,
env: env,
global: globalObject,
getNativePromise: getNativePromise,
domainBind: domainBind
};
ret.isRecentNode = ret.isNode && (function() {
var version = process.versions.node.split(".").map(Number);
return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})();
if (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;
},{"./es5":13}]},{},[4])(4)
}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":133}],41:[function(require,module,exports){
},{}],42:[function(require,module,exports){
(function (global){
'use strict';
var buffer = require('buffer');
var Buffer = buffer.Buffer;
var SlowBuffer = buffer.SlowBuffer;
var MAX_LEN = buffer.kMaxLength || 2147483647;
exports.alloc = function alloc(size, fill, encoding) {
if (typeof Buffer.alloc === 'function') {
return Buffer.alloc(size, fill, encoding);
}
if (typeof encoding === 'number') {
throw new TypeError('encoding must not be number');
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
var enc = encoding;
var _fill = fill;
if (_fill === undefined) {
enc = undefined;
_fill = 0;
}
var buf = new Buffer(size);
if (typeof _fill === 'string') {
var fillBuf = new Buffer(_fill, enc);
var flen = fillBuf.length;
var i = -1;
while (++i < size) {
buf[i] = fillBuf[i % flen];
}
} else {
buf.fill(_fill);
}
return buf;
}
exports.allocUnsafe = function allocUnsafe(size) {
if (typeof Buffer.allocUnsafe === 'function') {
return Buffer.allocUnsafe(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
return new Buffer(size);
}
exports.from = function from(value, encodingOrOffset, length) {
if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
return Buffer.from(value, encodingOrOffset, length);
}
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number');
}
if (typeof value === 'string') {
return new Buffer(value, encodingOrOffset);
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
var offset = encodingOrOffset;
if (arguments.length === 1) {
return new Buffer(value);
}
if (typeof offset === 'undefined') {
offset = 0;
}
var len = length;
if (typeof len === 'undefined') {
len = value.byteLength - offset;
}
if (offset >= value.byteLength) {
throw new RangeError('\'offset\' is out of bounds');
}
if (len > value.byteLength - offset) {
throw new RangeError('\'length\' is out of bounds');
}
return new Buffer(value.slice(offset, offset + len));
}
if (Buffer.isBuffer(value)) {
var out = new Buffer(value.length);
value.copy(out, 0, 0, value.length);
return out;
}
if (value) {
if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
return new Buffer(value);
}
if (value.type === 'Buffer' && Array.isArray(value.data)) {
return new Buffer(value.data);
}
}
throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
}
exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
if (typeof Buffer.allocUnsafeSlow === 'function') {
return Buffer.allocUnsafeSlow(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size >= MAX_LEN) {
throw new RangeError('size is too large');
}
return new SlowBuffer(size);
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"buffer":43}],43:[function(require,module,exports){
(function (global){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('isarray')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
var actual = that.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return ''
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"base64-js":39,"ieee754":85,"isarray":89}],44:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":88}],45:[function(require,module,exports){
var util = require('util')
, AbstractIterator = require('abstract-leveldown').AbstractIterator
function DeferredIterator (options) {
AbstractIterator.call(this, options)
this._options = options
this._iterator = null
this._operations = []
}
util.inherits(DeferredIterator, AbstractIterator)
DeferredIterator.prototype.setDb = function (db) {
var it = this._iterator = db.iterator(this._options)
this._operations.forEach(function (op) {
it[op.method].apply(it, op.args)
})
}
DeferredIterator.prototype._operation = function (method, args) {
if (this._iterator)
return this._iterator[method].apply(this._iterator, args)
this._operations.push({ method: method, args: args })
}
'next end'.split(' ').forEach(function (m) {
DeferredIterator.prototype['_' + m] = function () {
this._operation(m, arguments)
}
})
module.exports = DeferredIterator;
},{"abstract-leveldown":50,"util":297}],46:[function(require,module,exports){
(function (Buffer,process){
var util = require('util')
, AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
, DeferredIterator = require('./deferred-iterator')
function DeferredLevelDOWN (location) {
AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '') // optional location, who cares?
this._db = undefined
this._operations = []
this._iterators = []
}
util.inherits(DeferredLevelDOWN, AbstractLevelDOWN)
// called by LevelUP when we have a real DB to take its place
DeferredLevelDOWN.prototype.setDb = function (db) {
this._db = db
this._operations.forEach(function (op) {
db[op.method].apply(db, op.args)
})
this._iterators.forEach(function (it) {
it.setDb(db)
})
}
DeferredLevelDOWN.prototype._open = function (options, callback) {
return process.nextTick(callback)
}
// queue a new deferred operation
DeferredLevelDOWN.prototype._operation = function (method, args) {
if (this._db)
return this._db[method].apply(this._db, args)
this._operations.push({ method: method, args: args })
}
// deferrables
'put get del batch approximateSize'.split(' ').forEach(function (m) {
DeferredLevelDOWN.prototype['_' + m] = function () {
this._operation(m, arguments)
}
})
DeferredLevelDOWN.prototype._isBuffer = function (obj) {
return Buffer.isBuffer(obj)
}
DeferredLevelDOWN.prototype._iterator = function (options) {
if (this._db)
return this._db.iterator.apply(this._db, arguments)
var it = new DeferredIterator(options)
this._iterators.push(it)
return it
}
module.exports = DeferredLevelDOWN
module.exports.DeferredIterator = DeferredIterator
}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process'))
},{"../is-buffer/index.js":88,"./deferred-iterator":45,"_process":133,"abstract-leveldown":50,"util":297}],47:[function(require,module,exports){
(function (process){
/* Copyright (c) 2013 Rod Vagg, MIT License */
function AbstractChainedBatch (db) {
this._db = db
this._operations = []
this._written = false
}
AbstractChainedBatch.prototype._checkWritten = function () {
if (this._written)
throw new Error('write() already called on this batch')
}
AbstractChainedBatch.prototype.put = function (key, value) {
this._checkWritten()
var err = this._db._checkKey(key, 'key', this._db._isBuffer)
if (err)
throw err
if (!this._db._isBuffer(key)) key = String(key)
if (!this._db._isBuffer(value)) value = String(value)
if (typeof this._put == 'function' )
this._put(key, value)
else
this._operations.push({ type: 'put', key: key, value: value })
return this
}
AbstractChainedBatch.prototype.del = function (key) {
this._checkWritten()
var err = this._db._checkKey(key, 'key', this._db._isBuffer)
if (err) throw err
if (!this._db._isBuffer(key)) key = String(key)
if (typeof this._del == 'function' )
this._del(key)
else
this._operations.push({ type: 'del', key: key })
return this
}
AbstractChainedBatch.prototype.clear = function () {
this._checkWritten()
this._operations = []
if (typeof this._clear == 'function' )
this._clear()
return this
}
AbstractChainedBatch.prototype.write = function (options, callback) {
this._checkWritten()
if (typeof options == 'function')
callback = options
if (typeof callback != 'function')
throw new Error('write() requires a callback argument')
if (typeof options != 'object')
options = {}
this._written = true
if (typeof this._write == 'function' )
return this._write(callback)
if (typeof this._db._batch == 'function')
return this._db._batch(this._operations, options, callback)
process.nextTick(callback)
}
module.exports = AbstractChainedBatch
}).call(this,require('_process'))
},{"_process":133}],48:[function(require,module,exports){
(function (process){
/* Copyright (c) 2013 Rod Vagg, MIT License */
function AbstractIterator (db) {
this.db = db
this._ended = false
this._nexting = false
}
AbstractIterator.prototype.next = function (callback) {
var self = this
if (typeof callback != 'function')
throw new Error('next() requires a callback argument')
if (self._ended)
return callback(new Error('cannot call next() after end()'))
if (self._nexting)
return callback(new Error('cannot call next() before previous next() has completed'))
self._nexting = true
if (typeof self._next == 'function') {
return self._next(function () {
self._nexting = false
callback.apply(null, arguments)
})
}
process.nextTick(function () {
self._nexting = false
callback()
})
}
AbstractIterator.prototype.end = function (callback) {
if (typeof callback != 'function')
throw new Error('end() requires a callback argument')
if (this._ended)
return callback(new Error('end() already called on iterator'))
this._ended = true
if (typeof this._end == 'function')
return this._end(callback)
process.nextTick(callback)
}
module.exports = AbstractIterator
}).call(this,require('_process'))
},{"_process":133}],49:[function(require,module,exports){
(function (Buffer,process){
/* Copyright (c) 2013 Rod Vagg, MIT License */
var xtend = require('xtend')
, AbstractIterator = require('./abstract-iterator')
, AbstractChainedBatch = require('./abstract-chained-batch')
function AbstractLevelDOWN (location) {
if (!arguments.length || location === undefined)
throw new Error('constructor requires at least a location argument')
if (typeof location != 'string')
throw new Error('constructor requires a location string argument')
this.location = location
this.status = 'new'
}
AbstractLevelDOWN.prototype.open = function (options, callback) {
var self = this
, oldStatus = this.status
if (typeof options == 'function')
callback = options
if (typeof callback != 'function')
throw new Error('open() requires a callback argument')
if (typeof options != 'object')
options = {}
options.createIfMissing = options.createIfMissing != false
options.errorIfExists = !!options.errorIfExists
if (typeof this._open == 'function') {
this.status = 'opening'
this._open(options, function (err) {
if (err) {
self.status = oldStatus
return callback(err)
}
self.status = 'open'
callback()
})
} else {
this.status = 'open'
process.nextTick(callback)
}
}
AbstractLevelDOWN.prototype.close = function (callback) {
var self = this
, oldStatus = this.status
if (typeof callback != 'function')
throw new Error('close() requires a callback argument')
if (typeof this._close == 'function') {
this.status = 'closing'
this._close(function (err) {
if (err) {
self.status = oldStatus
return callback(err)
}
self.status = 'closed'
callback()
})
} else {
this.status = 'closed'
process.nextTick(callback)
}
}
AbstractLevelDOWN.prototype.get = function (key, options, callback) {
var err
if (typeof options == 'function')
callback = options
if (typeof callback != 'function')
throw new Error('get() requires a callback argument')
if (err = this._checkKey(key, 'key', this._isBuffer))
return callback(err)
if (!this._isBuffer(key))
key = String(key)
if (typeof options != 'object')
options = {}
options.asBuffer = options.asBuffer != false
if (typeof this._get == 'function')
return this._get(key, options, callback)
process.nextTick(function () { callback(new Error('NotFound')) })
}
AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
var err
if (typeof options == 'function')
callback = options
if (typeof callback != 'function')
throw new Error('put() requires a callback argument')
if (err = this._checkKey(key, 'key', this._isBuffer))
return callback(err)
if (!this._isBuffer(key))
key = String(key)
// coerce value to string in node, don't touch it in browser
// (indexeddb can store any JS type)
if (value != null && !this._isBuffer(value) && !process.browser)
value = String(value)
if (typeof options != 'object')
options = {}
if (typeof this._put == 'function')
return this._put(key, value, options, callback)
process.nextTick(callback)
}
AbstractLevelDOWN.prototype.del = function (key, options, callback) {
var err
if (typeof options == 'function')
callback = options
if (typeof callback != 'function')
throw new Error('del() requires a callback argument')
if (err = this._checkKey(key, 'key', this._isBuffer))
return callback(err)
if (!this._isBuffer(key))
key = String(key)
if (typeof options != 'object')
options = {}
if (typeof this._del == 'function')
return this._del(key, options, callback)
process.nextTick(callback)
}
AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
if (!arguments.length)
return this._chainedBatch()
if (typeof options == 'function')
callback = options
if (typeof array == 'function')
callback = array
if (typeof callback != 'function')
throw new Error('batch(array) requires a callback argument')
if (!Array.isArray(array))
return callback(new Error('batch(array) requires an array argument'))
if (!options || typeof options != 'object')
options = {}
var i = 0
, l = array.length
, e
, err
for (; i < l; i++) {
e = array[i]
if (typeof e != 'object')
continue
if (err = this._checkKey(e.type, 'type', this._isBuffer))
return callback(err)
if (err = this._checkKey(e.key, 'key', this._isBuffer))
return callback(err)
}
if (typeof this._batch == 'function')
return this._batch(array, options, callback)
process.nextTick(callback)
}
//TODO: remove from here, not a necessary primitive
AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
if ( start == null
|| end == null
|| typeof start == 'function'
|| typeof end == 'function') {
throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
}
if (typeof callback != 'function')
throw new Error('approximateSize() requires a callback argument')
if (!this._isBuffer(start))
start = String(start)
if (!this._isBuffer(end))
end = String(end)
if (typeof this._approximateSize == 'function')
return this._approximateSize(start, end, callback)
process.nextTick(function () {
callback(null, 0)
})
}
AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
var self = this
options = xtend(options)
;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
delete options[o]
})
options.reverse = !!options.reverse
options.keys = options.keys != false
options.values = options.values != false
options.limit = 'limit' in options ? options.limit : -1
options.keyAsBuffer = options.keyAsBuffer != false
options.valueAsBuffer = options.valueAsBuffer != false
return options
}
AbstractLevelDOWN.prototype.iterator = function (options) {
if (typeof options != 'object')
options = {}
options = this._setupIteratorOptions(options)
if (typeof this._iterator == 'function')
return this._iterator(options)
return new AbstractIterator(this)
}
AbstractLevelDOWN.prototype._chainedBatch = function () {
return new AbstractChainedBatch(this)
}
AbstractLevelDOWN.prototype._isBuffer = function (obj) {
return Buffer.isBuffer(obj)
}
AbstractLevelDOWN.prototype._checkKey = function (obj, type) {
if (obj === null || obj === undefined)
return new Error(type + ' cannot be `null` or `undefined`')
if (this._isBuffer(obj)) {
if (obj.length === 0)
return new Error(type + ' cannot be an empty Buffer')
} else if (String(obj) === '')
return new Error(type + ' cannot be an empty String')
}
module.exports = AbstractLevelDOWN
}).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process'))
},{"../../../is-buffer/index.js":88,"./abstract-chained-batch":47,"./abstract-iterator":48,"_process":133,"xtend":299}],50:[function(require,module,exports){
exports.AbstractLevelDOWN = require('./abstract-leveldown')
exports.AbstractIterator = require('./abstract-iterator')
exports.AbstractChainedBatch = require('./abstract-chained-batch')
exports.isLevelDOWN = require('./is-leveldown')
},{"./abstract-chained-batch":47,"./abstract-iterator":48,"./abstract-leveldown":49,"./is-leveldown":51}],51:[function(require,module,exports){
var AbstractLevelDOWN = require('./abstract-leveldown')
function isLevelDOWN (db) {
if (!db || typeof db !== 'object')
return false
return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) {
// TODO remove approximateSize check when method is gone
return name[0] != '_' && name != 'approximateSize'
}).every(function (name) {
return typeof db[name] == 'function'
})
}
module.exports = isLevelDOWN
},{"./abstract-leveldown":49}],52:[function(require,module,exports){
/**
* Copyright (c) 2013 Petka Antonov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
"use strict";
function Deque(capacity) {
this._capacity = getCapacity(capacity);
this._length = 0;
this._front = 0;
this._makeCapacity();
if (isArray(capacity)) {
var len = capacity.length;
for (var i = 0; i < len; ++i) {
this[i] = capacity[i];
}
this._length = len;
}
}
Deque.prototype.toArray = function Deque$toArray() {
var len = this._length;
var ret = new Array(len);
var front = this._front;
var capacity = this._capacity;
for (var j = 0; j < len; ++j) {
ret[j] = this[(front + j) & (capacity - 1)];
}
return ret;
};
Deque.prototype.push = function Deque$push(item) {
var argsLength = arguments.length;
var length = this._length;
if (argsLength > 1) {
var capacity = this._capacity;
if (length + argsLength > capacity) {
for (var i = 0; i < argsLength; ++i) {
this._checkCapacity(length + 1);
var j = (this._front + length) & (this._capacity - 1);
this[j] = arguments[i];
length++;
this._length = length;
}
return length;
}
else {
var j = this._front;
for (var i = 0; i < argsLength; ++i) {
this[(j + length) & (capacity - 1)] = arguments[i];
j++;
}
this._length = length + argsLength;
return length + argsLength;
}
}
if (argsLength === 0) return length;
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = item;
this._length = length + 1;
return length + 1;
};
Deque.prototype.pop = function Deque$pop() {
var length = this._length;
if (length === 0) {
return void 0;
}
var i = (this._front + length - 1) & (this._capacity - 1);
var ret = this[i];
this[i] = void 0;
this._length = length - 1;
return ret;
};
Deque.prototype.shift = function Deque$shift() {
var length = this._length;
if (length === 0) {
return void 0;
}
var front = this._front;
var ret = this[front];
this[front] = void 0;
this._front = (front + 1) & (this._capacity - 1);
this._length = length - 1;
return ret;
};
Deque.prototype.unshift = function Deque$unshift(item) {
var length = this._length;
var argsLength = arguments.length;
if (argsLength > 1) {
var capacity = this._capacity;
if (length + argsLength > capacity) {
for (var i = argsLength - 1; i >= 0; i--) {
this._checkCapacity(length + 1);
var capacity = this._capacity;
var j = (((( this._front - 1 ) &
( capacity - 1) ) ^ capacity ) - capacity );
this[j] = arguments[i];
length++;
this._length = length;
this._front = j;
}
return length;
}
else {
var front = this._front;
for (var i = argsLength - 1; i >= 0; i--) {
var j = (((( front - 1 ) &
( capacity - 1) ) ^ capacity ) - capacity );
this[j] = arguments[i];
front = j;
}
this._front = front;
this._length = length + argsLength;
return length + argsLength;
}
}
if (argsLength === 0) return length;
this._checkCapacity(length + 1);
var capacity = this._capacity;
var i = (((( this._front - 1 ) &
( capacity - 1) ) ^ capacity ) - capacity );
this[i] = item;
this._length = length + 1;
this._front = i;
return length + 1;
};
Deque.prototype.peekBack = function Deque$peekBack() {
var length = this._length;
if (length === 0) {
return void 0;
}
var index = (this._front + length - 1) & (this._capacity - 1);
return this[index];
};
Deque.prototype.peekFront = function Deque$peekFront() {
if (this._length === 0) {
return void 0;
}
return this[this._front];
};
Deque.prototype.get = function Deque$get(index) {
var i = index;
if ((i !== (i | 0))) {
return void 0;
}
var len = this._length;
if (i < 0) {
i = i + len;
}
if (i < 0 || i >= len) {
return void 0;
}
return this[(this._front + i) & (this._capacity - 1)];
};
Deque.prototype.isEmpty = function Deque$isEmpty() {
return this._length === 0;
};
Deque.prototype.clear = function Deque$clear() {
this._length = 0;
this._front = 0;
this._makeCapacity();
};
Deque.prototype.toString = function Deque$toString() {
return this.toArray().toString();
};
Deque.prototype.valueOf = Deque.prototype.toString;
Deque.prototype.removeFront = Deque.prototype.shift;
Deque.prototype.removeBack = Deque.prototype.pop;
Deque.prototype.insertFront = Deque.prototype.unshift;
Deque.prototype.insertBack = Deque.prototype.push;
Deque.prototype.enqueue = Deque.prototype.push;
Deque.prototype.dequeue = Deque.prototype.shift;
Deque.prototype.toJSON = Deque.prototype.toArray;
Object.defineProperty(Deque.prototype, "length", {
get: function() {
return this._length;
},
set: function() {
throw new RangeError("");
}
});
Deque.prototype._makeCapacity = function Deque$_makeCapacity() {
var len = this._capacity;
for (var i = 0; i < len; ++i) {
this[i] = void 0;
}
};
Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
if (this._capacity < size) {
this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
}
};
Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
var oldFront = this._front;
var oldCapacity = this._capacity;
var oldDeque = new Array(oldCapacity);
var length = this._length;
arrayCopy(this, 0, oldDeque, 0, oldCapacity);
this._capacity = capacity;
this._makeCapacity();
this._front = 0;
if (oldFront + length <= oldCapacity) {
arrayCopy(oldDeque, oldFront, this, 0, length);
} else { var lengthBeforeWrapping =
length - ((oldFront + length) & (oldCapacity - 1));
arrayCopy(oldDeque, oldFront, this, 0, lengthBeforeWrapping);
arrayCopy(oldDeque, 0, this, lengthBeforeWrapping,
length - lengthBeforeWrapping);
}
};
var isArray = Array.isArray;
function arrayCopy(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
}
}
function pow2AtLeast(n) {
n = n >>> 0;
n = n - 1;
n = n | (n >> 1);
n = n | (n >> 2);
n = n | (n >> 4);
n = n | (n >> 8);
n = n | (n >> 16);
return n + 1;
}
function getCapacity(capacity) {
if (typeof capacity !== "number") {
if (isArray(capacity)) {
capacity = capacity.length;
}
else {
return 16;
}
}
return pow2AtLeast(
Math.min(
Math.max(16, capacity), 1073741824)
);
}
module.exports = Deque;
},{}],53:[function(require,module,exports){
var prr = require('prr')
function init (type, message, cause) {
prr(this, {
type : type
, name : type
// can be passed just a 'cause'
, cause : typeof message != 'string' ? message : cause
, message : !!message && typeof message != 'string' ? message.message : message
}, 'ewr')
}
// generic prototype, not intended to be actually used - helpful for `instanceof`
function CustomError (message, cause) {
Error.call(this)
if (Error.captureStackTrace)
Error.captureStackTrace(this, arguments.callee)
init.call(this, 'CustomError', message, cause)
}
CustomError.prototype = new Error()
function createError (errno, type, proto) {
var err = function (message, cause) {
init.call(this, type, message, cause)
//TODO: the specificity here is stupid, errno should be available everywhere
if (type == 'FilesystemError') {
this.code = this.cause.code
this.path = this.cause.path
this.errno = this.cause.errno
this.message =
(errno.errno[this.cause.errno]
? errno.errno[this.cause.errno].description
: this.cause.message)
+ (this.cause.path ? ' [' + this.cause.path + ']' : '')
}
Error.call(this)
if (Error.captureStackTrace)
Error.captureStackTrace(this, arguments.callee)
}
err.prototype = !!proto ? new proto() : new CustomError()
return err
}
module.exports = function (errno) {
var ce = function (type, proto) {
return createError(errno, type, proto)
}
return {
CustomError : CustomError
, FilesystemError : ce('FilesystemError')
, createError : ce
}
}
},{"prr":134}],54:[function(require,module,exports){
var all = module.exports.all = [
{
errno: -2,
code: 'ENOENT',
description: 'no such file or directory'
},
{
errno: -1,
code: 'UNKNOWN',
description: 'unknown error'
},
{
errno: 0,
code: 'OK',
description: 'success'
},
{
errno: 1,
code: 'EOF',
description: 'end of file'
},
{
errno: 2,
code: 'EADDRINFO',
description: 'getaddrinfo error'
},
{
errno: 3,
code: 'EACCES',
description: 'permission denied'
},
{
errno: 4,
code: 'EAGAIN',
description: 'resource temporarily unavailable'
},
{
errno: 5,
code: 'EADDRINUSE',
description: 'address already in use'
},
{
errno: 6,
code: 'EADDRNOTAVAIL',
description: 'address not available'
},
{
errno: 7,
code: 'EAFNOSUPPORT',
description: 'address family not supported'
},
{
errno: 8,
code: 'EALREADY',
description: 'connection already in progress'
},
{
errno: 9,
code: 'EBADF',
description: 'bad file descriptor'
},
{
errno: 10,
code: 'EBUSY',
description: 'resource busy or locked'
},
{
errno: 11,
code: 'ECONNABORTED',
description: 'software caused connection abort'
},
{
errno: 12,
code: 'ECONNREFUSED',
description: 'connection refused'
},
{
errno: 13,
code: 'ECONNRESET',
description: 'connection reset by peer'
},
{
errno: 14,
code: 'EDESTADDRREQ',
description: 'destination address required'
},
{
errno: 15,
code: 'EFAULT',
description: 'bad address in system call argument'
},
{
errno: 16,
code: 'EHOSTUNREACH',
description: 'host is unreachable'
},
{
errno: 17,
code: 'EINTR',
description: 'interrupted system call'
},
{
errno: 18,
code: 'EINVAL',
description: 'invalid argument'
},
{
errno: 19,
code: 'EISCONN',
description: 'socket is already connected'
},
{
errno: 20,
code: 'EMFILE',
description: 'too many open files'
},
{
errno: 21,
code: 'EMSGSIZE',
description: 'message too long'
},
{
errno: 22,
code: 'ENETDOWN',
description: 'network is down'
},
{
errno: 23,
code: 'ENETUNREACH',
description: 'network is unreachable'
},
{
errno: 24,
code: 'ENFILE',
description: 'file table overflow'
},
{
errno: 25,
code: 'ENOBUFS',
description: 'no buffer space available'
},
{
errno: 26,
code: 'ENOMEM',
description: 'not enough memory'
},
{
errno: 27,
code: 'ENOTDIR',
description: 'not a directory'
},
{
errno: 28,
code: 'EISDIR',
description: 'illegal operation on a directory'
},
{
errno: 29,
code: 'ENONET',
description: 'machine is not on the network'
},
{
errno: 31,
code: 'ENOTCONN',
description: 'socket is not connected'
},
{
errno: 32,
code: 'ENOTSOCK',
description: 'socket operation on non-socket'
},
{
errno: 33,
code: 'ENOTSUP',
description: 'operation not supported on socket'
},
{
errno: 34,
code: 'ENOENT',
description: 'no such file or directory'
},
{
errno: 35,
code: 'ENOSYS',
description: 'function not implemented'
},
{
errno: 36,
code: 'EPIPE',
description: 'broken pipe'
},
{
errno: 37,
code: 'EPROTO',
description: 'protocol error'
},
{
errno: 38,
code: 'EPROTONOSUPPORT',
description: 'protocol not supported'
},
{
errno: 39,
code: 'EPROTOTYPE',
description: 'protocol wrong type for socket'
},
{
errno: 40,
code: 'ETIMEDOUT',
description: 'connection timed out'
},
{
errno: 41,
code: 'ECHARSET',
description: 'invalid Unicode character'
},
{
errno: 42,
code: 'EAIFAMNOSUPPORT',
description: 'address family for hostname not supported'
},
{
errno: 44,
code: 'EAISERVICE',
description: 'servname not supported for ai_socktype'
},
{
errno: 45,
code: 'EAISOCKTYPE',
description: 'ai_socktype not supported'
},
{
errno: 46,
code: 'ESHUTDOWN',
description: 'cannot send after transport endpoint shutdown'
},
{
errno: 47,
code: 'EEXIST',
description: 'file already exists'
},
{
errno: 48,
code: 'ESRCH',
description: 'no such process'
},
{
errno: 49,
code: 'ENAMETOOLONG',
description: 'name too long'
},
{
errno: 50,
code: 'EPERM',
description: 'operation not permitted'
},
{
errno: 51,
code: 'ELOOP',
description: 'too many symbolic links encountered'
},
{
errno: 52,
code: 'EXDEV',
description: 'cross-device link not permitted'
},
{
errno: 53,
code: 'ENOTEMPTY',
description: 'directory not empty'
},
{
errno: 54,
code: 'ENOSPC',
description: 'no space left on device'
},
{
errno: 55,
code: 'EIO',
description: 'i/o error'
},
{
errno: 56,
code: 'EROFS',
description: 'read-only file system'
},
{
errno: 57,
code: 'ENODEV',
description: 'no such device'
},
{
errno: 58,
code: 'ESPIPE',
description: 'invalid seek'
},
{
errno: 59,
code: 'ECANCELED',
description: 'operation canceled'
}
]
module.exports.errno = {}
module.exports.code = {}
all.forEach(function (error) {
module.exports.errno[error.errno] = error
module.exports.code[error.code] = error
})
module.exports.custom = require('./custom')(module.exports)
module.exports.create = module.exports.custom.createError
},{"./custom":53}],55:[function(require,module,exports){
(function (root, factory) {
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define([], factory)
} else if (typeof exports === 'object') {
module.exports = factory()
} else {
root.PromisePool = factory()
// Legacy API
root.promisePool = root.PromisePool
}
})(this, function () {
'use strict'
var EventTarget = function () {
this._listeners = {}
}
EventTarget.prototype.addEventListener = function (type, listener) {
this._listeners[type] = this._listeners[type] || []
if (this._listeners[type].indexOf(listener) < 0) {
this._listeners[type].push(listener)
}
}
EventTarget.prototype.removeEventListener = function (type, listener) {
if (this._listeners[type]) {
var p = this._listeners[type].indexOf(listener)
if (p >= 0) {
this._listeners[type].splice(p, 1)
}
}
}
EventTarget.prototype.dispatchEvent = function (evt) {
if (this._listeners[evt.type] && this._listeners[evt.type].length) {
var listeners = this._listeners[evt.type].slice()
for (var i = 0, l = listeners.length; i < l; ++i) {
listeners[i].call(this, evt)
}
}
}
var isGenerator = function (func) {
return (typeof func.constructor === 'function' &&
func.constructor.name === 'GeneratorFunction')
}
var functionToIterator = function (func) {
return {
next: function () {
var promise = func()
return promise ? {value: promise} : {done: true}
}
}
}
var promiseToIterator = function (promise) {
var called = false
return {
next: function () {
if (called) {
return {done: true}
}
called = true
return {value: promise}
}
}
}
var toIterator = function (obj, Promise) {
var type = typeof obj
if (type === 'object') {
if (typeof obj.next === 'function') {
return obj
}
/* istanbul ignore else */
if (typeof obj.then === 'function') {
return promiseToIterator(obj)
}
}
if (type === 'function') {
return isGenerator(obj) ? obj() : functionToIterator(obj)
}
return promiseToIterator(Promise.resolve(obj))
}
var PromisePoolEvent = function (target, type, data) {
this.target = target
this.type = type
this.data = data
}
var PromisePool = function (source, concurrency, options) {
EventTarget.call(this)
if (typeof concurrency !== 'number' ||
Math.floor(concurrency) !== concurrency ||
concurrency < 1) {
throw new Error('Invalid concurrency')
}
this._concurrency = concurrency
this._options = options || {}
this._options.promise = this._options.promise || Promise
this._iterator = toIterator(source, this._options.promise)
this._done = false
this._size = 0
this._promise = null
this._callbacks = null
}
PromisePool.prototype = new EventTarget()
PromisePool.prototype.constructor = PromisePool
PromisePool.prototype.concurrency = function (value) {
if (typeof value !== 'undefined') {
this._concurrency = value
if (this.active()) {
this._proceed()
}
}
return this._concurrency
}
PromisePool.prototype.size = function () {
return this._size
}
PromisePool.prototype.active = function () {
return !!this._promise
}
PromisePool.prototype.promise = function () {
return this._promise
}
PromisePool.prototype.start = function () {
var that = this
var Promise = this._options.promise
this._promise = new Promise(function (resolve, reject) {
that._callbacks = {
reject: reject,
resolve: resolve
}
that._proceed()
})
return this._promise
}
PromisePool.prototype._fireEvent = function (type, data) {
this.dispatchEvent(new PromisePoolEvent(this, type, data))
}
PromisePool.prototype._settle = function (error) {
if (error) {
this._callbacks.reject(error)
} else {
this._callbacks.resolve()
}
this._promise = null
this._callbacks = null
}
PromisePool.prototype._onPooledPromiseFulfilled = function (promise, result) {
this._size--
if (this.active()) {
this._fireEvent('fulfilled', {
promise: promise,
result: result
})
this._proceed()
}
}
PromisePool.prototype._onPooledPromiseRejected = function (promise, error) {
this._size--
if (this.active()) {
this._fireEvent('rejected', {
promise: promise,
error: error
})
this._settle(error || new Error('Unknown error'))
}
}
PromisePool.prototype._trackPromise = function (promise) {
var that = this
promise
.then(function (result) {
that._onPooledPromiseFulfilled(promise, result)
}, function (error) {
that._onPooledPromiseRejected(promise, error)
})['catch'](function (err) {
that._settle(new Error('Promise processing failed: ' + err))
})
}
PromisePool.prototype._proceed = function () {
if (!this._done) {
var result = null
while (this._size < this._concurrency &&
!(result = this._iterator.next()).done) {
this._size++
this._trackPromise(result.value)
}
this._done = (result === null || !!result.done)
}
if (this._done && this._size === 0) {
this._settle()
}
}
PromisePool.PromisePoolEvent = PromisePoolEvent
// Legacy API
PromisePool.PromisePool = PromisePool
return PromisePool
})
},{}],56:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],57:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-2015, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventListener
* @typechecks
*/
'use strict';
var emptyFunction = require('./emptyFunction');
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function (target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function () {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function () {
target.detachEvent('on' + eventType, callback);
}
};
}
},
/**
* Listen to DOM events during the capture phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
capture: function (target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, true);
return {
remove: function () {
target.removeEventListener(eventType, callback, true);
}
};
} else {
if (process.env.NODE_ENV !== 'production') {
console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.');
}
return {
remove: emptyFunction
};
}
},
registerDefault: function () {}
};
module.exports = EventListener;
}).call(this,require('_process'))
},{"./emptyFunction":64,"_process":133}],58:[function(require,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ExecutionEnvironment
*/
'use strict';
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
},{}],59:[function(require,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule camelize
* @typechecks
*/
"use strict";
var _hyphenPattern = /-(.)/g;
/**
* Camelcases a hyphenated string, for example:
*
* > camelize('background-color')
* < "backgroundColor"
*
* @param {string} string
* @return {string}
*/
function camelize(string) {
return string.replace(_hyphenPattern, function (_, character) {
return character.toUpperCase();
});
}
module.exports = camelize;
},{}],60:[function(require,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule camelizeStyleName
* @typechecks
*/
'use strict';
var camelize = require('./camelize');
var msPattern = /^-ms-/;
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
}
module.exports = camelizeStyleName;
},{"./camelize":59}],61:[function(require,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule containsNode
* @typechecks
*/
'use strict';
var isTextNode = require('./isTextNode');
/*eslint-disable no-bitwise */
/**
* Checks if a given DOM node contains or is another DOM node.
*
* @param {?DOMNode} outerNode Outer DOM node.
* @param {?DOMNode} innerNode Inner DOM node.
* @return {boolean} True if `outerNode` contains or is `innerNode`.
*/
function containsNode(_x, _x2) {
var _again = true;
_function: while (_again) {
var outerNode = _x,
innerNode = _x2;
_again = false;
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
_x = outerNode;
_x2 = innerNode.parentNode;
_again = true;
continue _function;
} else if (outerNode.contains) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
}
module.exports = containsNode;
},{"./isTextNode":74}],62:[function(require,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule createArrayFromMixed
* @typechecks
*/
'use strict';
var toArray = require('./toArray');
/**
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* It will return false for other array-like objects like Filelist.
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
return(
// not null/false
!!obj && (
// arrays are objects, NodeLists are functions in Safari
typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
'length' in obj &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
typeof obj.nodeType != 'number' && (
// a real array
Array.isArray(obj) ||
// arguments
'callee' in obj ||
// HTMLCollection/NodeList
'item' in obj)
);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFromMixed = require('createArrayFromMixed');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFromMixed(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* If you need to convert an array-like object, like `arguments`, into an array
* use toArray instead.
*
* @param {*} obj
* @return {array}
*/
function createArrayFromMixed(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFromMixed;
},{"./toArray":82}],63:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule createNodesFromMarkup
* @typechecks
*/
/*eslint-disable fb-www/unsafe-html*/
'use strict';
var ExecutionEnvironment = require('./ExecutionEnvironment');
var createArrayFromMixed = require('./createArrayFromMixed');
var getMarkupWrap = require('./getMarkupWrap');
var invariant = require('./invariant');
/**
* Dummy container used to render all markup.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Pattern used by `getNodeName`.
*/
var nodeNamePattern = /^\s*<(\w+)/;
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
*