(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;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 require=="function"&&require;for(var o=0;o= this.countPackets()) throw new Error("Packet out of bounds"); var start = i * packetSize; var end = Math.min(start + packetSize, this.size); return this.blob.slice(start, end); } } }); return UploadFile; })(); module.exports = UploadFile; },{}],"/Users/alex/Projects/webdrop/client/actions/DownloadActions.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var alt = _interopRequire(require("../alt")); module.exports = alt.createActions(function DownloadActions() { _classCallCheck(this, DownloadActions); this.generateActions("requestDownload", "beginDownload"); }); },{"../alt":"/Users/alex/Projects/webdrop/client/alt.js"}],"/Users/alex/Projects/webdrop/client/actions/UploadActions.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var alt = _interopRequire(require("../alt")); module.exports = alt.createActions(function UploadActions() { _classCallCheck(this, UploadActions); this.generateActions("sendToDownloader", "setUploadToken", "uploadFile"); }); },{"../alt":"/Users/alex/Projects/webdrop/client/alt.js"}],"/Users/alex/Projects/webdrop/client/alt.js":[function(require,module,exports){ "use strict"; var Alt = require("alt"); module.exports = new Alt(); },{"alt":"/Users/alex/Projects/webdrop/node_modules/alt/dist/alt.js"}],"/Users/alex/Projects/webdrop/client/components/App.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var FrozenHead = _interopRequire(require("react-frozenhead")); var React = _interopRequire(require("react")); var RouteHandler = require("react-router").RouteHandler; var App = (function (_React$Component) { function App() { _classCallCheck(this, App); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(App, _React$Component); _createClass(App, { render: { value: function render() { return React.createElement( "html", { lang: "en", "data-bootstrap": this.props.data }, React.createElement( FrozenHead, null, React.createElement("meta", { charSet: "utf-8" }), React.createElement( "title", null, "WebDrop - Send Files, Easily" ), React.createElement("link", { rel: "stylesheet", href: "/index.css" }), React.createElement("script", { src: "/app.js" }) ), React.createElement( "body", null, React.createElement(RouteHandler, null) ) ); } } }); return App; })(React.Component); module.exports = App; },{"react":"/Users/alex/Projects/webdrop/node_modules/react/react.js","react-frozenhead":"/Users/alex/Projects/webdrop/node_modules/react-frozenhead/lib/index.js","react-router":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/index.js"}],"/Users/alex/Projects/webdrop/client/components/Arrow.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; // TODO: Rename this. var React = _interopRequire(require("react")); var classnames = _interopRequire(require("classnames")); // Taken from StackOverflow // http://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript function formatSize(bytes) { if (bytes === 0) { return "0 Bytes"; }var k = 1000; var sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; var i = Math.floor(Math.log(bytes) / Math.log(k)); return (bytes / Math.pow(k, i)).toPrecision(3) + " " + sizes[i]; } var Arrow = (function (_React$Component) { function Arrow() { _classCallCheck(this, Arrow); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(Arrow, _React$Component); _createClass(Arrow, { render: { value: function render() { var classes = classnames("arrow", { "arrow-up": this.props.dir === "up", "arrow-down": this.props.dir === "down", "arrow-animated": this.props.animated }); return React.createElement( "div", { className: classes }, React.createElement("div", { className: "arrow-border" }), React.createElement( "div", { className: "arrow-image" }, this.props.dir === "up" ? "^" : "v" ), this.props.name === null ? null : React.createElement( "div", { className: "arrow-name" }, this.props.name ), this.props.size === null ? null : React.createElement( "div", { className: "arrow-size" }, formatSize(this.props.size) ) ); } } }); return Arrow; })(React.Component); module.exports = Arrow; Arrow.propTypes = { dir: React.PropTypes.oneOf(["up", "down"]).isRequired, name: React.PropTypes.string, size: React.PropTypes.number, animated: React.PropTypes.bool }; Arrow.defaultProps = { name: null, size: null, animated: false }; },{"classnames":"/Users/alex/Projects/webdrop/node_modules/classnames/index.js","react":"/Users/alex/Projects/webdrop/node_modules/react/react.js"}],"/Users/alex/Projects/webdrop/client/components/DownloadPage.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; // TODO: Flesh out this page further. var Arrow = _interopRequire(require("./Arrow")); var DownloadActions = _interopRequire(require("../actions/DownloadActions")); var DownloadStore = _interopRequire(require("../stores/DownloadStore")); var React = _interopRequire(require("react")); var peer = _interopRequire(require("../peer")); function formatProgress(dec) { return (dec * 100).toPrecision(3) + "%"; } var DownloadPage = (function (_React$Component) { function DownloadPage() { var _this = this; _classCallCheck(this, DownloadPage); this.state = DownloadStore.getState(); this._onChange = function () { _this.setState(DownloadStore.getState()); }; this._onConnection = function (conn) { DownloadActions.beginDownload(conn); }; } _inherits(DownloadPage, _React$Component); _createClass(DownloadPage, { componentDidMount: { value: function componentDidMount() { DownloadStore.listen(this._onChange); peer.on("connection", this._onConnection); } }, componentDidUnmount: { value: function componentDidUnmount() { DownloadStore.unlisten(this._onChange); peer.removeListener("connection", this._onConnection); } }, downloadFile: { value: function downloadFile() { DownloadActions.requestDownload(); } }, render: { value: function render() { switch (this.state.status) { case "ready": return React.createElement( "div", { className: "download-page" }, React.createElement(Arrow, { dir: "down", name: this.state.name, size: this.state.size }), React.createElement( "button", { onClick: this.downloadFile.bind(this) }, "Download" ), React.createElement( "span", null, "Progress: ", formatProgress(this.state.progress) ) ); case "downloading": return React.createElement( "div", { className: "download-page" }, React.createElement(Arrow, { dir: "down", name: this.state.name, size: this.state.size, animated: true }), React.createElement( "span", null, "Progress: ", formatProgress(this.state.progress) ) ); case "done": return React.createElement( "div", { className: "download-page" }, React.createElement(Arrow, { dir: "down", name: this.state.name, size: this.state.size }), React.createElement( "span", null, "Progress: ", formatProgress(this.state.progress) ) ); } } } }); return DownloadPage; })(React.Component); module.exports = DownloadPage; },{"../actions/DownloadActions":"/Users/alex/Projects/webdrop/client/actions/DownloadActions.js","../peer":"/Users/alex/Projects/webdrop/client/peer.js","../stores/DownloadStore":"/Users/alex/Projects/webdrop/client/stores/DownloadStore.js","./Arrow":"/Users/alex/Projects/webdrop/client/components/Arrow.js","react":"/Users/alex/Projects/webdrop/node_modules/react/react.js"}],"/Users/alex/Projects/webdrop/client/components/DropZone.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var React = _interopRequire(require("react")); var classnames = _interopRequire(require("classnames")); var DropZone = (function (_React$Component) { function DropZone() { _classCallCheck(this, DropZone); this.state = { focus: false }; } _inherits(DropZone, _React$Component); _createClass(DropZone, { onDragEnter: { value: function onDragEnter() { this.setState({ focus: true }); } }, onDragLeave: { value: function onDragLeave() { this.setState({ focus: false }); } }, onDragOver: { value: function onDragOver(e) { e.preventDefault(); e.dataTransfer.dropEffect = "copy"; } }, onDrop: { value: function onDrop(e) { e.preventDefault(); this.setState({ focus: false }); var file = e.dataTransfer.files[0]; if (this.props.onDrop) this.props.onDrop(file); } }, render: { value: function render() { var classes = classnames("drop-zone", { "drop-zone-focus": this.state.focus }); return React.createElement("div", { className: classes, onDragEnter: this.onDragEnter.bind(this), onDragLeave: this.onDragLeave.bind(this), onDragOver: this.onDragOver.bind(this), onDrop: this.onDrop.bind(this) }); } } }); return DropZone; })(React.Component); module.exports = DropZone; },{"classnames":"/Users/alex/Projects/webdrop/node_modules/classnames/index.js","react":"/Users/alex/Projects/webdrop/node_modules/react/react.js"}],"/Users/alex/Projects/webdrop/client/components/NotFoundPage.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var React = _interopRequire(require("react")); var NotFoundPage = (function (_React$Component) { function NotFoundPage() { _classCallCheck(this, NotFoundPage); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(NotFoundPage, _React$Component); _createClass(NotFoundPage, { render: { value: function render() { return React.createElement( "h1", null, "Not Found" ); } } }); return NotFoundPage; })(React.Component); module.exports = NotFoundPage; },{"react":"/Users/alex/Projects/webdrop/node_modules/react/react.js"}],"/Users/alex/Projects/webdrop/client/components/Tempalink.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var React = _interopRequire(require("react")); var Tempalink = (function (_React$Component) { function Tempalink() { _classCallCheck(this, Tempalink); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(Tempalink, _React$Component); _createClass(Tempalink, { onClick: { value: function onClick() { this.refs.input.getDOMNode().setSelectionRange(0, 9999); } }, render: { value: function render() { var url = window.location.origin + "/d/" + this.props.token; return React.createElement("input", { className: "tempalink", onClick: this.onClick.bind(this), readOnly: true, ref: "input", type: "text", value: url }); } } }); return Tempalink; })(React.Component); module.exports = Tempalink; },{"react":"/Users/alex/Projects/webdrop/node_modules/react/react.js"}],"/Users/alex/Projects/webdrop/client/components/UploadPage.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var Arrow = _interopRequire(require("./Arrow")); var DropZone = _interopRequire(require("./DropZone")); var React = _interopRequire(require("react")); var Tempalink = _interopRequire(require("./Tempalink")); var UploadActions = _interopRequire(require("../actions/UploadActions")); var UploadStore = _interopRequire(require("../stores/UploadStore")); var socket = _interopRequire(require("../socket")); var UploadPage = (function (_React$Component) { function UploadPage() { var _this = this; _classCallCheck(this, UploadPage); this.state = UploadStore.getState(); this._onChange = function () { _this.setState(UploadStore.getState()); }; this._onDownload = function (peerID) { UploadActions.sendToDownloader(peerID); }; } _inherits(UploadPage, _React$Component); _createClass(UploadPage, { componentDidMount: { value: function componentDidMount() { UploadStore.listen(this._onChange); socket.on("download", this._onDownload); } }, componentDidUnmount: { value: function componentDidUnmount() { UploadStore.unlisten(this._onChange); socket.removeListener("download", this._onDownload); } }, uploadFile: { value: function uploadFile(file) { UploadActions.uploadFile(file); } }, render: { value: function render() { switch (this.state.status) { case "ready": return React.createElement( "div", { className: "upload-page" }, React.createElement(DropZone, { onDrop: this.uploadFile.bind(this) }), React.createElement(Arrow, { dir: "up" }), React.createElement( "h1", null, "WebDrop" ), React.createElement( "p", null, "The easiest way to send someone a file." ), React.createElement( "p", null, "Drag the file into this window to get started." ) ); case "processing": return React.createElement( "div", { className: "upload-page" }, React.createElement(Arrow, { dir: "up", animated: true }), React.createElement( "h1", null, "WebDrop" ), React.createElement( "p", null, "Processing..." ) ); case "uploading": return React.createElement( "div", { className: "upload-page" }, React.createElement(Arrow, _extends({ dir: "up", animated: true }, this.state.file)), React.createElement(Tempalink, { token: this.state.token }), React.createElement( "p", null, "Send someone this link to download." ), React.createElement( "p", null, "This link will work as long as this page is open." ), React.createElement( "div", { className: "data" }, React.createElement( "div", { className: "datum" }, React.createElement( "strong", null, "In Progress:" ), " ", this.state.inProgress ), React.createElement( "div", { className: "datum" }, React.createElement( "strong", null, "Completed:" ), " ", this.state.completed ) ) ); } } } }); return UploadPage; })(React.Component); module.exports = UploadPage; },{"../actions/UploadActions":"/Users/alex/Projects/webdrop/client/actions/UploadActions.js","../socket":"/Users/alex/Projects/webdrop/client/socket.js","../stores/UploadStore":"/Users/alex/Projects/webdrop/client/stores/UploadStore.js","./Arrow":"/Users/alex/Projects/webdrop/client/components/Arrow.js","./DropZone":"/Users/alex/Projects/webdrop/client/components/DropZone.js","./Tempalink":"/Users/alex/Projects/webdrop/client/components/Tempalink.js","react":"/Users/alex/Projects/webdrop/node_modules/react/react.js"}],"/Users/alex/Projects/webdrop/client/index.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var React = _interopRequire(require("react")); var ReactRouter = _interopRequire(require("react-router")); var routes = _interopRequire(require("./routes")); var alt = _interopRequire(require("./alt")); var bootstrap = document.documentElement.getAttribute("data-bootstrap"); alt.bootstrap(bootstrap); ReactRouter.run(routes, ReactRouter.HistoryLocation, function (Handler) { React.render(React.createElement(Handler, { data: bootstrap }), document); }); },{"./alt":"/Users/alex/Projects/webdrop/client/alt.js","./routes":"/Users/alex/Projects/webdrop/client/routes.js","react":"/Users/alex/Projects/webdrop/node_modules/react/react.js","react-router":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/index.js"}],"/Users/alex/Projects/webdrop/client/peer.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var uuid = _interopRequire(require("node-uuid")); var id = uuid.v4(); if (typeof window === "undefined") { var peer = { id: id }; } else { var Peer = require("peerjs"); var peer = new Peer(id, { host: window.location.hostname, port: window.location.port, path: "/peer" }); } module.exports = peer; },{"node-uuid":"/Users/alex/Projects/webdrop/node_modules/node-uuid/uuid.js","peerjs":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/peer.js"}],"/Users/alex/Projects/webdrop/client/routes.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var React = _interopRequire(require("react")); var _reactRouter = require("react-router"); var Route = _reactRouter.Route; var DefaultRoute = _reactRouter.DefaultRoute; var NotFoundRoute = _reactRouter.NotFoundRoute; var RouteHandler = _reactRouter.RouteHandler; var App = _interopRequire(require("./components/App")); var DownloadPage = _interopRequire(require("./components/DownloadPage")); var UploadPage = _interopRequire(require("./components/UploadPage")); var NotFoundPage = _interopRequire(require("./components/NotFoundPage")); module.exports = React.createElement( Route, { handler: App }, React.createElement(DefaultRoute, { handler: UploadPage }), React.createElement(Route, { name: "download", path: "d/:token", handler: DownloadPage }), React.createElement(NotFoundRoute, { handler: NotFoundPage }) ); },{"./components/App":"/Users/alex/Projects/webdrop/client/components/App.js","./components/DownloadPage":"/Users/alex/Projects/webdrop/client/components/DownloadPage.js","./components/NotFoundPage":"/Users/alex/Projects/webdrop/client/components/NotFoundPage.js","./components/UploadPage":"/Users/alex/Projects/webdrop/client/components/UploadPage.js","react":"/Users/alex/Projects/webdrop/node_modules/react/react.js","react-router":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/index.js"}],"/Users/alex/Projects/webdrop/client/socket.js":[function(require,module,exports){ "use strict"; if (typeof window === "undefined") { var socket = {}; } else { var io = require("socket.io-client"); var socket = io.connect(); } module.exports = socket; },{"socket.io-client":"/Users/alex/Projects/webdrop/node_modules/socket.io-client/index.js"}],"/Users/alex/Projects/webdrop/client/stores/DownloadStore.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var DownloadActions = _interopRequire(require("../actions/DownloadActions")); var DownloadFile = _interopRequire(require("../DownloadFile")); var peer = _interopRequire(require("../peer")); var alt = _interopRequire(require("../alt")); var socket = _interopRequire(require("../socket")); module.exports = alt.createStore((function () { function DownloadStore() { var _this = this; _classCallCheck(this, DownloadStore); this.bindActions(DownloadActions); this.status = "offline"; this.token = null; this.file = null; this.progress = 0; this.on("bootstrap", function () { if (_this.file && !(_this.file instanceof DownloadFile)) _this.file = new DownloadFile(_this.file.name, _this.file.size, _this.file.type); }); } _createClass(DownloadStore, { onRequestDownload: { value: function onRequestDownload() { if (this.status !== "ready") { return; }this.status = "requesting"; socket.emit("download", { peerID: peer.id, token: this.token }); } }, onBeginDownload: { value: function onBeginDownload(conn) { var _this = this; if (this.status !== "requesting") { return; }this.status = "downloading"; var chunkSize = conn.metadata.chunkSize; var i = 0; conn.on("data", function (data) { if (_this.status !== "downloading") return; _this.file.addPacket(data); i++; if (_this.file.isComplete()) { _this.setState({ status: "done", progress: 1 }); _this.file.download(); conn.close(); } else { _this.setState({ progress: _this.file.getProgress() }); if (i % chunkSize === 0) conn.send("more"); } }); conn.on("close", function () { if (_this.status !== "downloading") return; _this.setState({ status: "cancelled", progress: 0 }); _this.file.clearPackets(); }); } } }); return DownloadStore; })(), "DownloadStore"); },{"../DownloadFile":"/Users/alex/Projects/webdrop/client/DownloadFile.js","../actions/DownloadActions":"/Users/alex/Projects/webdrop/client/actions/DownloadActions.js","../alt":"/Users/alex/Projects/webdrop/client/alt.js","../peer":"/Users/alex/Projects/webdrop/client/peer.js","../socket":"/Users/alex/Projects/webdrop/client/socket.js"}],"/Users/alex/Projects/webdrop/client/stores/UploadStore.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var UploadActions = _interopRequire(require("../actions/UploadActions")); var UploadFile = _interopRequire(require("../UploadFile")); var alt = _interopRequire(require("../alt")); var peer = _interopRequire(require("../peer")); var socket = _interopRequire(require("../socket")); var chunkSize = 32; module.exports = alt.createStore((function () { function UploadStore() { _classCallCheck(this, UploadStore); this.bindActions(UploadActions); this.status = "ready"; this.token = null; this.file = null; this.inProgress = 0; this.completed = 0; } _createClass(UploadStore, { onUploadFile: { value: function onUploadFile(file) { var _this = this; if (this.status !== "ready") { return; }this.status = "processing"; this.file = new UploadFile(file); socket.emit("upload", { name: this.file.name, size: this.file.size, type: this.file.type }, function (token) { _this.setState({ status: "uploading", token: token }); }); } }, onSendToDownloader: { value: function onSendToDownloader(peerID) { var _this = this; if (this.status !== "uploading") { return; }var conn = peer.connect(peerID, { reliable: true, metadata: { chunkSize: chunkSize } }); var complete = false; var totalPackets = this.file.countPackets(); var i = 0; var sendNextChunk = function () { if (complete) return; for (var j = 0; i < totalPackets && j < chunkSize; i++, j++) { var packet = _this.file.getPacket(i); conn.send(packet); } if (i === totalPackets) complete = true; }; conn.on("open", function () { _this.setState({ inProgress: _this.inProgress + 1 }); sendNextChunk(); }); conn.on("data", function (data) { if (data === "more") sendNextChunk(); }); conn.on("close", function () { _this.setState({ inProgress: _this.inProgress - 1, completed: _this.completed + (complete ? 1 : 0) }); }); } } }); return UploadStore; })(), "UploadStore"); },{"../UploadFile":"/Users/alex/Projects/webdrop/client/UploadFile.js","../actions/UploadActions":"/Users/alex/Projects/webdrop/client/actions/UploadActions.js","../alt":"/Users/alex/Projects/webdrop/client/alt.js","../peer":"/Users/alex/Projects/webdrop/client/peer.js","../socket":"/Users/alex/Projects/webdrop/client/socket.js"}],"/Users/alex/Projects/webdrop/node_modules/alt/dist/alt.js":[function(require,module,exports){ "use strict"; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var Dispatcher = require("flux").Dispatcher; var EventEmitter = _interopRequire(require("eventemitter3")); var Symbol = _interopRequire(require("es-symbol")); var assign = _interopRequire(require("object-assign")); var ACTION_HANDLER = Symbol("action creator handler"); var ACTION_KEY = Symbol("holds the actions uid symbol for listening"); var ACTION_UID = Symbol("the actions uid name"); var EE = Symbol("event emitter instance"); var INIT_SNAPSHOT = Symbol("init snapshot storage"); var LAST_SNAPSHOT = Symbol("last snapshot storage"); var LIFECYCLE = Symbol("store lifecycle listeners"); var LISTENERS = Symbol("stores action listeners storage"); var PUBLIC_METHODS = Symbol("store public method storage"); var STATE_CONTAINER = Symbol("the state container"); function formatAsConstant(name) { return name.replace(/[a-z]([A-Z])/g, function (i) { return "" + i[0] + "_" + i[1].toLowerCase(); }).toUpperCase(); } function uid(container, name) { var count = 0; var key = name; while (Object.hasOwnProperty.call(container, key)) { key = name + String(++count); } return key; } /* istanbul ignore next */ function NoopClass() {} var builtIns = Object.getOwnPropertyNames(NoopClass); var builtInProto = Object.getOwnPropertyNames(NoopClass.prototype); var getInternalMethods = function (obj, excluded) { return Object.getOwnPropertyNames(obj).reduce(function (value, m) { if (excluded.indexOf(m) !== -1) { return value; } value[m] = obj[m]; return value; }, {}); }; var AltStore = (function () { function AltStore(dispatcher, model, state) { var _this8 = this; _classCallCheck(this, AltStore); this[EE] = new EventEmitter(); this[LIFECYCLE] = {}; this[STATE_CONTAINER] = state || model; assign(this[LIFECYCLE], model[LIFECYCLE]); assign(this, model[PUBLIC_METHODS]); // Register dispatcher this.dispatchToken = dispatcher.register(function (payload) { if (model[LISTENERS][payload.action]) { var result = model[LISTENERS][payload.action](payload.data); if (result !== false) { _this8.emitChange(); } } }); if (this[LIFECYCLE].init) { this[LIFECYCLE].init(); } } _createClass(AltStore, { getEventEmitter: { value: function getEventEmitter() { return this[EE]; } }, emitChange: { value: function emitChange() { this[EE].emit("change", this[STATE_CONTAINER]); } }, listen: { value: function listen(cb) { this[EE].on("change", cb); } }, unlisten: { value: function unlisten(cb) { this[EE].removeListener("change", cb); } }, getState: { value: function getState() { // Copy over state so it's RO. return assign({}, this[STATE_CONTAINER]); } } }); return AltStore; })(); var ActionCreator = (function () { function ActionCreator(alt, name, action, actions) { _classCallCheck(this, ActionCreator); this[ACTION_UID] = name; this[ACTION_HANDLER] = action.bind(this); this.actions = actions; this.alt = alt; } _createClass(ActionCreator, { dispatch: { value: function dispatch(data) { this.alt.dispatch(this[ACTION_UID], data); } } }); return ActionCreator; })(); var StoreMixinListeners = { on: function on(lifecycleEvent, handler) { this[LIFECYCLE][lifecycleEvent] = handler.bind(this); }, bindAction: function bindAction(symbol, handler) { if (!symbol) { throw new ReferenceError("Invalid action reference passed in"); } if (typeof handler !== "function") { throw new TypeError("bindAction expects a function"); } if (handler.length > 1) { throw new TypeError("Action handler in store " + this._storeName + " for " + ("" + (symbol[ACTION_KEY] || symbol).toString() + " was defined with 2 ") + "parameters. Only a single parameter is passed through the " + "dispatcher, did you mean to pass in an Object instead?"); } // You can pass in the constant or the function itself if (symbol[ACTION_KEY]) { this[LISTENERS][symbol[ACTION_KEY]] = handler.bind(this); } else { this[LISTENERS][symbol] = handler.bind(this); } }, bindActions: function bindActions(actions) { var _this8 = this; Object.keys(actions).forEach(function (action) { var symbol = actions[action]; var matchFirstCharacter = /./; var assumedEventHandler = action.replace(matchFirstCharacter, function (x) { return "on" + x[0].toUpperCase(); }); var handler = null; if (_this8[action] && _this8[assumedEventHandler]) { // If you have both action and onAction throw new ReferenceError("You have multiple action handlers bound to an action: " + ("" + action + " and " + assumedEventHandler)); } else if (_this8[action]) { // action handler = _this8[action]; } else if (_this8[assumedEventHandler]) { // onAction handler = _this8[assumedEventHandler]; } if (handler) { _this8.bindAction(symbol, handler); } }); }, bindListeners: function bindListeners(obj) { var _this8 = this; Object.keys(obj).forEach(function (methodName) { var symbol = obj[methodName]; var listener = _this8[methodName]; if (!listener) { throw new ReferenceError("" + methodName + " defined but does not exist in " + _this8._storeName); } if (Array.isArray(symbol)) { symbol.forEach(function (action) { _this8.bindAction(action, listener); }); } else { _this8.bindAction(symbol, listener); } }); } }; var StoreMixinEssentials = { waitFor: function waitFor(sources) { if (!sources) { throw new ReferenceError("Dispatch tokens not provided"); } if (arguments.length === 1) { sources = Array.isArray(sources) ? sources : [sources]; } else { sources = Array.prototype.slice.call(arguments); } var tokens = sources.map(function (source) { return source.dispatchToken || source; }); this.dispatcher.waitFor(tokens); }, exportPublicMethods: function exportPublicMethods(methods) { var _this8 = this; Object.keys(methods).forEach(function (methodName) { if (typeof methods[methodName] !== "function") { throw new TypeError("exportPublicMethods expects a function"); } _this8[PUBLIC_METHODS][methodName] = methods[methodName]; }); }, emitChange: function emitChange() { this.getInstance().emitChange(); } }; var setAppState = function (instance, data, onStore) { var obj = JSON.parse(data); Object.keys(obj).forEach(function (key) { var store = instance.stores[key]; if (store[LIFECYCLE].deserialize) { obj[key] = store[LIFECYCLE].deserialize(obj[key]) || obj[key]; } assign(store[STATE_CONTAINER], obj[key]); onStore(store); }); }; var snapshot = function (instance) { return JSON.stringify(Object.keys(instance.stores).reduce(function (obj, key) { var store = instance.stores[key]; var customSnapshot = store[LIFECYCLE].serialize && store[LIFECYCLE].serialize(); obj[key] = customSnapshot ? customSnapshot : store.getState(); return obj; }, {})); }; var saveInitialSnapshot = function (instance, key) { var state = instance.stores[key][STATE_CONTAINER]; var initial = JSON.parse(instance[INIT_SNAPSHOT]); initial[key] = state; instance[INIT_SNAPSHOT] = JSON.stringify(initial); }; var filterSnapshotOfStores = function (serializedSnapshot, storeNames) { var stores = JSON.parse(serializedSnapshot); var storesToReset = storeNames.reduce(function (obj, name) { if (!stores[name]) { throw new ReferenceError("" + name + " is not a valid store"); } obj[name] = stores[name]; return obj; }, {}); return JSON.stringify(storesToReset); }; var createStoreFromObject = function (alt, StoreModel, key, saveStore) { var storeInstance = undefined; var StoreProto = {}; StoreProto[LIFECYCLE] = {}; StoreProto[LISTENERS] = {}; assign(StoreProto, { _storeName: key, alt: alt, dispatcher: alt.dispatcher, getInstance: function getInstance() { return storeInstance; }, setState: function setState() { var values = arguments[0] === undefined ? {} : arguments[0]; assign(this.state, values); this.emitChange(); return false; } }, StoreMixinListeners, StoreMixinEssentials, StoreModel); // bind the store listeners /* istanbul ignore else */ if (StoreProto.bindListeners) { StoreMixinListeners.bindListeners.call(StoreProto, StoreProto.bindListeners); } // bind the lifecycle events /* istanbul ignore else */ if (StoreProto.lifecycle) { Object.keys(StoreProto.lifecycle).forEach(function (event) { StoreMixinListeners.on.call(StoreProto, event, StoreProto.lifecycle[event]); }); } // create the instance and assign the public methods to the instance storeInstance = assign(new AltStore(alt.dispatcher, StoreProto, StoreProto.state), StoreProto.publicMethods); /* istanbul ignore else */ if (saveStore) { alt.stores[key] = storeInstance; saveInitialSnapshot(alt, key); } return storeInstance; }; var Alt = (function () { function Alt() { _classCallCheck(this, Alt); this.dispatcher = new Dispatcher(); this.actions = {}; this.stores = {}; this[LAST_SNAPSHOT] = null; this[INIT_SNAPSHOT] = "{}"; } _createClass(Alt, { dispatch: { value: function dispatch(action, data) { this.dispatcher.dispatch({ action: action, data: data }); } }, createStore: { value: function createStore(StoreModel, iden) { var saveStore = arguments[2] === undefined ? true : arguments[2]; var storeInstance = undefined; var key = iden || StoreModel.name || StoreModel.displayName || ""; if (saveStore && (this.stores[key] || !key)) { /* istanbul ignore else */ if (typeof console !== "undefined") { if (this.stores[key]) { console.warn(new ReferenceError("A store named " + key + " already exists, double check your store " + "names or pass in your own custom identifier for each store")); } else { console.warn(new ReferenceError("Store name was not specified")); } } key = uid(this.stores, key); } if (typeof StoreModel === "object") { return createStoreFromObject(this, StoreModel, key, saveStore); } // Creating a class here so we don't overload the provided store's // prototype with the mixin behaviour and I'm extending from StoreModel // so we can inherit any extensions from the provided store. var Store = (function (_StoreModel) { function Store(alt) { _classCallCheck(this, Store); _get(Object.getPrototypeOf(Store.prototype), "constructor", this).call(this, alt); } _inherits(Store, _StoreModel); return Store; })(StoreModel); assign(Store.prototype, StoreMixinListeners, StoreMixinEssentials, { _storeName: key, alt: this, dispatcher: this.dispatcher, getInstance: function getInstance() { return storeInstance; }, setState: function setState() { var values = arguments[0] === undefined ? {} : arguments[0]; assign(this, values); this.emitChange(); return false; } }); Store.prototype[LIFECYCLE] = {}; Store.prototype[LISTENERS] = {}; Store.prototype[PUBLIC_METHODS] = {}; var store = new Store(this); storeInstance = assign(new AltStore(this.dispatcher, store), getInternalMethods(StoreModel, builtIns)); if (saveStore) { this.stores[key] = storeInstance; saveInitialSnapshot(this, key); } return storeInstance; } }, generateActions: { value: function generateActions() { for (var _len = arguments.length, actionNames = Array(_len), _key = 0; _key < _len; _key++) { actionNames[_key] = arguments[_key]; } return this.createActions(function () { this.generateActions.apply(this, actionNames); }); } }, createActions: { value: function createActions(ActionsClass) { var _this8 = this; var exportObj = arguments[1] === undefined ? {} : arguments[1]; var actions = assign({}, getInternalMethods(ActionsClass.prototype, builtInProto)); var key = ActionsClass.name || ActionsClass.displayName || ""; var ActionsGenerator = (function (_ActionsClass) { function ActionsGenerator(alt) { _classCallCheck(this, ActionsGenerator); _get(Object.getPrototypeOf(ActionsGenerator.prototype), "constructor", this).call(this, alt); } _inherits(ActionsGenerator, _ActionsClass); _createClass(ActionsGenerator, { generateActions: { value: function generateActions() { for (var _len = arguments.length, actionNames = Array(_len), _key = 0; _key < _len; _key++) { actionNames[_key] = arguments[_key]; } actionNames.forEach(function (actionName) { // This is a function so we can later bind this to ActionCreator actions[actionName] = function (x) { for (var _len2 = arguments.length, a = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { a[_key2 - 1] = arguments[_key2]; } this.dispatch(a.length ? [x].concat(a) : x); }; }); } } }); return ActionsGenerator; })(ActionsClass); new ActionsGenerator(this); return Object.keys(actions).reduce(function (obj, action) { var constant = formatAsConstant(action); var actionName = Symbol("" + key + "#" + action); // Wrap the action so we can provide a dispatch method var newAction = new ActionCreator(_this8, actionName, actions[action], obj); // Set all the properties on action obj[action] = newAction[ACTION_HANDLER]; obj[action].defer = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } setTimeout(function () { newAction[ACTION_HANDLER].apply(null, args); }); }; obj[action][ACTION_KEY] = actionName; obj[constant] = actionName; return obj; }, exportObj); } }, takeSnapshot: { value: function takeSnapshot() { var state = snapshot(this); this[LAST_SNAPSHOT] = state; return state; } }, rollback: { value: function rollback() { setAppState(this, this[LAST_SNAPSHOT], function (store) { if (store[LIFECYCLE].rollback) { store[LIFECYCLE].rollback(); } }); } }, recycle: { value: function recycle() { for (var _len = arguments.length, storeNames = Array(_len), _key = 0; _key < _len; _key++) { storeNames[_key] = arguments[_key]; } var initialSnapshot = storeNames.length ? filterSnapshotOfStores(this[INIT_SNAPSHOT], storeNames) : this[INIT_SNAPSHOT]; setAppState(this, initialSnapshot, function (store) { if (store[LIFECYCLE].init) { store[LIFECYCLE].init(); } }); } }, flush: { value: function flush() { var state = snapshot(this); this.recycle(); return state; } }, bootstrap: { value: function bootstrap(data) { setAppState(this, data, function (store) { if (store[LIFECYCLE].bootstrap) { store[LIFECYCLE].bootstrap(); } }); } }, addActions: { // Instance type methods for injecting alt into your application as context value: function addActions(name, ActionsClass) { this.actions[name] = this.createActions(ActionsClass); } }, addStore: { value: function addStore(name, StoreModel, saveStore) { this.createStore(StoreModel, name, saveStore); } }, getActions: { value: function getActions(name) { return this.actions[name]; } }, getStore: { value: function getStore(name) { return this.stores[name]; } } }); return Alt; })(); module.exports = Alt; },{"es-symbol":"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/es-symbol/dist/symbol.js","eventemitter3":"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/eventemitter3/index.js","flux":"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/flux/index.js","object-assign":"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/object-assign/index.js"}],"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/es-symbol/dist/symbol.js":[function(require,module,exports){ "use strict"; var globalSymbolRegistryList = {}; // Aliases & Helpers var make = Object.create; var defProps = Object.defineProperties; var defProp = Object.defineProperty; var defValue = function (value) { var opts = arguments[1] === undefined ? {} : arguments[1]; return { value: value, configurable: !!opts.c, writable: !!opts.w, enumerable: !!opts.e }; }; var isSymbol = function (symbol) { return symbol && symbol[xSymbol.toStringTag] === "Symbol"; }; var supportsAccessors = undefined; try { var x = defProp({}, "y", { get: function () { return 1; } }); supportsAccessors = x.y === 1; } catch (e) { supportsAccessors = false; } var id = {}; var uid = function (desc) { desc = String(desc); var x = ""; var i = 0; while (id[desc + x]) { x = i += 1; } id[desc + x] = 1; var tag = "Symbol(" + desc + "" + x + ")"; /* istanbul ignore else */ if (supportsAccessors) { // Make the symbols hidden to pre-es6 code defProp(Object.prototype, tag, { get: undefined, set: function (value) { defProp(this, tag, defValue(value, { c: true, w: true })); }, configurable: true, enumerable: false }); } return tag; }; // The base symbol var SymbolProto = make(null); // 19.4.1.1 function xSymbol(descString) { if (this instanceof xSymbol) { throw new TypeError("Symbol is not a constructor"); } descString = descString === undefined ? "" : String(descString); var tag = uid(descString); /* istanbul ignore next */ if (!supportsAccessors) { return tag; } return make(SymbolProto, { __description__: defValue(descString), __tag__: defValue(tag) }); } defProps(xSymbol, { // 19.4.2.1 "for": defValue(function (key) { var stringKey = String(key); if (globalSymbolRegistryList[stringKey]) { return globalSymbolRegistryList[stringKey]; } var symbol = xSymbol(stringKey); globalSymbolRegistryList[stringKey] = symbol; return symbol; }), // 19.4.2.5 keyFor: defValue(function (sym) { if (!isSymbol(sym)) { throw new TypeError("" + sym + " is not a symbol"); } for (var key in globalSymbolRegistryList) { if (globalSymbolRegistryList[key] === sym) { return globalSymbolRegistryList[key].__description__; } } }) }); // 6.1.5.1 defProps(xSymbol, { hasInstance: defValue(xSymbol("hasInstance")), isConcatSpreadable: defValue(xSymbol("isConcatSpreadable")), iterator: defValue(xSymbol("iterator")), match: defValue(xSymbol("match")), replace: defValue(xSymbol("replace")), search: defValue(xSymbol("search")), species: defValue(xSymbol("species")), split: defValue(xSymbol("split")), toPrimitive: defValue(xSymbol("toPrimitive")), toStringTag: defValue(xSymbol("toStringTag")), unscopables: defValue(xSymbol("unscopables")) }); // 19.4.3 defProps(SymbolProto, { constructor: defValue(xSymbol), // 19.4.3.2 toString: defValue(function () { return this.__tag__; }), // 19.4.3.3 valueOf: defValue(function () { return "Symbol(" + this.__description__ + ")"; }) }); // 19.4.3.5 /* istanbul ignore else */ if (supportsAccessors) { defProp(SymbolProto, xSymbol.toStringTag, defValue("Symbol", { c: true })); } module.exports = typeof Symbol === "function" ? Symbol : xSymbol; },{}],"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/eventemitter3/index.js":[function(require,module,exports){ 'use strict'; /** * Representation of a single EventEmitter function. * * @param {Function} fn Event handler to be called. * @param {Mixed} context Context for function execution. * @param {Boolean} once Only emit once * @api private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Minimal EventEmitter interface that is molded against the Node.js * EventEmitter interface. * * @constructor * @api public */ function EventEmitter() { /* Nothing to set */ } /** * Holds the assigned EventEmitters by name. * * @type {Object} * @private */ EventEmitter.prototype._events = undefined; /** * Return a list of assigned event listeners. * * @param {String} event The events that should be listed. * @returns {Array} * @api public */ EventEmitter.prototype.listeners = function listeners(event) { if (!this._events || !this._events[event]) return []; if (this._events[event].fn) return [this._events[event].fn]; for (var i = 0, l = this._events[event].length, ee = new Array(l); i < l; i++) { ee[i] = this._events[event][i].fn; } return ee; }; /** * Emit an event to all registered event listeners. * * @param {String} event The name of the event. * @returns {Boolean} Indication if we've emitted an event. * @api public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { if (!this._events || !this._events[event]) return false; var listeners = this._events[event] , len = arguments.length , args , i; if ('function' === typeof listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Register a new EventListener for the given event. * * @param {String} event Name of the event. * @param {Functon} fn Callback function. * @param {Mixed} context The context of the function. * @api public */ EventEmitter.prototype.on = function on(event, fn, context) { var listener = new EE(fn, context || this); if (!this._events) this._events = {}; if (!this._events[event]) this._events[event] = listener; else { if (!this._events[event].fn) this._events[event].push(listener); else this._events[event] = [ this._events[event], listener ]; } return this; }; /** * Add an EventListener that's only called once. * * @param {String} event Name of the event. * @param {Function} fn Callback function. * @param {Mixed} context The context of the function. * @api public */ EventEmitter.prototype.once = function once(event, fn, context) { var listener = new EE(fn, context || this, true); if (!this._events) this._events = {}; if (!this._events[event]) this._events[event] = listener; else { if (!this._events[event].fn) this._events[event].push(listener); else this._events[event] = [ this._events[event], listener ]; } return this; }; /** * Remove event listeners. * * @param {String} event The event we want to remove. * @param {Function} fn The listener that we need to find. * @param {Boolean} once Only remove once listeners. * @api public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, once) { if (!this._events || !this._events[event]) return this; var listeners = this._events[event] , events = []; if (fn) { if (listeners.fn && (listeners.fn !== fn || (once && !listeners.once))) { events.push(listeners); } if (!listeners.fn) for (var i = 0, length = listeners.length; i < length; i++) { if (listeners[i].fn !== fn || (once && !listeners[i].once)) { events.push(listeners[i]); } } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) { this._events[event] = events.length === 1 ? events[0] : events; } else { delete this._events[event]; } return this; }; /** * Remove all listeners or only the listeners for the specified event. * * @param {String} event The event want to remove all listeners for. * @api public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { if (!this._events) return this; if (event) delete this._events[event]; else this._events = {}; return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // This function doesn't apply anymore. // EventEmitter.prototype.setMaxListeners = function setMaxListeners() { return this; }; // // Expose the module. // EventEmitter.EventEmitter = EventEmitter; EventEmitter.EventEmitter2 = EventEmitter; EventEmitter.EventEmitter3 = EventEmitter; // // Expose the module. // module.exports = EventEmitter; },{}],"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/flux/index.js":[function(require,module,exports){ /** * Copyright (c) 2014, 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. */ module.exports.Dispatcher = require('./lib/Dispatcher') },{"./lib/Dispatcher":"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/flux/lib/Dispatcher.js"}],"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/flux/lib/Dispatcher.js":[function(require,module,exports){ /* * Copyright (c) 2014, 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 Dispatcher * @typechecks */ "use strict"; var invariant = require('./invariant'); var _lastID = 1; var _prefix = 'ID_'; /** * Dispatcher is used to broadcast payloads to registered callbacks. This is * different from generic pub-sub systems in two ways: * * 1) Callbacks are not subscribed to particular events. Every payload is * dispatched to every registered callback. * 2) Callbacks can be deferred in whole or part until other callbacks have * been executed. * * For example, consider this hypothetical flight destination form, which * selects a default city when a country is selected: * * var flightDispatcher = new Dispatcher(); * * // Keeps track of which country is selected * var CountryStore = {country: null}; * * // Keeps track of which city is selected * var CityStore = {city: null}; * * // Keeps track of the base flight price of the selected city * var FlightPriceStore = {price: null} * * When a user changes the selected city, we dispatch the payload: * * flightDispatcher.dispatch({ * actionType: 'city-update', * selectedCity: 'paris' * }); * * This payload is digested by `CityStore`: * * flightDispatcher.register(function(payload) { * if (payload.actionType === 'city-update') { * CityStore.city = payload.selectedCity; * } * }); * * When the user selects a country, we dispatch the payload: * * flightDispatcher.dispatch({ * actionType: 'country-update', * selectedCountry: 'australia' * }); * * This payload is digested by both stores: * * CountryStore.dispatchToken = flightDispatcher.register(function(payload) { * if (payload.actionType === 'country-update') { * CountryStore.country = payload.selectedCountry; * } * }); * * When the callback to update `CountryStore` is registered, we save a reference * to the returned token. Using this token with `waitFor()`, we can guarantee * that `CountryStore` is updated before the callback that updates `CityStore` * needs to query its data. * * CityStore.dispatchToken = flightDispatcher.register(function(payload) { * if (payload.actionType === 'country-update') { * // `CountryStore.country` may not be updated. * flightDispatcher.waitFor([CountryStore.dispatchToken]); * // `CountryStore.country` is now guaranteed to be updated. * * // Select the default city for the new country * CityStore.city = getDefaultCityForCountry(CountryStore.country); * } * }); * * The usage of `waitFor()` can be chained, for example: * * FlightPriceStore.dispatchToken = * flightDispatcher.register(function(payload) { * switch (payload.actionType) { * case 'country-update': * flightDispatcher.waitFor([CityStore.dispatchToken]); * FlightPriceStore.price = * getFlightPriceStore(CountryStore.country, CityStore.city); * break; * * case 'city-update': * FlightPriceStore.price = * FlightPriceStore(CountryStore.country, CityStore.city); * break; * } * }); * * The `country-update` payload will be guaranteed to invoke the stores' * registered callbacks in order: `CountryStore`, `CityStore`, then * `FlightPriceStore`. */ function Dispatcher() { this.$Dispatcher_callbacks = {}; this.$Dispatcher_isPending = {}; this.$Dispatcher_isHandled = {}; this.$Dispatcher_isDispatching = false; this.$Dispatcher_pendingPayload = null; } /** * Registers a callback to be invoked with every dispatched payload. Returns * a token that can be used with `waitFor()`. * * @param {function} callback * @return {string} */ Dispatcher.prototype.register=function(callback) { var id = _prefix + _lastID++; this.$Dispatcher_callbacks[id] = callback; return id; }; /** * Removes a callback based on its token. * * @param {string} id */ Dispatcher.prototype.unregister=function(id) { invariant( this.$Dispatcher_callbacks[id], 'Dispatcher.unregister(...): `%s` does not map to a registered callback.', id ); delete this.$Dispatcher_callbacks[id]; }; /** * Waits for the callbacks specified to be invoked before continuing execution * of the current callback. This method should only be used by a callback in * response to a dispatched payload. * * @param {array} ids */ Dispatcher.prototype.waitFor=function(ids) { invariant( this.$Dispatcher_isDispatching, 'Dispatcher.waitFor(...): Must be invoked while dispatching.' ); for (var ii = 0; ii < ids.length; ii++) { var id = ids[ii]; if (this.$Dispatcher_isPending[id]) { invariant( this.$Dispatcher_isHandled[id], 'Dispatcher.waitFor(...): Circular dependency detected while ' + 'waiting for `%s`.', id ); continue; } invariant( this.$Dispatcher_callbacks[id], 'Dispatcher.waitFor(...): `%s` does not map to a registered callback.', id ); this.$Dispatcher_invokeCallback(id); } }; /** * Dispatches a payload to all registered callbacks. * * @param {object} payload */ Dispatcher.prototype.dispatch=function(payload) { invariant( !this.$Dispatcher_isDispatching, 'Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.' ); this.$Dispatcher_startDispatching(payload); try { for (var id in this.$Dispatcher_callbacks) { if (this.$Dispatcher_isPending[id]) { continue; } this.$Dispatcher_invokeCallback(id); } } finally { this.$Dispatcher_stopDispatching(); } }; /** * Is this Dispatcher currently dispatching. * * @return {boolean} */ Dispatcher.prototype.isDispatching=function() { return this.$Dispatcher_isDispatching; }; /** * Call the callback stored with the given id. Also do some internal * bookkeeping. * * @param {string} id * @internal */ Dispatcher.prototype.$Dispatcher_invokeCallback=function(id) { this.$Dispatcher_isPending[id] = true; this.$Dispatcher_callbacks[id](this.$Dispatcher_pendingPayload); this.$Dispatcher_isHandled[id] = true; }; /** * Set up bookkeeping needed when dispatching. * * @param {object} payload * @internal */ Dispatcher.prototype.$Dispatcher_startDispatching=function(payload) { for (var id in this.$Dispatcher_callbacks) { this.$Dispatcher_isPending[id] = false; this.$Dispatcher_isHandled[id] = false; } this.$Dispatcher_pendingPayload = payload; this.$Dispatcher_isDispatching = true; }; /** * Clear bookkeeping used for dispatching. * * @internal */ Dispatcher.prototype.$Dispatcher_stopDispatching=function() { this.$Dispatcher_pendingPayload = null; this.$Dispatcher_isDispatching = false; }; module.exports = Dispatcher; },{"./invariant":"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/flux/lib/invariant.js"}],"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/flux/lib/invariant.js":[function(require,module,exports){ /** * Copyright (c) 2014, 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 invariant */ "use strict"; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (false) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( 'Invariant Violation: ' + format.replace(/%s/g, function() { return args[argIndex++]; }) ); } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; },{}],"/Users/alex/Projects/webdrop/node_modules/alt/node_modules/object-assign/index.js":[function(require,module,exports){ 'use strict'; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = Object.keys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; },{}],"/Users/alex/Projects/webdrop/node_modules/browserify/node_modules/process/browser.js":[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],"/Users/alex/Projects/webdrop/node_modules/classnames/index.js":[function(require,module,exports){ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames in case the script is included directly on a page if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } },{}],"/Users/alex/Projects/webdrop/node_modules/node-uuid/uuid.js":[function(require,module,exports){ // uuid.js // // Copyright (c) 2010-2012 Robert Kieffer // MIT License - http://opensource.org/licenses/mit-license.php (function() { var _global = this; // Unique ID creation requires a high quality random # generator. We feature // detect to determine the best RNG source, normalizing to a function that // returns 128-bits of randomness, since that's what's usually required var _rng; // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html // // Moderately fast, high quality if (typeof(_global.require) == 'function') { try { var _rb = _global.require('crypto').randomBytes; _rng = _rb && function() {return _rb(16);}; } catch(e) {} } if (!_rng && _global.crypto && crypto.getRandomValues) { // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto // // Moderately fast, high quality var _rnds8 = new Uint8Array(16); _rng = function whatwgRNG() { crypto.getRandomValues(_rnds8); return _rnds8; }; } if (!_rng) { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var _rnds = new Array(16); _rng = function() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return _rnds; }; } // Buffer class to use var BufferClass = typeof(_global.Buffer) == 'function' ? _global.Buffer : Array; // Maps for number <-> hex string conversion var _byteToHex = []; var _hexToByte = {}; for (var i = 0; i < 256; i++) { _byteToHex[i] = (i + 0x100).toString(16).substr(1); _hexToByte[_byteToHex[i]] = i; } // **`parse()` - Parse a UUID into it's component bytes** function parse(s, buf, offset) { var i = (buf && offset) || 0, ii = 0; buf = buf || []; s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) { if (ii < 16) { // Don't overflow! buf[i + ii++] = _hexToByte[oct]; } }); // Zero out remaining bytes if string was short while (ii < 16) { buf[i + ii++] = 0; } return buf; } // **`unparse()` - Convert UUID byte array (ala parse()) into a string** function unparse(buf, offset) { var i = offset || 0, bth = _byteToHex; return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; } // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html // random #'s we need to init node and clockseq var _seedBytes = _rng(); // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) var _nodeId = [ _seedBytes[0] | 0x01, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] ]; // Per 4.2.2, randomize (14 bit) clockseq var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; // Previous uuid creation time var _lastMSecs = 0, _lastNSecs = 0; // See https://github.com/broofa/node-uuid for API details function v1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; options = options || {}; var clockseq = options.clockseq != null ? options.clockseq : _clockseq; // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options.msecs != null ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq == null) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` var node = options.node || _nodeId; for (var n = 0; n < 6; n++) { b[i + n] = node[n]; } return buf ? buf : unparse(b); } // **`v4()` - Generate random UUID** // See https://github.com/broofa/node-uuid for API details function v4(options, buf, offset) { // Deprecated - 'format' argument, as supported in v1.2 var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options == 'binary' ? new BufferClass(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || _rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ii++) { buf[i + ii] = rnds[ii]; } } return buf || unparse(rnds); } // Export public API var uuid = v4; uuid.v1 = v1; uuid.v4 = v4; uuid.parse = parse; uuid.unparse = unparse; uuid.BufferClass = BufferClass; if (typeof(module) != 'undefined' && module.exports) { // Publish as node.js module module.exports = uuid; } else if (typeof define === 'function' && define.amd) { // Publish as AMD module define(function() {return uuid;}); } else { // Publish as global (in browsers) var _previousRoot = _global.uuid; // **`noConflict()` - (browser only) to reset global 'uuid' var** uuid.noConflict = function() { _global.uuid = _previousRoot; return uuid; }; _global.uuid = uuid; } }).call(this); },{}],"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/adapter.js":[function(require,module,exports){ module.exports.RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription; module.exports.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; module.exports.RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate; },{}],"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/dataconnection.js":[function(require,module,exports){ var util = require('./util'); var EventEmitter = require('eventemitter3'); var Negotiator = require('./negotiator'); var Reliable = require('reliable'); /** * Wraps a DataChannel between two Peers. */ function DataConnection(peer, provider, options) { if (!(this instanceof DataConnection)) return new DataConnection(peer, provider, options); EventEmitter.call(this); this.options = util.extend({ serialization: 'binary', reliable: false }, options); // Connection is not open yet. this.open = false; this.type = 'data'; this.peer = peer; this.provider = provider; this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken(); this.label = this.options.label || this.id; this.metadata = this.options.metadata; this.serialization = this.options.serialization; this.reliable = this.options.reliable; // Data channel buffering. this._buffer = []; this._buffering = false; this.bufferSize = 0; // For storing large data. this._chunkedData = {}; if (this.options._payload) { this._peerBrowser = this.options._payload.browser; } Negotiator.startConnection( this, this.options._payload || { originator: true } ); } util.inherits(DataConnection, EventEmitter); DataConnection._idPrefix = 'dc_'; /** Called by the Negotiator when the DataChannel is ready. */ DataConnection.prototype.initialize = function(dc) { this._dc = this.dataChannel = dc; this._configureDataChannel(); } DataConnection.prototype._configureDataChannel = function() { var self = this; if (util.supports.sctp) { this._dc.binaryType = 'arraybuffer'; } this._dc.onopen = function() { util.log('Data channel connection success'); self.open = true; self.emit('open'); } // Use the Reliable shim for non Firefox browsers if (!util.supports.sctp && this.reliable) { this._reliable = new Reliable(this._dc, util.debug); } if (this._reliable) { this._reliable.onmessage = function(msg) { self.emit('data', msg); }; } else { this._dc.onmessage = function(e) { self._handleDataMessage(e); }; } this._dc.onclose = function(e) { util.log('DataChannel closed for:', self.peer); self.close(); }; } // Handles a DataChannel message. DataConnection.prototype._handleDataMessage = function(e) { var self = this; var data = e.data; var datatype = data.constructor; if (this.serialization === 'binary' || this.serialization === 'binary-utf8') { if (datatype === Blob) { // Datatype should never be blob util.blobToArrayBuffer(data, function(ab) { data = util.unpack(ab); self.emit('data', data); }); return; } else if (datatype === ArrayBuffer) { data = util.unpack(data); } else if (datatype === String) { // String fallback for binary data for browsers that don't support binary yet var ab = util.binaryStringToArrayBuffer(data); data = util.unpack(ab); } } else if (this.serialization === 'json') { data = JSON.parse(data); } // Check if we've chunked--if so, piece things back together. // We're guaranteed that this isn't 0. if (data.__peerData) { var id = data.__peerData; var chunkInfo = this._chunkedData[id] || {data: [], count: 0, total: data.total}; chunkInfo.data[data.n] = data.data; chunkInfo.count += 1; if (chunkInfo.total === chunkInfo.count) { // Clean up before making the recursive call to `_handleDataMessage`. delete this._chunkedData[id]; // We've received all the chunks--time to construct the complete data. data = new Blob(chunkInfo.data); this._handleDataMessage({data: data}); } this._chunkedData[id] = chunkInfo; return; } this.emit('data', data); } /** * Exposed functionality for users. */ /** Allows user to close connection. */ DataConnection.prototype.close = function() { if (!this.open) { return; } this.open = false; Negotiator.cleanup(this); this.emit('close'); } /** Allows user to send data. */ DataConnection.prototype.send = function(data, chunked) { if (!this.open) { this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.')); return; } if (this._reliable) { // Note: reliable shim sending will make it so that you cannot customize // serialization. this._reliable.send(data); return; } var self = this; if (this.serialization === 'json') { this._bufferedSend(JSON.stringify(data)); } else if (this.serialization === 'binary' || this.serialization === 'binary-utf8') { var blob = util.pack(data); // For Chrome-Firefox interoperability, we need to make Firefox "chunk" // the data it sends out. var needsChunking = util.chunkedBrowsers[this._peerBrowser] || util.chunkedBrowsers[util.browser]; if (needsChunking && !chunked && blob.size > util.chunkedMTU) { this._sendChunks(blob); return; } // DataChannel currently only supports strings. if (!util.supports.sctp) { util.blobToBinaryString(blob, function(str) { self._bufferedSend(str); }); } else if (!util.supports.binaryBlob) { // We only do this if we really need to (e.g. blobs are not supported), // because this conversion is costly. util.blobToArrayBuffer(blob, function(ab) { self._bufferedSend(ab); }); } else { this._bufferedSend(blob); } } else { this._bufferedSend(data); } } DataConnection.prototype._bufferedSend = function(msg) { if (this._buffering || !this._trySend(msg)) { this._buffer.push(msg); this.bufferSize = this._buffer.length; } } // Returns true if the send succeeds. DataConnection.prototype._trySend = function(msg) { try { this._dc.send(msg); } catch (e) { this._buffering = true; var self = this; setTimeout(function() { // Try again. self._buffering = false; self._tryBuffer(); }, 100); return false; } return true; } // Try to send the first message in the buffer. DataConnection.prototype._tryBuffer = function() { if (this._buffer.length === 0) { return; } var msg = this._buffer[0]; if (this._trySend(msg)) { this._buffer.shift(); this.bufferSize = this._buffer.length; this._tryBuffer(); } } DataConnection.prototype._sendChunks = function(blob) { var blobs = util.chunk(blob); for (var i = 0, ii = blobs.length; i < ii; i += 1) { var blob = blobs[i]; this.send(blob, true); } } DataConnection.prototype.handleMessage = function(message) { var payload = message.payload; switch (message.type) { case 'ANSWER': this._peerBrowser = payload.browser; // Forward to negotiator Negotiator.handleSDP(message.type, this, payload.sdp); break; case 'CANDIDATE': Negotiator.handleCandidate(this, payload.candidate); break; default: util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer); break; } } module.exports = DataConnection; },{"./negotiator":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/negotiator.js","./util":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/util.js","eventemitter3":"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/eventemitter3/index.js","reliable":"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/reliable/lib/reliable.js"}],"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/mediaconnection.js":[function(require,module,exports){ var util = require('./util'); var EventEmitter = require('eventemitter3'); var Negotiator = require('./negotiator'); /** * Wraps the streaming interface between two Peers. */ function MediaConnection(peer, provider, options) { if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options); EventEmitter.call(this); this.options = util.extend({}, options); this.open = false; this.type = 'media'; this.peer = peer; this.provider = provider; this.metadata = this.options.metadata; this.localStream = this.options._stream; this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken(); if (this.localStream) { Negotiator.startConnection( this, {_stream: this.localStream, originator: true} ); } }; util.inherits(MediaConnection, EventEmitter); MediaConnection._idPrefix = 'mc_'; MediaConnection.prototype.addStream = function(remoteStream) { util.log('Receiving stream', remoteStream); this.remoteStream = remoteStream; this.emit('stream', remoteStream); // Should we call this `open`? }; MediaConnection.prototype.handleMessage = function(message) { var payload = message.payload; switch (message.type) { case 'ANSWER': // Forward to negotiator Negotiator.handleSDP(message.type, this, payload.sdp); this.open = true; break; case 'CANDIDATE': Negotiator.handleCandidate(this, payload.candidate); break; default: util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer); break; } } MediaConnection.prototype.answer = function(stream) { if (this.localStream) { util.warn('Local stream already exists on this MediaConnection. Are you answering a call twice?'); return; } this.options._payload._stream = stream; this.localStream = stream; Negotiator.startConnection( this, this.options._payload ) // Retrieve lost messages stored because PeerConnection not set up. var messages = this.provider._getMessages(this.id); for (var i = 0, ii = messages.length; i < ii; i += 1) { this.handleMessage(messages[i]); } this.open = true; }; /** * Exposed functionality for users. */ /** Allows user to close connection. */ MediaConnection.prototype.close = function() { if (!this.open) { return; } this.open = false; Negotiator.cleanup(this); this.emit('close') }; module.exports = MediaConnection; },{"./negotiator":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/negotiator.js","./util":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/util.js","eventemitter3":"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/eventemitter3/index.js"}],"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/negotiator.js":[function(require,module,exports){ var util = require('./util'); var RTCPeerConnection = require('./adapter').RTCPeerConnection; var RTCSessionDescription = require('./adapter').RTCSessionDescription; var RTCIceCandidate = require('./adapter').RTCIceCandidate; /** * Manages all negotiations between Peers. */ var Negotiator = { pcs: { data: {}, media: {} }, // type => {peerId: {pc_id: pc}}. //providers: {}, // provider's id => providers (there may be multiple providers/client. queue: [] // connections that are delayed due to a PC being in use. } Negotiator._idPrefix = 'pc_'; /** Returns a PeerConnection object set up correctly (for data, media). */ Negotiator.startConnection = function(connection, options) { var pc = Negotiator._getPeerConnection(connection, options); if (connection.type === 'media' && options._stream) { // Add the stream. pc.addStream(options._stream); } // Set the connection's PC. connection.pc = connection.peerConnection = pc; // What do we need to do now? if (options.originator) { if (connection.type === 'data') { // Create the datachannel. var config = {}; // Dropping reliable:false support, since it seems to be crashing // Chrome. /*if (util.supports.sctp && !options.reliable) { // If we have canonical reliable support... config = {maxRetransmits: 0}; }*/ // Fallback to ensure older browsers don't crash. if (!util.supports.sctp) { config = {reliable: options.reliable}; } var dc = pc.createDataChannel(connection.label, config); connection.initialize(dc); } if (!util.supports.onnegotiationneeded) { Negotiator._makeOffer(connection); } } else { Negotiator.handleSDP('OFFER', connection, options.sdp); } } Negotiator._getPeerConnection = function(connection, options) { if (!Negotiator.pcs[connection.type]) { util.error(connection.type + ' is not a valid connection type. Maybe you overrode the `type` property somewhere.'); } if (!Negotiator.pcs[connection.type][connection.peer]) { Negotiator.pcs[connection.type][connection.peer] = {}; } var peerConnections = Negotiator.pcs[connection.type][connection.peer]; var pc; // Not multiplexing while FF and Chrome have not-great support for it. /*if (options.multiplex) { ids = Object.keys(peerConnections); for (var i = 0, ii = ids.length; i < ii; i += 1) { pc = peerConnections[ids[i]]; if (pc.signalingState === 'stable') { break; // We can go ahead and use this PC. } } } else */ if (options.pc) { // Simplest case: PC id already provided for us. pc = Negotiator.pcs[connection.type][connection.peer][options.pc]; } if (!pc || pc.signalingState !== 'stable') { pc = Negotiator._startPeerConnection(connection); } return pc; } /* Negotiator._addProvider = function(provider) { if ((!provider.id && !provider.disconnected) || !provider.socket.open) { // Wait for provider to obtain an ID. provider.on('open', function(id) { Negotiator._addProvider(provider); }); } else { Negotiator.providers[provider.id] = provider; } }*/ /** Start a PC. */ Negotiator._startPeerConnection = function(connection) { util.log('Creating RTCPeerConnection.'); var id = Negotiator._idPrefix + util.randomToken(); var optional = {}; if (connection.type === 'data' && !util.supports.sctp) { optional = {optional: [{RtpDataChannels: true}]}; } else if (connection.type === 'media') { // Interop req for chrome. optional = {optional: [{DtlsSrtpKeyAgreement: true}]}; } var pc = new RTCPeerConnection(connection.provider.options.config, optional); Negotiator.pcs[connection.type][connection.peer][id] = pc; Negotiator._setupListeners(connection, pc, id); return pc; } /** Set up various WebRTC listeners. */ Negotiator._setupListeners = function(connection, pc, pc_id) { var peerId = connection.peer; var connectionId = connection.id; var provider = connection.provider; // ICE CANDIDATES. util.log('Listening for ICE candidates.'); pc.onicecandidate = function(evt) { if (evt.candidate) { util.log('Received ICE candidates for:', connection.peer); provider.socket.send({ type: 'CANDIDATE', payload: { candidate: evt.candidate, type: connection.type, connectionId: connection.id }, dst: peerId }); } }; pc.oniceconnectionstatechange = function() { switch (pc.iceConnectionState) { case 'disconnected': case 'failed': util.log('iceConnectionState is disconnected, closing connections to ' + peerId); connection.close(); break; case 'completed': pc.onicecandidate = util.noop; break; } }; // Fallback for older Chrome impls. pc.onicechange = pc.oniceconnectionstatechange; // ONNEGOTIATIONNEEDED (Chrome) util.log('Listening for `negotiationneeded`'); pc.onnegotiationneeded = function() { util.log('`negotiationneeded` triggered'); if (pc.signalingState == 'stable') { Negotiator._makeOffer(connection); } else { util.log('onnegotiationneeded triggered when not stable. Is another connection being established?'); } }; // DATACONNECTION. util.log('Listening for data channel'); // Fired between offer and answer, so options should already be saved // in the options hash. pc.ondatachannel = function(evt) { util.log('Received data channel'); var dc = evt.channel; var connection = provider.getConnection(peerId, connectionId); connection.initialize(dc); }; // MEDIACONNECTION. util.log('Listening for remote stream'); pc.onaddstream = function(evt) { util.log('Received remote stream'); var stream = evt.stream; var connection = provider.getConnection(peerId, connectionId); // 10/10/2014: looks like in Chrome 38, onaddstream is triggered after // setting the remote description. Our connection object in these cases // is actually a DATA connection, so addStream fails. // TODO: This is hopefully just a temporary fix. We should try to // understand why this is happening. if (connection.type === 'media') { connection.addStream(stream); } }; } Negotiator.cleanup = function(connection) { util.log('Cleaning up PeerConnection to ' + connection.peer); var pc = connection.pc; if (!!pc && (pc.readyState !== 'closed' || pc.signalingState !== 'closed')) { pc.close(); connection.pc = null; } } Negotiator._makeOffer = function(connection) { var pc = connection.pc; pc.createOffer(function(offer) { util.log('Created offer.'); if (!util.supports.sctp && connection.type === 'data' && connection.reliable) { offer.sdp = Reliable.higherBandwidthSDP(offer.sdp); } pc.setLocalDescription(offer, function() { util.log('Set localDescription: offer', 'for:', connection.peer); connection.provider.socket.send({ type: 'OFFER', payload: { sdp: offer, type: connection.type, label: connection.label, connectionId: connection.id, reliable: connection.reliable, serialization: connection.serialization, metadata: connection.metadata, browser: util.browser }, dst: connection.peer }); }, function(err) { connection.provider.emitError('webrtc', err); util.log('Failed to setLocalDescription, ', err); }); }, function(err) { connection.provider.emitError('webrtc', err); util.log('Failed to createOffer, ', err); }, connection.options.constraints); } Negotiator._makeAnswer = function(connection) { var pc = connection.pc; pc.createAnswer(function(answer) { util.log('Created answer.'); if (!util.supports.sctp && connection.type === 'data' && connection.reliable) { answer.sdp = Reliable.higherBandwidthSDP(answer.sdp); } pc.setLocalDescription(answer, function() { util.log('Set localDescription: answer', 'for:', connection.peer); connection.provider.socket.send({ type: 'ANSWER', payload: { sdp: answer, type: connection.type, connectionId: connection.id, browser: util.browser }, dst: connection.peer }); }, function(err) { connection.provider.emitError('webrtc', err); util.log('Failed to setLocalDescription, ', err); }); }, function(err) { connection.provider.emitError('webrtc', err); util.log('Failed to create answer, ', err); }); } /** Handle an SDP. */ Negotiator.handleSDP = function(type, connection, sdp) { sdp = new RTCSessionDescription(sdp); var pc = connection.pc; util.log('Setting remote description', sdp); pc.setRemoteDescription(sdp, function() { util.log('Set remoteDescription:', type, 'for:', connection.peer); if (type === 'OFFER') { Negotiator._makeAnswer(connection); } }, function(err) { connection.provider.emitError('webrtc', err); util.log('Failed to setRemoteDescription, ', err); }); } /** Handle a candidate. */ Negotiator.handleCandidate = function(connection, ice) { var candidate = ice.candidate; var sdpMLineIndex = ice.sdpMLineIndex; connection.pc.addIceCandidate(new RTCIceCandidate({ sdpMLineIndex: sdpMLineIndex, candidate: candidate })); util.log('Added ICE candidate for:', connection.peer); } module.exports = Negotiator; },{"./adapter":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/adapter.js","./util":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/util.js"}],"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/peer.js":[function(require,module,exports){ var util = require('./util'); var EventEmitter = require('eventemitter3'); var Socket = require('./socket'); var MediaConnection = require('./mediaconnection'); var DataConnection = require('./dataconnection'); /** * A peer who can initiate connections with other peers. */ function Peer(id, options) { if (!(this instanceof Peer)) return new Peer(id, options); EventEmitter.call(this); // Deal with overloading if (id && id.constructor == Object) { options = id; id = undefined; } else if (id) { // Ensure id is a string id = id.toString(); } // // Configurize options options = util.extend({ debug: 0, // 1: Errors, 2: Warnings, 3: All logs host: util.CLOUD_HOST, port: util.CLOUD_PORT, key: 'peerjs', path: '/', token: util.randomToken(), config: util.defaultConfig }, options); this.options = options; // Detect relative URL host. if (options.host === '/') { options.host = window.location.hostname; } // Set path correctly. if (options.path[0] !== '/') { options.path = '/' + options.path; } if (options.path[options.path.length - 1] !== '/') { options.path += '/'; } // Set whether we use SSL to same as current host if (options.secure === undefined && options.host !== util.CLOUD_HOST) { options.secure = util.isSecure(); } // Set a custom log function if present if (options.logFunction) { util.setLogFunction(options.logFunction); } util.setLogLevel(options.debug); // // Sanity checks // Ensure WebRTC supported if (!util.supports.audioVideo && !util.supports.data ) { this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC'); return; } // Ensure alphanumeric id if (!util.validateId(id)) { this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid'); return; } // Ensure valid key if (!util.validateKey(options.key)) { this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid'); return; } // Ensure not using unsecure cloud server on SSL page if (options.secure && options.host === '0.peerjs.com') { this._delayedAbort('ssl-unavailable', 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.'); return; } // // States. this.destroyed = false; // Connections have been killed this.disconnected = false; // Connection to PeerServer killed but P2P connections still active this.open = false; // Sockets and such are not yet open. // // References this.connections = {}; // DataConnections for this peer. this._lostMessages = {}; // src => [list of messages] // // Start the server connection this._initializeServerConnection(); if (id) { this._initialize(id); } else { this._retrieveId(); } // } util.inherits(Peer, EventEmitter); // Initialize the 'socket' (which is actually a mix of XHR streaming and // websockets.) Peer.prototype._initializeServerConnection = function() { var self = this; this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.path, this.options.key); this.socket.on('message', function(data) { self._handleMessage(data); }); this.socket.on('error', function(error) { self._abort('socket-error', error); }); this.socket.on('disconnected', function() { // If we haven't explicitly disconnected, emit error and disconnect. if (!self.disconnected) { self.emitError('network', 'Lost connection to server.'); self.disconnect(); } }); this.socket.on('close', function() { // If we haven't explicitly disconnected, emit error. if (!self.disconnected) { self._abort('socket-closed', 'Underlying socket is already closed.'); } }); }; /** Get a unique ID from the server via XHR. */ Peer.prototype._retrieveId = function(cb) { var self = this; var http = new XMLHttpRequest(); var protocol = this.options.secure ? 'https://' : 'http://'; var url = protocol + this.options.host + ':' + this.options.port + this.options.path + this.options.key + '/id'; var queryString = '?ts=' + new Date().getTime() + '' + Math.random(); url += queryString; // If there's no ID we need to wait for one before trying to init socket. http.open('get', url, true); http.onerror = function(e) { util.error('Error retrieving ID', e); var pathError = ''; if (self.options.path === '/' && self.options.host !== util.CLOUD_HOST) { pathError = ' If you passed in a `path` to your self-hosted PeerServer, ' + 'you\'ll also need to pass in that same path when creating a new ' + 'Peer.'; } self._abort('server-error', 'Could not get an ID from the server.' + pathError); }; http.onreadystatechange = function() { if (http.readyState !== 4) { return; } if (http.status !== 200) { http.onerror(); return; } self._initialize(http.responseText); }; http.send(null); }; /** Initialize a connection with the server. */ Peer.prototype._initialize = function(id) { this.id = id; this.socket.start(this.id, this.options.token); }; /** Handles messages from the server. */ Peer.prototype._handleMessage = function(message) { var type = message.type; var payload = message.payload; var peer = message.src; var connection; switch (type) { case 'OPEN': // The connection to the server is open. this.emit('open', this.id); this.open = true; break; case 'ERROR': // Server error. this._abort('server-error', payload.msg); break; case 'ID-TAKEN': // The selected ID is taken. this._abort('unavailable-id', 'ID `' + this.id + '` is taken'); break; case 'INVALID-KEY': // The given API key cannot be found. this._abort('invalid-key', 'API KEY "' + this.options.key + '" is invalid'); break; // case 'LEAVE': // Another peer has closed its connection to this peer. util.log('Received leave message from', peer); this._cleanupPeer(peer); break; case 'EXPIRE': // The offer sent to a peer has expired without response. this.emitError('peer-unavailable', 'Could not connect to peer ' + peer); break; case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option. var connectionId = payload.connectionId; connection = this.getConnection(peer, connectionId); if (connection) { util.warn('Offer received for existing Connection ID:', connectionId); //connection.handleMessage(message); } else { // Create a new connection. if (payload.type === 'media') { connection = new MediaConnection(peer, this, { connectionId: connectionId, _payload: payload, metadata: payload.metadata }); this._addConnection(peer, connection); this.emit('call', connection); } else if (payload.type === 'data') { connection = new DataConnection(peer, this, { connectionId: connectionId, _payload: payload, metadata: payload.metadata, label: payload.label, serialization: payload.serialization, reliable: payload.reliable }); this._addConnection(peer, connection); this.emit('connection', connection); } else { util.warn('Received malformed connection type:', payload.type); return; } // Find messages. var messages = this._getMessages(connectionId); for (var i = 0, ii = messages.length; i < ii; i += 1) { connection.handleMessage(messages[i]); } } break; default: if (!payload) { util.warn('You received a malformed message from ' + peer + ' of type ' + type); return; } var id = payload.connectionId; connection = this.getConnection(peer, id); if (connection && connection.pc) { // Pass it on. connection.handleMessage(message); } else if (id) { // Store for possible later use this._storeMessage(id, message); } else { util.warn('You received an unrecognized message:', message); } break; } }; /** Stores messages without a set up connection, to be claimed later. */ Peer.prototype._storeMessage = function(connectionId, message) { if (!this._lostMessages[connectionId]) { this._lostMessages[connectionId] = []; } this._lostMessages[connectionId].push(message); }; /** Retrieve messages from lost message store */ Peer.prototype._getMessages = function(connectionId) { var messages = this._lostMessages[connectionId]; if (messages) { delete this._lostMessages[connectionId]; return messages; } else { return []; } }; /** * Returns a DataConnection to the specified peer. See documentation for a * complete list of options. */ Peer.prototype.connect = function(peer, options) { if (this.disconnected) { util.warn('You cannot connect to a new Peer because you called ' + '.disconnect() on this Peer and ended your connection with the ' + 'server. You can create a new Peer to reconnect, or call reconnect ' + 'on this peer if you believe its ID to still be available.'); this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.'); return; } var connection = new DataConnection(peer, this, options); this._addConnection(peer, connection); return connection; }; /** * Returns a MediaConnection to the specified peer. See documentation for a * complete list of options. */ Peer.prototype.call = function(peer, stream, options) { if (this.disconnected) { util.warn('You cannot connect to a new Peer because you called ' + '.disconnect() on this Peer and ended your connection with the ' + 'server. You can create a new Peer to reconnect.'); this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.'); return; } if (!stream) { util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.'); return; } options = options || {}; options._stream = stream; var call = new MediaConnection(peer, this, options); this._addConnection(peer, call); return call; }; /** Add a data/media connection to this peer. */ Peer.prototype._addConnection = function(peer, connection) { if (!this.connections[peer]) { this.connections[peer] = []; } this.connections[peer].push(connection); }; /** Retrieve a data/media connection for this peer. */ Peer.prototype.getConnection = function(peer, id) { var connections = this.connections[peer]; if (!connections) { return null; } for (var i = 0, ii = connections.length; i < ii; i++) { if (connections[i].id === id) { return connections[i]; } } return null; }; Peer.prototype._delayedAbort = function(type, message) { var self = this; util.setZeroTimeout(function(){ self._abort(type, message); }); }; /** * Destroys the Peer and emits an error message. * The Peer is not destroyed if it's in a disconnected state, in which case * it retains its disconnected state and its existing connections. */ Peer.prototype._abort = function(type, message) { util.error('Aborting!'); if (!this._lastServerId) { this.destroy(); } else { this.disconnect(); } this.emitError(type, message); }; /** Emits a typed error message. */ Peer.prototype.emitError = function(type, err) { util.error('Error:', err); if (typeof err === 'string') { err = new Error(err); } err.type = type; this.emit('error', err); }; /** * Destroys the Peer: closes all active connections as well as the connection * to the server. * Warning: The peer can no longer create or accept connections after being * destroyed. */ Peer.prototype.destroy = function() { if (!this.destroyed) { this._cleanup(); this.disconnect(); this.destroyed = true; } }; /** Disconnects every connection on this peer. */ Peer.prototype._cleanup = function() { if (this.connections) { var peers = Object.keys(this.connections); for (var i = 0, ii = peers.length; i < ii; i++) { this._cleanupPeer(peers[i]); } } this.emit('close'); }; /** Closes all connections to this peer. */ Peer.prototype._cleanupPeer = function(peer) { var connections = this.connections[peer]; for (var j = 0, jj = connections.length; j < jj; j += 1) { connections[j].close(); } }; /** * Disconnects the Peer's connection to the PeerServer. Does not close any * active connections. * Warning: The peer can no longer create or accept connections after being * disconnected. It also cannot reconnect to the server. */ Peer.prototype.disconnect = function() { var self = this; util.setZeroTimeout(function(){ if (!self.disconnected) { self.disconnected = true; self.open = false; if (self.socket) { self.socket.close(); } self.emit('disconnected', self.id); self._lastServerId = self.id; self.id = null; } }); }; /** Attempts to reconnect with the same ID. */ Peer.prototype.reconnect = function() { if (this.disconnected && !this.destroyed) { util.log('Attempting reconnection to server with ID ' + this._lastServerId); this.disconnected = false; this._initializeServerConnection(); this._initialize(this._lastServerId); } else if (this.destroyed) { throw new Error('This peer cannot reconnect to the server. It has already been destroyed.'); } else if (!this.disconnected && !this.open) { // Do nothing. We're still connecting the first time. util.error('In a hurry? We\'re still trying to make the initial connection!'); } else { throw new Error('Peer ' + this.id + ' cannot reconnect because it is not disconnected from the server!'); } }; /** * Get a list of available peer IDs. If you're running your own server, you'll * want to set allow_discovery: true in the PeerServer options. If you're using * the cloud server, email team@peerjs.com to get the functionality enabled for * your key. */ Peer.prototype.listAllPeers = function(cb) { cb = cb || function() {}; var self = this; var http = new XMLHttpRequest(); var protocol = this.options.secure ? 'https://' : 'http://'; var url = protocol + this.options.host + ':' + this.options.port + this.options.path + this.options.key + '/peers'; var queryString = '?ts=' + new Date().getTime() + '' + Math.random(); url += queryString; // If there's no ID we need to wait for one before trying to init socket. http.open('get', url, true); http.onerror = function(e) { self._abort('server-error', 'Could not get peers from the server.'); cb([]); }; http.onreadystatechange = function() { if (http.readyState !== 4) { return; } if (http.status === 401) { var helpfulError = ''; if (self.options.host !== util.CLOUD_HOST) { helpfulError = 'It looks like you\'re using the cloud server. You can email ' + 'team@peerjs.com to enable peer listing for your API key.'; } else { helpfulError = 'You need to enable `allow_discovery` on your self-hosted ' + 'PeerServer to use this feature.'; } cb([]); throw new Error('It doesn\'t look like you have permission to list peers IDs. ' + helpfulError); } else if (http.status !== 200) { cb([]); } else { cb(JSON.parse(http.responseText)); } }; http.send(null); }; module.exports = Peer; },{"./dataconnection":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/dataconnection.js","./mediaconnection":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/mediaconnection.js","./socket":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/socket.js","./util":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/util.js","eventemitter3":"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/eventemitter3/index.js"}],"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/socket.js":[function(require,module,exports){ var util = require('./util'); var EventEmitter = require('eventemitter3'); /** * An abstraction on top of WebSockets and XHR streaming to provide fastest * possible connection for peers. */ function Socket(secure, host, port, path, key) { if (!(this instanceof Socket)) return new Socket(secure, host, port, path, key); EventEmitter.call(this); // Disconnected manually. this.disconnected = false; this._queue = []; var httpProtocol = secure ? 'https://' : 'http://'; var wsProtocol = secure ? 'wss://' : 'ws://'; this._httpUrl = httpProtocol + host + ':' + port + path + key; this._wsUrl = wsProtocol + host + ':' + port + path + 'peerjs?key=' + key; } util.inherits(Socket, EventEmitter); /** Check in with ID or get one from server. */ Socket.prototype.start = function(id, token) { this.id = id; this._httpUrl += '/' + id + '/' + token; this._wsUrl += '&id=' + id + '&token=' + token; this._startXhrStream(); this._startWebSocket(); } /** Start up websocket communications. */ Socket.prototype._startWebSocket = function(id) { var self = this; if (this._socket) { return; } this._socket = new WebSocket(this._wsUrl); this._socket.onmessage = function(event) { try { var data = JSON.parse(event.data); } catch(e) { util.log('Invalid server message', event.data); return; } self.emit('message', data); }; this._socket.onclose = function(event) { util.log('Socket closed.'); self.disconnected = true; self.emit('disconnected'); }; // Take care of the queue of connections if necessary and make sure Peer knows // socket is open. this._socket.onopen = function() { if (self._timeout) { clearTimeout(self._timeout); setTimeout(function(){ self._http.abort(); self._http = null; }, 5000); } self._sendQueuedMessages(); util.log('Socket open'); }; } /** Start XHR streaming. */ Socket.prototype._startXhrStream = function(n) { try { var self = this; this._http = new XMLHttpRequest(); this._http._index = 1; this._http._streamIndex = n || 0; this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true); this._http.onerror = function() { // If we get an error, likely something went wrong. // Stop streaming. clearTimeout(self._timeout); self.emit('disconnected'); } this._http.onreadystatechange = function() { if (this.readyState == 2 && this.old) { this.old.abort(); delete this.old; } else if (this.readyState > 2 && this.status === 200 && this.responseText) { self._handleStream(this); } }; this._http.send(null); this._setHTTPTimeout(); } catch(e) { util.log('XMLHttpRequest not available; defaulting to WebSockets'); } } /** Handles onreadystatechange response as a stream. */ Socket.prototype._handleStream = function(http) { // 3 and 4 are loading/done state. All others are not relevant. var messages = http.responseText.split('\n'); // Check to see if anything needs to be processed on buffer. if (http._buffer) { while (http._buffer.length > 0) { var index = http._buffer.shift(); var bufferedMessage = messages[index]; try { bufferedMessage = JSON.parse(bufferedMessage); } catch(e) { http._buffer.shift(index); break; } this.emit('message', bufferedMessage); } } var message = messages[http._index]; if (message) { http._index += 1; // Buffering--this message is incomplete and we'll get to it next time. // This checks if the httpResponse ended in a `\n`, in which case the last // element of messages should be the empty string. if (http._index === messages.length) { if (!http._buffer) { http._buffer = []; } http._buffer.push(http._index - 1); } else { try { message = JSON.parse(message); } catch(e) { util.log('Invalid server message', message); return; } this.emit('message', message); } } } Socket.prototype._setHTTPTimeout = function() { var self = this; this._timeout = setTimeout(function() { var old = self._http; if (!self._wsOpen()) { self._startXhrStream(old._streamIndex + 1); self._http.old = old; } else { old.abort(); } }, 25000); } /** Is the websocket currently open? */ Socket.prototype._wsOpen = function() { return this._socket && this._socket.readyState == 1; } /** Send queued messages. */ Socket.prototype._sendQueuedMessages = function() { for (var i = 0, ii = this._queue.length; i < ii; i += 1) { this.send(this._queue[i]); } } /** Exposed send for DC & Peer. */ Socket.prototype.send = function(data) { if (this.disconnected) { return; } // If we didn't get an ID yet, we can't yet send anything so we should queue // up these messages. if (!this.id) { this._queue.push(data); return; } if (!data.type) { this.emit('error', 'Invalid message'); return; } var message = JSON.stringify(data); if (this._wsOpen()) { this._socket.send(message); } else { var http = new XMLHttpRequest(); var url = this._httpUrl + '/' + data.type.toLowerCase(); http.open('post', url, true); http.setRequestHeader('Content-Type', 'application/json'); http.send(message); } } Socket.prototype.close = function() { if (!this.disconnected && this._wsOpen()) { this._socket.close(); this.disconnected = true; } } module.exports = Socket; },{"./util":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/util.js","eventemitter3":"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/eventemitter3/index.js"}],"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/util.js":[function(require,module,exports){ var defaultConfig = {'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }]}; var dataCount = 1; var BinaryPack = require('js-binarypack'); var RTCPeerConnection = require('./adapter').RTCPeerConnection; var util = { noop: function() {}, CLOUD_HOST: '0.peerjs.com', CLOUD_PORT: 9000, // Browsers that need chunking: chunkedBrowsers: {'Chrome': 1}, chunkedMTU: 16300, // The original 60000 bytes setting does not work when sending data from Firefox to Chrome, which is "cut off" after 16384 bytes and delivered individually. // Logging logic logLevel: 0, setLogLevel: function(level) { var debugLevel = parseInt(level, 10); if (!isNaN(parseInt(level, 10))) { util.logLevel = debugLevel; } else { // If they are using truthy/falsy values for debug util.logLevel = level ? 3 : 0; } util.log = util.warn = util.error = util.noop; if (util.logLevel > 0) { util.error = util._printWith('ERROR'); } if (util.logLevel > 1) { util.warn = util._printWith('WARNING'); } if (util.logLevel > 2) { util.log = util._print; } }, setLogFunction: function(fn) { if (fn.constructor !== Function) { util.warn('The log function you passed in is not a function. Defaulting to regular logs.'); } else { util._print = fn; } }, _printWith: function(prefix) { return function() { var copy = Array.prototype.slice.call(arguments); copy.unshift(prefix); util._print.apply(util, copy); }; }, _print: function () { var err = false; var copy = Array.prototype.slice.call(arguments); copy.unshift('PeerJS: '); for (var i = 0, l = copy.length; i < l; i++){ if (copy[i] instanceof Error) { copy[i] = '(' + copy[i].name + ') ' + copy[i].message; err = true; } } err ? console.error.apply(console, copy) : console.log.apply(console, copy); }, // // Returns browser-agnostic default config defaultConfig: defaultConfig, // // Returns the current browser. browser: (function() { if (window.mozRTCPeerConnection) { return 'Firefox'; } else if (window.webkitRTCPeerConnection) { return 'Chrome'; } else if (window.RTCPeerConnection) { return 'Supported'; } else { return 'Unsupported'; } })(), // // Lists which features are supported supports: (function() { if (typeof RTCPeerConnection === 'undefined') { return {}; } var data = true; var audioVideo = true; var binaryBlob = false; var sctp = false; var onnegotiationneeded = !!window.webkitRTCPeerConnection; var pc, dc; try { pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]}); } catch (e) { data = false; audioVideo = false; } if (data) { try { dc = pc.createDataChannel('_PEERJSTEST'); } catch (e) { data = false; } } if (data) { // Binary test try { dc.binaryType = 'blob'; binaryBlob = true; } catch (e) { } // Reliable test. // Unfortunately Chrome is a bit unreliable about whether or not they // support reliable. var reliablePC = new RTCPeerConnection(defaultConfig, {}); try { var reliableDC = reliablePC.createDataChannel('_PEERJSRELIABLETEST', {}); sctp = reliableDC.reliable; } catch (e) { } reliablePC.close(); } // FIXME: not really the best check... if (audioVideo) { audioVideo = !!pc.addStream; } // FIXME: this is not great because in theory it doesn't work for // av-only browsers (?). if (!onnegotiationneeded && data) { // sync default check. var negotiationPC = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]}); negotiationPC.onnegotiationneeded = function() { onnegotiationneeded = true; // async check. if (util && util.supports) { util.supports.onnegotiationneeded = true; } }; negotiationPC.createDataChannel('_PEERJSNEGOTIATIONTEST'); setTimeout(function() { negotiationPC.close(); }, 1000); } if (pc) { pc.close(); } return { audioVideo: audioVideo, data: data, binaryBlob: binaryBlob, binary: sctp, // deprecated; sctp implies binary support. reliable: sctp, // deprecated; sctp implies reliable data. sctp: sctp, onnegotiationneeded: onnegotiationneeded }; }()), // // Ensure alphanumeric ids validateId: function(id) { // Allow empty ids return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id); }, validateKey: function(key) { // Allow empty keys return !key || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(key); }, debug: false, inherits: function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }, extend: function(dest, source) { for(var key in source) { if(source.hasOwnProperty(key)) { dest[key] = source[key]; } } return dest; }, pack: BinaryPack.pack, unpack: BinaryPack.unpack, log: function () { if (util.debug) { var err = false; var copy = Array.prototype.slice.call(arguments); copy.unshift('PeerJS: '); for (var i = 0, l = copy.length; i < l; i++){ if (copy[i] instanceof Error) { copy[i] = '(' + copy[i].name + ') ' + copy[i].message; err = true; } } err ? console.error.apply(console, copy) : console.log.apply(console, copy); } }, setZeroTimeout: (function(global) { var timeouts = []; var messageName = 'zero-timeout-message'; // Like setTimeout, but only takes a function argument. There's // no time argument (always zero) and no arguments (you have to // use a closure). function setZeroTimeoutPostMessage(fn) { timeouts.push(fn); global.postMessage(messageName, '*'); } function handleMessage(event) { if (event.source == global && event.data == messageName) { if (event.stopPropagation) { event.stopPropagation(); } if (timeouts.length) { timeouts.shift()(); } } } if (global.addEventListener) { global.addEventListener('message', handleMessage, true); } else if (global.attachEvent) { global.attachEvent('onmessage', handleMessage); } return setZeroTimeoutPostMessage; }(window)), // Binary stuff // chunks a blob. chunk: function(bl) { var chunks = []; var size = bl.size; var start = index = 0; var total = Math.ceil(size / util.chunkedMTU); while (start < size) { var end = Math.min(size, start + util.chunkedMTU); var b = bl.slice(start, end); var chunk = { __peerData: dataCount, n: index, data: b, total: total }; chunks.push(chunk); start = end; index += 1; } dataCount += 1; return chunks; }, blobToArrayBuffer: function(blob, cb){ var fr = new FileReader(); fr.onload = function(evt) { cb(evt.target.result); }; fr.readAsArrayBuffer(blob); }, blobToBinaryString: function(blob, cb){ var fr = new FileReader(); fr.onload = function(evt) { cb(evt.target.result); }; fr.readAsBinaryString(blob); }, binaryStringToArrayBuffer: function(binary) { var byteArray = new Uint8Array(binary.length); for (var i = 0; i < binary.length; i++) { byteArray[i] = binary.charCodeAt(i) & 0xff; } return byteArray.buffer; }, randomToken: function () { return Math.random().toString(36).substr(2); }, // isSecure: function() { return location.protocol === 'https:'; } }; module.exports = util; },{"./adapter":"/Users/alex/Projects/webdrop/node_modules/peerjs/lib/adapter.js","js-binarypack":"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/js-binarypack/lib/binarypack.js"}],"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/eventemitter3/index.js":[function(require,module,exports){ arguments[4]["/Users/alex/Projects/webdrop/node_modules/alt/node_modules/eventemitter3/index.js"][0].apply(exports,arguments) },{}],"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/js-binarypack/lib/binarypack.js":[function(require,module,exports){ var BufferBuilder = require('./bufferbuilder').BufferBuilder; var binaryFeatures = require('./bufferbuilder').binaryFeatures; var BinaryPack = { unpack: function(data){ var unpacker = new Unpacker(data); return unpacker.unpack(); }, pack: function(data){ var packer = new Packer(); packer.pack(data); var buffer = packer.getBuffer(); return buffer; } }; module.exports = BinaryPack; function Unpacker (data){ // Data is ArrayBuffer this.index = 0; this.dataBuffer = data; this.dataView = new Uint8Array(this.dataBuffer); this.length = this.dataBuffer.byteLength; } Unpacker.prototype.unpack = function(){ var type = this.unpack_uint8(); if (type < 0x80){ var positive_fixnum = type; return positive_fixnum; } else if ((type ^ 0xe0) < 0x20){ var negative_fixnum = (type ^ 0xe0) - 0x20; return negative_fixnum; } var size; if ((size = type ^ 0xa0) <= 0x0f){ return this.unpack_raw(size); } else if ((size = type ^ 0xb0) <= 0x0f){ return this.unpack_string(size); } else if ((size = type ^ 0x90) <= 0x0f){ return this.unpack_array(size); } else if ((size = type ^ 0x80) <= 0x0f){ return this.unpack_map(size); } switch(type){ case 0xc0: return null; case 0xc1: return undefined; case 0xc2: return false; case 0xc3: return true; case 0xca: return this.unpack_float(); case 0xcb: return this.unpack_double(); case 0xcc: return this.unpack_uint8(); case 0xcd: return this.unpack_uint16(); case 0xce: return this.unpack_uint32(); case 0xcf: return this.unpack_uint64(); case 0xd0: return this.unpack_int8(); case 0xd1: return this.unpack_int16(); case 0xd2: return this.unpack_int32(); case 0xd3: return this.unpack_int64(); case 0xd4: return undefined; case 0xd5: return undefined; case 0xd6: return undefined; case 0xd7: return undefined; case 0xd8: size = this.unpack_uint16(); return this.unpack_string(size); case 0xd9: size = this.unpack_uint32(); return this.unpack_string(size); case 0xda: size = this.unpack_uint16(); return this.unpack_raw(size); case 0xdb: size = this.unpack_uint32(); return this.unpack_raw(size); case 0xdc: size = this.unpack_uint16(); return this.unpack_array(size); case 0xdd: size = this.unpack_uint32(); return this.unpack_array(size); case 0xde: size = this.unpack_uint16(); return this.unpack_map(size); case 0xdf: size = this.unpack_uint32(); return this.unpack_map(size); } } Unpacker.prototype.unpack_uint8 = function(){ var byte = this.dataView[this.index] & 0xff; this.index++; return byte; }; Unpacker.prototype.unpack_uint16 = function(){ var bytes = this.read(2); var uint16 = ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff); this.index += 2; return uint16; } Unpacker.prototype.unpack_uint32 = function(){ var bytes = this.read(4); var uint32 = ((bytes[0] * 256 + bytes[1]) * 256 + bytes[2]) * 256 + bytes[3]; this.index += 4; return uint32; } Unpacker.prototype.unpack_uint64 = function(){ var bytes = this.read(8); var uint64 = ((((((bytes[0] * 256 + bytes[1]) * 256 + bytes[2]) * 256 + bytes[3]) * 256 + bytes[4]) * 256 + bytes[5]) * 256 + bytes[6]) * 256 + bytes[7]; this.index += 8; return uint64; } Unpacker.prototype.unpack_int8 = function(){ var uint8 = this.unpack_uint8(); return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8); }; Unpacker.prototype.unpack_int16 = function(){ var uint16 = this.unpack_uint16(); return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16); } Unpacker.prototype.unpack_int32 = function(){ var uint32 = this.unpack_uint32(); return (uint32 < Math.pow(2, 31) ) ? uint32 : uint32 - Math.pow(2, 32); } Unpacker.prototype.unpack_int64 = function(){ var uint64 = this.unpack_uint64(); return (uint64 < Math.pow(2, 63) ) ? uint64 : uint64 - Math.pow(2, 64); } Unpacker.prototype.unpack_raw = function(size){ if ( this.length < this.index + size){ throw new Error('BinaryPackFailure: index is out of range' + ' ' + this.index + ' ' + size + ' ' + this.length); } var buf = this.dataBuffer.slice(this.index, this.index + size); this.index += size; //buf = util.bufferToString(buf); return buf; } Unpacker.prototype.unpack_string = function(size){ var bytes = this.read(size); var i = 0, str = '', c, code; while(i < size){ c = bytes[i]; if ( c < 128){ str += String.fromCharCode(c); i++; } else if ((c ^ 0xc0) < 32){ code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63); str += String.fromCharCode(code); i += 2; } else { code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) | (bytes[i+2] & 63); str += String.fromCharCode(code); i += 3; } } this.index += size; return str; } Unpacker.prototype.unpack_array = function(size){ var objects = new Array(size); for(var i = 0; i < size ; i++){ objects[i] = this.unpack(); } return objects; } Unpacker.prototype.unpack_map = function(size){ var map = {}; for(var i = 0; i < size ; i++){ var key = this.unpack(); var value = this.unpack(); map[key] = value; } return map; } Unpacker.prototype.unpack_float = function(){ var uint32 = this.unpack_uint32(); var sign = uint32 >> 31; var exp = ((uint32 >> 23) & 0xff) - 127; var fraction = ( uint32 & 0x7fffff ) | 0x800000; return (sign == 0 ? 1 : -1) * fraction * Math.pow(2, exp - 23); } Unpacker.prototype.unpack_double = function(){ var h32 = this.unpack_uint32(); var l32 = this.unpack_uint32(); var sign = h32 >> 31; var exp = ((h32 >> 20) & 0x7ff) - 1023; var hfrac = ( h32 & 0xfffff ) | 0x100000; var frac = hfrac * Math.pow(2, exp - 20) + l32 * Math.pow(2, exp - 52); return (sign == 0 ? 1 : -1) * frac; } Unpacker.prototype.read = function(length){ var j = this.index; if (j + length <= this.length) { return this.dataView.subarray(j, j + length); } else { throw new Error('BinaryPackFailure: read index out of range'); } } function Packer(){ this.bufferBuilder = new BufferBuilder(); } Packer.prototype.getBuffer = function(){ return this.bufferBuilder.getBuffer(); } Packer.prototype.pack = function(value){ var type = typeof(value); if (type == 'string'){ this.pack_string(value); } else if (type == 'number'){ if (Math.floor(value) === value){ this.pack_integer(value); } else{ this.pack_double(value); } } else if (type == 'boolean'){ if (value === true){ this.bufferBuilder.append(0xc3); } else if (value === false){ this.bufferBuilder.append(0xc2); } } else if (type == 'undefined'){ this.bufferBuilder.append(0xc0); } else if (type == 'object'){ if (value === null){ this.bufferBuilder.append(0xc0); } else { var constructor = value.constructor; if (constructor == Array){ this.pack_array(value); } else if (constructor == Blob || constructor == File) { this.pack_bin(value); } else if (constructor == ArrayBuffer) { if(binaryFeatures.useArrayBufferView) { this.pack_bin(new Uint8Array(value)); } else { this.pack_bin(value); } } else if ('BYTES_PER_ELEMENT' in value){ if(binaryFeatures.useArrayBufferView) { this.pack_bin(new Uint8Array(value.buffer)); } else { this.pack_bin(value.buffer); } } else if (constructor == Object){ this.pack_object(value); } else if (constructor == Date){ this.pack_string(value.toString()); } else if (typeof value.toBinaryPack == 'function'){ this.bufferBuilder.append(value.toBinaryPack()); } else { throw new Error('Type "' + constructor.toString() + '" not yet supported'); } } } else { throw new Error('Type "' + type + '" not yet supported'); } this.bufferBuilder.flush(); } Packer.prototype.pack_bin = function(blob){ var length = blob.length || blob.byteLength || blob.size; if (length <= 0x0f){ this.pack_uint8(0xa0 + length); } else if (length <= 0xffff){ this.bufferBuilder.append(0xda) ; this.pack_uint16(length); } else if (length <= 0xffffffff){ this.bufferBuilder.append(0xdb); this.pack_uint32(length); } else{ throw new Error('Invalid length'); } this.bufferBuilder.append(blob); } Packer.prototype.pack_string = function(str){ var length = utf8Length(str); if (length <= 0x0f){ this.pack_uint8(0xb0 + length); } else if (length <= 0xffff){ this.bufferBuilder.append(0xd8) ; this.pack_uint16(length); } else if (length <= 0xffffffff){ this.bufferBuilder.append(0xd9); this.pack_uint32(length); } else{ throw new Error('Invalid length'); } this.bufferBuilder.append(str); } Packer.prototype.pack_array = function(ary){ var length = ary.length; if (length <= 0x0f){ this.pack_uint8(0x90 + length); } else if (length <= 0xffff){ this.bufferBuilder.append(0xdc) this.pack_uint16(length); } else if (length <= 0xffffffff){ this.bufferBuilder.append(0xdd); this.pack_uint32(length); } else{ throw new Error('Invalid length'); } for(var i = 0; i < length ; i++){ this.pack(ary[i]); } } Packer.prototype.pack_integer = function(num){ if ( -0x20 <= num && num <= 0x7f){ this.bufferBuilder.append(num & 0xff); } else if (0x00 <= num && num <= 0xff){ this.bufferBuilder.append(0xcc); this.pack_uint8(num); } else if (-0x80 <= num && num <= 0x7f){ this.bufferBuilder.append(0xd0); this.pack_int8(num); } else if ( 0x0000 <= num && num <= 0xffff){ this.bufferBuilder.append(0xcd); this.pack_uint16(num); } else if (-0x8000 <= num && num <= 0x7fff){ this.bufferBuilder.append(0xd1); this.pack_int16(num); } else if ( 0x00000000 <= num && num <= 0xffffffff){ this.bufferBuilder.append(0xce); this.pack_uint32(num); } else if (-0x80000000 <= num && num <= 0x7fffffff){ this.bufferBuilder.append(0xd2); this.pack_int32(num); } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){ this.bufferBuilder.append(0xd3); this.pack_int64(num); } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){ this.bufferBuilder.append(0xcf); this.pack_uint64(num); } else{ throw new Error('Invalid integer'); } } Packer.prototype.pack_double = function(num){ var sign = 0; if (num < 0){ sign = 1; num = -num; } var exp = Math.floor(Math.log(num) / Math.LN2); var frac0 = num / Math.pow(2, exp) - 1; var frac1 = Math.floor(frac0 * Math.pow(2, 52)); var b32 = Math.pow(2, 32); var h32 = (sign << 31) | ((exp+1023) << 20) | (frac1 / b32) & 0x0fffff; var l32 = frac1 % b32; this.bufferBuilder.append(0xcb); this.pack_int32(h32); this.pack_int32(l32); } Packer.prototype.pack_object = function(obj){ var keys = Object.keys(obj); var length = keys.length; if (length <= 0x0f){ this.pack_uint8(0x80 + length); } else if (length <= 0xffff){ this.bufferBuilder.append(0xde); this.pack_uint16(length); } else if (length <= 0xffffffff){ this.bufferBuilder.append(0xdf); this.pack_uint32(length); } else{ throw new Error('Invalid length'); } for(var prop in obj){ if (obj.hasOwnProperty(prop)){ this.pack(prop); this.pack(obj[prop]); } } } Packer.prototype.pack_uint8 = function(num){ this.bufferBuilder.append(num); } Packer.prototype.pack_uint16 = function(num){ this.bufferBuilder.append(num >> 8); this.bufferBuilder.append(num & 0xff); } Packer.prototype.pack_uint32 = function(num){ var n = num & 0xffffffff; this.bufferBuilder.append((n & 0xff000000) >>> 24); this.bufferBuilder.append((n & 0x00ff0000) >>> 16); this.bufferBuilder.append((n & 0x0000ff00) >>> 8); this.bufferBuilder.append((n & 0x000000ff)); } Packer.prototype.pack_uint64 = function(num){ var high = num / Math.pow(2, 32); var low = num % Math.pow(2, 32); this.bufferBuilder.append((high & 0xff000000) >>> 24); this.bufferBuilder.append((high & 0x00ff0000) >>> 16); this.bufferBuilder.append((high & 0x0000ff00) >>> 8); this.bufferBuilder.append((high & 0x000000ff)); this.bufferBuilder.append((low & 0xff000000) >>> 24); this.bufferBuilder.append((low & 0x00ff0000) >>> 16); this.bufferBuilder.append((low & 0x0000ff00) >>> 8); this.bufferBuilder.append((low & 0x000000ff)); } Packer.prototype.pack_int8 = function(num){ this.bufferBuilder.append(num & 0xff); } Packer.prototype.pack_int16 = function(num){ this.bufferBuilder.append((num & 0xff00) >> 8); this.bufferBuilder.append(num & 0xff); } Packer.prototype.pack_int32 = function(num){ this.bufferBuilder.append((num >>> 24) & 0xff); this.bufferBuilder.append((num & 0x00ff0000) >>> 16); this.bufferBuilder.append((num & 0x0000ff00) >>> 8); this.bufferBuilder.append((num & 0x000000ff)); } Packer.prototype.pack_int64 = function(num){ var high = Math.floor(num / Math.pow(2, 32)); var low = num % Math.pow(2, 32); this.bufferBuilder.append((high & 0xff000000) >>> 24); this.bufferBuilder.append((high & 0x00ff0000) >>> 16); this.bufferBuilder.append((high & 0x0000ff00) >>> 8); this.bufferBuilder.append((high & 0x000000ff)); this.bufferBuilder.append((low & 0xff000000) >>> 24); this.bufferBuilder.append((low & 0x00ff0000) >>> 16); this.bufferBuilder.append((low & 0x0000ff00) >>> 8); this.bufferBuilder.append((low & 0x000000ff)); } function _utf8Replace(m){ var code = m.charCodeAt(0); if(code <= 0x7ff) return '00'; if(code <= 0xffff) return '000'; if(code <= 0x1fffff) return '0000'; if(code <= 0x3ffffff) return '00000'; return '000000'; } function utf8Length(str){ if (str.length > 600) { // Blob method faster for large strings return (new Blob([str])).size; } else { return str.replace(/[^\u0000-\u007F]/g, _utf8Replace).length; } } },{"./bufferbuilder":"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/js-binarypack/lib/bufferbuilder.js"}],"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/js-binarypack/lib/bufferbuilder.js":[function(require,module,exports){ var binaryFeatures = {}; binaryFeatures.useBlobBuilder = (function(){ try { new Blob([]); return false; } catch (e) { return true; } })(); binaryFeatures.useArrayBufferView = !binaryFeatures.useBlobBuilder && (function(){ try { return (new Blob([new Uint8Array([])])).size === 0; } catch (e) { return true; } })(); module.exports.binaryFeatures = binaryFeatures; var BlobBuilder = module.exports.BlobBuilder; if (typeof window != 'undefined') { BlobBuilder = module.exports.BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder; } function BufferBuilder(){ this._pieces = []; this._parts = []; } BufferBuilder.prototype.append = function(data) { if(typeof data === 'number') { this._pieces.push(data); } else { this.flush(); this._parts.push(data); } }; BufferBuilder.prototype.flush = function() { if (this._pieces.length > 0) { var buf = new Uint8Array(this._pieces); if(!binaryFeatures.useArrayBufferView) { buf = buf.buffer; } this._parts.push(buf); this._pieces = []; } }; BufferBuilder.prototype.getBuffer = function() { this.flush(); if(binaryFeatures.useBlobBuilder) { var builder = new BlobBuilder(); for(var i = 0, ii = this._parts.length; i < ii; i++) { builder.append(this._parts[i]); } return builder.getBlob(); } else { return new Blob(this._parts); } }; module.exports.BufferBuilder = BufferBuilder; },{}],"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/reliable/lib/reliable.js":[function(require,module,exports){ var util = require('./util'); /** * Reliable transfer for Chrome Canary DataChannel impl. * Author: @michellebu */ function Reliable(dc, debug) { if (!(this instanceof Reliable)) return new Reliable(dc); this._dc = dc; util.debug = debug; // Messages sent/received so far. // id: { ack: n, chunks: [...] } this._outgoing = {}; // id: { ack: ['ack', id, n], chunks: [...] } this._incoming = {}; this._received = {}; // Window size. this._window = 1000; // MTU. this._mtu = 500; // Interval for setInterval. In ms. this._interval = 0; // Messages sent. this._count = 0; // Outgoing message queue. this._queue = []; this._setupDC(); }; // Send a message reliably. Reliable.prototype.send = function(msg) { // Determine if chunking is necessary. var bl = util.pack(msg); if (bl.size < this._mtu) { this._handleSend(['no', bl]); return; } this._outgoing[this._count] = { ack: 0, chunks: this._chunk(bl) }; if (util.debug) { this._outgoing[this._count].timer = new Date(); } // Send prelim window. this._sendWindowedChunks(this._count); this._count += 1; }; // Set up interval for processing queue. Reliable.prototype._setupInterval = function() { // TODO: fail gracefully. var self = this; this._timeout = setInterval(function() { // FIXME: String stuff makes things terribly async. var msg = self._queue.shift(); if (msg._multiple) { for (var i = 0, ii = msg.length; i < ii; i += 1) { self._intervalSend(msg[i]); } } else { self._intervalSend(msg); } }, this._interval); }; Reliable.prototype._intervalSend = function(msg) { var self = this; msg = util.pack(msg); util.blobToBinaryString(msg, function(str) { self._dc.send(str); }); if (self._queue.length === 0) { clearTimeout(self._timeout); self._timeout = null; //self._processAcks(); } }; // Go through ACKs to send missing pieces. Reliable.prototype._processAcks = function() { for (var id in this._outgoing) { if (this._outgoing.hasOwnProperty(id)) { this._sendWindowedChunks(id); } } }; // Handle sending a message. // FIXME: Don't wait for interval time for all messages... Reliable.prototype._handleSend = function(msg) { var push = true; for (var i = 0, ii = this._queue.length; i < ii; i += 1) { var item = this._queue[i]; if (item === msg) { push = false; } else if (item._multiple && item.indexOf(msg) !== -1) { push = false; } } if (push) { this._queue.push(msg); if (!this._timeout) { this._setupInterval(); } } }; // Set up DataChannel handlers. Reliable.prototype._setupDC = function() { // Handle various message types. var self = this; this._dc.onmessage = function(e) { var msg = e.data; var datatype = msg.constructor; // FIXME: msg is String until binary is supported. // Once that happens, this will have to be smarter. if (datatype === String) { var ab = util.binaryStringToArrayBuffer(msg); msg = util.unpack(ab); self._handleMessage(msg); } }; }; // Handles an incoming message. Reliable.prototype._handleMessage = function(msg) { var id = msg[1]; var idata = this._incoming[id]; var odata = this._outgoing[id]; var data; switch (msg[0]) { // No chunking was done. case 'no': var message = id; if (!!message) { this.onmessage(util.unpack(message)); } break; // Reached the end of the message. case 'end': data = idata; // In case end comes first. this._received[id] = msg[2]; if (!data) { break; } this._ack(id); break; case 'ack': data = odata; if (!!data) { var ack = msg[2]; // Take the larger ACK, for out of order messages. data.ack = Math.max(ack, data.ack); // Clean up when all chunks are ACKed. if (data.ack >= data.chunks.length) { util.log('Time: ', new Date() - data.timer); delete this._outgoing[id]; } else { this._processAcks(); } } // If !data, just ignore. break; // Received a chunk of data. case 'chunk': // Create a new entry if none exists. data = idata; if (!data) { var end = this._received[id]; if (end === true) { break; } data = { ack: ['ack', id, 0], chunks: [] }; this._incoming[id] = data; } var n = msg[2]; var chunk = msg[3]; data.chunks[n] = new Uint8Array(chunk); // If we get the chunk we're looking for, ACK for next missing. // Otherwise, ACK the same N again. if (n === data.ack[2]) { this._calculateNextAck(id); } this._ack(id); break; default: // Shouldn't happen, but would make sense for message to just go // through as is. this._handleSend(msg); break; } }; // Chunks BL into smaller messages. Reliable.prototype._chunk = function(bl) { var chunks = []; var size = bl.size; var start = 0; while (start < size) { var end = Math.min(size, start + this._mtu); var b = bl.slice(start, end); var chunk = { payload: b } chunks.push(chunk); start = end; } util.log('Created', chunks.length, 'chunks.'); return chunks; }; // Sends ACK N, expecting Nth blob chunk for message ID. Reliable.prototype._ack = function(id) { var ack = this._incoming[id].ack; // if ack is the end value, then call _complete. if (this._received[id] === ack[2]) { this._complete(id); this._received[id] = true; } this._handleSend(ack); }; // Calculates the next ACK number, given chunks. Reliable.prototype._calculateNextAck = function(id) { var data = this._incoming[id]; var chunks = data.chunks; for (var i = 0, ii = chunks.length; i < ii; i += 1) { // This chunk is missing!!! Better ACK for it. if (chunks[i] === undefined) { data.ack[2] = i; return; } } data.ack[2] = chunks.length; }; // Sends the next window of chunks. Reliable.prototype._sendWindowedChunks = function(id) { util.log('sendWindowedChunks for: ', id); var data = this._outgoing[id]; var ch = data.chunks; var chunks = []; var limit = Math.min(data.ack + this._window, ch.length); for (var i = data.ack; i < limit; i += 1) { if (!ch[i].sent || i === data.ack) { ch[i].sent = true; chunks.push(['chunk', id, i, ch[i].payload]); } } if (data.ack + this._window >= ch.length) { chunks.push(['end', id, ch.length]) } chunks._multiple = true; this._handleSend(chunks); }; // Puts together a message from chunks. Reliable.prototype._complete = function(id) { util.log('Completed called for', id); var self = this; var chunks = this._incoming[id].chunks; var bl = new Blob(chunks); util.blobToArrayBuffer(bl, function(ab) { self.onmessage(util.unpack(ab)); }); delete this._incoming[id]; }; // Ups bandwidth limit on SDP. Meant to be called during offer/answer. Reliable.higherBandwidthSDP = function(sdp) { // AS stands for Application-Specific Maximum. // Bandwidth number is in kilobits / sec. // See RFC for more info: http://www.ietf.org/rfc/rfc2327.txt // Chrome 31+ doesn't want us munging the SDP, so we'll let them have their // way. var version = navigator.appVersion.match(/Chrome\/(.*?) /); if (version) { version = parseInt(version[1].split('.').shift()); if (version < 31) { var parts = sdp.split('b=AS:30'); var replace = 'b=AS:102400'; // 100 Mbps if (parts.length > 1) { return parts[0] + replace + parts[1]; } } } return sdp; }; // Overwritten, typically. Reliable.prototype.onmessage = function(msg) {}; module.exports.Reliable = Reliable; },{"./util":"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/reliable/lib/util.js"}],"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/reliable/lib/util.js":[function(require,module,exports){ var BinaryPack = require('js-binarypack'); var util = { debug: false, inherits: function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }, extend: function(dest, source) { for(var key in source) { if(source.hasOwnProperty(key)) { dest[key] = source[key]; } } return dest; }, pack: BinaryPack.pack, unpack: BinaryPack.unpack, log: function () { if (util.debug) { var copy = []; for (var i = 0; i < arguments.length; i++) { copy[i] = arguments[i]; } copy.unshift('Reliable: '); console.log.apply(console, copy); } }, setZeroTimeout: (function(global) { var timeouts = []; var messageName = 'zero-timeout-message'; // Like setTimeout, but only takes a function argument. There's // no time argument (always zero) and no arguments (you have to // use a closure). function setZeroTimeoutPostMessage(fn) { timeouts.push(fn); global.postMessage(messageName, '*'); } function handleMessage(event) { if (event.source == global && event.data == messageName) { if (event.stopPropagation) { event.stopPropagation(); } if (timeouts.length) { timeouts.shift()(); } } } if (global.addEventListener) { global.addEventListener('message', handleMessage, true); } else if (global.attachEvent) { global.attachEvent('onmessage', handleMessage); } return setZeroTimeoutPostMessage; }(this)), blobToArrayBuffer: function(blob, cb){ var fr = new FileReader(); fr.onload = function(evt) { cb(evt.target.result); }; fr.readAsArrayBuffer(blob); }, blobToBinaryString: function(blob, cb){ var fr = new FileReader(); fr.onload = function(evt) { cb(evt.target.result); }; fr.readAsBinaryString(blob); }, binaryStringToArrayBuffer: function(binary) { var byteArray = new Uint8Array(binary.length); for (var i = 0; i < binary.length; i++) { byteArray[i] = binary.charCodeAt(i) & 0xff; } return byteArray.buffer; }, randomToken: function () { return Math.random().toString(36).substr(2); } }; module.exports = util; },{"js-binarypack":"/Users/alex/Projects/webdrop/node_modules/peerjs/node_modules/js-binarypack/lib/binarypack.js"}],"/Users/alex/Projects/webdrop/node_modules/react-frozenhead/lib/index.js":[function(require,module,exports){ var React = require('react'), it = require('./it'); head = React.DOM.head; var isString = function (node) { return typeof node === 'string'; }; var isTitleNode = function (node) { // Ideally we would just check `tagName`, but composite components don't // have that. return ( (React.isValidElement || React.isValidComponent)(node) && node.type === 'title' || (node.type && node.type.displayName === 'ReactFullPageComponenttitle') || (node.type && node.type.displayName === 'title') ); }; var findTitle = function (children) { // Sucks to have to crawl the DOM descriptors like this. But how else // could we do it without mucking up our API? return it.find(it.find(children, isTitleNode), isString); }; var FrozenHead = React.createClass({ getInitialState: function () { return { title: findTitle(this.props.children) }; }, shouldComponentUpdate: function () { // Once the component is mounted in the DOM, we should never update. return !this.isMounted(); }, componentWillReceiveProps: function (nextProps) { if (this.isMounted()) { var oldTitle = this.state.title; newTitle = findTitle(nextProps.children); if (newTitle && newTitle !== oldTitle) { document.title = newTitle; this.setState({title: newTitle}); } } }, render: function () { // This will only ever be called once because you can't update unmounted // components (i.e. call `setProps` or `setState` on them to trigger a // render) and, once the component's mounted, all future renders are // prevented by `shouldComponentUpdate`. var html = ''; it.forEach(this.props.children, function (child) { // Since we don't want React to diff the DOM, we can just render to // static HTML without markers. html += (React.renderToStaticMarkup || React.renderComponentToStaticMarkup)(child); }); return head({dangerouslySetInnerHTML: {__html: html}}); } }); module.exports = FrozenHead; },{"./it":"/Users/alex/Projects/webdrop/node_modules/react-frozenhead/lib/it.js","react":"/Users/alex/Projects/webdrop/node_modules/react/react.js"}],"/Users/alex/Projects/webdrop/node_modules/react-frozenhead/lib/it.js":[function(require,module,exports){ // React children iteration utilities. var React = require('react'); // Iterate over each child in the children object. This is necessary because the // ReactChildren.* methods can't be broken. var forEach = function (children, func, context) { var child; if (Array.isArray(children)) { for (var i = 0, len = children.length; i < len; i++) { child = children[i]; if (child != null && func.call(context, child) === false) { return false; } } } else { child = children; if (child != null && func.call(context, child) === false) { return false; } } }; var walk = function (children, func, context) { return forEach(children, function (child) { if (func.call(context, child) === false) { return false; } if ((React.isValidElement || React.isValidComponent)(child)) { return walk(child.props.children, func, context); } }); }; var find = function (children, test) { var match; walk(children, function (child) { if (test(child)) { match = child; return false; } }); return match; }; module.exports = { forEach: forEach, walk: walk, find: find }; },{"react":"/Users/alex/Projects/webdrop/node_modules/react/react.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/Cancellation.js":[function(require,module,exports){ "use strict"; /** * Represents a cancellation caused by navigating away * before the previous transition has fully resolved. */ function Cancellation() {} module.exports = Cancellation; },{}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/History.js":[function(require,module,exports){ "use strict"; var invariant = require("react/lib/invariant"); var canUseDOM = require("react/lib/ExecutionEnvironment").canUseDOM; var History = { /** * The current number of entries in the history. * * Note: This property is read-only. */ length: 1, /** * Sends the browser back one entry in the history. */ back: function back() { invariant(canUseDOM, "Cannot use History.back without a DOM"); // Do this first so that History.length will // be accurate in location change listeners. History.length -= 1; window.history.back(); } }; module.exports = History; },{"react/lib/ExecutionEnvironment":"/Users/alex/Projects/webdrop/node_modules/react/lib/ExecutionEnvironment.js","react/lib/invariant":"/Users/alex/Projects/webdrop/node_modules/react/lib/invariant.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/Match.js":[function(require,module,exports){ "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /* jshint -W084 */ var PathUtils = require("./PathUtils"); function deepSearch(route, pathname, query) { // Check the subtree first to find the most deeply-nested match. var childRoutes = route.childRoutes; if (childRoutes) { var match, childRoute; for (var i = 0, len = childRoutes.length; i < len; ++i) { childRoute = childRoutes[i]; if (childRoute.isDefault || childRoute.isNotFound) continue; // Check these in order later. if (match = deepSearch(childRoute, pathname, query)) { // A route in the subtree matched! Add this route and we're done. match.routes.unshift(route); return match; } } } // No child routes matched; try the default route. var defaultRoute = route.defaultRoute; if (defaultRoute && (params = PathUtils.extractParams(defaultRoute.path, pathname))) { return new Match(pathname, params, query, [route, defaultRoute]); } // Does the "not found" route match? var notFoundRoute = route.notFoundRoute; if (notFoundRoute && (params = PathUtils.extractParams(notFoundRoute.path, pathname))) { return new Match(pathname, params, query, [route, notFoundRoute]); } // Last attempt: check this route. var params = PathUtils.extractParams(route.path, pathname); if (params) { return new Match(pathname, params, query, [route]); }return null; } var Match = (function () { function Match(pathname, params, query, routes) { _classCallCheck(this, Match); this.pathname = pathname; this.params = params; this.query = query; this.routes = routes; } _createClass(Match, null, { findMatch: { /** * Attempts to match depth-first a route in the given route's * subtree against the given path and returns the match if it * succeeds, null if no match can be made. */ value: function findMatch(routes, path) { var pathname = PathUtils.withoutQuery(path); var query = PathUtils.extractQuery(path); var match = null; for (var i = 0, len = routes.length; match == null && i < len; ++i) match = deepSearch(routes[i], pathname, query); return match; } } }); return Match; })(); module.exports = Match; },{"./PathUtils":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PathUtils.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/Navigation.js":[function(require,module,exports){ "use strict"; var warning = require("react/lib/warning"); var PropTypes = require("./PropTypes"); function deprecatedMethod(routerMethodName, fn) { return function () { warning(false, "Router.Navigation is deprecated. Please use this.context.router." + routerMethodName + "() instead"); return fn.apply(this, arguments); }; } /** * A mixin for components that modify the URL. * * Example: * * var MyLink = React.createClass({ * mixins: [ Router.Navigation ], * handleClick(event) { * event.preventDefault(); * this.transitionTo('aRoute', { the: 'params' }, { the: 'query' }); * }, * render() { * return ( * Click me! * ); * } * }); */ var Navigation = { contextTypes: { router: PropTypes.router.isRequired }, /** * Returns an absolute URL path created from the given route * name, URL parameters, and query values. */ makePath: deprecatedMethod("makePath", function (to, params, query) { return this.context.router.makePath(to, params, query); }), /** * Returns a string that may safely be used as the href of a * link to the route with the given name. */ makeHref: deprecatedMethod("makeHref", function (to, params, query) { return this.context.router.makeHref(to, params, query); }), /** * Transitions to the URL specified in the arguments by pushing * a new URL onto the history stack. */ transitionTo: deprecatedMethod("transitionTo", function (to, params, query) { this.context.router.transitionTo(to, params, query); }), /** * Transitions to the URL specified in the arguments by replacing * the current URL in the history stack. */ replaceWith: deprecatedMethod("replaceWith", function (to, params, query) { this.context.router.replaceWith(to, params, query); }), /** * Transitions to the previous URL. */ goBack: deprecatedMethod("goBack", function () { return this.context.router.goBack(); }) }; module.exports = Navigation; },{"./PropTypes":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PropTypes.js","react/lib/warning":"/Users/alex/Projects/webdrop/node_modules/react/lib/warning.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PathUtils.js":[function(require,module,exports){ "use strict"; var invariant = require("react/lib/invariant"); var merge = require("qs/lib/utils").merge; var qs = require("qs"); var paramCompileMatcher = /:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g; var paramInjectMatcher = /:([a-zA-Z_$][a-zA-Z0-9_$?]*[?]?)|[*]/g; var paramInjectTrailingSlashMatcher = /\/\/\?|\/\?\/|\/\?/g; var queryMatcher = /\?(.+)/; var _compiledPatterns = {}; function compilePattern(pattern) { if (!(pattern in _compiledPatterns)) { var paramNames = []; var source = pattern.replace(paramCompileMatcher, function (match, paramName) { if (paramName) { paramNames.push(paramName); return "([^/?#]+)"; } else if (match === "*") { paramNames.push("splat"); return "(.*?)"; } else { return "\\" + match; } }); _compiledPatterns[pattern] = { matcher: new RegExp("^" + source + "$", "i"), paramNames: paramNames }; } return _compiledPatterns[pattern]; } var PathUtils = { /** * Returns true if the given path is absolute. */ isAbsolute: function isAbsolute(path) { return path.charAt(0) === "/"; }, /** * Joins two URL paths together. */ join: function join(a, b) { return a.replace(/\/*$/, "/") + b; }, /** * Returns an array of the names of all parameters in the given pattern. */ extractParamNames: function extractParamNames(pattern) { return compilePattern(pattern).paramNames; }, /** * Extracts the portions of the given URL path that match the given pattern * and returns an object of param name => value pairs. Returns null if the * pattern does not match the given path. */ extractParams: function extractParams(pattern, path) { var _compilePattern = compilePattern(pattern); var matcher = _compilePattern.matcher; var paramNames = _compilePattern.paramNames; var match = path.match(matcher); if (!match) { return null; }var params = {}; paramNames.forEach(function (paramName, index) { params[paramName] = match[index + 1]; }); return params; }, /** * Returns a version of the given route path with params interpolated. Throws * if there is a dynamic segment of the route path for which there is no param. */ injectParams: function injectParams(pattern, params) { params = params || {}; var splatIndex = 0; return pattern.replace(paramInjectMatcher, function (match, paramName) { paramName = paramName || "splat"; // If param is optional don't check for existence if (paramName.slice(-1) === "?") { paramName = paramName.slice(0, -1); if (params[paramName] == null) return ""; } else { invariant(params[paramName] != null, "Missing \"%s\" parameter for path \"%s\"", paramName, pattern); } var segment; if (paramName === "splat" && Array.isArray(params[paramName])) { segment = params[paramName][splatIndex++]; invariant(segment != null, "Missing splat # %s for path \"%s\"", splatIndex, pattern); } else { segment = params[paramName]; } return segment; }).replace(paramInjectTrailingSlashMatcher, "/"); }, /** * Returns an object that is the result of parsing any query string contained * in the given path, null if the path contains no query string. */ extractQuery: function extractQuery(path) { var match = path.match(queryMatcher); return match && qs.parse(match[1]); }, /** * Returns a version of the given path without the query string. */ withoutQuery: function withoutQuery(path) { return path.replace(queryMatcher, ""); }, /** * Returns a version of the given path with the parameters in the given * query merged into the query string. */ withQuery: function withQuery(path, query) { var existingQuery = PathUtils.extractQuery(path); if (existingQuery) query = query ? merge(existingQuery, query) : existingQuery; var queryString = qs.stringify(query, { arrayFormat: "brackets" }); if (queryString) { return PathUtils.withoutQuery(path) + "?" + queryString; }return path; } }; module.exports = PathUtils; },{"qs":"/Users/alex/Projects/webdrop/node_modules/react-router/node_modules/qs/index.js","qs/lib/utils":"/Users/alex/Projects/webdrop/node_modules/react-router/node_modules/qs/lib/utils.js","react/lib/invariant":"/Users/alex/Projects/webdrop/node_modules/react/lib/invariant.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PropTypes.js":[function(require,module,exports){ "use strict"; var assign = require("react/lib/Object.assign"); var ReactPropTypes = require("react").PropTypes; var Route = require("./Route"); var PropTypes = assign({}, ReactPropTypes, { /** * Indicates that a prop should be falsy. */ falsy: function falsy(props, propName, componentName) { if (props[propName]) { return new Error("<" + componentName + "> may not have a \"" + propName + "\" prop"); } }, /** * Indicates that a prop should be a Route object. */ route: ReactPropTypes.instanceOf(Route), /** * Indicates that a prop should be a Router object. */ //router: ReactPropTypes.instanceOf(Router) // TODO router: ReactPropTypes.func }); module.exports = PropTypes; },{"./Route":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/Route.js","react":"/Users/alex/Projects/webdrop/node_modules/react/react.js","react/lib/Object.assign":"/Users/alex/Projects/webdrop/node_modules/react/lib/Object.assign.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/Redirect.js":[function(require,module,exports){ "use strict"; /** * Encapsulates a redirect to the given route. */ function Redirect(to, params, query) { this.to = to; this.params = params; this.query = query; } module.exports = Redirect; },{}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/Route.js":[function(require,module,exports){ "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var assign = require("react/lib/Object.assign"); var invariant = require("react/lib/invariant"); var warning = require("react/lib/warning"); var PathUtils = require("./PathUtils"); var _currentRoute; var Route = (function () { function Route(name, path, ignoreScrollBehavior, isDefault, isNotFound, onEnter, onLeave, handler) { _classCallCheck(this, Route); this.name = name; this.path = path; this.paramNames = PathUtils.extractParamNames(this.path); this.ignoreScrollBehavior = !!ignoreScrollBehavior; this.isDefault = !!isDefault; this.isNotFound = !!isNotFound; this.onEnter = onEnter; this.onLeave = onLeave; this.handler = handler; } _createClass(Route, { appendChild: { /** * Appends the given route to this route's child routes. */ value: function appendChild(route) { invariant(route instanceof Route, "route.appendChild must use a valid Route"); if (!this.childRoutes) this.childRoutes = []; this.childRoutes.push(route); } }, toString: { value: function toString() { var string = ""; return string; } } }, { createRoute: { /** * Creates and returns a new route. Options may be a URL pathname string * with placeholders for named params or an object with any of the following * properties: * * - name The name of the route. This is used to lookup a * route relative to its parent route and should be * unique among all child routes of the same parent * - path A URL pathname string with optional placeholders * that specify the names of params to extract from * the URL when the path matches. Defaults to `/${name}` * when there is a name given, or the path of the parent * route, or / * - ignoreScrollBehavior True to make this route (and all descendants) ignore * the scroll behavior of the router * - isDefault True to make this route the default route among all * its siblings * - isNotFound True to make this route the "not found" route among * all its siblings * - onEnter A transition hook that will be called when the * router is going to enter this route * - onLeave A transition hook that will be called when the * router is going to leave this route * - handler A React component that will be rendered when * this route is active * - parentRoute The parent route to use for this route. This option * is automatically supplied when creating routes inside * the callback to another invocation of createRoute. You * only ever need to use this when declaring routes * independently of one another to manually piece together * the route hierarchy * * The callback may be used to structure your route hierarchy. Any call to * createRoute, createDefaultRoute, createNotFoundRoute, or createRedirect * inside the callback automatically uses this route as its parent. */ value: function createRoute(options, callback) { options = options || {}; if (typeof options === "string") options = { path: options }; var parentRoute = _currentRoute; if (parentRoute) { warning(options.parentRoute == null || options.parentRoute === parentRoute, "You should not use parentRoute with createRoute inside another route's child callback; it is ignored"); } else { parentRoute = options.parentRoute; } var name = options.name; var path = options.path || name; if (path && !(options.isDefault || options.isNotFound)) { if (PathUtils.isAbsolute(path)) { if (parentRoute) { invariant(path === parentRoute.path || parentRoute.paramNames.length === 0, "You cannot nest path \"%s\" inside \"%s\"; the parent requires URL parameters", path, parentRoute.path); } } else if (parentRoute) { // Relative paths extend their parent. path = PathUtils.join(parentRoute.path, path); } else { path = "/" + path; } } else { path = parentRoute ? parentRoute.path : "/"; } if (options.isNotFound && !/\*$/.test(path)) path += "*"; // Auto-append * to the path of not found routes. var route = new Route(name, path, options.ignoreScrollBehavior, options.isDefault, options.isNotFound, options.onEnter, options.onLeave, options.handler); if (parentRoute) { if (route.isDefault) { invariant(parentRoute.defaultRoute == null, "%s may not have more than one default route", parentRoute); parentRoute.defaultRoute = route; } else if (route.isNotFound) { invariant(parentRoute.notFoundRoute == null, "%s may not have more than one not found route", parentRoute); parentRoute.notFoundRoute = route; } parentRoute.appendChild(route); } // Any routes created in the callback // use this route as their parent. if (typeof callback === "function") { var currentRoute = _currentRoute; _currentRoute = route; callback.call(route, route); _currentRoute = currentRoute; } return route; } }, createDefaultRoute: { /** * Creates and returns a route that is rendered when its parent matches * the current URL. */ value: function createDefaultRoute(options) { return Route.createRoute(assign({}, options, { isDefault: true })); } }, createNotFoundRoute: { /** * Creates and returns a route that is rendered when its parent matches * the current URL but none of its siblings do. */ value: function createNotFoundRoute(options) { return Route.createRoute(assign({}, options, { isNotFound: true })); } }, createRedirect: { /** * Creates and returns a route that automatically redirects the transition * to another route. In addition to the normal options to createRoute, this * function accepts the following options: * * - from An alias for the `path` option. Defaults to * * - to The path/route/route name to redirect to * - params The params to use in the redirect URL. Defaults * to using the current params * - query The query to use in the redirect URL. Defaults * to using the current query */ value: function createRedirect(options) { return Route.createRoute(assign({}, options, { path: options.path || options.from || "*", onEnter: function onEnter(transition, params, query) { transition.redirect(options.to, options.params || params, options.query || query); } })); } } }); return Route; })(); module.exports = Route; },{"./PathUtils":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PathUtils.js","react/lib/Object.assign":"/Users/alex/Projects/webdrop/node_modules/react/lib/Object.assign.js","react/lib/invariant":"/Users/alex/Projects/webdrop/node_modules/react/lib/invariant.js","react/lib/warning":"/Users/alex/Projects/webdrop/node_modules/react/lib/warning.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/ScrollHistory.js":[function(require,module,exports){ "use strict"; var invariant = require("react/lib/invariant"); var canUseDOM = require("react/lib/ExecutionEnvironment").canUseDOM; var getWindowScrollPosition = require("./getWindowScrollPosition"); function shouldUpdateScroll(state, prevState) { if (!prevState) { return true; } // Don't update scroll position when only the query has changed. if (state.pathname === prevState.pathname) { return false; }var routes = state.routes; var prevRoutes = prevState.routes; var sharedAncestorRoutes = routes.filter(function (route) { return prevRoutes.indexOf(route) !== -1; }); return !sharedAncestorRoutes.some(function (route) { return route.ignoreScrollBehavior; }); } /** * Provides the router with the ability to manage window scroll position * according to its scroll behavior. */ var ScrollHistory = { statics: { /** * Records curent scroll position as the last known position for the given URL path. */ recordScrollPosition: function recordScrollPosition(path) { if (!this.scrollHistory) this.scrollHistory = {}; this.scrollHistory[path] = getWindowScrollPosition(); }, /** * Returns the last known scroll position for the given URL path. */ getScrollPosition: function getScrollPosition(path) { if (!this.scrollHistory) this.scrollHistory = {}; return this.scrollHistory[path] || null; } }, componentWillMount: function componentWillMount() { invariant(this.constructor.getScrollBehavior() == null || canUseDOM, "Cannot use scroll behavior without a DOM"); }, componentDidMount: function componentDidMount() { this._updateScroll(); }, componentDidUpdate: function componentDidUpdate(prevProps, prevState) { this._updateScroll(prevState); }, _updateScroll: function _updateScroll(prevState) { if (!shouldUpdateScroll(this.state, prevState)) { return; }var scrollBehavior = this.constructor.getScrollBehavior(); if (scrollBehavior) scrollBehavior.updateScrollPosition(this.constructor.getScrollPosition(this.state.path), this.state.action); } }; module.exports = ScrollHistory; },{"./getWindowScrollPosition":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/getWindowScrollPosition.js","react/lib/ExecutionEnvironment":"/Users/alex/Projects/webdrop/node_modules/react/lib/ExecutionEnvironment.js","react/lib/invariant":"/Users/alex/Projects/webdrop/node_modules/react/lib/invariant.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/State.js":[function(require,module,exports){ "use strict"; var warning = require("react/lib/warning"); var PropTypes = require("./PropTypes"); function deprecatedMethod(routerMethodName, fn) { return function () { warning(false, "Router.State is deprecated. Please use this.context.router." + routerMethodName + "() instead"); return fn.apply(this, arguments); }; } /** * A mixin for components that need to know the path, routes, URL * params and query that are currently active. * * Example: * * var AboutLink = React.createClass({ * mixins: [ Router.State ], * render() { * var className = this.props.className; * * if (this.isActive('about')) * className += ' is-active'; * * return React.DOM.a({ className: className }, this.props.children); * } * }); */ var State = { contextTypes: { router: PropTypes.router.isRequired }, /** * Returns the current URL path. */ getPath: deprecatedMethod("getCurrentPath", function () { return this.context.router.getCurrentPath(); }), /** * Returns the current URL path without the query string. */ getPathname: deprecatedMethod("getCurrentPathname", function () { return this.context.router.getCurrentPathname(); }), /** * Returns an object of the URL params that are currently active. */ getParams: deprecatedMethod("getCurrentParams", function () { return this.context.router.getCurrentParams(); }), /** * Returns an object of the query params that are currently active. */ getQuery: deprecatedMethod("getCurrentQuery", function () { return this.context.router.getCurrentQuery(); }), /** * Returns an array of the routes that are currently active. */ getRoutes: deprecatedMethod("getCurrentRoutes", function () { return this.context.router.getCurrentRoutes(); }), /** * A helper method to determine if a given route, params, and query * are active. */ isActive: deprecatedMethod("isActive", function (to, params, query) { return this.context.router.isActive(to, params, query); }) }; module.exports = State; },{"./PropTypes":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PropTypes.js","react/lib/warning":"/Users/alex/Projects/webdrop/node_modules/react/lib/warning.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/Transition.js":[function(require,module,exports){ "use strict"; /* jshint -W058 */ var Cancellation = require("./Cancellation"); var Redirect = require("./Redirect"); /** * Encapsulates a transition to a given path. * * The willTransitionTo and willTransitionFrom handlers receive * an instance of this class as their first argument. */ function Transition(path, retry) { this.path = path; this.abortReason = null; // TODO: Change this to router.retryTransition(transition) this.retry = retry.bind(this); } Transition.prototype.abort = function (reason) { if (this.abortReason == null) this.abortReason = reason || "ABORT"; }; Transition.prototype.redirect = function (to, params, query) { this.abort(new Redirect(to, params, query)); }; Transition.prototype.cancel = function () { this.abort(new Cancellation()); }; Transition.from = function (transition, routes, components, callback) { routes.reduce(function (callback, route, index) { return function (error) { if (error || transition.abortReason) { callback(error); } else if (route.onLeave) { try { route.onLeave(transition, components[index], callback); // If there is no callback in the argument list, call it automatically. if (route.onLeave.length < 3) callback(); } catch (e) { callback(e); } } else { callback(); } }; }, callback)(); }; Transition.to = function (transition, routes, params, query, callback) { routes.reduceRight(function (callback, route) { return function (error) { if (error || transition.abortReason) { callback(error); } else if (route.onEnter) { try { route.onEnter(transition, params, query, callback); // If there is no callback in the argument list, call it automatically. if (route.onEnter.length < 4) callback(); } catch (e) { callback(e); } } else { callback(); } }; }, callback)(); }; module.exports = Transition; },{"./Cancellation":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/Cancellation.js","./Redirect":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/Redirect.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/actions/LocationActions.js":[function(require,module,exports){ "use strict"; /** * Actions that modify the URL. */ var LocationActions = { /** * Indicates a new location is being pushed to the history stack. */ PUSH: "push", /** * Indicates the current location should be replaced. */ REPLACE: "replace", /** * Indicates the most recent entry should be removed from the history stack. */ POP: "pop" }; module.exports = LocationActions; },{}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/behaviors/ImitateBrowserBehavior.js":[function(require,module,exports){ "use strict"; var LocationActions = require("../actions/LocationActions"); /** * A scroll behavior that attempts to imitate the default behavior * of modern browsers. */ var ImitateBrowserBehavior = { updateScrollPosition: function updateScrollPosition(position, actionType) { switch (actionType) { case LocationActions.PUSH: case LocationActions.REPLACE: window.scrollTo(0, 0); break; case LocationActions.POP: if (position) { window.scrollTo(position.x, position.y); } else { window.scrollTo(0, 0); } break; } } }; module.exports = ImitateBrowserBehavior; },{"../actions/LocationActions":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/actions/LocationActions.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/behaviors/ScrollToTopBehavior.js":[function(require,module,exports){ "use strict"; /** * A scroll behavior that always scrolls to the top of the page * after a transition. */ var ScrollToTopBehavior = { updateScrollPosition: function updateScrollPosition() { window.scrollTo(0, 0); } }; module.exports = ScrollToTopBehavior; },{}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/ContextWrapper.js":[function(require,module,exports){ "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /** * This component is necessary to get around a context warning * present in React 0.13.0. It sovles this by providing a separation * between the "owner" and "parent" contexts. */ var React = require("react"); var ContextWrapper = (function (_React$Component) { function ContextWrapper() { _classCallCheck(this, ContextWrapper); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(ContextWrapper, _React$Component); _createClass(ContextWrapper, { render: { value: function render() { return this.props.children; } } }); return ContextWrapper; })(React.Component); module.exports = ContextWrapper; },{"react":"/Users/alex/Projects/webdrop/node_modules/react/react.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/DefaultRoute.js":[function(require,module,exports){ "use strict"; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var PropTypes = require("../PropTypes"); var RouteHandler = require("./RouteHandler"); var Route = require("./Route"); /** * A component is a special kind of that * renders when its parent matches but none of its siblings do. * Only one such route may be used at any given level in the * route hierarchy. */ var DefaultRoute = (function (_Route) { function DefaultRoute() { _classCallCheck(this, DefaultRoute); if (_Route != null) { _Route.apply(this, arguments); } } _inherits(DefaultRoute, _Route); return DefaultRoute; })(Route); // TODO: Include these in the above class definition // once we can use ES7 property initializers. // https://github.com/babel/babel/issues/619 DefaultRoute.propTypes = { name: PropTypes.string, path: PropTypes.falsy, children: PropTypes.falsy, handler: PropTypes.func.isRequired }; DefaultRoute.defaultProps = { handler: RouteHandler }; module.exports = DefaultRoute; },{"../PropTypes":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PropTypes.js","./Route":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/Route.js","./RouteHandler":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/RouteHandler.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/Link.js":[function(require,module,exports){ "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var React = require("react"); var assign = require("react/lib/Object.assign"); var PropTypes = require("../PropTypes"); function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } /** * components are used to create an element that links to a route. * When that route is active, the link gets an "active" class name (or the * value of its `activeClassName` prop). * * For example, assuming you have the following route: * * * * You could use the following component to link to that route: * * * * In addition to params, links may pass along query string parameters * using the `query` prop. * * */ var Link = (function (_React$Component) { function Link() { _classCallCheck(this, Link); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(Link, _React$Component); _createClass(Link, { handleClick: { value: function handleClick(event) { var allowTransition = true; var clickResult; if (this.props.onClick) clickResult = this.props.onClick(event); if (isModifiedEvent(event) || !isLeftClickEvent(event)) { return; }if (clickResult === false || event.defaultPrevented === true) allowTransition = false; event.preventDefault(); if (allowTransition) this.context.router.transitionTo(this.props.to, this.props.params, this.props.query); } }, getHref: { /** * Returns the value of the "href" attribute to use on the DOM element. */ value: function getHref() { return this.context.router.makeHref(this.props.to, this.props.params, this.props.query); } }, getClassName: { /** * Returns the value of the "class" attribute to use on the DOM element, which contains * the value of the activeClassName property when this is active. */ value: function getClassName() { var className = this.props.className; if (this.getActiveState()) className += " " + this.props.activeClassName; return className; } }, getActiveState: { value: function getActiveState() { return this.context.router.isActive(this.props.to, this.props.params, this.props.query); } }, render: { value: function render() { var props = assign({}, this.props, { href: this.getHref(), className: this.getClassName(), onClick: this.handleClick.bind(this) }); if (props.activeStyle && this.getActiveState()) props.style = props.activeStyle; return React.DOM.a(props, this.props.children); } } }); return Link; })(React.Component); // TODO: Include these in the above class definition // once we can use ES7 property initializers. // https://github.com/babel/babel/issues/619 Link.contextTypes = { router: PropTypes.router.isRequired }; Link.propTypes = { activeClassName: PropTypes.string.isRequired, to: PropTypes.oneOfType([PropTypes.string, PropTypes.route]).isRequired, params: PropTypes.object, query: PropTypes.object, activeStyle: PropTypes.object, onClick: PropTypes.func }; Link.defaultProps = { activeClassName: "active", className: "" }; module.exports = Link; },{"../PropTypes":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PropTypes.js","react":"/Users/alex/Projects/webdrop/node_modules/react/react.js","react/lib/Object.assign":"/Users/alex/Projects/webdrop/node_modules/react/lib/Object.assign.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/NotFoundRoute.js":[function(require,module,exports){ "use strict"; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var PropTypes = require("../PropTypes"); var RouteHandler = require("./RouteHandler"); var Route = require("./Route"); /** * A is a special kind of that * renders when the beginning of its parent's path matches * but none of its siblings do, including any . * Only one such route may be used at any given level in the * route hierarchy. */ var NotFoundRoute = (function (_Route) { function NotFoundRoute() { _classCallCheck(this, NotFoundRoute); if (_Route != null) { _Route.apply(this, arguments); } } _inherits(NotFoundRoute, _Route); return NotFoundRoute; })(Route); // TODO: Include these in the above class definition // once we can use ES7 property initializers. // https://github.com/babel/babel/issues/619 NotFoundRoute.propTypes = { name: PropTypes.string, path: PropTypes.falsy, children: PropTypes.falsy, handler: PropTypes.func.isRequired }; NotFoundRoute.defaultProps = { handler: RouteHandler }; module.exports = NotFoundRoute; },{"../PropTypes":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PropTypes.js","./Route":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/Route.js","./RouteHandler":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/RouteHandler.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/Redirect.js":[function(require,module,exports){ "use strict"; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var PropTypes = require("../PropTypes"); var Route = require("./Route"); /** * A component is a special kind of that always * redirects to another route when it matches. */ var Redirect = (function (_Route) { function Redirect() { _classCallCheck(this, Redirect); if (_Route != null) { _Route.apply(this, arguments); } } _inherits(Redirect, _Route); return Redirect; })(Route); // TODO: Include these in the above class definition // once we can use ES7 property initializers. // https://github.com/babel/babel/issues/619 Redirect.propTypes = { path: PropTypes.string, from: PropTypes.string, // Alias for path. to: PropTypes.string, handler: PropTypes.falsy }; // Redirects should not have a default handler Redirect.defaultProps = {}; module.exports = Redirect; },{"../PropTypes":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PropTypes.js","./Route":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/Route.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/Route.js":[function(require,module,exports){ "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var React = require("react"); var invariant = require("react/lib/invariant"); var PropTypes = require("../PropTypes"); var RouteHandler = require("./RouteHandler"); /** * components specify components that are rendered to the page when the * URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is requested, * the tree is searched depth-first to find a route whose path matches the URL. * When one is found, all routes in the tree that lead to it are considered * "active" and their components are rendered into the DOM, nested in the same * order as they are in the tree. * * The preferred way to configure a router is using JSX. The XML-like syntax is * a great way to visualize how routes are laid out in an application. * * var routes = [ * * * * * * ]; * * Router.run(routes, function (Handler) { * React.render(, document.body); * }); * * Handlers for Route components that contain children can render their active * child route using a element. * * var App = React.createClass({ * render: function () { * return ( *
* *
* ); * } * }); * * If no handler is provided for the route, it will render a matched child route. */ var Route = (function (_React$Component) { function Route() { _classCallCheck(this, Route); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(Route, _React$Component); _createClass(Route, { render: { value: function render() { invariant(false, "%s elements are for router configuration only and should not be rendered", this.constructor.name); } } }); return Route; })(React.Component); // TODO: Include these in the above class definition // once we can use ES7 property initializers. // https://github.com/babel/babel/issues/619 Route.propTypes = { name: PropTypes.string, path: PropTypes.string, handler: PropTypes.func, ignoreScrollBehavior: PropTypes.bool }; Route.defaultProps = { handler: RouteHandler }; module.exports = Route; },{"../PropTypes":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/PropTypes.js","./RouteHandler":"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/RouteHandler.js","react":"/Users/alex/Projects/webdrop/node_modules/react/react.js","react/lib/invariant":"/Users/alex/Projects/webdrop/node_modules/react/lib/invariant.js"}],"/Users/alex/Projects/webdrop/node_modules/react-router/lib/components/RouteHandler.js":[function(require,module,exports){ "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var React = require("react"); var ContextWrapper = require("./ContextWrapper"); var assign = require("react/lib/Object.assign"); var PropTypes = require("../PropTypes"); var REF_NAME = "__routeHandler__"; /** * A component renders the active child route handler * when routes are nested. */ var RouteHandler = (function (_React$Component) { function RouteHandler() { _classCallCheck(this, RouteHandler); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(RouteHandler, _React$Component); _createClass(RouteHandler, { getChildContext: { value: function getChildContext() { return { routeDepth: this.context.routeDepth + 1 }; } }, componentDidMount: { value: function componentDidMount() { this._updateRouteComponent(this.refs[REF_NAME]); } }, componentDidUpdate: { value: function componentDidUpdate() { this._updateRouteComponent(this.refs[REF_NAME]); } }, componentWillUnmount: { value: function componentWillUnmount() { this._updateRouteComponent(null); } }, _updateRouteComponent: { value: function _updateRouteComponent(component) { this.context.router.setRouteComponentAtDepth(this.getRouteDepth(), component); } }, getRouteDepth: { value: function getRouteDepth() { return this.context.routeDepth; } }, createChildRouteHandler: { value: function createChildRouteHandler(props) { var route = this.context.router.getRouteAtDepth(this.getRouteDepth()); return route ? React.createElement(route.handler, assign({}, props || this.props, { ref: REF_NAME })) : null; } }, render: { value: function render() { var handler = this.createChildRouteHandler(); //