diff --git a/README.md b/README.md index 8d5155d5..b86c5b91 100644 --- a/README.md +++ b/README.md @@ -55,23 +55,23 @@ Install Yjs, and its modules with [bower](http://bower.io/), or [npm](https://www.npmjs.org/package/yjs). ### Bower -``` +```sh bower install --save yjs y-array % add all y-* modules you want to use ``` You only need to include the `y.js` file. Yjs is able to automatically require missing modules. -``` +```html ``` ### Npm -``` +```sh npm install --save yjs % add all y-* modules you want to use ``` If you don't include via script tag, you have to explicitly include all modules! (Same goes for other module systems) -``` +```js var Y = require('yjs') require('y-array')(Y) // add the y-array type to Yjs require('y-websockets-client')(Y) @@ -84,7 +84,7 @@ require('y-text')(Y) ``` ### ES6 Syntax -``` +```js import Y from 'yjs' import yArray from 'y-array' import yWebsocketsClient from 'y-webrtc' @@ -98,7 +98,7 @@ Y.extend(yArray, yWebsocketsClient, yMemory, yArray, yMap, yText /*, .. */) # Text editing example Install dependencies -``` +```sh bower i yjs y-memory y-webrtc y-array y-text ``` @@ -166,6 +166,25 @@ soon, if possible. endpoint of the used connector. * All of our connectors also have a default connection endpoint that you can use for development. + * We provide basic authentification for all connectors. The value of + `options.connector.auth` (this can be a passphase) is sent to all connected + Yjs instances. `options.connector.checkAuth` may grant read or write access + depending on the `auth` information. + Example: A client specifies `options.connector.auth = 'superSecretPassword`. + A server specifies + ```js + options.connector.checkAuth = function (auth, yjsInstance, sender) { + return new Promise(function (resolve, reject){ + if (auth === 'superSecretPassword') { + resolve('write') // grant read-write access + } else if (auth === 'different password') { + resolve('read') // grant read-only access + } else { + reject('wrong password!') // reject connection + } + }) + } + ``` * Set `options.connector.generateUserId = true` in order to genenerate a userid, instead of receiving one from the server. This way the `Y(..)` is immediately going to be resolved, without waiting for any confirmation from @@ -181,7 +200,7 @@ soon, if possible. * Defaults to `/bower_components` * Not required when running on `nodejs` / `iojs` * When using nodejs you need to manually extend Yjs: -``` +```js var Y = require('yjs') // you have to require a db, connector, and *all* types you use! require('y-memory')(Y) diff --git a/bower.json b/bower.json index 1ff77bb5..fe960820 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "yjs", - "version": "12.3.2", + "version": "12.3.3", "homepage": "y-js.org", "authors": [ "Kevin Jahns " diff --git a/y.es6 b/y.es6 index a554be39..68a38765 100644 --- a/y.es6 +++ b/y.es6 @@ -1,6 +1,6 @@ /** * yjs - A framework for real-time p2p shared editing on any data - * @version v12.3.1 + * @version v12.3.2 * @link http://y-js.org * @license MIT */ @@ -777,7 +777,6 @@ module.exports = function (Y/* :any */) { // this client receives operations from only one other client. // In particular, this does not work with y-webrtc. // It will work with y-websockets-client - this.preferUntransformed = opts.preferUntransformed || false if (opts.role == null || opts.role === 'master') { this.role = 'master' } else if (opts.role === 'slave') { @@ -929,9 +928,6 @@ module.exports = function (Y/* :any */) { protocolVersion: conn.protocolVersion, auth: conn.authInfo } - if (conn.preferUntransformed && Object.keys(stateSet).length === 0) { - answer.preferUntransformed = true - } conn.send(syncUser, answer) }) } else { @@ -1045,11 +1041,7 @@ module.exports = function (Y/* :any */) { protocolVersion: this.protocolVersion, auth: this.authInfo } - if (message.preferUntransformed === true && Object.keys(m.stateSet).length === 0) { - answer.osUntransformed = yield* this.getOperationsUntransformed() - } else { - answer.os = yield* this.getOperations(m.stateSet) - } + answer.os = yield* this.getOperations(m.stateSet) conn.send(sender, answer) if (this.forwardToSyncingClients) { conn.syncingClients.push(sender) @@ -2534,7 +2526,7 @@ module.exports = function (Y/* :any */) { send.push(Y.Struct[op.struct].encode(op)) } } - if (this.store.y.connector.isSynced && send.length > 0) { // TODO: && !this.store.forwardAppliedOperations (but then i don't send delete ops) + if (send.length > 0) { // TODO: && !this.store.forwardAppliedOperations (but then i don't send delete ops) // is connected, and this is not going to be send in addOperation this.store.y.connector.broadcastOps(send) } @@ -3155,7 +3147,7 @@ module.exports = function (Y/* :any */) { } * addOperation (op) { yield* this.os.put(op) - if (this.store.y.connector.isSynced && this.store.forwardAppliedOperations && typeof op.id[1] !== 'string') { + if (this.store.forwardAppliedOperations && typeof op.id[1] !== 'string') { // is connected, and this is not going to be send in addOperation this.store.y.connector.broadcastOps([op]) } diff --git a/y.es6.map b/y.es6.map index 985d87cc..4dbacdc0 100644 --- a/y.es6.map +++ b/y.es6.map @@ -1 +1 @@ -{"version":3,"sources":["node_modules/browser-pack/_prelude.js","node_modules/debug/src/browser.js","node_modules/debug/src/debug.js","node_modules/ms/index.js","node_modules/process/browser.js","src/Connector.js","src/Connectors/Test.js","src/Database.js","src/Struct.js","src/Transaction.js","src/Utils.js","src/y.js"],"names":[],"mappings":";;;;;;AAAA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACzLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7eA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5lBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9ZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1kCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3xBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"y.es6","sourcesContent":["(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= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return;\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name;\n }\n return Math.ceil(ms / n) + ' ' + name + 's';\n}\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","function canRead (auth) { return auth === 'read' || auth === 'write' }\nfunction canWrite (auth) { return auth === 'write' }\n\nmodule.exports = function (Y/* :any */) {\n class AbstractConnector {\n /* ::\n y: YConfig;\n role: SyncRole;\n connections: Object;\n isSynced: boolean;\n userEventListeners: Array;\n whenSyncedListeners: Array;\n currentSyncTarget: ?UserId;\n syncingClients: Array;\n forwardToSyncingClients: boolean;\n debug: boolean;\n syncStep2: Promise;\n userId: UserId;\n send: Function;\n broadcast: Function;\n broadcastOpBuffer: Array;\n protocolVersion: number;\n */\n /*\n opts contains the following information:\n role : String Role of this client (\"master\" or \"slave\")\n userId : String Uniquely defines the user.\n debug: Boolean Whether to print debug messages (optional)\n */\n constructor (y, opts) {\n this.y = y\n if (opts == null) {\n opts = {}\n }\n // Prefer to receive untransformed operations. This does only work if\n // this client receives operations from only one other client.\n // In particular, this does not work with y-webrtc.\n // It will work with y-websockets-client\n this.preferUntransformed = opts.preferUntransformed || false\n if (opts.role == null || opts.role === 'master') {\n this.role = 'master'\n } else if (opts.role === 'slave') {\n this.role = 'slave'\n } else {\n throw new Error(\"Role must be either 'master' or 'slave'!\")\n }\n this.log = Y.debug('y:connector')\n this.logMessage = Y.debug('y:connector-message')\n this.y.db.forwardAppliedOperations = opts.forwardAppliedOperations || false\n this.role = opts.role\n this.connections = {}\n this.isSynced = false\n this.userEventListeners = []\n this.whenSyncedListeners = []\n this.currentSyncTarget = null\n this.syncingClients = []\n this.forwardToSyncingClients = opts.forwardToSyncingClients !== false\n this.debug = opts.debug === true\n this.syncStep2 = Promise.resolve()\n this.broadcastOpBuffer = []\n this.protocolVersion = 11\n this.authInfo = opts.auth || null\n this.checkAuth = opts.checkAuth || function () { return Promise.resolve('write') } // default is everyone has write access\n if (opts.generateUserId === true) {\n this.setUserId(Y.utils.generateGuid())\n }\n }\n resetAuth (auth) {\n if (this.authInfo !== auth) {\n this.authInfo = auth\n this.broadcast({\n type: 'auth',\n auth: this.authInfo\n })\n }\n }\n reconnect () {\n this.log('reconnecting..')\n return this.y.db.startGarbageCollector()\n }\n disconnect () {\n this.log('discronnecting..')\n this.connections = {}\n this.isSynced = false\n this.currentSyncTarget = null\n this.syncingClients = []\n this.whenSyncedListeners = []\n this.y.db.stopGarbageCollector()\n return this.y.db.whenTransactionsFinished()\n }\n repair () {\n this.log('Repairing the state of Yjs. This can happen if messages get lost, and Yjs detects that something is wrong. If this happens often, please report an issue here: https://github.com/y-js/yjs/issues')\n for (var name in this.connections) {\n this.connections[name].isSynced = false\n }\n this.isSynced = false\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n setUserId (userId) {\n if (this.userId == null) {\n this.log('Set userId to \"%s\"', userId)\n this.userId = userId\n return this.y.db.setUserId(userId)\n } else {\n return null\n }\n }\n onUserEvent (f) {\n this.userEventListeners.push(f)\n }\n removeUserEventListener (f) {\n this.userEventListeners = this.userEventListeners.filter(g => { f !== g })\n }\n userLeft (user) {\n if (this.connections[user] != null) {\n this.log('User left: %s', user)\n delete this.connections[user]\n if (user === this.currentSyncTarget) {\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n this.syncingClients = this.syncingClients.filter(function (cli) {\n return cli !== user\n })\n for (var f of this.userEventListeners) {\n f({\n action: 'userLeft',\n user: user\n })\n }\n }\n }\n userJoined (user, role) {\n if (role == null) {\n throw new Error('You must specify the role of the joined user!')\n }\n if (this.connections[user] != null) {\n throw new Error('This user already joined!')\n }\n this.log('User joined: %s', user)\n this.connections[user] = {\n isSynced: false,\n role: role\n }\n for (var f of this.userEventListeners) {\n f({\n action: 'userJoined',\n user: user,\n role: role\n })\n }\n if (this.currentSyncTarget == null) {\n this.findNextSyncTarget()\n }\n }\n // Execute a function _when_ we are connected.\n // If not connected, wait until connected\n whenSynced (f) {\n if (this.isSynced) {\n f()\n } else {\n this.whenSyncedListeners.push(f)\n }\n }\n findNextSyncTarget () {\n if (this.currentSyncTarget != null) {\n return // \"The current sync has not finished!\"\n }\n\n var syncUser = null\n for (var uid in this.connections) {\n if (!this.connections[uid].isSynced) {\n syncUser = uid\n break\n }\n }\n var conn = this\n if (syncUser != null) {\n this.currentSyncTarget = syncUser\n this.y.db.requestTransaction(function *() {\n var stateSet = yield* this.getStateSet()\n var deleteSet = yield* this.getDeleteSet()\n var answer = {\n type: 'sync step 1',\n stateSet: stateSet,\n deleteSet: deleteSet,\n protocolVersion: conn.protocolVersion,\n auth: conn.authInfo\n }\n if (conn.preferUntransformed && Object.keys(stateSet).length === 0) {\n answer.preferUntransformed = true\n }\n conn.send(syncUser, answer)\n })\n } else {\n if (!conn.isSynced) {\n this.y.db.requestTransaction(function *() {\n if (!conn.isSynced) {\n // it is crucial that isSynced is set at the time garbageCollectAfterSync is called\n conn.isSynced = true\n yield* this.garbageCollectAfterSync()\n // call whensynced listeners\n for (var f of conn.whenSyncedListeners) {\n f()\n }\n conn.whenSyncedListeners = []\n }\n })\n }\n }\n }\n send (uid, message) {\n this.log('Send \\'%s\\' to %s', message.type, uid)\n this.logMessage('Message: %j', message)\n }\n broadcast (message) {\n this.log('Broadcast \\'%s\\'', message.type)\n this.logMessage('Message: %j', message)\n }\n /*\n Buffer operations, and broadcast them when ready.\n */\n broadcastOps (ops) {\n ops = ops.map(function (op) {\n return Y.Struct[op.struct].encode(op)\n })\n var self = this\n function broadcastOperations () {\n if (self.broadcastOpBuffer.length > 0) {\n self.broadcast({\n type: 'update',\n ops: self.broadcastOpBuffer\n })\n self.broadcastOpBuffer = []\n }\n }\n if (this.broadcastOpBuffer.length === 0) {\n this.broadcastOpBuffer = ops\n if (this.y.db.transactionInProgress) {\n this.y.db.whenTransactionsFinished().then(broadcastOperations)\n } else {\n setTimeout(broadcastOperations, 0)\n }\n } else {\n this.broadcastOpBuffer = this.broadcastOpBuffer.concat(ops)\n }\n }\n /*\n You received a raw message, and you know that it is intended for Yjs. Then call this function.\n */\n receiveMessage (sender/* :UserId */, message/* :Message */) {\n if (sender === this.userId) {\n return Promise.resolve()\n }\n this.log('Receive \\'%s\\' from %s', message.type, sender)\n this.logMessage('Message: %j', message)\n if (message.protocolVersion != null && message.protocolVersion !== this.protocolVersion) {\n this.log(\n `You tried to sync with a yjs instance that has a different protocol version\n (You: ${this.protocolVersion}, Client: ${message.protocolVersion}).\n The sync was stopped. You need to upgrade your dependencies (especially Yjs & the Connector)!\n `)\n this.send(sender, {\n type: 'sync stop',\n protocolVersion: this.protocolVersion\n })\n return Promise.reject('Incompatible protocol version')\n }\n if (message.auth != null && this.connections[sender] != null) {\n // authenticate using auth in message\n var auth = this.checkAuth(message.auth, this.y, sender)\n this.connections[sender].auth = auth\n auth.then(auth => {\n for (var f of this.userEventListeners) {\n f({\n action: 'userAuthenticated',\n user: sender,\n auth: auth\n })\n }\n })\n } else if (this.connections[sender] != null && this.connections[sender].auth == null) {\n // authenticate without otherwise\n this.connections[sender].auth = this.checkAuth(null, this.y, sender)\n }\n if (this.connections[sender] != null && this.connections[sender].auth != null) {\n return this.connections[sender].auth.then((auth) => {\n if (message.type === 'sync step 1' && canRead(auth)) {\n let conn = this\n let m = message\n\n this.y.db.requestTransaction(function *() {\n var currentStateSet = yield* this.getStateSet()\n if (canWrite(auth)) {\n yield* this.applyDeleteSet(m.deleteSet)\n }\n\n var ds = yield* this.getDeleteSet()\n var answer = {\n type: 'sync step 2',\n stateSet: currentStateSet,\n deleteSet: ds,\n protocolVersion: this.protocolVersion,\n auth: this.authInfo\n }\n if (message.preferUntransformed === true && Object.keys(m.stateSet).length === 0) {\n answer.osUntransformed = yield* this.getOperationsUntransformed()\n } else {\n answer.os = yield* this.getOperations(m.stateSet)\n }\n conn.send(sender, answer)\n if (this.forwardToSyncingClients) {\n conn.syncingClients.push(sender)\n setTimeout(function () {\n conn.syncingClients = conn.syncingClients.filter(function (cli) {\n return cli !== sender\n })\n conn.send(sender, {\n type: 'sync done'\n })\n }, 5000) // TODO: conn.syncingClientDuration)\n } else {\n conn.send(sender, {\n type: 'sync done'\n })\n }\n })\n } else if (message.type === 'sync step 2' && canWrite(auth)) {\n var db = this.y.db\n var defer = {}\n defer.promise = new Promise(function (resolve) {\n defer.resolve = resolve\n })\n this.syncStep2 = defer.promise\n let m /* :MessageSyncStep2 */ = message\n db.requestTransaction(function * () {\n yield* this.applyDeleteSet(m.deleteSet)\n if (m.osUntransformed != null) {\n yield* this.applyOperationsUntransformed(m.osUntransformed, m.stateSet)\n } else {\n this.store.apply(m.os)\n }\n /*\n * This just sends the complete hb after some time\n * Mostly for debugging..\n *\n db.requestTransaction(function * () {\n var ops = yield* this.getOperations(m.stateSet)\n if (ops.length > 0) {\n if (!broadcastHB) { // TODO: consider to broadcast here..\n conn.send(sender, {\n type: 'update',\n ops: ops\n })\n } else {\n // broadcast only once!\n conn.broadcastOps(ops)\n }\n }\n })\n */\n defer.resolve()\n })\n } else if (message.type === 'sync done') {\n var self = this\n this.syncStep2.then(function () {\n self._setSyncedWith(sender)\n })\n } else if (message.type === 'update' && canWrite(auth)) {\n if (this.forwardToSyncingClients) {\n for (var client of this.syncingClients) {\n this.send(client, message)\n }\n }\n if (this.y.db.forwardAppliedOperations) {\n var delops = message.ops.filter(function (o) {\n return o.struct === 'Delete'\n })\n if (delops.length > 0) {\n this.broadcastOps(delops)\n }\n }\n this.y.db.apply(message.ops)\n }\n })\n } else {\n return Promise.reject('Unable to deliver message')\n }\n }\n _setSyncedWith (user) {\n var conn = this.connections[user]\n if (conn != null) {\n conn.isSynced = true\n }\n if (user === this.currentSyncTarget) {\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n }\n /*\n Currently, the HB encodes operations as JSON. For the moment I want to keep it\n that way. Maybe we support encoding in the HB as XML in the future, but for now I don't want\n too much overhead. Y is very likely to get changed a lot in the future\n\n Because we don't want to encode JSON as string (with character escaping, wich makes it pretty much unreadable)\n we encode the JSON as XML.\n\n When the HB support encoding as XML, the format should look pretty much like this.\n\n does not support primitive values as array elements\n expects an ltx (less than xml) object\n */\n parseMessageFromXml (m/* :any */) {\n function parseArray (node) {\n for (var n of node.children) {\n if (n.getAttribute('isArray') === 'true') {\n return parseArray(n)\n } else {\n return parseObject(n)\n }\n }\n }\n function parseObject (node/* :any */) {\n var json = {}\n for (var attrName in node.attrs) {\n var value = node.attrs[attrName]\n var int = parseInt(value, 10)\n if (isNaN(int) || ('' + int) !== value) {\n json[attrName] = value\n } else {\n json[attrName] = int\n }\n }\n for (var n/* :any */ in node.children) {\n var name = n.name\n if (n.getAttribute('isArray') === 'true') {\n json[name] = parseArray(n)\n } else {\n json[name] = parseObject(n)\n }\n }\n return json\n }\n parseObject(m)\n }\n /*\n encode message in xml\n we use string because Strophe only accepts an \"xml-string\"..\n So {a:4,b:{c:5}} will look like\n \n \n \n m - ltx element\n json - Object\n */\n encodeMessageToXml (msg, obj) {\n // attributes is optional\n function encodeObject (m, json) {\n for (var name in json) {\n var value = json[name]\n if (name == null) {\n // nop\n } else if (value.constructor === Object) {\n encodeObject(m.c(name), value)\n } else if (value.constructor === Array) {\n encodeArray(m.c(name), value)\n } else {\n m.setAttribute(name, value)\n }\n }\n }\n function encodeArray (m, array) {\n m.setAttribute('isArray', 'true')\n for (var e of array) {\n if (e.constructor === Object) {\n encodeObject(m.c('array-element'), e)\n } else {\n encodeArray(m.c('array-element'), e)\n }\n }\n }\n if (obj.constructor === Object) {\n encodeObject(msg.c('y', { xmlns: 'http://y.ninja/connector-stanza' }), obj)\n } else if (obj.constructor === Array) {\n encodeArray(msg.c('y', { xmlns: 'http://y.ninja/connector-stanza' }), obj)\n } else {\n throw new Error(\"I can't encode this json!\")\n }\n }\n }\n Y.AbstractConnector = AbstractConnector\n}\n","/* global getRandom, async */\n'use strict'\n\nmodule.exports = function (Y) {\n var globalRoom = {\n users: {},\n buffers: {},\n removeUser: function (user) {\n for (var i in this.users) {\n this.users[i].userLeft(user)\n }\n delete this.users[user]\n delete this.buffers[user]\n },\n addUser: function (connector) {\n this.users[connector.userId] = connector\n this.buffers[connector.userId] = {}\n for (var uname in this.users) {\n if (uname !== connector.userId) {\n var u = this.users[uname]\n u.userJoined(connector.userId, 'master')\n connector.userJoined(u.userId, 'master')\n }\n }\n },\n whenTransactionsFinished: function () {\n var self = this\n return new Promise(function (resolve, reject) {\n // The connector first has to send the messages to the db.\n // Wait for the checkAuth-function to resolve\n // The test lib only has a simple checkAuth function: `() => Promise.resolve()`\n // Just add a function to the event-queue, in order to wait for the event.\n // TODO: this may be buggy in test applications (but it isn't be for real-life apps)\n setTimeout(function () {\n var ps = []\n for (var name in self.users) {\n ps.push(self.users[name].y.db.whenTransactionsFinished())\n }\n Promise.all(ps).then(resolve, reject)\n }, 10)\n })\n },\n flushOne: function flushOne () {\n var bufs = []\n for (var receiver in globalRoom.buffers) {\n let buff = globalRoom.buffers[receiver]\n var push = false\n for (let sender in buff) {\n if (buff[sender].length > 0) {\n push = true\n break\n }\n }\n if (push) {\n bufs.push(receiver)\n }\n }\n if (bufs.length > 0) {\n var userId = getRandom(bufs)\n let buff = globalRoom.buffers[userId]\n let sender = getRandom(Object.keys(buff))\n var m = buff[sender].shift()\n if (buff[sender].length === 0) {\n delete buff[sender]\n }\n var user = globalRoom.users[userId]\n return user.receiveMessage(m[0], m[1]).then(function () {\n return user.y.db.whenTransactionsFinished()\n }, function () {})\n } else {\n return false\n }\n },\n flushAll: function () {\n return new Promise(function (resolve) {\n // flushes may result in more created operations,\n // flush until there is nothing more to flush\n function nextFlush () {\n var c = globalRoom.flushOne()\n if (c) {\n while (c) {\n c = globalRoom.flushOne()\n }\n globalRoom.whenTransactionsFinished().then(nextFlush)\n } else {\n c = globalRoom.flushOne()\n if (c) {\n c.then(function () {\n globalRoom.whenTransactionsFinished().then(nextFlush)\n })\n } else {\n resolve()\n }\n }\n }\n globalRoom.whenTransactionsFinished().then(nextFlush)\n })\n }\n }\n Y.utils.globalRoom = globalRoom\n\n var userIdCounter = 0\n\n class Test extends Y.AbstractConnector {\n constructor (y, options) {\n if (options === undefined) {\n throw new Error('Options must not be undefined!')\n }\n options.role = 'master'\n options.forwardToSyncingClients = false\n super(y, options)\n this.setUserId((userIdCounter++) + '').then(() => {\n globalRoom.addUser(this)\n })\n this.globalRoom = globalRoom\n this.syncingClientDuration = 0\n }\n receiveMessage (sender, m) {\n return super.receiveMessage(sender, JSON.parse(JSON.stringify(m)))\n }\n send (userId, message) {\n var buffer = globalRoom.buffers[userId]\n if (buffer != null) {\n if (buffer[this.userId] == null) {\n buffer[this.userId] = []\n }\n buffer[this.userId].push(JSON.parse(JSON.stringify([this.userId, message])))\n }\n }\n broadcast (message) {\n for (var key in globalRoom.buffers) {\n var buff = globalRoom.buffers[key]\n if (buff[this.userId] == null) {\n buff[this.userId] = []\n }\n buff[this.userId].push(JSON.parse(JSON.stringify([this.userId, message])))\n }\n }\n isDisconnected () {\n return globalRoom.users[this.userId] == null\n }\n reconnect () {\n if (this.isDisconnected()) {\n globalRoom.addUser(this)\n super.reconnect()\n }\n return Y.utils.globalRoom.flushAll()\n }\n disconnect () {\n var waitForMe = Promise.resolve()\n if (!this.isDisconnected()) {\n globalRoom.removeUser(this.userId)\n waitForMe = super.disconnect()\n }\n var self = this\n return waitForMe.then(function () {\n return self.y.db.whenTransactionsFinished()\n })\n }\n flush () {\n var self = this\n return async(function * () {\n var buff = globalRoom.buffers[self.userId]\n while (Object.keys(buff).length > 0) {\n var sender = getRandom(Object.keys(buff))\n var m = buff[sender].shift()\n if (buff[sender].length === 0) {\n delete buff[sender]\n }\n yield this.receiveMessage(m[0], m[1])\n }\n yield self.whenTransactionsFinished()\n })\n }\n }\n\n Y.Test = Test\n}\n","/* @flow */\n'use strict'\n\nmodule.exports = function (Y /* :any */) {\n /*\n Partial definition of an OperationStore.\n TODO: name it Database, operation store only holds operations.\n\n A database definition must alse define the following methods:\n * logTable() (optional)\n - show relevant information information in a table\n * requestTransaction(makeGen)\n - request a transaction\n * destroy()\n - destroy the database\n */\n class AbstractDatabase {\n /* ::\n y: YConfig;\n forwardAppliedOperations: boolean;\n listenersById: Object;\n listenersByIdExecuteNow: Array;\n listenersByIdRequestPending: boolean;\n initializedTypes: Object;\n whenUserIdSetListener: ?Function;\n waitingTransactions: Array;\n transactionInProgress: boolean;\n executeOrder: Array;\n gc1: Array;\n gc2: Array;\n gcTimeout: number;\n gcInterval: any;\n garbageCollect: Function;\n executeOrder: Array; // for debugging only\n userId: UserId;\n opClock: number;\n transactionsFinished: ?{promise: Promise, resolve: any};\n transact: (x: ?Generator) => any;\n */\n constructor (y, opts) {\n this.y = y\n this.dbOpts = opts\n var os = this\n this.userId = null\n var resolve\n this.userIdPromise = new Promise(function (r) {\n resolve = r\n })\n this.userIdPromise.resolve = resolve\n // whether to broadcast all applied operations (insert & delete hook)\n this.forwardAppliedOperations = false\n // E.g. this.listenersById[id] : Array\n this.listenersById = {}\n // Execute the next time a transaction is requested\n this.listenersByIdExecuteNow = []\n // A transaction is requested\n this.listenersByIdRequestPending = false\n /* To make things more clear, the following naming conventions:\n * ls : we put this.listenersById on ls\n * l : Array\n * id : Id (can't use as property name)\n * sid : String (converted from id via JSON.stringify\n so we can use it as a property name)\n\n Always remember to first overwrite\n a property before you iterate over it!\n */\n // TODO: Use ES7 Weak Maps. This way types that are no longer user,\n // wont be kept in memory.\n this.initializedTypes = {}\n this.waitingTransactions = []\n this.transactionInProgress = false\n this.transactionIsFlushed = false\n if (typeof YConcurrency_TestingMode !== 'undefined') {\n this.executeOrder = []\n }\n this.gc1 = [] // first stage\n this.gc2 = [] // second stage -> after that, remove the op\n\n function garbageCollect () {\n return os.whenTransactionsFinished().then(function () {\n if (os.gc1.length > 0 || os.gc2.length > 0) {\n if (!os.y.connector.isSynced) {\n console.warn('gc should be empty when not synced!')\n }\n return new Promise((resolve) => {\n os.requestTransaction(function * () {\n if (os.y.connector != null && os.y.connector.isSynced) {\n for (var i = 0; i < os.gc2.length; i++) {\n var oid = os.gc2[i]\n yield* this.garbageCollectOperation(oid)\n }\n os.gc2 = os.gc1\n os.gc1 = []\n }\n // TODO: Use setInterval here instead (when garbageCollect is called several times there will be several timeouts..)\n if (os.gcTimeout > 0) {\n os.gcInterval = setTimeout(garbageCollect, os.gcTimeout)\n }\n resolve()\n })\n })\n } else {\n // TODO: see above\n if (os.gcTimeout > 0) {\n os.gcInterval = setTimeout(garbageCollect, os.gcTimeout)\n }\n return Promise.resolve()\n }\n })\n }\n this.garbageCollect = garbageCollect\n this.startGarbageCollector()\n\n this.repairCheckInterval = !opts.repairCheckInterval ? 6000 : opts.repairCheckInterval\n this.opsReceivedTimestamp = new Date()\n this.startRepairCheck()\n }\n startGarbageCollector () {\n this.gc = this.dbOpts.gc == null || this.dbOpts.gc\n if (this.gc) {\n this.gcTimeout = !this.dbOpts.gcTimeout ? 50000 : this.dbOpts.gcTimeout\n } else {\n this.gcTimeout = -1\n }\n if (this.gcTimeout > 0) {\n this.garbageCollect()\n }\n }\n startRepairCheck () {\n var os = this\n if (this.repairCheckInterval > 0) {\n this.repairCheckIntervalHandler = setInterval(function repairOnMissingOperations () {\n /*\n Case 1. No ops have been received in a while (new Date() - os.opsReceivedTimestamp > os.repairCheckInterval)\n - 1.1 os.listenersById is empty. Then the state was correct the whole time. -> Nothing to do (nor to update)\n - 1.2 os.listenersById is not empty.\n * Then the state was incorrect for at least {os.repairCheckInterval} seconds.\n * -> Remove everything in os.listenersById and sync again (connector.repair())\n Case 2. An op has been received in the last {os.repairCheckInterval } seconds.\n It is not yet necessary to check for faulty behavior. Everything can still resolve itself. Wait for more messages.\n If nothing was received for a while and os.listenersById is still not emty, we are in case 1.2\n -> Do nothing\n\n Baseline here is: we really only have to catch case 1.2..\n */\n if (\n new Date() - os.opsReceivedTimestamp > os.repairCheckInterval &&\n Object.keys(os.listenersById).length > 0 // os.listenersById is not empty\n ) {\n // haven't received operations for over {os.repairCheckInterval} seconds, resend state vector\n os.listenersById = {}\n os.opsReceivedTimestamp = new Date() // update so you don't send repair several times in a row\n os.y.connector.repair()\n }\n }, this.repairCheckInterval)\n }\n }\n stopRepairCheck () {\n clearInterval(this.repairCheckIntervalHandler)\n }\n queueGarbageCollector (id) {\n if (this.y.connector.isSynced && this.gc) {\n this.gc1.push(id)\n }\n }\n emptyGarbageCollector () {\n return new Promise(resolve => {\n var check = () => {\n if (this.gc1.length > 0 || this.gc2.length > 0) {\n this.garbageCollect().then(check)\n } else {\n resolve()\n }\n }\n setTimeout(check, 0)\n })\n }\n addToDebug () {\n if (typeof YConcurrency_TestingMode !== 'undefined') {\n var command /* :string */ = Array.prototype.map.call(arguments, function (s) {\n if (typeof s === 'string') {\n return s\n } else {\n return JSON.stringify(s)\n }\n }).join('').replace(/\"/g, \"'\").replace(/,/g, ', ').replace(/:/g, ': ')\n this.executeOrder.push(command)\n }\n }\n getDebugData () {\n console.log(this.executeOrder.join('\\n'))\n }\n stopGarbageCollector () {\n var self = this\n this.gc = false\n this.gcTimeout = -1\n return new Promise(function (resolve) {\n self.requestTransaction(function * () {\n var ungc /* :Array */ = self.gc1.concat(self.gc2)\n self.gc1 = []\n self.gc2 = []\n for (var i = 0; i < ungc.length; i++) {\n var op = yield* this.getOperation(ungc[i])\n if (op != null) {\n delete op.gc\n yield* this.setOperation(op)\n }\n }\n resolve()\n })\n })\n }\n /*\n Try to add to GC.\n\n TODO: rename this function\n\n Rulez:\n * Only gc if this user is online & gc turned on\n * The most left element in a list must not be gc'd.\n => There is at least one element in the list\n\n returns true iff op was added to GC\n */\n * addToGarbageCollector (op, left) {\n if (\n op.gc == null &&\n op.deleted === true &&\n this.store.gc &&\n this.store.y.connector.isSynced\n ) {\n var gc = false\n if (left != null && left.deleted === true) {\n gc = true\n } else if (op.content != null && op.content.length > 1) {\n op = yield* this.getInsertionCleanStart([op.id[0], op.id[1] + 1])\n gc = true\n }\n if (gc) {\n op.gc = true\n yield* this.setOperation(op)\n this.store.queueGarbageCollector(op.id)\n return true\n }\n }\n return false\n }\n removeFromGarbageCollector (op) {\n function filter (o) {\n return !Y.utils.compareIds(o, op.id)\n }\n this.gc1 = this.gc1.filter(filter)\n this.gc2 = this.gc2.filter(filter)\n delete op.gc\n }\n destroyTypes () {\n for (var key in this.initializedTypes) {\n var type = this.initializedTypes[key]\n if (type._destroy != null) {\n type._destroy()\n } else {\n console.error('The type you included does not provide destroy functionality, it will remain in memory (updating your packages will help).')\n }\n }\n }\n * destroy () {\n clearInterval(this.gcInterval)\n this.gcInterval = null\n this.stopRepairCheck()\n }\n setUserId (userId) {\n if (!this.userIdPromise.inProgress) {\n this.userIdPromise.inProgress = true\n var self = this\n self.requestTransaction(function * () {\n self.userId = userId\n var state = yield* this.getState(userId)\n self.opClock = state.clock\n self.userIdPromise.resolve(userId)\n })\n }\n return this.userIdPromise\n }\n whenUserIdSet (f) {\n this.userIdPromise.then(f)\n }\n getNextOpId (numberOfIds) {\n if (numberOfIds == null) {\n throw new Error('getNextOpId expects the number of created ids to create!')\n } else if (this.userId == null) {\n throw new Error('OperationStore not yet initialized!')\n } else {\n var id = [this.userId, this.opClock]\n this.opClock += numberOfIds\n return id\n }\n }\n /*\n Apply a list of operations.\n\n * we save a timestamp, because we received new operations that could resolve ops in this.listenersById (see this.startRepairCheck)\n * get a transaction\n * check whether all Struct.*.requiredOps are in the OS\n * check if it is an expected op (otherwise wait for it)\n * check if was deleted, apply a delete operation after op was applied\n */\n apply (ops) {\n this.opsReceivedTimestamp = new Date()\n for (var i = 0; i < ops.length; i++) {\n var o = ops[i]\n if (o.id == null || o.id[0] !== this.y.connector.userId) {\n var required = Y.Struct[o.struct].requiredOps(o)\n if (o.requires != null) {\n required = required.concat(o.requires)\n }\n this.whenOperationsExist(required, o)\n }\n }\n }\n /*\n op is executed as soon as every operation requested is available.\n Note that Transaction can (and should) buffer requests.\n */\n whenOperationsExist (ids, op) {\n if (ids.length > 0) {\n let listener = {\n op: op,\n missing: ids.length\n }\n\n for (let i = 0; i < ids.length; i++) {\n let id = ids[i]\n let sid = JSON.stringify(id)\n let l = this.listenersById[sid]\n if (l == null) {\n l = []\n this.listenersById[sid] = l\n }\n l.push(listener)\n }\n } else {\n this.listenersByIdExecuteNow.push({\n op: op\n })\n }\n\n if (this.listenersByIdRequestPending) {\n return\n }\n\n this.listenersByIdRequestPending = true\n var store = this\n\n this.requestTransaction(function * () {\n var exeNow = store.listenersByIdExecuteNow\n store.listenersByIdExecuteNow = []\n\n var ls = store.listenersById\n store.listenersById = {}\n\n store.listenersByIdRequestPending = false\n\n for (let key = 0; key < exeNow.length; key++) {\n let o = exeNow[key].op\n yield* store.tryExecute.call(this, o)\n }\n\n for (var sid in ls) {\n var l = ls[sid]\n var id = JSON.parse(sid)\n var op\n if (typeof id[1] === 'string') {\n op = yield* this.getOperation(id)\n } else {\n op = yield* this.getInsertion(id)\n }\n if (op == null) {\n store.listenersById[sid] = l\n } else {\n for (let i = 0; i < l.length; i++) {\n let listener = l[i]\n let o = listener.op\n if (--listener.missing === 0) {\n yield* store.tryExecute.call(this, o)\n }\n }\n }\n }\n })\n }\n /*\n Actually execute an operation, when all expected operations are available.\n */\n /* :: // TODO: this belongs somehow to transaction\n store: Object;\n getOperation: any;\n isGarbageCollected: any;\n addOperation: any;\n whenOperationsExist: any;\n */\n * tryExecute (op) {\n this.store.addToDebug('yield* this.store.tryExecute.call(this, ', JSON.stringify(op), ')')\n if (op.struct === 'Delete') {\n yield* Y.Struct.Delete.execute.call(this, op)\n // this is now called in Transaction.deleteOperation!\n // yield* this.store.operationAdded(this, op)\n } else {\n // check if this op was defined\n var defined = yield* this.getInsertion(op.id)\n while (defined != null && defined.content != null) {\n // check if this op has a longer content in the case it is defined\n if (defined.id[1] + defined.content.length < op.id[1] + op.content.length) {\n var overlapSize = defined.content.length - (op.id[1] - defined.id[1])\n op.content.splice(0, overlapSize)\n op.id = [op.id[0], op.id[1] + overlapSize]\n op.left = Y.utils.getLastId(defined)\n op.origin = op.left\n defined = yield* this.getOperation(op.id) // getOperation suffices here\n } else {\n break\n }\n }\n if (defined == null) {\n var opid = op.id\n var isGarbageCollected = yield* this.isGarbageCollected(opid)\n if (!isGarbageCollected) {\n // TODO: reduce number of get / put calls for op ..\n yield* Y.Struct[op.struct].execute.call(this, op)\n yield* this.addOperation(op)\n yield* this.store.operationAdded(this, op)\n // operationAdded can change op..\n op = yield* this.getOperation(opid)\n // if insertion, try to combine with left\n yield* this.tryCombineWithLeft(op)\n }\n }\n }\n }\n /*\n * Called by a transaction when an operation is added.\n * This function is especially important for y-indexeddb, where several instances may share a single database.\n * Every time an operation is created by one instance, it is send to all other instances and operationAdded is called\n *\n * If it's not a Delete operation:\n * * Checks if another operation is executable (listenersById)\n * * Update state, if possible\n *\n * Always:\n * * Call type\n */\n * operationAdded (transaction, op) {\n if (op.struct === 'Delete') {\n var type = this.initializedTypes[JSON.stringify(op.targetParent)]\n if (type != null) {\n yield* type._changed(transaction, op)\n }\n } else {\n // increase SS\n yield* transaction.updateState(op.id[0])\n var opLen = op.content != null ? op.content.length : 1\n for (let i = 0; i < opLen; i++) {\n // notify whenOperation listeners (by id)\n var sid = JSON.stringify([op.id[0], op.id[1] + i])\n var l = this.listenersById[sid]\n delete this.listenersById[sid]\n if (l != null) {\n for (var key in l) {\n var listener = l[key]\n if (--listener.missing === 0) {\n this.whenOperationsExist([], listener.op)\n }\n }\n }\n }\n var t = this.initializedTypes[JSON.stringify(op.parent)]\n\n // if parent is deleted, mark as gc'd and return\n if (op.parent != null) {\n var parentIsDeleted = yield* transaction.isDeleted(op.parent)\n if (parentIsDeleted) {\n yield* transaction.deleteList(op.id)\n return\n }\n }\n\n // notify parent, if it was instanciated as a custom type\n if (t != null) {\n let o = Y.utils.copyOperation(op)\n yield* t._changed(transaction, o)\n }\n if (!op.deleted) {\n // Delete if DS says this is actually deleted\n var len = op.content != null ? op.content.length : 1\n var startId = op.id // You must not use op.id in the following loop, because op will change when deleted\n // TODO: !! console.log('TODO: change this before commiting')\n for (let i = 0; i < len; i++) {\n var id = [startId[0], startId[1] + i]\n var opIsDeleted = yield* transaction.isDeleted(id)\n if (opIsDeleted) {\n var delop = {\n struct: 'Delete',\n target: id\n }\n yield* this.tryExecute.call(transaction, delop)\n }\n }\n }\n }\n }\n whenTransactionsFinished () {\n if (this.transactionInProgress) {\n if (this.transactionsFinished == null) {\n var resolve\n var promise = new Promise(function (r) {\n resolve = r\n })\n this.transactionsFinished = {\n resolve: resolve,\n promise: promise\n }\n }\n return this.transactionsFinished.promise\n } else {\n return Promise.resolve()\n }\n }\n // Check if there is another transaction request.\n // * the last transaction is always a flush :)\n getNextRequest () {\n if (this.waitingTransactions.length === 0) {\n if (this.transactionIsFlushed) {\n this.transactionInProgress = false\n this.transactionIsFlushed = false\n if (this.transactionsFinished != null) {\n this.transactionsFinished.resolve()\n this.transactionsFinished = null\n }\n return null\n } else {\n this.transactionIsFlushed = true\n return function * () {\n yield* this.flush()\n }\n }\n } else {\n this.transactionIsFlushed = false\n return this.waitingTransactions.shift()\n }\n }\n requestTransaction (makeGen/* :any */, callImmediately) {\n this.waitingTransactions.push(makeGen)\n if (!this.transactionInProgress) {\n this.transactionInProgress = true\n setTimeout(() => {\n this.transact(this.getNextRequest())\n }, 0)\n }\n }\n /*\n Get a created/initialized type.\n */\n getType (id) {\n return this.initializedTypes[JSON.stringify(id)]\n }\n /*\n Init type. This is called when a remote operation is retrieved, and transformed to a type\n TODO: delete type from store.initializedTypes[id] when corresponding id was deleted!\n */\n * initType (id, args) {\n var sid = JSON.stringify(id)\n var t = this.store.initializedTypes[sid]\n if (t == null) {\n var op/* :MapStruct | ListStruct */ = yield* this.getOperation(id)\n if (op != null) {\n t = yield* Y[op.type].typeDefinition.initType.call(this, this.store, op, args)\n this.store.initializedTypes[sid] = t\n }\n }\n return t\n }\n /*\n Create type. This is called when the local user creates a type (which is a synchronous action)\n */\n createType (typedefinition, id) {\n var structname = typedefinition[0].struct\n id = id || this.getNextOpId(1)\n var op = Y.Struct[structname].create(id)\n op.type = typedefinition[0].name\n\n this.requestTransaction(function * () {\n if (op.id[0] === '_') {\n yield* this.setOperation(op)\n } else {\n yield* this.applyCreatedOperations([op])\n }\n })\n var t = Y[op.type].typeDefinition.createType(this, op, typedefinition[1])\n this.initializedTypes[JSON.stringify(op.id)] = t\n return t\n }\n }\n Y.AbstractDatabase = AbstractDatabase\n}\n","/* @flow */\n'use strict'\n\n/*\n An operation also defines the structure of a type. This is why operation and\n structure are used interchangeably here.\n\n It must be of the type Object. I hope to achieve some performance\n improvements when working on databases that support the json format.\n\n An operation must have the following properties:\n\n * encode\n - Encode the structure in a readable format (preferably string- todo)\n * decode (todo)\n - decode structure to json\n * execute\n - Execute the semantics of an operation.\n * requiredOps\n - Operations that are required to execute this operation.\n*/\nmodule.exports = function (Y/* :any */) {\n var Struct = {\n /* This is the only operation that is actually not a structure, because\n it is not stored in the OS. This is why it _does not_ have an id\n\n op = {\n target: Id\n }\n */\n Delete: {\n encode: function (op) {\n return {\n target: op.target,\n length: op.length || 0,\n struct: 'Delete'\n }\n },\n requiredOps: function (op) {\n return [] // [op.target]\n },\n execute: function * (op) {\n return yield* this.deleteOperation(op.target, op.length || 1)\n }\n },\n Insert: {\n /* {\n content: [any],\n opContent: Id,\n id: Id,\n left: Id,\n origin: Id,\n right: Id,\n parent: Id,\n parentSub: string (optional), // child of Map type\n }\n */\n encode: function (op/* :Insertion */) /* :Insertion */ {\n // TODO: you could not send the \"left\" property, then you also have to\n // \"op.left = null\" in $execute or $decode\n var e/* :any */ = {\n id: op.id,\n left: op.left,\n right: op.right,\n origin: op.origin,\n parent: op.parent,\n struct: op.struct\n }\n if (op.parentSub != null) {\n e.parentSub = op.parentSub\n }\n if (op.hasOwnProperty('opContent')) {\n e.opContent = op.opContent\n } else {\n e.content = op.content.slice()\n }\n\n return e\n },\n requiredOps: function (op) {\n var ids = []\n if (op.left != null) {\n ids.push(op.left)\n }\n if (op.right != null) {\n ids.push(op.right)\n }\n if (op.origin != null && !Y.utils.compareIds(op.left, op.origin)) {\n ids.push(op.origin)\n }\n // if (op.right == null && op.left == null) {\n ids.push(op.parent)\n\n if (op.opContent != null) {\n ids.push(op.opContent)\n }\n return ids\n },\n getDistanceToOrigin: function * (op) {\n if (op.left == null) {\n return 0\n } else {\n var d = 0\n var o = yield* this.getInsertion(op.left)\n while (!Y.utils.matchesId(o, op.origin)) {\n d++\n if (o.left == null) {\n break\n } else {\n o = yield* this.getInsertion(o.left)\n }\n }\n return d\n }\n },\n /*\n # $this has to find a unique position between origin and the next known character\n # case 1: $origin equals $o.origin: the $creator parameter decides if left or right\n # let $OL= [o1,o2,o3,o4], whereby $this is to be inserted between o1 and o4\n # o2,o3 and o4 origin is 1 (the position of o2)\n # there is the case that $this.creator < o2.creator, but o3.creator < $this.creator\n # then o2 knows o3. Since on another client $OL could be [o1,o3,o4] the problem is complex\n # therefore $this would be always to the right of o3\n # case 2: $origin < $o.origin\n # if current $this insert_position > $o origin: $this ins\n # else $insert_position will not change\n # (maybe we encounter case 1 later, then this will be to the right of $o)\n # case 3: $origin > $o.origin\n # $this insert_position is to the left of $o (forever!)\n */\n execute: function * (op) {\n var i // loop counter\n\n // during this function some ops may get split into two pieces (e.g. with getInsertionCleanEnd)\n // We try to merge them later, if possible\n var tryToRemergeLater = []\n\n if (op.origin != null) { // TODO: !== instead of !=\n // we save in origin that op originates in it\n // we need that later when we eventually garbage collect origin (see transaction)\n var origin = yield* this.getInsertionCleanEnd(op.origin)\n if (origin.originOf == null) {\n origin.originOf = []\n }\n origin.originOf.push(op.id)\n yield* this.setOperation(origin)\n if (origin.right != null) {\n tryToRemergeLater.push(origin.right)\n }\n }\n var distanceToOrigin = i = yield* Struct.Insert.getDistanceToOrigin.call(this, op) // most cases: 0 (starts from 0)\n\n // now we begin to insert op in the list of insertions..\n var o\n var parent\n var start\n\n // find o. o is the first conflicting operation\n if (op.left != null) {\n o = yield* this.getInsertionCleanEnd(op.left)\n if (!Y.utils.compareIds(op.left, op.origin) && o.right != null) {\n // only if not added previously\n tryToRemergeLater.push(o.right)\n }\n o = (o.right == null) ? null : yield* this.getOperation(o.right)\n } else { // left == null\n parent = yield* this.getOperation(op.parent)\n let startId = op.parentSub ? parent.map[op.parentSub] : parent.start\n start = startId == null ? null : yield* this.getOperation(startId)\n o = start\n }\n\n // make sure to split op.right if necessary (also add to tryCombineWithLeft)\n if (op.right != null) {\n tryToRemergeLater.push(op.right)\n yield* this.getInsertionCleanStart(op.right)\n }\n\n // handle conflicts\n while (true) {\n if (o != null && !Y.utils.compareIds(o.id, op.right)) {\n var oOriginDistance = yield* Struct.Insert.getDistanceToOrigin.call(this, o)\n if (oOriginDistance === i) {\n // case 1\n if (o.id[0] < op.id[0]) {\n op.left = Y.utils.getLastId(o)\n distanceToOrigin = i + 1 // just ignore o.content.length, doesn't make a difference\n }\n } else if (oOriginDistance < i) {\n // case 2\n if (i - distanceToOrigin <= oOriginDistance) {\n op.left = Y.utils.getLastId(o)\n distanceToOrigin = i + 1 // just ignore o.content.length, doesn't make a difference\n }\n } else {\n break\n }\n i++\n if (o.right != null) {\n o = yield* this.getInsertion(o.right)\n } else {\n o = null\n }\n } else {\n break\n }\n }\n\n // reconnect..\n var left = null\n var right = null\n if (parent == null) {\n parent = yield* this.getOperation(op.parent)\n }\n\n // reconnect left and set right of op\n if (op.left != null) {\n left = yield* this.getInsertion(op.left)\n // link left\n op.right = left.right\n left.right = op.id\n\n yield* this.setOperation(left)\n } else {\n // set op.right from parent, if necessary\n op.right = op.parentSub ? parent.map[op.parentSub] || null : parent.start\n }\n // reconnect right\n if (op.right != null) {\n // TODO: wanna connect right too?\n right = yield* this.getOperation(op.right)\n right.left = Y.utils.getLastId(op)\n\n // if right exists, and it is supposed to be gc'd. Remove it from the gc\n if (right.gc != null) {\n if (right.content != null && right.content.length > 1) {\n right = yield* this.getInsertionCleanEnd(right.id)\n }\n this.store.removeFromGarbageCollector(right)\n }\n yield* this.setOperation(right)\n }\n\n // update parents .map/start/end properties\n if (op.parentSub != null) {\n if (left == null) {\n parent.map[op.parentSub] = op.id\n yield* this.setOperation(parent)\n }\n // is a child of a map struct.\n // Then also make sure that only the most left element is not deleted\n // We do not call the type in this case (this is what the third parameter is for)\n if (op.right != null) {\n yield* this.deleteOperation(op.right, 1, true)\n }\n if (op.left != null) {\n yield* this.deleteOperation(op.id, 1, true)\n }\n } else {\n if (right == null || left == null) {\n if (right == null) {\n parent.end = Y.utils.getLastId(op)\n }\n if (left == null) {\n parent.start = op.id\n }\n yield* this.setOperation(parent)\n }\n }\n\n // try to merge original op.left and op.origin\n for (i = 0; i < tryToRemergeLater.length; i++) {\n var m = yield* this.getOperation(tryToRemergeLater[i])\n yield* this.tryCombineWithLeft(m)\n }\n }\n },\n List: {\n /*\n {\n start: null,\n end: null,\n struct: \"List\",\n type: \"\",\n id: this.os.getNextOpId(1)\n }\n */\n create: function (id) {\n return {\n start: null,\n end: null,\n struct: 'List',\n id: id\n }\n },\n encode: function (op) {\n var e = {\n struct: 'List',\n id: op.id,\n type: op.type\n }\n if (op.requires != null) {\n e.requires = op.requires\n }\n if (op.info != null) {\n e.info = op.info\n }\n return e\n },\n requiredOps: function () {\n /*\n var ids = []\n if (op.start != null) {\n ids.push(op.start)\n }\n if (op.end != null){\n ids.push(op.end)\n }\n return ids\n */\n return []\n },\n execute: function * (op) {\n op.start = null\n op.end = null\n },\n ref: function * (op, pos) {\n if (op.start == null) {\n return null\n }\n var res = null\n var o = yield* this.getOperation(op.start)\n\n while (true) {\n if (!o.deleted) {\n res = o\n pos--\n }\n if (pos >= 0 && o.right != null) {\n o = yield* this.getOperation(o.right)\n } else {\n break\n }\n }\n return res\n },\n map: function * (o, f) {\n o = o.start\n var res = []\n while (o != null) { // TODO: change to != (at least some convention)\n var operation = yield* this.getOperation(o)\n if (!operation.deleted) {\n res.push(f(operation))\n }\n o = operation.right\n }\n return res\n }\n },\n Map: {\n /*\n {\n map: {},\n struct: \"Map\",\n type: \"\",\n id: this.os.getNextOpId(1)\n }\n */\n create: function (id) {\n return {\n id: id,\n map: {},\n struct: 'Map'\n }\n },\n encode: function (op) {\n var e = {\n struct: 'Map',\n type: op.type,\n id: op.id,\n map: {} // overwrite map!!\n }\n if (op.requires != null) {\n e.requires = op.requires\n }\n if (op.info != null) {\n e.info = op.info\n }\n return e\n },\n requiredOps: function () {\n return []\n },\n execute: function * () {},\n /*\n Get a property by name\n */\n get: function * (op, name) {\n var oid = op.map[name]\n if (oid != null) {\n var res = yield* this.getOperation(oid)\n if (res == null || res.deleted) {\n return void 0\n } else if (res.opContent == null) {\n return res.content[0]\n } else {\n return yield* this.getType(res.opContent)\n }\n }\n }\n }\n }\n Y.Struct = Struct\n}\n","/* @flow */\n'use strict'\n\n/*\n Partial definition of a transaction\n\n A transaction provides all the the async functionality on a database.\n\n By convention, a transaction has the following properties:\n * ss for StateSet\n * os for OperationStore\n * ds for DeleteStore\n\n A transaction must also define the following methods:\n * checkDeleteStoreForState(state)\n - When increasing the state of a user, an operation with an higher id\n may already be garbage collected, and therefore it will never be received.\n update the state to reflect this knowledge. This won't call a method to save the state!\n * getDeleteSet(id)\n - Get the delete set in a readable format:\n {\n \"userX\": [\n [5,1], // starting from position 5, one operations is deleted\n [9,4] // starting from position 9, four operations are deleted\n ],\n \"userY\": ...\n }\n * getOpsFromDeleteSet(ds) -- TODO: just call this.deleteOperation(id) here\n - get a set of deletions that need to be applied in order to get to\n achieve the state of the supplied ds\n * setOperation(op)\n - write `op` to the database.\n Note: this is allowed to return an in-memory object.\n E.g. the Memory adapter returns the object that it has in-memory.\n Changing values on this object will be stored directly in the database\n without calling this function. Therefore,\n setOperation may have no functionality in some adapters. This also has\n implications on the way we use operations that were served from the database.\n We try not to call copyObject, if not necessary.\n * addOperation(op)\n - add an operation to the database.\n This may only be called once for every op.id\n Must return a function that returns the next operation in the database (ordered by id)\n * getOperation(id)\n * removeOperation(id)\n - remove an operation from the database. This is called when an operation\n is garbage collected.\n * setState(state)\n - `state` is of the form\n {\n user: \"1\",\n clock: 4\n } <- meaning that we have four operations from user \"1\"\n (with these id's respectively: 0, 1, 2, and 3)\n * getState(user)\n * getStateVector()\n - Get the state of the OS in the form\n [{\n user: \"userX\",\n clock: 11\n },\n ..\n ]\n * getStateSet()\n - Get the state of the OS in the form\n {\n \"userX\": 11,\n \"userY\": 22\n }\n * getOperations(startSS)\n - Get the all the operations that are necessary in order to achive the\n stateSet of this user, starting from a stateSet supplied by another user\n * makeOperationReady(ss, op)\n - this is called only by `getOperations(startSS)`. It makes an operation\n applyable on a given SS.\n*/\nmodule.exports = function (Y/* :any */) {\n class TransactionInterface {\n /* ::\n store: Y.AbstractDatabase;\n ds: Store;\n os: Store;\n ss: Store;\n */\n /*\n Apply operations that this user created (no remote ones!)\n * does not check for Struct.*.requiredOps()\n * also broadcasts it through the connector\n */\n * applyCreatedOperations (ops) {\n var send = []\n for (var i = 0; i < ops.length; i++) {\n var op = ops[i]\n yield* this.store.tryExecute.call(this, op)\n if (op.id == null || typeof op.id[1] !== 'string') {\n send.push(Y.Struct[op.struct].encode(op))\n }\n }\n if (this.store.y.connector.isSynced && send.length > 0) { // TODO: && !this.store.forwardAppliedOperations (but then i don't send delete ops)\n // is connected, and this is not going to be send in addOperation\n this.store.y.connector.broadcastOps(send)\n }\n }\n\n * deleteList (start) {\n while (start != null) {\n start = yield* this.getOperation(start)\n if (!start.gc) {\n start.gc = true\n start.deleted = true\n yield* this.setOperation(start)\n var delLength = start.content != null ? start.content.length : 1\n yield* this.markDeleted(start.id, delLength)\n if (start.opContent != null) {\n yield* this.deleteOperation(start.opContent)\n }\n this.store.queueGarbageCollector(start.id)\n }\n start = start.right\n }\n }\n\n /*\n Mark an operation as deleted, and add it to the GC, if possible.\n */\n * deleteOperation (targetId, length, preventCallType) /* :Generator */ {\n if (length == null) {\n length = 1\n }\n yield* this.markDeleted(targetId, length)\n while (length > 0) {\n var callType = false\n var target = yield* this.os.findWithUpperBound([targetId[0], targetId[1] + length - 1])\n var targetLength = target != null && target.content != null ? target.content.length : 1\n if (target == null || target.id[0] !== targetId[0] || target.id[1] + targetLength <= targetId[1]) {\n // does not exist or is not in the range of the deletion\n target = null\n length = 0\n } else {\n // does exist, check if it is too long\n if (!target.deleted) {\n if (target.id[1] < targetId[1]) {\n // starts to the left of the deletion range\n target = yield* this.getInsertionCleanStart(targetId)\n targetLength = target.content.length // must have content property!\n }\n if (target.id[1] + targetLength > targetId[1] + length) {\n // ends to the right of the deletion range\n target = yield* this.getInsertionCleanEnd([targetId[0], targetId[1] + length - 1])\n targetLength = target.content.length\n }\n }\n length = target.id[1] - targetId[1]\n }\n\n if (target != null) {\n if (!target.deleted) {\n callType = true\n // set deleted & notify type\n target.deleted = true\n // delete containing lists\n if (target.start != null) {\n // TODO: don't do it like this .. -.-\n yield* this.deleteList(target.start)\n // yield* this.deleteList(target.id) -- do not gc itself because this may still get referenced\n }\n if (target.map != null) {\n for (var name in target.map) {\n yield* this.deleteList(target.map[name])\n }\n // TODO: here to.. (see above)\n // yield* this.deleteList(target.id) -- see above\n }\n if (target.opContent != null) {\n yield* this.deleteOperation(target.opContent)\n // target.opContent = null\n }\n if (target.requires != null) {\n for (var i = 0; i < target.requires.length; i++) {\n yield* this.deleteOperation(target.requires[i])\n }\n }\n }\n var left\n if (target.left != null) {\n left = yield* this.getInsertion(target.left)\n } else {\n left = null\n }\n\n // set here because it was deleted and/or gc'd\n yield* this.setOperation(target)\n\n /*\n Check if it is possible to add right to the gc.\n Because this delete can't be responsible for left being gc'd,\n we don't have to add left to the gc..\n */\n var right\n if (target.right != null) {\n right = yield* this.getOperation(target.right)\n } else {\n right = null\n }\n if (callType && !preventCallType) {\n yield* this.store.operationAdded(this, {\n struct: 'Delete',\n target: target.id,\n length: targetLength,\n targetParent: target.parent\n })\n }\n // need to gc in the end!\n yield* this.store.addToGarbageCollector.call(this, target, left)\n if (right != null) {\n yield* this.store.addToGarbageCollector.call(this, right, target)\n }\n }\n }\n }\n /*\n Mark an operation as deleted&gc'd\n */\n * markGarbageCollected (id, len) {\n // this.mem.push([\"gc\", id]);\n this.store.addToDebug('yield* this.markGarbageCollected(', id, ', ', len, ')')\n var n = yield* this.markDeleted(id, len)\n if (n.id[1] < id[1] && !n.gc) {\n // un-extend left\n var newlen = n.len - (id[1] - n.id[1])\n n.len -= newlen\n yield* this.ds.put(n)\n n = {id: id, len: newlen, gc: false}\n yield* this.ds.put(n)\n }\n // get prev&next before adding a new operation\n var prev = yield* this.ds.findPrev(id)\n var next = yield* this.ds.findNext(id)\n\n if (id[1] + len < n.id[1] + n.len && !n.gc) {\n // un-extend right\n yield* this.ds.put({id: [id[0], id[1] + len], len: n.len - len, gc: false})\n n.len = len\n }\n // set gc'd\n n.gc = true\n // can extend left?\n if (\n prev != null &&\n prev.gc &&\n Y.utils.compareIds([prev.id[0], prev.id[1] + prev.len], n.id)\n ) {\n prev.len += n.len\n yield* this.ds.delete(n.id)\n n = prev\n // ds.put n here?\n }\n // can extend right?\n if (\n next != null &&\n next.gc &&\n Y.utils.compareIds([n.id[0], n.id[1] + n.len], next.id)\n ) {\n n.len += next.len\n yield* this.ds.delete(next.id)\n }\n yield* this.ds.put(n)\n yield* this.updateState(n.id[0])\n }\n /*\n Mark an operation as deleted.\n\n returns the delete node\n */\n * markDeleted (id, length) {\n if (length == null) {\n length = 1\n }\n // this.mem.push([\"del\", id]);\n var n = yield* this.ds.findWithUpperBound(id)\n if (n != null && n.id[0] === id[0]) {\n if (n.id[1] <= id[1] && id[1] <= n.id[1] + n.len) {\n // id is in n's range\n var diff = id[1] + length - (n.id[1] + n.len) // overlapping right\n if (diff > 0) {\n // id+length overlaps n\n if (!n.gc) {\n n.len += diff\n } else {\n diff = n.id[1] + n.len - id[1] // overlapping left (id till n.end)\n if (diff < length) {\n // a partial deletion\n n = {id: [id[0], id[1] + diff], len: length - diff, gc: false}\n yield* this.ds.put(n)\n } else {\n // already gc'd\n throw new Error('Cannot happen! (it dit though.. :()')\n // return n\n }\n }\n } else {\n // no overlapping, already deleted\n return n\n }\n } else {\n // cannot extend left (there is no left!)\n n = {id: id, len: length, gc: false}\n yield* this.ds.put(n) // TODO: you double-put !!\n }\n } else {\n // cannot extend left\n n = {id: id, len: length, gc: false}\n yield* this.ds.put(n)\n }\n // can extend right?\n var next = yield* this.ds.findNext(n.id)\n if (\n next != null &&\n n.id[0] === next.id[0] &&\n n.id[1] + n.len >= next.id[1]\n ) {\n diff = n.id[1] + n.len - next.id[1] // from next.start to n.end\n while (diff >= 0) {\n // n overlaps with next\n if (next.gc) {\n // gc is stronger, so reduce length of n\n n.len -= diff\n if (diff >= next.len) {\n // delete the missing range after next\n diff = diff - next.len // missing range after next\n if (diff > 0) {\n yield* this.ds.put(n) // unneccessary? TODO!\n yield* this.markDeleted([next.id[0], next.id[1] + next.len], diff)\n }\n }\n break\n } else {\n // we can extend n with next\n if (diff > next.len) {\n // n is even longer than next\n // get next.next, and try to extend it\n var _next = yield* this.ds.findNext(next.id)\n yield* this.ds.delete(next.id)\n if (_next == null || n.id[0] !== _next.id[0]) {\n break\n } else {\n next = _next\n diff = n.id[1] + n.len - next.id[1] // from next.start to n.end\n // continue!\n }\n } else {\n // n just partially overlaps with next. extend n, delete next, and break this loop\n n.len += next.len - diff\n yield* this.ds.delete(next.id)\n break\n }\n }\n }\n }\n yield* this.ds.put(n)\n return n\n }\n /*\n Call this method when the client is connected&synced with the\n other clients (e.g. master). This will query the database for\n operations that can be gc'd and add them to the garbage collector.\n */\n * garbageCollectAfterSync () {\n if (this.store.gc1.length > 0 || this.store.gc2.length > 0) {\n console.warn('gc should be empty after sync')\n }\n if (!this.store.gc) {\n return\n }\n yield* this.os.iterate(this, null, null, function * (op) {\n if (op.gc) {\n delete op.gc\n yield* this.setOperation(op)\n }\n if (op.parent != null) {\n var parentDeleted = yield* this.isDeleted(op.parent)\n if (parentDeleted) {\n op.gc = true\n if (!op.deleted) {\n yield* this.markDeleted(op.id, op.content != null ? op.content.length : 1)\n op.deleted = true\n if (op.opContent != null) {\n yield* this.deleteOperation(op.opContent)\n }\n if (op.requires != null) {\n for (var i = 0; i < op.requires.length; i++) {\n yield* this.deleteOperation(op.requires[i])\n }\n }\n }\n yield* this.setOperation(op)\n this.store.gc1.push(op.id) // this is ok becaues its shortly before sync (otherwise use queueGarbageCollector!)\n return\n }\n }\n if (op.deleted) {\n var left = null\n if (op.left != null) {\n left = yield* this.getInsertion(op.left)\n }\n yield* this.store.addToGarbageCollector.call(this, op, left)\n }\n })\n }\n /*\n Really remove an op and all its effects.\n The complicated case here is the Insert operation:\n * reset left\n * reset right\n * reset parent.start\n * reset parent.end\n * reset origins of all right ops\n */\n * garbageCollectOperation (id) {\n this.store.addToDebug('yield* this.garbageCollectOperation(', id, ')')\n var o = yield* this.getOperation(id)\n yield* this.markGarbageCollected(id, (o != null && o.content != null) ? o.content.length : 1) // always mark gc'd\n // if op exists, then clean that mess up..\n if (o != null) {\n var deps = []\n if (o.opContent != null) {\n deps.push(o.opContent)\n }\n if (o.requires != null) {\n deps = deps.concat(o.requires)\n }\n for (var i = 0; i < deps.length; i++) {\n var dep = yield* this.getOperation(deps[i])\n if (dep != null) {\n if (!dep.deleted) {\n yield* this.deleteOperation(dep.id)\n dep = yield* this.getOperation(dep.id)\n }\n dep.gc = true\n yield* this.setOperation(dep)\n this.store.queueGarbageCollector(dep.id)\n } else {\n yield* this.markGarbageCollected(deps[i], 1)\n }\n }\n\n // remove gc'd op from the left op, if it exists\n if (o.left != null) {\n var left = yield* this.getInsertion(o.left)\n left.right = o.right\n yield* this.setOperation(left)\n }\n // remove gc'd op from the right op, if it exists\n // also reset origins of right ops\n if (o.right != null) {\n var right = yield* this.getOperation(o.right)\n right.left = o.left\n yield* this.setOperation(right)\n\n if (o.originOf != null && o.originOf.length > 0) {\n // find new origin of right ops\n // origin is the first left deleted operation\n var neworigin = o.left\n var neworigin_ = null\n while (neworigin != null) {\n neworigin_ = yield* this.getInsertion(neworigin)\n if (neworigin_.deleted) {\n break\n }\n neworigin = neworigin_.left\n }\n\n // reset origin of all right ops (except first right - duh!),\n\n /* ** The following code does not rely on the the originOf property **\n I recently added originOf to all Insert Operations (see Struct.Insert.execute),\n which saves which operations originate in a Insert operation.\n Garbage collecting without originOf is more memory efficient, but is nearly impossible for large texts, or lists!\n But I keep this code for now\n ```\n // reset origin of right\n right.origin = neworigin\n // search until you find origin pointer to the left of o\n if (right.right != null) {\n var i = yield* this.getOperation(right.right)\n var ids = [o.id, o.right]\n while (ids.some(function (id) {\n return Y.utils.compareIds(id, i.origin)\n })) {\n if (Y.utils.compareIds(i.origin, o.id)) {\n // reset origin of i\n i.origin = neworigin\n yield* this.setOperation(i)\n }\n // get next i\n if (i.right == null) {\n break\n } else {\n ids.push(i.id)\n i = yield* this.getOperation(i.right)\n }\n }\n }\n ```\n */\n // ** Now the new implementation starts **\n // reset neworigin of all originOf[*]\n for (var _i in o.originOf) {\n var originsIn = yield* this.getOperation(o.originOf[_i])\n if (originsIn != null) {\n originsIn.origin = neworigin\n yield* this.setOperation(originsIn)\n }\n }\n if (neworigin != null) {\n if (neworigin_.originOf == null) {\n neworigin_.originOf = o.originOf\n } else {\n neworigin_.originOf = o.originOf.concat(neworigin_.originOf)\n }\n yield* this.setOperation(neworigin_)\n }\n // we don't need to set right here, because\n // right should be in o.originOf => it is set it the previous for loop\n }\n }\n // o may originate in another operation.\n // Since o is deleted, we have to reset o.origin's `originOf` property\n if (o.origin != null) {\n var origin = yield* this.getInsertion(o.origin)\n origin.originOf = origin.originOf.filter(function (_id) {\n return !Y.utils.compareIds(id, _id)\n })\n yield* this.setOperation(origin)\n }\n var parent\n if (o.parent != null) {\n parent = yield* this.getOperation(o.parent)\n }\n // remove gc'd op from parent, if it exists\n if (parent != null) {\n var setParent = false // whether to save parent to the os\n if (o.parentSub != null) {\n if (Y.utils.compareIds(parent.map[o.parentSub], o.id)) {\n setParent = true\n if (o.right != null) {\n parent.map[o.parentSub] = o.right\n } else {\n delete parent.map[o.parentSub]\n }\n }\n } else {\n if (Y.utils.compareIds(parent.start, o.id)) {\n // gc'd op is the start\n setParent = true\n parent.start = o.right\n }\n if (Y.utils.matchesId(o, parent.end)) {\n // gc'd op is the end\n setParent = true\n parent.end = o.left\n }\n }\n if (setParent) {\n yield* this.setOperation(parent)\n }\n }\n // finally remove it from the os\n yield* this.removeOperation(o.id)\n }\n }\n * checkDeleteStoreForState (state) {\n var n = yield* this.ds.findWithUpperBound([state.user, state.clock])\n if (n != null && n.id[0] === state.user && n.gc) {\n state.clock = Math.max(state.clock, n.id[1] + n.len)\n }\n }\n * updateState (user) {\n var state = yield* this.getState(user)\n yield* this.checkDeleteStoreForState(state)\n var o = yield* this.getInsertion([user, state.clock])\n var oLength = (o != null && o.content != null) ? o.content.length : 1\n while (o != null && user === o.id[0] && o.id[1] <= state.clock && o.id[1] + oLength > state.clock) {\n // either its a new operation (1. case), or it is an operation that was deleted, but is not yet in the OS\n state.clock += oLength\n yield* this.checkDeleteStoreForState(state)\n o = yield* this.os.findNext(o.id)\n oLength = (o != null && o.content != null) ? o.content.length : 1\n }\n yield* this.setState(state)\n }\n /*\n apply a delete set in order to get\n the state of the supplied ds\n */\n * applyDeleteSet (ds) {\n var deletions = []\n\n for (var user in ds) {\n var dv = ds[user]\n var pos = 0\n var d = dv[pos]\n yield* this.ds.iterate(this, [user, 0], [user, Number.MAX_VALUE], function * (n) {\n // cases:\n // 1. d deletes something to the right of n\n // => go to next n (break)\n // 2. d deletes something to the left of n\n // => create deletions\n // => reset d accordingly\n // *)=> if d doesn't delete anything anymore, go to next d (continue)\n // 3. not 2) and d deletes something that also n deletes\n // => reset d so that it doesn't contain n's deletion\n // *)=> if d does not delete anything anymore, go to next d (continue)\n while (d != null) {\n var diff = 0 // describe the diff of length in 1) and 2)\n if (n.id[1] + n.len <= d[0]) {\n // 1)\n break\n } else if (d[0] < n.id[1]) {\n // 2)\n // delete maximum the len of d\n // else delete as much as possible\n diff = Math.min(n.id[1] - d[0], d[1])\n deletions.push([user, d[0], diff, d[2]])\n } else {\n // 3)\n diff = n.id[1] + n.len - d[0] // never null (see 1)\n if (d[2] && !n.gc) {\n // d marks as gc'd but n does not\n // then delete either way\n deletions.push([user, d[0], Math.min(diff, d[1]), d[2]])\n }\n }\n if (d[1] <= diff) {\n // d doesn't delete anything anymore\n d = dv[++pos]\n } else {\n d[0] = d[0] + diff // reset pos\n d[1] = d[1] - diff // reset length\n }\n }\n })\n // for the rest.. just apply it\n for (; pos < dv.length; pos++) {\n d = dv[pos]\n deletions.push([user, d[0], d[1], d[2]])\n }\n }\n for (var i = 0; i < deletions.length; i++) {\n var del = deletions[i]\n // always try to delete..\n yield* this.deleteOperation([del[0], del[1]], del[2])\n if (del[3]) {\n // gc..\n yield* this.markGarbageCollected([del[0], del[1]], del[2]) // always mark gc'd\n // remove operation..\n var counter = del[1] + del[2]\n while (counter >= del[1]) {\n var o = yield* this.os.findWithUpperBound([del[0], counter - 1])\n if (o == null) {\n break\n }\n var oLen = o.content != null ? o.content.length : 1\n if (o.id[0] !== del[0] || o.id[1] + oLen <= del[1]) {\n // not in range\n break\n }\n if (o.id[1] + oLen > del[1] + del[2]) {\n // overlaps right\n o = yield* this.getInsertionCleanEnd([del[0], del[1] + del[2] - 1])\n }\n if (o.id[1] < del[1]) {\n // overlaps left\n o = yield* this.getInsertionCleanStart([del[0], del[1]])\n }\n counter = o.id[1]\n yield* this.garbageCollectOperation(o.id)\n }\n }\n if (this.store.forwardAppliedOperations) {\n var ops = []\n ops.push({struct: 'Delete', target: [del[0], del[1]], length: del[2]})\n this.store.y.connector.broadcastOps(ops)\n }\n }\n }\n * isGarbageCollected (id) {\n var n = yield* this.ds.findWithUpperBound(id)\n return n != null && n.id[0] === id[0] && id[1] < n.id[1] + n.len && n.gc\n }\n /*\n A DeleteSet (ds) describes all the deleted ops in the OS\n */\n * getDeleteSet () {\n var ds = {}\n yield* this.ds.iterate(this, null, null, function * (n) {\n var user = n.id[0]\n var counter = n.id[1]\n var len = n.len\n var gc = n.gc\n var dv = ds[user]\n if (dv === void 0) {\n dv = []\n ds[user] = dv\n }\n dv.push([counter, len, gc])\n })\n return ds\n }\n * isDeleted (id) {\n var n = yield* this.ds.findWithUpperBound(id)\n return n != null && n.id[0] === id[0] && id[1] < n.id[1] + n.len\n }\n * setOperation (op) {\n yield* this.os.put(op)\n return op\n }\n * addOperation (op) {\n yield* this.os.put(op)\n if (this.store.y.connector.isSynced && this.store.forwardAppliedOperations && typeof op.id[1] !== 'string') {\n // is connected, and this is not going to be send in addOperation\n this.store.y.connector.broadcastOps([op])\n }\n }\n // if insertion, try to combine with left insertion (if both have content property)\n * tryCombineWithLeft (op) {\n if (\n op != null &&\n op.left != null &&\n op.content != null &&\n op.left[0] === op.id[0] &&\n Y.utils.compareIds(op.left, op.origin)\n ) {\n var left = yield* this.getInsertion(op.left)\n if (left.content != null &&\n left.id[1] + left.content.length === op.id[1] &&\n left.originOf.length === 1 &&\n !left.gc && !left.deleted &&\n !op.gc && !op.deleted\n ) {\n // combine!\n if (op.originOf != null) {\n left.originOf = op.originOf\n } else {\n delete left.originOf\n }\n left.content = left.content.concat(op.content)\n left.right = op.right\n yield* this.os.delete(op.id)\n yield* this.setOperation(left)\n }\n }\n }\n * getInsertion (id) {\n var ins = yield* this.os.findWithUpperBound(id)\n if (ins == null) {\n return null\n } else {\n var len = ins.content != null ? ins.content.length : 1 // in case of opContent\n if (id[0] === ins.id[0] && id[1] < ins.id[1] + len) {\n return ins\n } else {\n return null\n }\n }\n }\n * getInsertionCleanStartEnd (id) {\n yield* this.getInsertionCleanStart(id)\n return yield* this.getInsertionCleanEnd(id)\n }\n // Return an insertion such that id is the first element of content\n // This function manipulates an operation, if necessary\n * getInsertionCleanStart (id) {\n var ins = yield* this.getInsertion(id)\n if (ins != null) {\n if (ins.id[1] === id[1]) {\n return ins\n } else {\n var left = Y.utils.copyObject(ins)\n ins.content = left.content.splice(id[1] - ins.id[1])\n ins.id = id\n var leftLid = Y.utils.getLastId(left)\n ins.origin = leftLid\n left.originOf = [ins.id]\n left.right = ins.id\n ins.left = leftLid\n // debugger // check\n yield* this.setOperation(left)\n yield* this.setOperation(ins)\n if (left.gc) {\n this.store.queueGarbageCollector(ins.id)\n }\n return ins\n }\n } else {\n return null\n }\n }\n // Return an insertion such that id is the last element of content\n // This function manipulates an operation, if necessary\n * getInsertionCleanEnd (id) {\n var ins = yield* this.getInsertion(id)\n if (ins != null) {\n if (ins.content == null || (ins.id[1] + ins.content.length - 1 === id[1])) {\n return ins\n } else {\n var right = Y.utils.copyObject(ins)\n right.content = ins.content.splice(id[1] - ins.id[1] + 1) // cut off remainder\n right.id = [id[0], id[1] + 1]\n var insLid = Y.utils.getLastId(ins)\n right.origin = insLid\n ins.originOf = [right.id]\n ins.right = right.id\n right.left = insLid\n // debugger // check\n yield* this.setOperation(right)\n yield* this.setOperation(ins)\n if (ins.gc) {\n this.store.queueGarbageCollector(right.id)\n }\n return ins\n }\n } else {\n return null\n }\n }\n * getOperation (id/* :any */)/* :Transaction */ {\n var o = yield* this.os.find(id)\n if (id[0] !== '_' || o != null) {\n return o\n } else { // type is string\n // generate this operation?\n var comp = id[1].split('_')\n if (comp.length > 1) {\n var struct = comp[0]\n var op = Y.Struct[struct].create(id)\n op.type = comp[1]\n yield* this.setOperation(op)\n return op\n } else {\n // won't be called. but just in case..\n console.error('Unexpected case. How can this happen?')\n debugger // eslint-disable-line\n return null\n }\n }\n }\n * removeOperation (id) {\n yield* this.os.delete(id)\n }\n * setState (state) {\n var val = {\n id: [state.user],\n clock: state.clock\n }\n yield* this.ss.put(val)\n }\n * getState (user) {\n var n = yield* this.ss.find([user])\n var clock = n == null ? null : n.clock\n if (clock == null) {\n clock = 0\n }\n return {\n user: user,\n clock: clock\n }\n }\n * getStateVector () {\n var stateVector = []\n yield* this.ss.iterate(this, null, null, function * (n) {\n stateVector.push({\n user: n.id[0],\n clock: n.clock\n })\n })\n return stateVector\n }\n * getStateSet () {\n var ss = {}\n yield* this.ss.iterate(this, null, null, function * (n) {\n ss[n.id[0]] = n.clock\n })\n return ss\n }\n /*\n Here, we make all missing operations executable for the receiving user.\n\n Notes:\n startSS: denotes to the SV that the remote user sent\n currSS: denotes to the state vector that the user should have if he\n applies all already sent operations (increases is each step)\n\n We face several problems:\n * Execute op as is won't work because ops depend on each other\n -> find a way so that they do not anymore\n * When changing left, must not go more to the left than the origin\n * When changing right, you have to consider that other ops may have op\n as their origin, this means that you must not set one of these ops\n as the new right (interdependencies of ops)\n * can't just go to the right until you find the first known operation,\n With currSS\n -> interdependency of ops is a problem\n With startSS\n -> leads to inconsistencies when two users join at the same time.\n Then the position depends on the order of execution -> error!\n\n Solution:\n -> re-create originial situation\n -> set op.left = op.origin (which never changes)\n -> set op.right\n to the first operation that is known (according to startSS)\n or to the first operation that has an origin that is not to the\n right of op.\n -> Enforces unique execution order -> happy user\n\n Improvements: TODO\n * Could set left to origin, or the first known operation\n (startSS or currSS.. ?)\n -> Could be necessary when I turn GC again.\n -> Is a bad(ish) idea because it requires more computation\n\n What we do:\n * Iterate over all missing operations.\n * When there is an operation, where the right op is known, send this op all missing ops to the left to the user\n * I explained above what we have to do with each operation. Here is how we do it efficiently:\n 1. Go to the left until you find either op.origin, or a known operation (let o denote current operation in the iteration)\n 2. Found a known operation -> set op.left = o, and send it to the user. stop\n 3. Found o = op.origin -> set op.left = op.origin, and send it to the user. start again from 1. (set op = o)\n 4. Found some o -> set o.right = op, o.left = o.origin, send it to the user, continue\n */\n * getOperations (startSS) {\n // TODO: use bounds here!\n if (startSS == null) {\n startSS = {}\n }\n var send = []\n\n var endSV = yield* this.getStateVector()\n for (var endState of endSV) {\n var user = endState.user\n if (user === '_') {\n continue\n }\n var startPos = startSS[user] || 0\n if (startPos > 0) {\n // There is a change that [user, startPos] is in a composed Insertion (with a smaller counter)\n // find out if that is the case\n var firstMissing = yield* this.getInsertion([user, startPos])\n if (firstMissing != null) {\n // update startPos\n startPos = firstMissing.id[1]\n startSS[user] = startPos\n }\n }\n yield* this.os.iterate(this, [user, startPos], [user, Number.MAX_VALUE], function * (op) {\n op = Y.Struct[op.struct].encode(op)\n if (op.struct !== 'Insert') {\n send.push(op)\n } else if (op.right == null || op.right[1] < (startSS[op.right[0]] || 0)) {\n // case 1. op.right is known\n var o = op\n // Remember: ?\n // -> set op.right\n // 1. to the first operation that is known (according to startSS)\n // 2. or to the first operation that has an origin that is not to the\n // right of op.\n // For this we maintain a list of ops which origins are not found yet.\n var missing_origins = [op]\n var newright = op.right\n while (true) {\n if (o.left == null) {\n op.left = null\n send.push(op)\n if (!Y.utils.compareIds(o.id, op.id)) {\n o = Y.Struct[op.struct].encode(o)\n o.right = missing_origins[missing_origins.length - 1].id\n send.push(o)\n }\n break\n }\n o = yield* this.getInsertion(o.left)\n // we set another o, check if we can reduce $missing_origins\n while (missing_origins.length > 0 && Y.utils.matchesId(o, missing_origins[missing_origins.length - 1].origin)) {\n missing_origins.pop()\n }\n if (o.id[1] < (startSS[o.id[0]] || 0)) {\n // case 2. o is known\n op.left = Y.utils.getLastId(o)\n send.push(op)\n break\n } else if (Y.utils.matchesId(o, op.origin)) {\n // case 3. o is op.origin\n op.left = op.origin\n send.push(op)\n op = Y.Struct[op.struct].encode(o)\n op.right = newright\n if (missing_origins.length > 0) {\n console.log('This should not happen .. :( please report this')\n }\n missing_origins = [op]\n } else {\n // case 4. send o, continue to find op.origin\n var s = Y.Struct[op.struct].encode(o)\n s.right = missing_origins[missing_origins.length - 1].id\n s.left = s.origin\n send.push(s)\n missing_origins.push(o)\n }\n }\n }\n })\n }\n return send.reverse()\n }\n /*\n * Get the plain untransformed operations from the database.\n * You can apply these operations using .applyOperationsUntransformed(ops)\n *\n */\n * getOperationsUntransformed () {\n var ops = []\n yield* this.os.iterate(this, null, null, function * (op) {\n if (op.id[0] !== '_') {\n ops.push(op)\n }\n })\n return {\n untransformed: ops\n }\n }\n * applyOperationsUntransformed (m, stateSet) {\n var ops = m.untransformed\n for (var i = 0; i < ops.length; i++) {\n var op = ops[i]\n // create, and modify parent, if it is created implicitly\n if (op.parent != null && op.parent[0] === '_') {\n if (op.struct === 'Insert') {\n // update parents .map/start/end properties\n if (op.parentSub != null && op.left == null) {\n // op is child of Map\n let parent = yield* this.getOperation(op.parent)\n parent.map[op.parentSub] = op.id\n yield* this.setOperation(parent)\n } else if (op.right == null || op.left == null) {\n let parent = yield* this.getOperation(op.parent)\n if (op.right == null) {\n parent.end = Y.utils.getLastId(op)\n }\n if (op.left == null) {\n parent.start = op.id\n }\n yield* this.setOperation(parent)\n }\n }\n }\n yield* this.os.put(op)\n }\n for (var user in stateSet) {\n yield* this.ss.put({\n id: [user],\n clock: stateSet[user]\n })\n }\n }\n /* this is what we used before.. use this as a reference..\n * makeOperationReady (startSS, op) {\n op = Y.Struct[op.struct].encode(op)\n op = Y.utils.copyObject(op) -- use copyoperation instead now!\n var o = op\n var ids = [op.id]\n // search for the new op.right\n // it is either the first known op (according to startSS)\n // or the o that has no origin to the right of op\n // (this is why we use the ids array)\n while (o.right != null) {\n var right = yield* this.getOperation(o.right)\n if (o.right[1] < (startSS[o.right[0]] || 0) || !ids.some(function (id) {\n return Y.utils.compareIds(id, right.origin)\n })) {\n break\n }\n ids.push(o.right)\n o = right\n }\n op.right = o.right\n op.left = op.origin\n return op\n }\n */\n * flush () {\n yield* this.os.flush()\n yield* this.ss.flush()\n yield* this.ds.flush()\n }\n }\n Y.Transaction = TransactionInterface\n}\n","/* @flow */\n'use strict'\n\n/*\n EventHandler is an helper class for constructing custom types.\n\n Why: When constructing custom types, you sometimes want your types to work\n synchronous: E.g.\n ``` Synchronous\n mytype.setSomething(\"yay\")\n mytype.getSomething() === \"yay\"\n ```\n versus\n ``` Asynchronous\n mytype.setSomething(\"yay\")\n mytype.getSomething() === undefined\n mytype.waitForSomething().then(function(){\n mytype.getSomething() === \"yay\"\n })\n ```\n\n The structures usually work asynchronously (you have to wait for the\n database request to finish). EventHandler helps you to make your type\n synchronous.\n*/\nmodule.exports = function (Y /* : any*/) {\n Y.utils = {}\n\n Y.utils.bubbleEvent = function (type, event) {\n type.eventHandler.callEventListeners(event)\n event.path = []\n while (type != null && type._deepEventHandler != null) {\n type._deepEventHandler.callEventListeners(event)\n var parent = null\n if (type._parent != null) {\n parent = type.os.getType(type._parent)\n }\n if (parent != null && parent._getPathToChild != null) {\n event.path = [parent._getPathToChild(type._model)].concat(event.path)\n type = parent\n } else {\n type = null\n }\n }\n }\n\n class EventListenerHandler {\n constructor () {\n this.eventListeners = []\n }\n destroy () {\n this.eventListeners = null\n }\n /*\n Basic event listener boilerplate...\n */\n addEventListener (f) {\n this.eventListeners.push(f)\n }\n removeEventListener (f) {\n this.eventListeners = this.eventListeners.filter(function (g) {\n return f !== g\n })\n }\n removeAllEventListeners () {\n this.eventListeners = []\n }\n callEventListeners (event) {\n for (var i = 0; i < this.eventListeners.length; i++) {\n try {\n var _event = {}\n for (var name in event) {\n _event[name] = event[name]\n }\n this.eventListeners[i](_event)\n } catch (e) {\n console.error('Your observer threw an error. This error was caught so that Yjs still can ensure data consistency! In order to debug this error you have to check \"Pause On Caught Exceptions\"', e)\n }\n }\n }\n }\n Y.utils.EventListenerHandler = EventListenerHandler\n\n class EventHandler extends EventListenerHandler {\n /* ::\n waiting: Array;\n awaiting: number;\n onevent: Function;\n eventListeners: Array;\n */\n /*\n onevent: is called when the structure changes.\n\n Note: \"awaiting opertations\" is used to denote operations that were\n prematurely called. Events for received operations can not be executed until\n all prematurely called operations were executed (\"waiting operations\")\n */\n constructor (onevent /* : Function */) {\n super()\n this.waiting = []\n this.awaiting = 0\n this.onevent = onevent\n }\n destroy () {\n super.destroy()\n this.waiting = null\n this.onevent = null\n }\n /*\n Call this when a new operation arrives. It will be executed right away if\n there are no waiting operations, that you prematurely executed\n */\n receivedOp (op) {\n if (this.awaiting <= 0) {\n this.onevent(op)\n } else if (op.struct === 'Delete') {\n var self = this\n var checkDelete = function checkDelete (d) {\n if (d.length == null) {\n throw new Error('This shouldn\\'t happen! d.length must be defined!')\n }\n // we check if o deletes something in self.waiting\n // if so, we remove the deleted operation\n for (var w = 0; w < self.waiting.length; w++) {\n var i = self.waiting[w]\n if (i.struct === 'Insert' && i.id[0] === d.target[0]) {\n var iLength = i.hasOwnProperty('content') ? i.content.length : 1\n var dStart = d.target[1]\n var dEnd = d.target[1] + (d.length || 1)\n var iStart = i.id[1]\n var iEnd = i.id[1] + iLength\n // Check if they don't overlap\n if (iEnd <= dStart || dEnd <= iStart) {\n // no overlapping\n continue\n }\n // we check all overlapping cases. All cases:\n /*\n 1) iiiii\n ddddd\n --> modify i and d\n 2) iiiiiii\n ddddd\n --> modify i, remove d\n 3) iiiiiii\n ddd\n --> remove d, modify i, and create another i (for the right hand side)\n 4) iiiii\n ddddddd\n --> remove i, modify d\n 5) iiiiiii\n ddddddd\n --> remove both i and d (**)\n 6) iiiiiii\n ddddd\n --> modify i, remove d\n 7) iii\n ddddddd\n --> remove i, create and apply two d with checkDelete(d) (**)\n 8) iiiii\n ddddddd\n --> remove i, modify d (**)\n 9) iiiii\n ddddd\n --> modify i and d\n (**) (also check if i contains content or type)\n */\n // TODO: I left some debugger statements, because I want to debug all cases once in production. REMEMBER END TODO\n if (iStart < dStart) {\n if (dStart < iEnd) {\n if (iEnd < dEnd) {\n // Case 1\n // remove the right part of i's content\n i.content.splice(dStart - iStart)\n // remove the start of d's deletion\n d.length = dEnd - iEnd\n d.target = [d.target[0], iEnd]\n continue\n } else if (iEnd === dEnd) {\n // Case 2\n i.content.splice(dStart - iStart)\n // remove d, we do that by simply ending this function\n return\n } else { // (dEnd < iEnd)\n // Case 3\n var newI = {\n id: [i.id[0], dEnd],\n content: i.content.slice(dEnd - iStart),\n struct: 'Insert'\n }\n self.waiting.push(newI)\n i.content.splice(dStart - iStart)\n return\n }\n }\n } else if (dStart === iStart) {\n if (iEnd < dEnd) {\n // Case 4\n d.length = dEnd - iEnd\n d.target = [d.target[0], iEnd]\n i.content = []\n continue\n } else if (iEnd === dEnd) {\n // Case 5\n self.waiting.splice(w, 1)\n return\n } else { // (dEnd < iEnd)\n // Case 6\n i.content = i.content.slice(dEnd - iStart)\n i.id = [i.id[0], dEnd]\n return\n }\n } else { // (dStart < iStart)\n if (iStart < dEnd) {\n // they overlap\n /*\n 7) iii\n ddddddd\n --> remove i, create and apply two d with checkDelete(d) (**)\n 8) iiiii\n ddddddd\n --> remove i, modify d (**)\n 9) iiiii\n ddddd\n --> modify i and d\n */\n if (iEnd < dEnd) {\n // Case 7\n // debugger // TODO: You did not test this case yet!!!! (add the debugger here)\n self.waiting.splice(w, 1)\n checkDelete({\n target: [d.target[0], dStart],\n length: iStart - dStart,\n struct: 'Delete'\n })\n checkDelete({\n target: [d.target[0], iEnd],\n length: iEnd - dEnd,\n struct: 'Delete'\n })\n return\n } else if (iEnd === dEnd) {\n // Case 8\n self.waiting.splice(w, 1)\n w--\n d.length -= iLength\n continue\n } else { // dEnd < iEnd\n // Case 9\n d.length = iStart - dStart\n i.content.splice(0, dEnd - iStart)\n i.id = [i.id[0], dEnd]\n continue\n }\n }\n }\n }\n }\n // finished with remaining operations\n self.waiting.push(d)\n }\n if (op.key == null) {\n // deletes in list\n checkDelete(op)\n } else {\n // deletes in map\n this.waiting.push(op)\n }\n } else {\n this.waiting.push(op)\n }\n }\n /*\n You created some operations, and you want the `onevent` function to be\n called right away. Received operations will not be executed untill all\n prematurely called operations are executed\n */\n awaitAndPrematurelyCall (ops) {\n this.awaiting++\n ops.map(Y.utils.copyOperation).forEach(this.onevent)\n }\n * awaitOps (transaction, f, args) {\n function notSoSmartSort (array) {\n // this function sorts insertions in a executable order\n var result = []\n while (array.length > 0) {\n for (var i = 0; i < array.length; i++) {\n var independent = true\n for (var j = 0; j < array.length; j++) {\n if (Y.utils.matchesId(array[j], array[i].left)) {\n // array[i] depends on array[j]\n independent = false\n break\n }\n }\n if (independent) {\n result.push(array.splice(i, 1)[0])\n i--\n }\n }\n }\n return result\n }\n var before = this.waiting.length\n // somehow create new operations\n yield* f.apply(transaction, args)\n // remove all appended ops / awaited ops\n this.waiting.splice(before)\n if (this.awaiting > 0) this.awaiting--\n // if there are no awaited ops anymore, we can update all waiting ops, and send execute them (if there are still no awaited ops)\n if (this.awaiting === 0 && this.waiting.length > 0) {\n // update all waiting ops\n for (let i = 0; i < this.waiting.length; i++) {\n var o = this.waiting[i]\n if (o.struct === 'Insert') {\n var _o = yield* transaction.getInsertion(o.id)\n if (_o.parentSub != null && _o.left != null) {\n // if o is an insertion of a map struc (parentSub is defined), then it shouldn't be necessary to compute left\n this.waiting.splice(i, 1)\n i-- // update index\n } else if (!Y.utils.compareIds(_o.id, o.id)) {\n // o got extended\n o.left = [o.id[0], o.id[1] - 1]\n } else if (_o.left == null) {\n o.left = null\n } else {\n // find next undeleted op\n var left = yield* transaction.getInsertion(_o.left)\n while (left.deleted != null) {\n if (left.left != null) {\n left = yield* transaction.getInsertion(left.left)\n } else {\n left = null\n break\n }\n }\n o.left = left != null ? Y.utils.getLastId(left) : null\n }\n }\n }\n // the previous stuff was async, so we have to check again!\n // We also pull changes from the bindings, if there exists such a method, this could increase awaiting too\n if (this._pullChanges != null) {\n this._pullChanges()\n }\n if (this.awaiting === 0) {\n // sort by type, execute inserts first\n var ins = []\n var dels = []\n this.waiting.forEach(function (o) {\n if (o.struct === 'Delete') {\n dels.push(o)\n } else {\n ins.push(o)\n }\n })\n this.waiting = []\n // put in executable order\n ins = notSoSmartSort(ins)\n // this.onevent can trigger the creation of another operation\n // -> check if this.awaiting increased & stop computation if it does\n for (var i = 0; i < ins.length; i++) {\n if (this.awaiting === 0) {\n this.onevent(ins[i])\n } else {\n this.waiting = this.waiting.concat(ins.slice(i))\n break\n }\n }\n for (i = 0; i < dels.length; i++) {\n if (this.awaiting === 0) {\n this.onevent(dels[i])\n } else {\n this.waiting = this.waiting.concat(dels.slice(i))\n break\n }\n }\n }\n }\n }\n // TODO: Remove awaitedInserts and awaitedDeletes in favor of awaitedOps, as they are deprecated and do not always work\n // Do this in one of the coming releases that are breaking anyway\n /*\n Call this when you successfully awaited the execution of n Insert operations\n */\n awaitedInserts (n) {\n var ops = this.waiting.splice(this.waiting.length - n)\n for (var oid = 0; oid < ops.length; oid++) {\n var op = ops[oid]\n if (op.struct === 'Insert') {\n for (var i = this.waiting.length - 1; i >= 0; i--) {\n let w = this.waiting[i]\n // TODO: do I handle split operations correctly here? Super unlikely, but yeah..\n // Also: can this case happen? Can op be inserted in the middle of a larger op that is in $waiting?\n if (w.struct === 'Insert') {\n if (Y.utils.matchesId(w, op.left)) {\n // include the effect of op in w\n w.right = op.id\n // exclude the effect of w in op\n op.left = w.left\n } else if (Y.utils.compareIds(w.id, op.right)) {\n // similar..\n w.left = Y.utils.getLastId(op)\n op.right = w.right\n }\n }\n }\n } else {\n throw new Error('Expected Insert Operation!')\n }\n }\n this._tryCallEvents(n)\n }\n /*\n Call this when you successfully awaited the execution of n Delete operations\n */\n awaitedDeletes (n, newLeft) {\n var ops = this.waiting.splice(this.waiting.length - n)\n for (var j = 0; j < ops.length; j++) {\n var del = ops[j]\n if (del.struct === 'Delete') {\n if (newLeft != null) {\n for (var i = 0; i < this.waiting.length; i++) {\n let w = this.waiting[i]\n // We will just care about w.left\n if (w.struct === 'Insert' && Y.utils.compareIds(del.target, w.left)) {\n w.left = newLeft\n }\n }\n }\n } else {\n throw new Error('Expected Delete Operation!')\n }\n }\n this._tryCallEvents(n)\n }\n /* (private)\n Try to execute the events for the waiting operations\n */\n _tryCallEvents () {\n function notSoSmartSort (array) {\n var result = []\n while (array.length > 0) {\n for (var i = 0; i < array.length; i++) {\n var independent = true\n for (var j = 0; j < array.length; j++) {\n if (Y.utils.matchesId(array[j], array[i].left)) {\n // array[i] depends on array[j]\n independent = false\n break\n }\n }\n if (independent) {\n result.push(array.splice(i, 1)[0])\n i--\n }\n }\n }\n return result\n }\n if (this.awaiting > 0) this.awaiting--\n if (this.awaiting === 0 && this.waiting.length > 0) {\n var ins = []\n var dels = []\n this.waiting.forEach(function (o) {\n if (o.struct === 'Delete') {\n dels.push(o)\n } else {\n ins.push(o)\n }\n })\n ins = notSoSmartSort(ins)\n ins.forEach(this.onevent)\n dels.forEach(this.onevent)\n this.waiting = []\n }\n }\n }\n Y.utils.EventHandler = EventHandler\n\n /*\n Default class of custom types!\n */\n class CustomType {\n getPath () {\n var parent = null\n if (this._parent != null) {\n parent = this.os.getType(this._parent)\n }\n if (parent != null && parent._getPathToChild != null) {\n var firstKey = parent._getPathToChild(this._model)\n var parentKeys = parent.getPath()\n parentKeys.push(firstKey)\n return parentKeys\n } else {\n return []\n }\n }\n }\n Y.utils.CustomType = CustomType\n\n /*\n A wrapper for the definition of a custom type.\n Every custom type must have three properties:\n\n * struct\n - Structname of this type\n * initType\n - Given a model, creates a custom type\n * class\n - the constructor of the custom type (e.g. in order to inherit from a type)\n */\n class CustomTypeDefinition { // eslint-disable-line\n /* ::\n struct: any;\n initType: any;\n class: Function;\n name: String;\n */\n constructor (def) {\n if (def.struct == null ||\n def.initType == null ||\n def.class == null ||\n def.name == null ||\n def.createType == null\n ) {\n throw new Error('Custom type was not initialized correctly!')\n }\n this.struct = def.struct\n this.initType = def.initType\n this.createType = def.createType\n this.class = def.class\n this.name = def.name\n if (def.appendAdditionalInfo != null) {\n this.appendAdditionalInfo = def.appendAdditionalInfo\n }\n this.parseArguments = (def.parseArguments || function () {\n return [this]\n }).bind(this)\n this.parseArguments.typeDefinition = this\n }\n }\n Y.utils.CustomTypeDefinition = CustomTypeDefinition\n\n Y.utils.isTypeDefinition = function isTypeDefinition (v) {\n if (v != null) {\n if (v instanceof Y.utils.CustomTypeDefinition) return [v]\n else if (v.constructor === Array && v[0] instanceof Y.utils.CustomTypeDefinition) return v\n else if (v instanceof Function && v.typeDefinition instanceof Y.utils.CustomTypeDefinition) return [v.typeDefinition]\n }\n return false\n }\n\n /*\n Make a flat copy of an object\n (just copy properties)\n */\n function copyObject (o) {\n var c = {}\n for (var key in o) {\n c[key] = o[key]\n }\n return c\n }\n Y.utils.copyObject = copyObject\n\n /*\n Copy an operation, so that it can be manipulated.\n Note: You must not change subproperties (except o.content)!\n */\n function copyOperation (o) {\n o = copyObject(o)\n if (o.content != null) {\n o.content = o.content.map(function (c) { return c })\n }\n return o\n }\n\n Y.utils.copyOperation = copyOperation\n\n /*\n Defines a smaller relation on Id's\n */\n function smaller (a, b) {\n return a[0] < b[0] || (a[0] === b[0] && (a[1] < b[1] || typeof a[1] < typeof b[1]))\n }\n Y.utils.smaller = smaller\n\n function inDeletionRange (del, ins) {\n return del.target[0] === ins[0] && del.target[1] <= ins[1] && ins[1] < del.target[1] + (del.length || 1)\n }\n Y.utils.inDeletionRange = inDeletionRange\n\n function compareIds (id1, id2) {\n if (id1 == null || id2 == null) {\n return id1 === id2\n } else {\n return id1[0] === id2[0] && id1[1] === id2[1]\n }\n }\n Y.utils.compareIds = compareIds\n\n function matchesId (op, id) {\n if (id == null || op == null) {\n return id === op\n } else {\n if (id[0] === op.id[0]) {\n if (op.content == null) {\n return id[1] === op.id[1]\n } else {\n return id[1] >= op.id[1] && id[1] < op.id[1] + op.content.length\n }\n }\n }\n }\n Y.utils.matchesId = matchesId\n\n function getLastId (op) {\n if (op.content == null || op.content.length === 1) {\n return op.id\n } else {\n return [op.id[0], op.id[1] + op.content.length - 1]\n }\n }\n Y.utils.getLastId = getLastId\n\n function createEmptyOpsArray (n) {\n var a = new Array(n)\n for (var i = 0; i < a.length; i++) {\n a[i] = {\n id: [null, null]\n }\n }\n return a\n }\n\n function createSmallLookupBuffer (Store) {\n /*\n This buffer implements a very small buffer that temporarily stores operations\n after they are read / before they are written.\n The buffer basically implements FIFO. Often requested lookups will be re-queued every time they are looked up / written.\n\n It can speed up lookups on Operation Stores and State Stores. But it does not require notable use of memory or processing power.\n\n Good for os and ss, bot not for ds (because it often uses methods that require a flush)\n\n I tried to optimize this for performance, therefore no highlevel operations.\n */\n class SmallLookupBuffer extends Store {\n constructor (arg1, arg2) {\n // super(...arguments) -- do this when this is supported by stable nodejs\n super(arg1, arg2)\n this.writeBuffer = createEmptyOpsArray(5)\n this.readBuffer = createEmptyOpsArray(10)\n }\n * find (id, noSuperCall) {\n var i, r\n for (i = this.readBuffer.length - 1; i >= 0; i--) {\n r = this.readBuffer[i]\n // we don't have to use compareids, because id is always defined!\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n // found r\n // move r to the end of readBuffer\n for (; i < this.readBuffer.length - 1; i++) {\n this.readBuffer[i] = this.readBuffer[i + 1]\n }\n this.readBuffer[this.readBuffer.length - 1] = r\n return r\n }\n }\n var o\n for (i = this.writeBuffer.length - 1; i >= 0; i--) {\n r = this.writeBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n o = r\n break\n }\n }\n if (i < 0 && noSuperCall === undefined) {\n // did not reach break in last loop\n // read id and put it to the end of readBuffer\n o = yield* super.find(id)\n }\n if (o != null) {\n for (i = 0; i < this.readBuffer.length - 1; i++) {\n this.readBuffer[i] = this.readBuffer[i + 1]\n }\n this.readBuffer[this.readBuffer.length - 1] = o\n }\n return o\n }\n * put (o) {\n var id = o.id\n var i, r // helper variables\n for (i = this.writeBuffer.length - 1; i >= 0; i--) {\n r = this.writeBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n // is already in buffer\n // forget r, and move o to the end of writeBuffer\n for (; i < this.writeBuffer.length - 1; i++) {\n this.writeBuffer[i] = this.writeBuffer[i + 1]\n }\n this.writeBuffer[this.writeBuffer.length - 1] = o\n break\n }\n }\n if (i < 0) {\n // did not reach break in last loop\n // write writeBuffer[0]\n var write = this.writeBuffer[0]\n if (write.id[0] !== null) {\n yield* super.put(write)\n }\n // put o to the end of writeBuffer\n for (i = 0; i < this.writeBuffer.length - 1; i++) {\n this.writeBuffer[i] = this.writeBuffer[i + 1]\n }\n this.writeBuffer[this.writeBuffer.length - 1] = o\n }\n // check readBuffer for every occurence of o.id, overwrite if found\n // whether found or not, we'll append o to the readbuffer\n for (i = 0; i < this.readBuffer.length - 1; i++) {\n r = this.readBuffer[i + 1]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n this.readBuffer[i] = o\n } else {\n this.readBuffer[i] = r\n }\n }\n this.readBuffer[this.readBuffer.length - 1] = o\n }\n * delete (id) {\n var i, r\n for (i = 0; i < this.readBuffer.length; i++) {\n r = this.readBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n this.readBuffer[i] = {\n id: [null, null]\n }\n }\n }\n yield* this.flush()\n yield* super.delete(id)\n }\n * findWithLowerBound (id) {\n var o = yield* this.find(id, true)\n if (o != null) {\n return o\n } else {\n yield* this.flush()\n return yield* super.findWithLowerBound.apply(this, arguments)\n }\n }\n * findWithUpperBound (id) {\n var o = yield* this.find(id, true)\n if (o != null) {\n return o\n } else {\n yield* this.flush()\n return yield* super.findWithUpperBound.apply(this, arguments)\n }\n }\n * findNext () {\n yield* this.flush()\n return yield* super.findNext.apply(this, arguments)\n }\n * findPrev () {\n yield* this.flush()\n return yield* super.findPrev.apply(this, arguments)\n }\n * iterate () {\n yield* this.flush()\n yield* super.iterate.apply(this, arguments)\n }\n * flush () {\n for (var i = 0; i < this.writeBuffer.length; i++) {\n var write = this.writeBuffer[i]\n if (write.id[0] !== null) {\n yield* super.put(write)\n this.writeBuffer[i] = {\n id: [null, null]\n }\n }\n }\n }\n }\n return SmallLookupBuffer\n }\n Y.utils.createSmallLookupBuffer = createSmallLookupBuffer\n\n // Generates a unique id, for use as a user id.\n // Thx to @jed for this script https://gist.github.com/jed/982883\n function generateGuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,generateGuid)} // eslint-disable-line\n Y.utils.generateGuid = generateGuid\n}\n","/* @flow */\n'use strict'\n\nrequire('./Connector.js')(Y)\nrequire('./Database.js')(Y)\nrequire('./Transaction.js')(Y)\nrequire('./Struct.js')(Y)\nrequire('./Utils.js')(Y)\nrequire('./Connectors/Test.js')(Y)\n\nY.debug = require('debug')\n\nvar requiringModules = {}\n\nmodule.exports = Y\nY.requiringModules = requiringModules\n\nY.extend = function (name, value) {\n if (arguments.length === 2 && typeof name === 'string') {\n if (value instanceof Y.utils.CustomTypeDefinition) {\n Y[name] = value.parseArguments\n } else {\n Y[name] = value\n }\n if (requiringModules[name] != null) {\n requiringModules[name].resolve()\n delete requiringModules[name]\n }\n } else {\n for (var i = 0; i < arguments.length; i++) {\n var f = arguments[i]\n if (typeof f === 'function') {\n f(Y)\n } else {\n throw new Error('Expected function!')\n }\n }\n }\n}\n\nY.requestModules = requestModules\nfunction requestModules (modules) {\n var sourceDir\n if (Y.sourceDir === null) {\n sourceDir = null\n } else {\n sourceDir = Y.sourceDir || '/bower_components'\n }\n // determine if this module was compiled for es5 or es6 (y.js vs. y.es6)\n // if Insert.execute is a Function, then it isnt a generator..\n // then load the es5(.js) files..\n var extention = typeof regeneratorRuntime !== 'undefined' ? '.js' : '.es6'\n var promises = []\n for (var i = 0; i < modules.length; i++) {\n var module = modules[i].split('(')[0]\n var modulename = 'y-' + module.toLowerCase()\n if (Y[module] == null) {\n if (requiringModules[module] == null) {\n // module does not exist\n if (typeof window !== 'undefined' && window.Y !== 'undefined') {\n if (sourceDir != null) {\n var imported = document.createElement('script')\n imported.src = sourceDir + '/' + modulename + '/' + modulename + extention\n document.head.appendChild(imported)\n }\n let requireModule = {}\n requiringModules[module] = requireModule\n requireModule.promise = new Promise(function (resolve) {\n requireModule.resolve = resolve\n })\n promises.push(requireModule.promise)\n } else {\n console.info('YJS: Please do not depend on automatic requiring of modules anymore! Extend modules as follows `require(\\'y-modulename\\')(Y)`')\n require(modulename)(Y)\n }\n } else {\n promises.push(requiringModules[modules[i]].promise)\n }\n }\n }\n return Promise.all(promises)\n}\n\n/* ::\ntype MemoryOptions = {\n name: 'memory'\n}\ntype IndexedDBOptions = {\n name: 'indexeddb',\n namespace: string\n}\ntype DbOptions = MemoryOptions | IndexedDBOptions\n\ntype WebRTCOptions = {\n name: 'webrtc',\n room: string\n}\ntype WebsocketsClientOptions = {\n name: 'websockets-client',\n room: string\n}\ntype ConnectionOptions = WebRTCOptions | WebsocketsClientOptions\n\ntype YOptions = {\n connector: ConnectionOptions,\n db: DbOptions,\n types: Array,\n sourceDir: string,\n share: {[key: string]: TypeName}\n}\n*/\n\nfunction Y (opts/* :YOptions */) /* :Promise */ {\n if (opts.hasOwnProperty('sourceDir')) {\n Y.sourceDir = opts.sourceDir\n }\n opts.types = opts.types != null ? opts.types : []\n var modules = [opts.db.name, opts.connector.name].concat(opts.types)\n for (var name in opts.share) {\n modules.push(opts.share[name])\n }\n return new Promise(function (resolve, reject) {\n if (opts == null) reject('An options object is expected! ')\n else if (opts.connector == null) reject('You must specify a connector! (missing connector property)')\n else if (opts.connector.name == null) reject('You must specify connector name! (missing connector.name property)')\n else if (opts.db == null) reject('You must specify a database! (missing db property)')\n else if (opts.connector.name == null) reject('You must specify db name! (missing db.name property)')\n else {\n opts = Y.utils.copyObject(opts)\n opts.connector = Y.utils.copyObject(opts.connector)\n opts.db = Y.utils.copyObject(opts.db)\n opts.share = Y.utils.copyObject(opts.share)\n setTimeout(function () {\n Y.requestModules(modules).then(function () {\n var yconfig = new YConfig(opts)\n yconfig.db.whenUserIdSet(function () {\n yconfig.init(function () {\n resolve(yconfig)\n })\n })\n }).catch(reject)\n }, 0)\n }\n })\n}\n\nclass YConfig {\n /* ::\n db: Y.AbstractDatabase;\n connector: Y.AbstractConnector;\n share: {[key: string]: any};\n options: Object;\n */\n constructor (opts, callback) {\n this.options = opts\n this.db = new Y[opts.db.name](this, opts.db)\n this.connector = new Y[opts.connector.name](this, opts.connector)\n this.connected = true\n }\n init (callback) {\n var opts = this.options\n var share = {}\n this.share = share\n this.db.requestTransaction(function * requestTransaction () {\n // create shared object\n for (var propertyname in opts.share) {\n var typeConstructor = opts.share[propertyname].split('(')\n var typeName = typeConstructor.splice(0, 1)\n var type = Y[typeName]\n var typedef = type.typeDefinition\n var id = ['_', typedef.struct + '_' + typeName + '_' + propertyname + '_' + typeConstructor]\n var args = []\n if (typeConstructor.length === 1) {\n try {\n args = JSON.parse('[' + typeConstructor[0].split(')')[0] + ']')\n } catch (e) {\n throw new Error('Was not able to parse type definition! (share.' + propertyname + ')')\n }\n if (type.typeDefinition.parseArguments == null) {\n throw new Error(typeName + ' does not expect arguments!')\n } else {\n args = typedef.parseArguments(args[0])[1]\n }\n }\n share[propertyname] = yield* this.store.initType.call(this, id, args)\n }\n this.store.whenTransactionsFinished()\n .then(callback)\n })\n }\n isConnected () {\n return this.connector.isSynced\n }\n disconnect () {\n if (this.connected) {\n this.connected = false\n return this.connector.disconnect()\n } else {\n return Promise.resolve()\n }\n }\n reconnect () {\n if (!this.connected) {\n this.connected = true\n return this.connector.reconnect()\n } else {\n return Promise.resolve()\n }\n }\n destroy () {\n var self = this\n return this.close().then(function () {\n if (self.db.deleteDB != null) {\n return self.db.deleteDB()\n } else {\n return Promise.resolve()\n }\n })\n }\n close () {\n var self = this\n this.share = null\n if (this.connector.destroy != null) {\n this.connector.destroy()\n } else {\n this.connector.disconnect()\n }\n return this.db.whenTransactionsFinished(function () {\n this.db.destroyTypes()\n // make sure to wait for all transactions before destroying the db\n this.db.requestTransaction(function * () {\n yield* self.db.destroy()\n })\n return this.db.whenTransactionsFinished()\n })\n }\n}\n"]} \ No newline at end of file +{"version":3,"sources":["node_modules/browser-pack/_prelude.js","node_modules/debug/src/browser.js","node_modules/debug/src/debug.js","node_modules/ms/index.js","node_modules/process/browser.js","src/Connector.js","src/Connectors/Test.js","src/Database.js","src/Struct.js","src/Transaction.js","src/Utils.js","src/y.js"],"names":[],"mappings":";;;;;;AAAA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACzLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACreA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5lBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9ZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1kCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3xBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"y.es6","sourcesContent":["(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= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return;\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name;\n }\n return Math.ceil(ms / n) + ' ' + name + 's';\n}\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","function canRead (auth) { return auth === 'read' || auth === 'write' }\nfunction canWrite (auth) { return auth === 'write' }\n\nmodule.exports = function (Y/* :any */) {\n class AbstractConnector {\n /* ::\n y: YConfig;\n role: SyncRole;\n connections: Object;\n isSynced: boolean;\n userEventListeners: Array;\n whenSyncedListeners: Array;\n currentSyncTarget: ?UserId;\n syncingClients: Array;\n forwardToSyncingClients: boolean;\n debug: boolean;\n syncStep2: Promise;\n userId: UserId;\n send: Function;\n broadcast: Function;\n broadcastOpBuffer: Array;\n protocolVersion: number;\n */\n /*\n opts contains the following information:\n role : String Role of this client (\"master\" or \"slave\")\n userId : String Uniquely defines the user.\n debug: Boolean Whether to print debug messages (optional)\n */\n constructor (y, opts) {\n this.y = y\n if (opts == null) {\n opts = {}\n }\n // Prefer to receive untransformed operations. This does only work if\n // this client receives operations from only one other client.\n // In particular, this does not work with y-webrtc.\n // It will work with y-websockets-client\n if (opts.role == null || opts.role === 'master') {\n this.role = 'master'\n } else if (opts.role === 'slave') {\n this.role = 'slave'\n } else {\n throw new Error(\"Role must be either 'master' or 'slave'!\")\n }\n this.log = Y.debug('y:connector')\n this.logMessage = Y.debug('y:connector-message')\n this.y.db.forwardAppliedOperations = opts.forwardAppliedOperations || false\n this.role = opts.role\n this.connections = {}\n this.isSynced = false\n this.userEventListeners = []\n this.whenSyncedListeners = []\n this.currentSyncTarget = null\n this.syncingClients = []\n this.forwardToSyncingClients = opts.forwardToSyncingClients !== false\n this.debug = opts.debug === true\n this.syncStep2 = Promise.resolve()\n this.broadcastOpBuffer = []\n this.protocolVersion = 11\n this.authInfo = opts.auth || null\n this.checkAuth = opts.checkAuth || function () { return Promise.resolve('write') } // default is everyone has write access\n if (opts.generateUserId === true) {\n this.setUserId(Y.utils.generateGuid())\n }\n }\n resetAuth (auth) {\n if (this.authInfo !== auth) {\n this.authInfo = auth\n this.broadcast({\n type: 'auth',\n auth: this.authInfo\n })\n }\n }\n reconnect () {\n this.log('reconnecting..')\n return this.y.db.startGarbageCollector()\n }\n disconnect () {\n this.log('discronnecting..')\n this.connections = {}\n this.isSynced = false\n this.currentSyncTarget = null\n this.syncingClients = []\n this.whenSyncedListeners = []\n this.y.db.stopGarbageCollector()\n return this.y.db.whenTransactionsFinished()\n }\n repair () {\n this.log('Repairing the state of Yjs. This can happen if messages get lost, and Yjs detects that something is wrong. If this happens often, please report an issue here: https://github.com/y-js/yjs/issues')\n for (var name in this.connections) {\n this.connections[name].isSynced = false\n }\n this.isSynced = false\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n setUserId (userId) {\n if (this.userId == null) {\n this.log('Set userId to \"%s\"', userId)\n this.userId = userId\n return this.y.db.setUserId(userId)\n } else {\n return null\n }\n }\n onUserEvent (f) {\n this.userEventListeners.push(f)\n }\n removeUserEventListener (f) {\n this.userEventListeners = this.userEventListeners.filter(g => { f !== g })\n }\n userLeft (user) {\n if (this.connections[user] != null) {\n this.log('User left: %s', user)\n delete this.connections[user]\n if (user === this.currentSyncTarget) {\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n this.syncingClients = this.syncingClients.filter(function (cli) {\n return cli !== user\n })\n for (var f of this.userEventListeners) {\n f({\n action: 'userLeft',\n user: user\n })\n }\n }\n }\n userJoined (user, role) {\n if (role == null) {\n throw new Error('You must specify the role of the joined user!')\n }\n if (this.connections[user] != null) {\n throw new Error('This user already joined!')\n }\n this.log('User joined: %s', user)\n this.connections[user] = {\n isSynced: false,\n role: role\n }\n for (var f of this.userEventListeners) {\n f({\n action: 'userJoined',\n user: user,\n role: role\n })\n }\n if (this.currentSyncTarget == null) {\n this.findNextSyncTarget()\n }\n }\n // Execute a function _when_ we are connected.\n // If not connected, wait until connected\n whenSynced (f) {\n if (this.isSynced) {\n f()\n } else {\n this.whenSyncedListeners.push(f)\n }\n }\n findNextSyncTarget () {\n if (this.currentSyncTarget != null) {\n return // \"The current sync has not finished!\"\n }\n\n var syncUser = null\n for (var uid in this.connections) {\n if (!this.connections[uid].isSynced) {\n syncUser = uid\n break\n }\n }\n var conn = this\n if (syncUser != null) {\n this.currentSyncTarget = syncUser\n this.y.db.requestTransaction(function *() {\n var stateSet = yield* this.getStateSet()\n var deleteSet = yield* this.getDeleteSet()\n var answer = {\n type: 'sync step 1',\n stateSet: stateSet,\n deleteSet: deleteSet,\n protocolVersion: conn.protocolVersion,\n auth: conn.authInfo\n }\n conn.send(syncUser, answer)\n })\n } else {\n if (!conn.isSynced) {\n this.y.db.requestTransaction(function *() {\n if (!conn.isSynced) {\n // it is crucial that isSynced is set at the time garbageCollectAfterSync is called\n conn.isSynced = true\n yield* this.garbageCollectAfterSync()\n // call whensynced listeners\n for (var f of conn.whenSyncedListeners) {\n f()\n }\n conn.whenSyncedListeners = []\n }\n })\n }\n }\n }\n send (uid, message) {\n this.log('Send \\'%s\\' to %s', message.type, uid)\n this.logMessage('Message: %j', message)\n }\n broadcast (message) {\n this.log('Broadcast \\'%s\\'', message.type)\n this.logMessage('Message: %j', message)\n }\n /*\n Buffer operations, and broadcast them when ready.\n */\n broadcastOps (ops) {\n ops = ops.map(function (op) {\n return Y.Struct[op.struct].encode(op)\n })\n var self = this\n function broadcastOperations () {\n if (self.broadcastOpBuffer.length > 0) {\n self.broadcast({\n type: 'update',\n ops: self.broadcastOpBuffer\n })\n self.broadcastOpBuffer = []\n }\n }\n if (this.broadcastOpBuffer.length === 0) {\n this.broadcastOpBuffer = ops\n if (this.y.db.transactionInProgress) {\n this.y.db.whenTransactionsFinished().then(broadcastOperations)\n } else {\n setTimeout(broadcastOperations, 0)\n }\n } else {\n this.broadcastOpBuffer = this.broadcastOpBuffer.concat(ops)\n }\n }\n /*\n You received a raw message, and you know that it is intended for Yjs. Then call this function.\n */\n receiveMessage (sender/* :UserId */, message/* :Message */) {\n if (sender === this.userId) {\n return Promise.resolve()\n }\n this.log('Receive \\'%s\\' from %s', message.type, sender)\n this.logMessage('Message: %j', message)\n if (message.protocolVersion != null && message.protocolVersion !== this.protocolVersion) {\n this.log(\n `You tried to sync with a yjs instance that has a different protocol version\n (You: ${this.protocolVersion}, Client: ${message.protocolVersion}).\n The sync was stopped. You need to upgrade your dependencies (especially Yjs & the Connector)!\n `)\n this.send(sender, {\n type: 'sync stop',\n protocolVersion: this.protocolVersion\n })\n return Promise.reject('Incompatible protocol version')\n }\n if (message.auth != null && this.connections[sender] != null) {\n // authenticate using auth in message\n var auth = this.checkAuth(message.auth, this.y, sender)\n this.connections[sender].auth = auth\n auth.then(auth => {\n for (var f of this.userEventListeners) {\n f({\n action: 'userAuthenticated',\n user: sender,\n auth: auth\n })\n }\n })\n } else if (this.connections[sender] != null && this.connections[sender].auth == null) {\n // authenticate without otherwise\n this.connections[sender].auth = this.checkAuth(null, this.y, sender)\n }\n if (this.connections[sender] != null && this.connections[sender].auth != null) {\n return this.connections[sender].auth.then((auth) => {\n if (message.type === 'sync step 1' && canRead(auth)) {\n let conn = this\n let m = message\n\n this.y.db.requestTransaction(function *() {\n var currentStateSet = yield* this.getStateSet()\n if (canWrite(auth)) {\n yield* this.applyDeleteSet(m.deleteSet)\n }\n\n var ds = yield* this.getDeleteSet()\n var answer = {\n type: 'sync step 2',\n stateSet: currentStateSet,\n deleteSet: ds,\n protocolVersion: this.protocolVersion,\n auth: this.authInfo\n }\n answer.os = yield* this.getOperations(m.stateSet)\n conn.send(sender, answer)\n if (this.forwardToSyncingClients) {\n conn.syncingClients.push(sender)\n setTimeout(function () {\n conn.syncingClients = conn.syncingClients.filter(function (cli) {\n return cli !== sender\n })\n conn.send(sender, {\n type: 'sync done'\n })\n }, 5000) // TODO: conn.syncingClientDuration)\n } else {\n conn.send(sender, {\n type: 'sync done'\n })\n }\n })\n } else if (message.type === 'sync step 2' && canWrite(auth)) {\n var db = this.y.db\n var defer = {}\n defer.promise = new Promise(function (resolve) {\n defer.resolve = resolve\n })\n this.syncStep2 = defer.promise\n let m /* :MessageSyncStep2 */ = message\n db.requestTransaction(function * () {\n yield* this.applyDeleteSet(m.deleteSet)\n if (m.osUntransformed != null) {\n yield* this.applyOperationsUntransformed(m.osUntransformed, m.stateSet)\n } else {\n this.store.apply(m.os)\n }\n /*\n * This just sends the complete hb after some time\n * Mostly for debugging..\n *\n db.requestTransaction(function * () {\n var ops = yield* this.getOperations(m.stateSet)\n if (ops.length > 0) {\n if (!broadcastHB) { // TODO: consider to broadcast here..\n conn.send(sender, {\n type: 'update',\n ops: ops\n })\n } else {\n // broadcast only once!\n conn.broadcastOps(ops)\n }\n }\n })\n */\n defer.resolve()\n })\n } else if (message.type === 'sync done') {\n var self = this\n this.syncStep2.then(function () {\n self._setSyncedWith(sender)\n })\n } else if (message.type === 'update' && canWrite(auth)) {\n if (this.forwardToSyncingClients) {\n for (var client of this.syncingClients) {\n this.send(client, message)\n }\n }\n if (this.y.db.forwardAppliedOperations) {\n var delops = message.ops.filter(function (o) {\n return o.struct === 'Delete'\n })\n if (delops.length > 0) {\n this.broadcastOps(delops)\n }\n }\n this.y.db.apply(message.ops)\n }\n })\n } else {\n return Promise.reject('Unable to deliver message')\n }\n }\n _setSyncedWith (user) {\n var conn = this.connections[user]\n if (conn != null) {\n conn.isSynced = true\n }\n if (user === this.currentSyncTarget) {\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n }\n /*\n Currently, the HB encodes operations as JSON. For the moment I want to keep it\n that way. Maybe we support encoding in the HB as XML in the future, but for now I don't want\n too much overhead. Y is very likely to get changed a lot in the future\n\n Because we don't want to encode JSON as string (with character escaping, wich makes it pretty much unreadable)\n we encode the JSON as XML.\n\n When the HB support encoding as XML, the format should look pretty much like this.\n\n does not support primitive values as array elements\n expects an ltx (less than xml) object\n */\n parseMessageFromXml (m/* :any */) {\n function parseArray (node) {\n for (var n of node.children) {\n if (n.getAttribute('isArray') === 'true') {\n return parseArray(n)\n } else {\n return parseObject(n)\n }\n }\n }\n function parseObject (node/* :any */) {\n var json = {}\n for (var attrName in node.attrs) {\n var value = node.attrs[attrName]\n var int = parseInt(value, 10)\n if (isNaN(int) || ('' + int) !== value) {\n json[attrName] = value\n } else {\n json[attrName] = int\n }\n }\n for (var n/* :any */ in node.children) {\n var name = n.name\n if (n.getAttribute('isArray') === 'true') {\n json[name] = parseArray(n)\n } else {\n json[name] = parseObject(n)\n }\n }\n return json\n }\n parseObject(m)\n }\n /*\n encode message in xml\n we use string because Strophe only accepts an \"xml-string\"..\n So {a:4,b:{c:5}} will look like\n \n \n \n m - ltx element\n json - Object\n */\n encodeMessageToXml (msg, obj) {\n // attributes is optional\n function encodeObject (m, json) {\n for (var name in json) {\n var value = json[name]\n if (name == null) {\n // nop\n } else if (value.constructor === Object) {\n encodeObject(m.c(name), value)\n } else if (value.constructor === Array) {\n encodeArray(m.c(name), value)\n } else {\n m.setAttribute(name, value)\n }\n }\n }\n function encodeArray (m, array) {\n m.setAttribute('isArray', 'true')\n for (var e of array) {\n if (e.constructor === Object) {\n encodeObject(m.c('array-element'), e)\n } else {\n encodeArray(m.c('array-element'), e)\n }\n }\n }\n if (obj.constructor === Object) {\n encodeObject(msg.c('y', { xmlns: 'http://y.ninja/connector-stanza' }), obj)\n } else if (obj.constructor === Array) {\n encodeArray(msg.c('y', { xmlns: 'http://y.ninja/connector-stanza' }), obj)\n } else {\n throw new Error(\"I can't encode this json!\")\n }\n }\n }\n Y.AbstractConnector = AbstractConnector\n}\n","/* global getRandom, async */\n'use strict'\n\nmodule.exports = function (Y) {\n var globalRoom = {\n users: {},\n buffers: {},\n removeUser: function (user) {\n for (var i in this.users) {\n this.users[i].userLeft(user)\n }\n delete this.users[user]\n delete this.buffers[user]\n },\n addUser: function (connector) {\n this.users[connector.userId] = connector\n this.buffers[connector.userId] = {}\n for (var uname in this.users) {\n if (uname !== connector.userId) {\n var u = this.users[uname]\n u.userJoined(connector.userId, 'master')\n connector.userJoined(u.userId, 'master')\n }\n }\n },\n whenTransactionsFinished: function () {\n var self = this\n return new Promise(function (resolve, reject) {\n // The connector first has to send the messages to the db.\n // Wait for the checkAuth-function to resolve\n // The test lib only has a simple checkAuth function: `() => Promise.resolve()`\n // Just add a function to the event-queue, in order to wait for the event.\n // TODO: this may be buggy in test applications (but it isn't be for real-life apps)\n setTimeout(function () {\n var ps = []\n for (var name in self.users) {\n ps.push(self.users[name].y.db.whenTransactionsFinished())\n }\n Promise.all(ps).then(resolve, reject)\n }, 10)\n })\n },\n flushOne: function flushOne () {\n var bufs = []\n for (var receiver in globalRoom.buffers) {\n let buff = globalRoom.buffers[receiver]\n var push = false\n for (let sender in buff) {\n if (buff[sender].length > 0) {\n push = true\n break\n }\n }\n if (push) {\n bufs.push(receiver)\n }\n }\n if (bufs.length > 0) {\n var userId = getRandom(bufs)\n let buff = globalRoom.buffers[userId]\n let sender = getRandom(Object.keys(buff))\n var m = buff[sender].shift()\n if (buff[sender].length === 0) {\n delete buff[sender]\n }\n var user = globalRoom.users[userId]\n return user.receiveMessage(m[0], m[1]).then(function () {\n return user.y.db.whenTransactionsFinished()\n }, function () {})\n } else {\n return false\n }\n },\n flushAll: function () {\n return new Promise(function (resolve) {\n // flushes may result in more created operations,\n // flush until there is nothing more to flush\n function nextFlush () {\n var c = globalRoom.flushOne()\n if (c) {\n while (c) {\n c = globalRoom.flushOne()\n }\n globalRoom.whenTransactionsFinished().then(nextFlush)\n } else {\n c = globalRoom.flushOne()\n if (c) {\n c.then(function () {\n globalRoom.whenTransactionsFinished().then(nextFlush)\n })\n } else {\n resolve()\n }\n }\n }\n globalRoom.whenTransactionsFinished().then(nextFlush)\n })\n }\n }\n Y.utils.globalRoom = globalRoom\n\n var userIdCounter = 0\n\n class Test extends Y.AbstractConnector {\n constructor (y, options) {\n if (options === undefined) {\n throw new Error('Options must not be undefined!')\n }\n options.role = 'master'\n options.forwardToSyncingClients = false\n super(y, options)\n this.setUserId((userIdCounter++) + '').then(() => {\n globalRoom.addUser(this)\n })\n this.globalRoom = globalRoom\n this.syncingClientDuration = 0\n }\n receiveMessage (sender, m) {\n return super.receiveMessage(sender, JSON.parse(JSON.stringify(m)))\n }\n send (userId, message) {\n var buffer = globalRoom.buffers[userId]\n if (buffer != null) {\n if (buffer[this.userId] == null) {\n buffer[this.userId] = []\n }\n buffer[this.userId].push(JSON.parse(JSON.stringify([this.userId, message])))\n }\n }\n broadcast (message) {\n for (var key in globalRoom.buffers) {\n var buff = globalRoom.buffers[key]\n if (buff[this.userId] == null) {\n buff[this.userId] = []\n }\n buff[this.userId].push(JSON.parse(JSON.stringify([this.userId, message])))\n }\n }\n isDisconnected () {\n return globalRoom.users[this.userId] == null\n }\n reconnect () {\n if (this.isDisconnected()) {\n globalRoom.addUser(this)\n super.reconnect()\n }\n return Y.utils.globalRoom.flushAll()\n }\n disconnect () {\n var waitForMe = Promise.resolve()\n if (!this.isDisconnected()) {\n globalRoom.removeUser(this.userId)\n waitForMe = super.disconnect()\n }\n var self = this\n return waitForMe.then(function () {\n return self.y.db.whenTransactionsFinished()\n })\n }\n flush () {\n var self = this\n return async(function * () {\n var buff = globalRoom.buffers[self.userId]\n while (Object.keys(buff).length > 0) {\n var sender = getRandom(Object.keys(buff))\n var m = buff[sender].shift()\n if (buff[sender].length === 0) {\n delete buff[sender]\n }\n yield this.receiveMessage(m[0], m[1])\n }\n yield self.whenTransactionsFinished()\n })\n }\n }\n\n Y.Test = Test\n}\n","/* @flow */\n'use strict'\n\nmodule.exports = function (Y /* :any */) {\n /*\n Partial definition of an OperationStore.\n TODO: name it Database, operation store only holds operations.\n\n A database definition must alse define the following methods:\n * logTable() (optional)\n - show relevant information information in a table\n * requestTransaction(makeGen)\n - request a transaction\n * destroy()\n - destroy the database\n */\n class AbstractDatabase {\n /* ::\n y: YConfig;\n forwardAppliedOperations: boolean;\n listenersById: Object;\n listenersByIdExecuteNow: Array;\n listenersByIdRequestPending: boolean;\n initializedTypes: Object;\n whenUserIdSetListener: ?Function;\n waitingTransactions: Array;\n transactionInProgress: boolean;\n executeOrder: Array;\n gc1: Array;\n gc2: Array;\n gcTimeout: number;\n gcInterval: any;\n garbageCollect: Function;\n executeOrder: Array; // for debugging only\n userId: UserId;\n opClock: number;\n transactionsFinished: ?{promise: Promise, resolve: any};\n transact: (x: ?Generator) => any;\n */\n constructor (y, opts) {\n this.y = y\n this.dbOpts = opts\n var os = this\n this.userId = null\n var resolve\n this.userIdPromise = new Promise(function (r) {\n resolve = r\n })\n this.userIdPromise.resolve = resolve\n // whether to broadcast all applied operations (insert & delete hook)\n this.forwardAppliedOperations = false\n // E.g. this.listenersById[id] : Array\n this.listenersById = {}\n // Execute the next time a transaction is requested\n this.listenersByIdExecuteNow = []\n // A transaction is requested\n this.listenersByIdRequestPending = false\n /* To make things more clear, the following naming conventions:\n * ls : we put this.listenersById on ls\n * l : Array\n * id : Id (can't use as property name)\n * sid : String (converted from id via JSON.stringify\n so we can use it as a property name)\n\n Always remember to first overwrite\n a property before you iterate over it!\n */\n // TODO: Use ES7 Weak Maps. This way types that are no longer user,\n // wont be kept in memory.\n this.initializedTypes = {}\n this.waitingTransactions = []\n this.transactionInProgress = false\n this.transactionIsFlushed = false\n if (typeof YConcurrency_TestingMode !== 'undefined') {\n this.executeOrder = []\n }\n this.gc1 = [] // first stage\n this.gc2 = [] // second stage -> after that, remove the op\n\n function garbageCollect () {\n return os.whenTransactionsFinished().then(function () {\n if (os.gc1.length > 0 || os.gc2.length > 0) {\n if (!os.y.connector.isSynced) {\n console.warn('gc should be empty when not synced!')\n }\n return new Promise((resolve) => {\n os.requestTransaction(function * () {\n if (os.y.connector != null && os.y.connector.isSynced) {\n for (var i = 0; i < os.gc2.length; i++) {\n var oid = os.gc2[i]\n yield* this.garbageCollectOperation(oid)\n }\n os.gc2 = os.gc1\n os.gc1 = []\n }\n // TODO: Use setInterval here instead (when garbageCollect is called several times there will be several timeouts..)\n if (os.gcTimeout > 0) {\n os.gcInterval = setTimeout(garbageCollect, os.gcTimeout)\n }\n resolve()\n })\n })\n } else {\n // TODO: see above\n if (os.gcTimeout > 0) {\n os.gcInterval = setTimeout(garbageCollect, os.gcTimeout)\n }\n return Promise.resolve()\n }\n })\n }\n this.garbageCollect = garbageCollect\n this.startGarbageCollector()\n\n this.repairCheckInterval = !opts.repairCheckInterval ? 6000 : opts.repairCheckInterval\n this.opsReceivedTimestamp = new Date()\n this.startRepairCheck()\n }\n startGarbageCollector () {\n this.gc = this.dbOpts.gc == null || this.dbOpts.gc\n if (this.gc) {\n this.gcTimeout = !this.dbOpts.gcTimeout ? 50000 : this.dbOpts.gcTimeout\n } else {\n this.gcTimeout = -1\n }\n if (this.gcTimeout > 0) {\n this.garbageCollect()\n }\n }\n startRepairCheck () {\n var os = this\n if (this.repairCheckInterval > 0) {\n this.repairCheckIntervalHandler = setInterval(function repairOnMissingOperations () {\n /*\n Case 1. No ops have been received in a while (new Date() - os.opsReceivedTimestamp > os.repairCheckInterval)\n - 1.1 os.listenersById is empty. Then the state was correct the whole time. -> Nothing to do (nor to update)\n - 1.2 os.listenersById is not empty.\n * Then the state was incorrect for at least {os.repairCheckInterval} seconds.\n * -> Remove everything in os.listenersById and sync again (connector.repair())\n Case 2. An op has been received in the last {os.repairCheckInterval } seconds.\n It is not yet necessary to check for faulty behavior. Everything can still resolve itself. Wait for more messages.\n If nothing was received for a while and os.listenersById is still not emty, we are in case 1.2\n -> Do nothing\n\n Baseline here is: we really only have to catch case 1.2..\n */\n if (\n new Date() - os.opsReceivedTimestamp > os.repairCheckInterval &&\n Object.keys(os.listenersById).length > 0 // os.listenersById is not empty\n ) {\n // haven't received operations for over {os.repairCheckInterval} seconds, resend state vector\n os.listenersById = {}\n os.opsReceivedTimestamp = new Date() // update so you don't send repair several times in a row\n os.y.connector.repair()\n }\n }, this.repairCheckInterval)\n }\n }\n stopRepairCheck () {\n clearInterval(this.repairCheckIntervalHandler)\n }\n queueGarbageCollector (id) {\n if (this.y.connector.isSynced && this.gc) {\n this.gc1.push(id)\n }\n }\n emptyGarbageCollector () {\n return new Promise(resolve => {\n var check = () => {\n if (this.gc1.length > 0 || this.gc2.length > 0) {\n this.garbageCollect().then(check)\n } else {\n resolve()\n }\n }\n setTimeout(check, 0)\n })\n }\n addToDebug () {\n if (typeof YConcurrency_TestingMode !== 'undefined') {\n var command /* :string */ = Array.prototype.map.call(arguments, function (s) {\n if (typeof s === 'string') {\n return s\n } else {\n return JSON.stringify(s)\n }\n }).join('').replace(/\"/g, \"'\").replace(/,/g, ', ').replace(/:/g, ': ')\n this.executeOrder.push(command)\n }\n }\n getDebugData () {\n console.log(this.executeOrder.join('\\n'))\n }\n stopGarbageCollector () {\n var self = this\n this.gc = false\n this.gcTimeout = -1\n return new Promise(function (resolve) {\n self.requestTransaction(function * () {\n var ungc /* :Array */ = self.gc1.concat(self.gc2)\n self.gc1 = []\n self.gc2 = []\n for (var i = 0; i < ungc.length; i++) {\n var op = yield* this.getOperation(ungc[i])\n if (op != null) {\n delete op.gc\n yield* this.setOperation(op)\n }\n }\n resolve()\n })\n })\n }\n /*\n Try to add to GC.\n\n TODO: rename this function\n\n Rulez:\n * Only gc if this user is online & gc turned on\n * The most left element in a list must not be gc'd.\n => There is at least one element in the list\n\n returns true iff op was added to GC\n */\n * addToGarbageCollector (op, left) {\n if (\n op.gc == null &&\n op.deleted === true &&\n this.store.gc &&\n this.store.y.connector.isSynced\n ) {\n var gc = false\n if (left != null && left.deleted === true) {\n gc = true\n } else if (op.content != null && op.content.length > 1) {\n op = yield* this.getInsertionCleanStart([op.id[0], op.id[1] + 1])\n gc = true\n }\n if (gc) {\n op.gc = true\n yield* this.setOperation(op)\n this.store.queueGarbageCollector(op.id)\n return true\n }\n }\n return false\n }\n removeFromGarbageCollector (op) {\n function filter (o) {\n return !Y.utils.compareIds(o, op.id)\n }\n this.gc1 = this.gc1.filter(filter)\n this.gc2 = this.gc2.filter(filter)\n delete op.gc\n }\n destroyTypes () {\n for (var key in this.initializedTypes) {\n var type = this.initializedTypes[key]\n if (type._destroy != null) {\n type._destroy()\n } else {\n console.error('The type you included does not provide destroy functionality, it will remain in memory (updating your packages will help).')\n }\n }\n }\n * destroy () {\n clearInterval(this.gcInterval)\n this.gcInterval = null\n this.stopRepairCheck()\n }\n setUserId (userId) {\n if (!this.userIdPromise.inProgress) {\n this.userIdPromise.inProgress = true\n var self = this\n self.requestTransaction(function * () {\n self.userId = userId\n var state = yield* this.getState(userId)\n self.opClock = state.clock\n self.userIdPromise.resolve(userId)\n })\n }\n return this.userIdPromise\n }\n whenUserIdSet (f) {\n this.userIdPromise.then(f)\n }\n getNextOpId (numberOfIds) {\n if (numberOfIds == null) {\n throw new Error('getNextOpId expects the number of created ids to create!')\n } else if (this.userId == null) {\n throw new Error('OperationStore not yet initialized!')\n } else {\n var id = [this.userId, this.opClock]\n this.opClock += numberOfIds\n return id\n }\n }\n /*\n Apply a list of operations.\n\n * we save a timestamp, because we received new operations that could resolve ops in this.listenersById (see this.startRepairCheck)\n * get a transaction\n * check whether all Struct.*.requiredOps are in the OS\n * check if it is an expected op (otherwise wait for it)\n * check if was deleted, apply a delete operation after op was applied\n */\n apply (ops) {\n this.opsReceivedTimestamp = new Date()\n for (var i = 0; i < ops.length; i++) {\n var o = ops[i]\n if (o.id == null || o.id[0] !== this.y.connector.userId) {\n var required = Y.Struct[o.struct].requiredOps(o)\n if (o.requires != null) {\n required = required.concat(o.requires)\n }\n this.whenOperationsExist(required, o)\n }\n }\n }\n /*\n op is executed as soon as every operation requested is available.\n Note that Transaction can (and should) buffer requests.\n */\n whenOperationsExist (ids, op) {\n if (ids.length > 0) {\n let listener = {\n op: op,\n missing: ids.length\n }\n\n for (let i = 0; i < ids.length; i++) {\n let id = ids[i]\n let sid = JSON.stringify(id)\n let l = this.listenersById[sid]\n if (l == null) {\n l = []\n this.listenersById[sid] = l\n }\n l.push(listener)\n }\n } else {\n this.listenersByIdExecuteNow.push({\n op: op\n })\n }\n\n if (this.listenersByIdRequestPending) {\n return\n }\n\n this.listenersByIdRequestPending = true\n var store = this\n\n this.requestTransaction(function * () {\n var exeNow = store.listenersByIdExecuteNow\n store.listenersByIdExecuteNow = []\n\n var ls = store.listenersById\n store.listenersById = {}\n\n store.listenersByIdRequestPending = false\n\n for (let key = 0; key < exeNow.length; key++) {\n let o = exeNow[key].op\n yield* store.tryExecute.call(this, o)\n }\n\n for (var sid in ls) {\n var l = ls[sid]\n var id = JSON.parse(sid)\n var op\n if (typeof id[1] === 'string') {\n op = yield* this.getOperation(id)\n } else {\n op = yield* this.getInsertion(id)\n }\n if (op == null) {\n store.listenersById[sid] = l\n } else {\n for (let i = 0; i < l.length; i++) {\n let listener = l[i]\n let o = listener.op\n if (--listener.missing === 0) {\n yield* store.tryExecute.call(this, o)\n }\n }\n }\n }\n })\n }\n /*\n Actually execute an operation, when all expected operations are available.\n */\n /* :: // TODO: this belongs somehow to transaction\n store: Object;\n getOperation: any;\n isGarbageCollected: any;\n addOperation: any;\n whenOperationsExist: any;\n */\n * tryExecute (op) {\n this.store.addToDebug('yield* this.store.tryExecute.call(this, ', JSON.stringify(op), ')')\n if (op.struct === 'Delete') {\n yield* Y.Struct.Delete.execute.call(this, op)\n // this is now called in Transaction.deleteOperation!\n // yield* this.store.operationAdded(this, op)\n } else {\n // check if this op was defined\n var defined = yield* this.getInsertion(op.id)\n while (defined != null && defined.content != null) {\n // check if this op has a longer content in the case it is defined\n if (defined.id[1] + defined.content.length < op.id[1] + op.content.length) {\n var overlapSize = defined.content.length - (op.id[1] - defined.id[1])\n op.content.splice(0, overlapSize)\n op.id = [op.id[0], op.id[1] + overlapSize]\n op.left = Y.utils.getLastId(defined)\n op.origin = op.left\n defined = yield* this.getOperation(op.id) // getOperation suffices here\n } else {\n break\n }\n }\n if (defined == null) {\n var opid = op.id\n var isGarbageCollected = yield* this.isGarbageCollected(opid)\n if (!isGarbageCollected) {\n // TODO: reduce number of get / put calls for op ..\n yield* Y.Struct[op.struct].execute.call(this, op)\n yield* this.addOperation(op)\n yield* this.store.operationAdded(this, op)\n // operationAdded can change op..\n op = yield* this.getOperation(opid)\n // if insertion, try to combine with left\n yield* this.tryCombineWithLeft(op)\n }\n }\n }\n }\n /*\n * Called by a transaction when an operation is added.\n * This function is especially important for y-indexeddb, where several instances may share a single database.\n * Every time an operation is created by one instance, it is send to all other instances and operationAdded is called\n *\n * If it's not a Delete operation:\n * * Checks if another operation is executable (listenersById)\n * * Update state, if possible\n *\n * Always:\n * * Call type\n */\n * operationAdded (transaction, op) {\n if (op.struct === 'Delete') {\n var type = this.initializedTypes[JSON.stringify(op.targetParent)]\n if (type != null) {\n yield* type._changed(transaction, op)\n }\n } else {\n // increase SS\n yield* transaction.updateState(op.id[0])\n var opLen = op.content != null ? op.content.length : 1\n for (let i = 0; i < opLen; i++) {\n // notify whenOperation listeners (by id)\n var sid = JSON.stringify([op.id[0], op.id[1] + i])\n var l = this.listenersById[sid]\n delete this.listenersById[sid]\n if (l != null) {\n for (var key in l) {\n var listener = l[key]\n if (--listener.missing === 0) {\n this.whenOperationsExist([], listener.op)\n }\n }\n }\n }\n var t = this.initializedTypes[JSON.stringify(op.parent)]\n\n // if parent is deleted, mark as gc'd and return\n if (op.parent != null) {\n var parentIsDeleted = yield* transaction.isDeleted(op.parent)\n if (parentIsDeleted) {\n yield* transaction.deleteList(op.id)\n return\n }\n }\n\n // notify parent, if it was instanciated as a custom type\n if (t != null) {\n let o = Y.utils.copyOperation(op)\n yield* t._changed(transaction, o)\n }\n if (!op.deleted) {\n // Delete if DS says this is actually deleted\n var len = op.content != null ? op.content.length : 1\n var startId = op.id // You must not use op.id in the following loop, because op will change when deleted\n // TODO: !! console.log('TODO: change this before commiting')\n for (let i = 0; i < len; i++) {\n var id = [startId[0], startId[1] + i]\n var opIsDeleted = yield* transaction.isDeleted(id)\n if (opIsDeleted) {\n var delop = {\n struct: 'Delete',\n target: id\n }\n yield* this.tryExecute.call(transaction, delop)\n }\n }\n }\n }\n }\n whenTransactionsFinished () {\n if (this.transactionInProgress) {\n if (this.transactionsFinished == null) {\n var resolve\n var promise = new Promise(function (r) {\n resolve = r\n })\n this.transactionsFinished = {\n resolve: resolve,\n promise: promise\n }\n }\n return this.transactionsFinished.promise\n } else {\n return Promise.resolve()\n }\n }\n // Check if there is another transaction request.\n // * the last transaction is always a flush :)\n getNextRequest () {\n if (this.waitingTransactions.length === 0) {\n if (this.transactionIsFlushed) {\n this.transactionInProgress = false\n this.transactionIsFlushed = false\n if (this.transactionsFinished != null) {\n this.transactionsFinished.resolve()\n this.transactionsFinished = null\n }\n return null\n } else {\n this.transactionIsFlushed = true\n return function * () {\n yield* this.flush()\n }\n }\n } else {\n this.transactionIsFlushed = false\n return this.waitingTransactions.shift()\n }\n }\n requestTransaction (makeGen/* :any */, callImmediately) {\n this.waitingTransactions.push(makeGen)\n if (!this.transactionInProgress) {\n this.transactionInProgress = true\n setTimeout(() => {\n this.transact(this.getNextRequest())\n }, 0)\n }\n }\n /*\n Get a created/initialized type.\n */\n getType (id) {\n return this.initializedTypes[JSON.stringify(id)]\n }\n /*\n Init type. This is called when a remote operation is retrieved, and transformed to a type\n TODO: delete type from store.initializedTypes[id] when corresponding id was deleted!\n */\n * initType (id, args) {\n var sid = JSON.stringify(id)\n var t = this.store.initializedTypes[sid]\n if (t == null) {\n var op/* :MapStruct | ListStruct */ = yield* this.getOperation(id)\n if (op != null) {\n t = yield* Y[op.type].typeDefinition.initType.call(this, this.store, op, args)\n this.store.initializedTypes[sid] = t\n }\n }\n return t\n }\n /*\n Create type. This is called when the local user creates a type (which is a synchronous action)\n */\n createType (typedefinition, id) {\n var structname = typedefinition[0].struct\n id = id || this.getNextOpId(1)\n var op = Y.Struct[structname].create(id)\n op.type = typedefinition[0].name\n\n this.requestTransaction(function * () {\n if (op.id[0] === '_') {\n yield* this.setOperation(op)\n } else {\n yield* this.applyCreatedOperations([op])\n }\n })\n var t = Y[op.type].typeDefinition.createType(this, op, typedefinition[1])\n this.initializedTypes[JSON.stringify(op.id)] = t\n return t\n }\n }\n Y.AbstractDatabase = AbstractDatabase\n}\n","/* @flow */\n'use strict'\n\n/*\n An operation also defines the structure of a type. This is why operation and\n structure are used interchangeably here.\n\n It must be of the type Object. I hope to achieve some performance\n improvements when working on databases that support the json format.\n\n An operation must have the following properties:\n\n * encode\n - Encode the structure in a readable format (preferably string- todo)\n * decode (todo)\n - decode structure to json\n * execute\n - Execute the semantics of an operation.\n * requiredOps\n - Operations that are required to execute this operation.\n*/\nmodule.exports = function (Y/* :any */) {\n var Struct = {\n /* This is the only operation that is actually not a structure, because\n it is not stored in the OS. This is why it _does not_ have an id\n\n op = {\n target: Id\n }\n */\n Delete: {\n encode: function (op) {\n return {\n target: op.target,\n length: op.length || 0,\n struct: 'Delete'\n }\n },\n requiredOps: function (op) {\n return [] // [op.target]\n },\n execute: function * (op) {\n return yield* this.deleteOperation(op.target, op.length || 1)\n }\n },\n Insert: {\n /* {\n content: [any],\n opContent: Id,\n id: Id,\n left: Id,\n origin: Id,\n right: Id,\n parent: Id,\n parentSub: string (optional), // child of Map type\n }\n */\n encode: function (op/* :Insertion */) /* :Insertion */ {\n // TODO: you could not send the \"left\" property, then you also have to\n // \"op.left = null\" in $execute or $decode\n var e/* :any */ = {\n id: op.id,\n left: op.left,\n right: op.right,\n origin: op.origin,\n parent: op.parent,\n struct: op.struct\n }\n if (op.parentSub != null) {\n e.parentSub = op.parentSub\n }\n if (op.hasOwnProperty('opContent')) {\n e.opContent = op.opContent\n } else {\n e.content = op.content.slice()\n }\n\n return e\n },\n requiredOps: function (op) {\n var ids = []\n if (op.left != null) {\n ids.push(op.left)\n }\n if (op.right != null) {\n ids.push(op.right)\n }\n if (op.origin != null && !Y.utils.compareIds(op.left, op.origin)) {\n ids.push(op.origin)\n }\n // if (op.right == null && op.left == null) {\n ids.push(op.parent)\n\n if (op.opContent != null) {\n ids.push(op.opContent)\n }\n return ids\n },\n getDistanceToOrigin: function * (op) {\n if (op.left == null) {\n return 0\n } else {\n var d = 0\n var o = yield* this.getInsertion(op.left)\n while (!Y.utils.matchesId(o, op.origin)) {\n d++\n if (o.left == null) {\n break\n } else {\n o = yield* this.getInsertion(o.left)\n }\n }\n return d\n }\n },\n /*\n # $this has to find a unique position between origin and the next known character\n # case 1: $origin equals $o.origin: the $creator parameter decides if left or right\n # let $OL= [o1,o2,o3,o4], whereby $this is to be inserted between o1 and o4\n # o2,o3 and o4 origin is 1 (the position of o2)\n # there is the case that $this.creator < o2.creator, but o3.creator < $this.creator\n # then o2 knows o3. Since on another client $OL could be [o1,o3,o4] the problem is complex\n # therefore $this would be always to the right of o3\n # case 2: $origin < $o.origin\n # if current $this insert_position > $o origin: $this ins\n # else $insert_position will not change\n # (maybe we encounter case 1 later, then this will be to the right of $o)\n # case 3: $origin > $o.origin\n # $this insert_position is to the left of $o (forever!)\n */\n execute: function * (op) {\n var i // loop counter\n\n // during this function some ops may get split into two pieces (e.g. with getInsertionCleanEnd)\n // We try to merge them later, if possible\n var tryToRemergeLater = []\n\n if (op.origin != null) { // TODO: !== instead of !=\n // we save in origin that op originates in it\n // we need that later when we eventually garbage collect origin (see transaction)\n var origin = yield* this.getInsertionCleanEnd(op.origin)\n if (origin.originOf == null) {\n origin.originOf = []\n }\n origin.originOf.push(op.id)\n yield* this.setOperation(origin)\n if (origin.right != null) {\n tryToRemergeLater.push(origin.right)\n }\n }\n var distanceToOrigin = i = yield* Struct.Insert.getDistanceToOrigin.call(this, op) // most cases: 0 (starts from 0)\n\n // now we begin to insert op in the list of insertions..\n var o\n var parent\n var start\n\n // find o. o is the first conflicting operation\n if (op.left != null) {\n o = yield* this.getInsertionCleanEnd(op.left)\n if (!Y.utils.compareIds(op.left, op.origin) && o.right != null) {\n // only if not added previously\n tryToRemergeLater.push(o.right)\n }\n o = (o.right == null) ? null : yield* this.getOperation(o.right)\n } else { // left == null\n parent = yield* this.getOperation(op.parent)\n let startId = op.parentSub ? parent.map[op.parentSub] : parent.start\n start = startId == null ? null : yield* this.getOperation(startId)\n o = start\n }\n\n // make sure to split op.right if necessary (also add to tryCombineWithLeft)\n if (op.right != null) {\n tryToRemergeLater.push(op.right)\n yield* this.getInsertionCleanStart(op.right)\n }\n\n // handle conflicts\n while (true) {\n if (o != null && !Y.utils.compareIds(o.id, op.right)) {\n var oOriginDistance = yield* Struct.Insert.getDistanceToOrigin.call(this, o)\n if (oOriginDistance === i) {\n // case 1\n if (o.id[0] < op.id[0]) {\n op.left = Y.utils.getLastId(o)\n distanceToOrigin = i + 1 // just ignore o.content.length, doesn't make a difference\n }\n } else if (oOriginDistance < i) {\n // case 2\n if (i - distanceToOrigin <= oOriginDistance) {\n op.left = Y.utils.getLastId(o)\n distanceToOrigin = i + 1 // just ignore o.content.length, doesn't make a difference\n }\n } else {\n break\n }\n i++\n if (o.right != null) {\n o = yield* this.getInsertion(o.right)\n } else {\n o = null\n }\n } else {\n break\n }\n }\n\n // reconnect..\n var left = null\n var right = null\n if (parent == null) {\n parent = yield* this.getOperation(op.parent)\n }\n\n // reconnect left and set right of op\n if (op.left != null) {\n left = yield* this.getInsertion(op.left)\n // link left\n op.right = left.right\n left.right = op.id\n\n yield* this.setOperation(left)\n } else {\n // set op.right from parent, if necessary\n op.right = op.parentSub ? parent.map[op.parentSub] || null : parent.start\n }\n // reconnect right\n if (op.right != null) {\n // TODO: wanna connect right too?\n right = yield* this.getOperation(op.right)\n right.left = Y.utils.getLastId(op)\n\n // if right exists, and it is supposed to be gc'd. Remove it from the gc\n if (right.gc != null) {\n if (right.content != null && right.content.length > 1) {\n right = yield* this.getInsertionCleanEnd(right.id)\n }\n this.store.removeFromGarbageCollector(right)\n }\n yield* this.setOperation(right)\n }\n\n // update parents .map/start/end properties\n if (op.parentSub != null) {\n if (left == null) {\n parent.map[op.parentSub] = op.id\n yield* this.setOperation(parent)\n }\n // is a child of a map struct.\n // Then also make sure that only the most left element is not deleted\n // We do not call the type in this case (this is what the third parameter is for)\n if (op.right != null) {\n yield* this.deleteOperation(op.right, 1, true)\n }\n if (op.left != null) {\n yield* this.deleteOperation(op.id, 1, true)\n }\n } else {\n if (right == null || left == null) {\n if (right == null) {\n parent.end = Y.utils.getLastId(op)\n }\n if (left == null) {\n parent.start = op.id\n }\n yield* this.setOperation(parent)\n }\n }\n\n // try to merge original op.left and op.origin\n for (i = 0; i < tryToRemergeLater.length; i++) {\n var m = yield* this.getOperation(tryToRemergeLater[i])\n yield* this.tryCombineWithLeft(m)\n }\n }\n },\n List: {\n /*\n {\n start: null,\n end: null,\n struct: \"List\",\n type: \"\",\n id: this.os.getNextOpId(1)\n }\n */\n create: function (id) {\n return {\n start: null,\n end: null,\n struct: 'List',\n id: id\n }\n },\n encode: function (op) {\n var e = {\n struct: 'List',\n id: op.id,\n type: op.type\n }\n if (op.requires != null) {\n e.requires = op.requires\n }\n if (op.info != null) {\n e.info = op.info\n }\n return e\n },\n requiredOps: function () {\n /*\n var ids = []\n if (op.start != null) {\n ids.push(op.start)\n }\n if (op.end != null){\n ids.push(op.end)\n }\n return ids\n */\n return []\n },\n execute: function * (op) {\n op.start = null\n op.end = null\n },\n ref: function * (op, pos) {\n if (op.start == null) {\n return null\n }\n var res = null\n var o = yield* this.getOperation(op.start)\n\n while (true) {\n if (!o.deleted) {\n res = o\n pos--\n }\n if (pos >= 0 && o.right != null) {\n o = yield* this.getOperation(o.right)\n } else {\n break\n }\n }\n return res\n },\n map: function * (o, f) {\n o = o.start\n var res = []\n while (o != null) { // TODO: change to != (at least some convention)\n var operation = yield* this.getOperation(o)\n if (!operation.deleted) {\n res.push(f(operation))\n }\n o = operation.right\n }\n return res\n }\n },\n Map: {\n /*\n {\n map: {},\n struct: \"Map\",\n type: \"\",\n id: this.os.getNextOpId(1)\n }\n */\n create: function (id) {\n return {\n id: id,\n map: {},\n struct: 'Map'\n }\n },\n encode: function (op) {\n var e = {\n struct: 'Map',\n type: op.type,\n id: op.id,\n map: {} // overwrite map!!\n }\n if (op.requires != null) {\n e.requires = op.requires\n }\n if (op.info != null) {\n e.info = op.info\n }\n return e\n },\n requiredOps: function () {\n return []\n },\n execute: function * () {},\n /*\n Get a property by name\n */\n get: function * (op, name) {\n var oid = op.map[name]\n if (oid != null) {\n var res = yield* this.getOperation(oid)\n if (res == null || res.deleted) {\n return void 0\n } else if (res.opContent == null) {\n return res.content[0]\n } else {\n return yield* this.getType(res.opContent)\n }\n }\n }\n }\n }\n Y.Struct = Struct\n}\n","/* @flow */\n'use strict'\n\n/*\n Partial definition of a transaction\n\n A transaction provides all the the async functionality on a database.\n\n By convention, a transaction has the following properties:\n * ss for StateSet\n * os for OperationStore\n * ds for DeleteStore\n\n A transaction must also define the following methods:\n * checkDeleteStoreForState(state)\n - When increasing the state of a user, an operation with an higher id\n may already be garbage collected, and therefore it will never be received.\n update the state to reflect this knowledge. This won't call a method to save the state!\n * getDeleteSet(id)\n - Get the delete set in a readable format:\n {\n \"userX\": [\n [5,1], // starting from position 5, one operations is deleted\n [9,4] // starting from position 9, four operations are deleted\n ],\n \"userY\": ...\n }\n * getOpsFromDeleteSet(ds) -- TODO: just call this.deleteOperation(id) here\n - get a set of deletions that need to be applied in order to get to\n achieve the state of the supplied ds\n * setOperation(op)\n - write `op` to the database.\n Note: this is allowed to return an in-memory object.\n E.g. the Memory adapter returns the object that it has in-memory.\n Changing values on this object will be stored directly in the database\n without calling this function. Therefore,\n setOperation may have no functionality in some adapters. This also has\n implications on the way we use operations that were served from the database.\n We try not to call copyObject, if not necessary.\n * addOperation(op)\n - add an operation to the database.\n This may only be called once for every op.id\n Must return a function that returns the next operation in the database (ordered by id)\n * getOperation(id)\n * removeOperation(id)\n - remove an operation from the database. This is called when an operation\n is garbage collected.\n * setState(state)\n - `state` is of the form\n {\n user: \"1\",\n clock: 4\n } <- meaning that we have four operations from user \"1\"\n (with these id's respectively: 0, 1, 2, and 3)\n * getState(user)\n * getStateVector()\n - Get the state of the OS in the form\n [{\n user: \"userX\",\n clock: 11\n },\n ..\n ]\n * getStateSet()\n - Get the state of the OS in the form\n {\n \"userX\": 11,\n \"userY\": 22\n }\n * getOperations(startSS)\n - Get the all the operations that are necessary in order to achive the\n stateSet of this user, starting from a stateSet supplied by another user\n * makeOperationReady(ss, op)\n - this is called only by `getOperations(startSS)`. It makes an operation\n applyable on a given SS.\n*/\nmodule.exports = function (Y/* :any */) {\n class TransactionInterface {\n /* ::\n store: Y.AbstractDatabase;\n ds: Store;\n os: Store;\n ss: Store;\n */\n /*\n Apply operations that this user created (no remote ones!)\n * does not check for Struct.*.requiredOps()\n * also broadcasts it through the connector\n */\n * applyCreatedOperations (ops) {\n var send = []\n for (var i = 0; i < ops.length; i++) {\n var op = ops[i]\n yield* this.store.tryExecute.call(this, op)\n if (op.id == null || typeof op.id[1] !== 'string') {\n send.push(Y.Struct[op.struct].encode(op))\n }\n }\n if (send.length > 0) { // TODO: && !this.store.forwardAppliedOperations (but then i don't send delete ops)\n // is connected, and this is not going to be send in addOperation\n this.store.y.connector.broadcastOps(send)\n }\n }\n\n * deleteList (start) {\n while (start != null) {\n start = yield* this.getOperation(start)\n if (!start.gc) {\n start.gc = true\n start.deleted = true\n yield* this.setOperation(start)\n var delLength = start.content != null ? start.content.length : 1\n yield* this.markDeleted(start.id, delLength)\n if (start.opContent != null) {\n yield* this.deleteOperation(start.opContent)\n }\n this.store.queueGarbageCollector(start.id)\n }\n start = start.right\n }\n }\n\n /*\n Mark an operation as deleted, and add it to the GC, if possible.\n */\n * deleteOperation (targetId, length, preventCallType) /* :Generator */ {\n if (length == null) {\n length = 1\n }\n yield* this.markDeleted(targetId, length)\n while (length > 0) {\n var callType = false\n var target = yield* this.os.findWithUpperBound([targetId[0], targetId[1] + length - 1])\n var targetLength = target != null && target.content != null ? target.content.length : 1\n if (target == null || target.id[0] !== targetId[0] || target.id[1] + targetLength <= targetId[1]) {\n // does not exist or is not in the range of the deletion\n target = null\n length = 0\n } else {\n // does exist, check if it is too long\n if (!target.deleted) {\n if (target.id[1] < targetId[1]) {\n // starts to the left of the deletion range\n target = yield* this.getInsertionCleanStart(targetId)\n targetLength = target.content.length // must have content property!\n }\n if (target.id[1] + targetLength > targetId[1] + length) {\n // ends to the right of the deletion range\n target = yield* this.getInsertionCleanEnd([targetId[0], targetId[1] + length - 1])\n targetLength = target.content.length\n }\n }\n length = target.id[1] - targetId[1]\n }\n\n if (target != null) {\n if (!target.deleted) {\n callType = true\n // set deleted & notify type\n target.deleted = true\n // delete containing lists\n if (target.start != null) {\n // TODO: don't do it like this .. -.-\n yield* this.deleteList(target.start)\n // yield* this.deleteList(target.id) -- do not gc itself because this may still get referenced\n }\n if (target.map != null) {\n for (var name in target.map) {\n yield* this.deleteList(target.map[name])\n }\n // TODO: here to.. (see above)\n // yield* this.deleteList(target.id) -- see above\n }\n if (target.opContent != null) {\n yield* this.deleteOperation(target.opContent)\n // target.opContent = null\n }\n if (target.requires != null) {\n for (var i = 0; i < target.requires.length; i++) {\n yield* this.deleteOperation(target.requires[i])\n }\n }\n }\n var left\n if (target.left != null) {\n left = yield* this.getInsertion(target.left)\n } else {\n left = null\n }\n\n // set here because it was deleted and/or gc'd\n yield* this.setOperation(target)\n\n /*\n Check if it is possible to add right to the gc.\n Because this delete can't be responsible for left being gc'd,\n we don't have to add left to the gc..\n */\n var right\n if (target.right != null) {\n right = yield* this.getOperation(target.right)\n } else {\n right = null\n }\n if (callType && !preventCallType) {\n yield* this.store.operationAdded(this, {\n struct: 'Delete',\n target: target.id,\n length: targetLength,\n targetParent: target.parent\n })\n }\n // need to gc in the end!\n yield* this.store.addToGarbageCollector.call(this, target, left)\n if (right != null) {\n yield* this.store.addToGarbageCollector.call(this, right, target)\n }\n }\n }\n }\n /*\n Mark an operation as deleted&gc'd\n */\n * markGarbageCollected (id, len) {\n // this.mem.push([\"gc\", id]);\n this.store.addToDebug('yield* this.markGarbageCollected(', id, ', ', len, ')')\n var n = yield* this.markDeleted(id, len)\n if (n.id[1] < id[1] && !n.gc) {\n // un-extend left\n var newlen = n.len - (id[1] - n.id[1])\n n.len -= newlen\n yield* this.ds.put(n)\n n = {id: id, len: newlen, gc: false}\n yield* this.ds.put(n)\n }\n // get prev&next before adding a new operation\n var prev = yield* this.ds.findPrev(id)\n var next = yield* this.ds.findNext(id)\n\n if (id[1] + len < n.id[1] + n.len && !n.gc) {\n // un-extend right\n yield* this.ds.put({id: [id[0], id[1] + len], len: n.len - len, gc: false})\n n.len = len\n }\n // set gc'd\n n.gc = true\n // can extend left?\n if (\n prev != null &&\n prev.gc &&\n Y.utils.compareIds([prev.id[0], prev.id[1] + prev.len], n.id)\n ) {\n prev.len += n.len\n yield* this.ds.delete(n.id)\n n = prev\n // ds.put n here?\n }\n // can extend right?\n if (\n next != null &&\n next.gc &&\n Y.utils.compareIds([n.id[0], n.id[1] + n.len], next.id)\n ) {\n n.len += next.len\n yield* this.ds.delete(next.id)\n }\n yield* this.ds.put(n)\n yield* this.updateState(n.id[0])\n }\n /*\n Mark an operation as deleted.\n\n returns the delete node\n */\n * markDeleted (id, length) {\n if (length == null) {\n length = 1\n }\n // this.mem.push([\"del\", id]);\n var n = yield* this.ds.findWithUpperBound(id)\n if (n != null && n.id[0] === id[0]) {\n if (n.id[1] <= id[1] && id[1] <= n.id[1] + n.len) {\n // id is in n's range\n var diff = id[1] + length - (n.id[1] + n.len) // overlapping right\n if (diff > 0) {\n // id+length overlaps n\n if (!n.gc) {\n n.len += diff\n } else {\n diff = n.id[1] + n.len - id[1] // overlapping left (id till n.end)\n if (diff < length) {\n // a partial deletion\n n = {id: [id[0], id[1] + diff], len: length - diff, gc: false}\n yield* this.ds.put(n)\n } else {\n // already gc'd\n throw new Error('Cannot happen! (it dit though.. :()')\n // return n\n }\n }\n } else {\n // no overlapping, already deleted\n return n\n }\n } else {\n // cannot extend left (there is no left!)\n n = {id: id, len: length, gc: false}\n yield* this.ds.put(n) // TODO: you double-put !!\n }\n } else {\n // cannot extend left\n n = {id: id, len: length, gc: false}\n yield* this.ds.put(n)\n }\n // can extend right?\n var next = yield* this.ds.findNext(n.id)\n if (\n next != null &&\n n.id[0] === next.id[0] &&\n n.id[1] + n.len >= next.id[1]\n ) {\n diff = n.id[1] + n.len - next.id[1] // from next.start to n.end\n while (diff >= 0) {\n // n overlaps with next\n if (next.gc) {\n // gc is stronger, so reduce length of n\n n.len -= diff\n if (diff >= next.len) {\n // delete the missing range after next\n diff = diff - next.len // missing range after next\n if (diff > 0) {\n yield* this.ds.put(n) // unneccessary? TODO!\n yield* this.markDeleted([next.id[0], next.id[1] + next.len], diff)\n }\n }\n break\n } else {\n // we can extend n with next\n if (diff > next.len) {\n // n is even longer than next\n // get next.next, and try to extend it\n var _next = yield* this.ds.findNext(next.id)\n yield* this.ds.delete(next.id)\n if (_next == null || n.id[0] !== _next.id[0]) {\n break\n } else {\n next = _next\n diff = n.id[1] + n.len - next.id[1] // from next.start to n.end\n // continue!\n }\n } else {\n // n just partially overlaps with next. extend n, delete next, and break this loop\n n.len += next.len - diff\n yield* this.ds.delete(next.id)\n break\n }\n }\n }\n }\n yield* this.ds.put(n)\n return n\n }\n /*\n Call this method when the client is connected&synced with the\n other clients (e.g. master). This will query the database for\n operations that can be gc'd and add them to the garbage collector.\n */\n * garbageCollectAfterSync () {\n if (this.store.gc1.length > 0 || this.store.gc2.length > 0) {\n console.warn('gc should be empty after sync')\n }\n if (!this.store.gc) {\n return\n }\n yield* this.os.iterate(this, null, null, function * (op) {\n if (op.gc) {\n delete op.gc\n yield* this.setOperation(op)\n }\n if (op.parent != null) {\n var parentDeleted = yield* this.isDeleted(op.parent)\n if (parentDeleted) {\n op.gc = true\n if (!op.deleted) {\n yield* this.markDeleted(op.id, op.content != null ? op.content.length : 1)\n op.deleted = true\n if (op.opContent != null) {\n yield* this.deleteOperation(op.opContent)\n }\n if (op.requires != null) {\n for (var i = 0; i < op.requires.length; i++) {\n yield* this.deleteOperation(op.requires[i])\n }\n }\n }\n yield* this.setOperation(op)\n this.store.gc1.push(op.id) // this is ok becaues its shortly before sync (otherwise use queueGarbageCollector!)\n return\n }\n }\n if (op.deleted) {\n var left = null\n if (op.left != null) {\n left = yield* this.getInsertion(op.left)\n }\n yield* this.store.addToGarbageCollector.call(this, op, left)\n }\n })\n }\n /*\n Really remove an op and all its effects.\n The complicated case here is the Insert operation:\n * reset left\n * reset right\n * reset parent.start\n * reset parent.end\n * reset origins of all right ops\n */\n * garbageCollectOperation (id) {\n this.store.addToDebug('yield* this.garbageCollectOperation(', id, ')')\n var o = yield* this.getOperation(id)\n yield* this.markGarbageCollected(id, (o != null && o.content != null) ? o.content.length : 1) // always mark gc'd\n // if op exists, then clean that mess up..\n if (o != null) {\n var deps = []\n if (o.opContent != null) {\n deps.push(o.opContent)\n }\n if (o.requires != null) {\n deps = deps.concat(o.requires)\n }\n for (var i = 0; i < deps.length; i++) {\n var dep = yield* this.getOperation(deps[i])\n if (dep != null) {\n if (!dep.deleted) {\n yield* this.deleteOperation(dep.id)\n dep = yield* this.getOperation(dep.id)\n }\n dep.gc = true\n yield* this.setOperation(dep)\n this.store.queueGarbageCollector(dep.id)\n } else {\n yield* this.markGarbageCollected(deps[i], 1)\n }\n }\n\n // remove gc'd op from the left op, if it exists\n if (o.left != null) {\n var left = yield* this.getInsertion(o.left)\n left.right = o.right\n yield* this.setOperation(left)\n }\n // remove gc'd op from the right op, if it exists\n // also reset origins of right ops\n if (o.right != null) {\n var right = yield* this.getOperation(o.right)\n right.left = o.left\n yield* this.setOperation(right)\n\n if (o.originOf != null && o.originOf.length > 0) {\n // find new origin of right ops\n // origin is the first left deleted operation\n var neworigin = o.left\n var neworigin_ = null\n while (neworigin != null) {\n neworigin_ = yield* this.getInsertion(neworigin)\n if (neworigin_.deleted) {\n break\n }\n neworigin = neworigin_.left\n }\n\n // reset origin of all right ops (except first right - duh!),\n\n /* ** The following code does not rely on the the originOf property **\n I recently added originOf to all Insert Operations (see Struct.Insert.execute),\n which saves which operations originate in a Insert operation.\n Garbage collecting without originOf is more memory efficient, but is nearly impossible for large texts, or lists!\n But I keep this code for now\n ```\n // reset origin of right\n right.origin = neworigin\n // search until you find origin pointer to the left of o\n if (right.right != null) {\n var i = yield* this.getOperation(right.right)\n var ids = [o.id, o.right]\n while (ids.some(function (id) {\n return Y.utils.compareIds(id, i.origin)\n })) {\n if (Y.utils.compareIds(i.origin, o.id)) {\n // reset origin of i\n i.origin = neworigin\n yield* this.setOperation(i)\n }\n // get next i\n if (i.right == null) {\n break\n } else {\n ids.push(i.id)\n i = yield* this.getOperation(i.right)\n }\n }\n }\n ```\n */\n // ** Now the new implementation starts **\n // reset neworigin of all originOf[*]\n for (var _i in o.originOf) {\n var originsIn = yield* this.getOperation(o.originOf[_i])\n if (originsIn != null) {\n originsIn.origin = neworigin\n yield* this.setOperation(originsIn)\n }\n }\n if (neworigin != null) {\n if (neworigin_.originOf == null) {\n neworigin_.originOf = o.originOf\n } else {\n neworigin_.originOf = o.originOf.concat(neworigin_.originOf)\n }\n yield* this.setOperation(neworigin_)\n }\n // we don't need to set right here, because\n // right should be in o.originOf => it is set it the previous for loop\n }\n }\n // o may originate in another operation.\n // Since o is deleted, we have to reset o.origin's `originOf` property\n if (o.origin != null) {\n var origin = yield* this.getInsertion(o.origin)\n origin.originOf = origin.originOf.filter(function (_id) {\n return !Y.utils.compareIds(id, _id)\n })\n yield* this.setOperation(origin)\n }\n var parent\n if (o.parent != null) {\n parent = yield* this.getOperation(o.parent)\n }\n // remove gc'd op from parent, if it exists\n if (parent != null) {\n var setParent = false // whether to save parent to the os\n if (o.parentSub != null) {\n if (Y.utils.compareIds(parent.map[o.parentSub], o.id)) {\n setParent = true\n if (o.right != null) {\n parent.map[o.parentSub] = o.right\n } else {\n delete parent.map[o.parentSub]\n }\n }\n } else {\n if (Y.utils.compareIds(parent.start, o.id)) {\n // gc'd op is the start\n setParent = true\n parent.start = o.right\n }\n if (Y.utils.matchesId(o, parent.end)) {\n // gc'd op is the end\n setParent = true\n parent.end = o.left\n }\n }\n if (setParent) {\n yield* this.setOperation(parent)\n }\n }\n // finally remove it from the os\n yield* this.removeOperation(o.id)\n }\n }\n * checkDeleteStoreForState (state) {\n var n = yield* this.ds.findWithUpperBound([state.user, state.clock])\n if (n != null && n.id[0] === state.user && n.gc) {\n state.clock = Math.max(state.clock, n.id[1] + n.len)\n }\n }\n * updateState (user) {\n var state = yield* this.getState(user)\n yield* this.checkDeleteStoreForState(state)\n var o = yield* this.getInsertion([user, state.clock])\n var oLength = (o != null && o.content != null) ? o.content.length : 1\n while (o != null && user === o.id[0] && o.id[1] <= state.clock && o.id[1] + oLength > state.clock) {\n // either its a new operation (1. case), or it is an operation that was deleted, but is not yet in the OS\n state.clock += oLength\n yield* this.checkDeleteStoreForState(state)\n o = yield* this.os.findNext(o.id)\n oLength = (o != null && o.content != null) ? o.content.length : 1\n }\n yield* this.setState(state)\n }\n /*\n apply a delete set in order to get\n the state of the supplied ds\n */\n * applyDeleteSet (ds) {\n var deletions = []\n\n for (var user in ds) {\n var dv = ds[user]\n var pos = 0\n var d = dv[pos]\n yield* this.ds.iterate(this, [user, 0], [user, Number.MAX_VALUE], function * (n) {\n // cases:\n // 1. d deletes something to the right of n\n // => go to next n (break)\n // 2. d deletes something to the left of n\n // => create deletions\n // => reset d accordingly\n // *)=> if d doesn't delete anything anymore, go to next d (continue)\n // 3. not 2) and d deletes something that also n deletes\n // => reset d so that it doesn't contain n's deletion\n // *)=> if d does not delete anything anymore, go to next d (continue)\n while (d != null) {\n var diff = 0 // describe the diff of length in 1) and 2)\n if (n.id[1] + n.len <= d[0]) {\n // 1)\n break\n } else if (d[0] < n.id[1]) {\n // 2)\n // delete maximum the len of d\n // else delete as much as possible\n diff = Math.min(n.id[1] - d[0], d[1])\n deletions.push([user, d[0], diff, d[2]])\n } else {\n // 3)\n diff = n.id[1] + n.len - d[0] // never null (see 1)\n if (d[2] && !n.gc) {\n // d marks as gc'd but n does not\n // then delete either way\n deletions.push([user, d[0], Math.min(diff, d[1]), d[2]])\n }\n }\n if (d[1] <= diff) {\n // d doesn't delete anything anymore\n d = dv[++pos]\n } else {\n d[0] = d[0] + diff // reset pos\n d[1] = d[1] - diff // reset length\n }\n }\n })\n // for the rest.. just apply it\n for (; pos < dv.length; pos++) {\n d = dv[pos]\n deletions.push([user, d[0], d[1], d[2]])\n }\n }\n for (var i = 0; i < deletions.length; i++) {\n var del = deletions[i]\n // always try to delete..\n yield* this.deleteOperation([del[0], del[1]], del[2])\n if (del[3]) {\n // gc..\n yield* this.markGarbageCollected([del[0], del[1]], del[2]) // always mark gc'd\n // remove operation..\n var counter = del[1] + del[2]\n while (counter >= del[1]) {\n var o = yield* this.os.findWithUpperBound([del[0], counter - 1])\n if (o == null) {\n break\n }\n var oLen = o.content != null ? o.content.length : 1\n if (o.id[0] !== del[0] || o.id[1] + oLen <= del[1]) {\n // not in range\n break\n }\n if (o.id[1] + oLen > del[1] + del[2]) {\n // overlaps right\n o = yield* this.getInsertionCleanEnd([del[0], del[1] + del[2] - 1])\n }\n if (o.id[1] < del[1]) {\n // overlaps left\n o = yield* this.getInsertionCleanStart([del[0], del[1]])\n }\n counter = o.id[1]\n yield* this.garbageCollectOperation(o.id)\n }\n }\n if (this.store.forwardAppliedOperations) {\n var ops = []\n ops.push({struct: 'Delete', target: [del[0], del[1]], length: del[2]})\n this.store.y.connector.broadcastOps(ops)\n }\n }\n }\n * isGarbageCollected (id) {\n var n = yield* this.ds.findWithUpperBound(id)\n return n != null && n.id[0] === id[0] && id[1] < n.id[1] + n.len && n.gc\n }\n /*\n A DeleteSet (ds) describes all the deleted ops in the OS\n */\n * getDeleteSet () {\n var ds = {}\n yield* this.ds.iterate(this, null, null, function * (n) {\n var user = n.id[0]\n var counter = n.id[1]\n var len = n.len\n var gc = n.gc\n var dv = ds[user]\n if (dv === void 0) {\n dv = []\n ds[user] = dv\n }\n dv.push([counter, len, gc])\n })\n return ds\n }\n * isDeleted (id) {\n var n = yield* this.ds.findWithUpperBound(id)\n return n != null && n.id[0] === id[0] && id[1] < n.id[1] + n.len\n }\n * setOperation (op) {\n yield* this.os.put(op)\n return op\n }\n * addOperation (op) {\n yield* this.os.put(op)\n if (this.store.forwardAppliedOperations && typeof op.id[1] !== 'string') {\n // is connected, and this is not going to be send in addOperation\n this.store.y.connector.broadcastOps([op])\n }\n }\n // if insertion, try to combine with left insertion (if both have content property)\n * tryCombineWithLeft (op) {\n if (\n op != null &&\n op.left != null &&\n op.content != null &&\n op.left[0] === op.id[0] &&\n Y.utils.compareIds(op.left, op.origin)\n ) {\n var left = yield* this.getInsertion(op.left)\n if (left.content != null &&\n left.id[1] + left.content.length === op.id[1] &&\n left.originOf.length === 1 &&\n !left.gc && !left.deleted &&\n !op.gc && !op.deleted\n ) {\n // combine!\n if (op.originOf != null) {\n left.originOf = op.originOf\n } else {\n delete left.originOf\n }\n left.content = left.content.concat(op.content)\n left.right = op.right\n yield* this.os.delete(op.id)\n yield* this.setOperation(left)\n }\n }\n }\n * getInsertion (id) {\n var ins = yield* this.os.findWithUpperBound(id)\n if (ins == null) {\n return null\n } else {\n var len = ins.content != null ? ins.content.length : 1 // in case of opContent\n if (id[0] === ins.id[0] && id[1] < ins.id[1] + len) {\n return ins\n } else {\n return null\n }\n }\n }\n * getInsertionCleanStartEnd (id) {\n yield* this.getInsertionCleanStart(id)\n return yield* this.getInsertionCleanEnd(id)\n }\n // Return an insertion such that id is the first element of content\n // This function manipulates an operation, if necessary\n * getInsertionCleanStart (id) {\n var ins = yield* this.getInsertion(id)\n if (ins != null) {\n if (ins.id[1] === id[1]) {\n return ins\n } else {\n var left = Y.utils.copyObject(ins)\n ins.content = left.content.splice(id[1] - ins.id[1])\n ins.id = id\n var leftLid = Y.utils.getLastId(left)\n ins.origin = leftLid\n left.originOf = [ins.id]\n left.right = ins.id\n ins.left = leftLid\n // debugger // check\n yield* this.setOperation(left)\n yield* this.setOperation(ins)\n if (left.gc) {\n this.store.queueGarbageCollector(ins.id)\n }\n return ins\n }\n } else {\n return null\n }\n }\n // Return an insertion such that id is the last element of content\n // This function manipulates an operation, if necessary\n * getInsertionCleanEnd (id) {\n var ins = yield* this.getInsertion(id)\n if (ins != null) {\n if (ins.content == null || (ins.id[1] + ins.content.length - 1 === id[1])) {\n return ins\n } else {\n var right = Y.utils.copyObject(ins)\n right.content = ins.content.splice(id[1] - ins.id[1] + 1) // cut off remainder\n right.id = [id[0], id[1] + 1]\n var insLid = Y.utils.getLastId(ins)\n right.origin = insLid\n ins.originOf = [right.id]\n ins.right = right.id\n right.left = insLid\n // debugger // check\n yield* this.setOperation(right)\n yield* this.setOperation(ins)\n if (ins.gc) {\n this.store.queueGarbageCollector(right.id)\n }\n return ins\n }\n } else {\n return null\n }\n }\n * getOperation (id/* :any */)/* :Transaction */ {\n var o = yield* this.os.find(id)\n if (id[0] !== '_' || o != null) {\n return o\n } else { // type is string\n // generate this operation?\n var comp = id[1].split('_')\n if (comp.length > 1) {\n var struct = comp[0]\n var op = Y.Struct[struct].create(id)\n op.type = comp[1]\n yield* this.setOperation(op)\n return op\n } else {\n // won't be called. but just in case..\n console.error('Unexpected case. How can this happen?')\n debugger // eslint-disable-line\n return null\n }\n }\n }\n * removeOperation (id) {\n yield* this.os.delete(id)\n }\n * setState (state) {\n var val = {\n id: [state.user],\n clock: state.clock\n }\n yield* this.ss.put(val)\n }\n * getState (user) {\n var n = yield* this.ss.find([user])\n var clock = n == null ? null : n.clock\n if (clock == null) {\n clock = 0\n }\n return {\n user: user,\n clock: clock\n }\n }\n * getStateVector () {\n var stateVector = []\n yield* this.ss.iterate(this, null, null, function * (n) {\n stateVector.push({\n user: n.id[0],\n clock: n.clock\n })\n })\n return stateVector\n }\n * getStateSet () {\n var ss = {}\n yield* this.ss.iterate(this, null, null, function * (n) {\n ss[n.id[0]] = n.clock\n })\n return ss\n }\n /*\n Here, we make all missing operations executable for the receiving user.\n\n Notes:\n startSS: denotes to the SV that the remote user sent\n currSS: denotes to the state vector that the user should have if he\n applies all already sent operations (increases is each step)\n\n We face several problems:\n * Execute op as is won't work because ops depend on each other\n -> find a way so that they do not anymore\n * When changing left, must not go more to the left than the origin\n * When changing right, you have to consider that other ops may have op\n as their origin, this means that you must not set one of these ops\n as the new right (interdependencies of ops)\n * can't just go to the right until you find the first known operation,\n With currSS\n -> interdependency of ops is a problem\n With startSS\n -> leads to inconsistencies when two users join at the same time.\n Then the position depends on the order of execution -> error!\n\n Solution:\n -> re-create originial situation\n -> set op.left = op.origin (which never changes)\n -> set op.right\n to the first operation that is known (according to startSS)\n or to the first operation that has an origin that is not to the\n right of op.\n -> Enforces unique execution order -> happy user\n\n Improvements: TODO\n * Could set left to origin, or the first known operation\n (startSS or currSS.. ?)\n -> Could be necessary when I turn GC again.\n -> Is a bad(ish) idea because it requires more computation\n\n What we do:\n * Iterate over all missing operations.\n * When there is an operation, where the right op is known, send this op all missing ops to the left to the user\n * I explained above what we have to do with each operation. Here is how we do it efficiently:\n 1. Go to the left until you find either op.origin, or a known operation (let o denote current operation in the iteration)\n 2. Found a known operation -> set op.left = o, and send it to the user. stop\n 3. Found o = op.origin -> set op.left = op.origin, and send it to the user. start again from 1. (set op = o)\n 4. Found some o -> set o.right = op, o.left = o.origin, send it to the user, continue\n */\n * getOperations (startSS) {\n // TODO: use bounds here!\n if (startSS == null) {\n startSS = {}\n }\n var send = []\n\n var endSV = yield* this.getStateVector()\n for (var endState of endSV) {\n var user = endState.user\n if (user === '_') {\n continue\n }\n var startPos = startSS[user] || 0\n if (startPos > 0) {\n // There is a change that [user, startPos] is in a composed Insertion (with a smaller counter)\n // find out if that is the case\n var firstMissing = yield* this.getInsertion([user, startPos])\n if (firstMissing != null) {\n // update startPos\n startPos = firstMissing.id[1]\n startSS[user] = startPos\n }\n }\n yield* this.os.iterate(this, [user, startPos], [user, Number.MAX_VALUE], function * (op) {\n op = Y.Struct[op.struct].encode(op)\n if (op.struct !== 'Insert') {\n send.push(op)\n } else if (op.right == null || op.right[1] < (startSS[op.right[0]] || 0)) {\n // case 1. op.right is known\n var o = op\n // Remember: ?\n // -> set op.right\n // 1. to the first operation that is known (according to startSS)\n // 2. or to the first operation that has an origin that is not to the\n // right of op.\n // For this we maintain a list of ops which origins are not found yet.\n var missing_origins = [op]\n var newright = op.right\n while (true) {\n if (o.left == null) {\n op.left = null\n send.push(op)\n if (!Y.utils.compareIds(o.id, op.id)) {\n o = Y.Struct[op.struct].encode(o)\n o.right = missing_origins[missing_origins.length - 1].id\n send.push(o)\n }\n break\n }\n o = yield* this.getInsertion(o.left)\n // we set another o, check if we can reduce $missing_origins\n while (missing_origins.length > 0 && Y.utils.matchesId(o, missing_origins[missing_origins.length - 1].origin)) {\n missing_origins.pop()\n }\n if (o.id[1] < (startSS[o.id[0]] || 0)) {\n // case 2. o is known\n op.left = Y.utils.getLastId(o)\n send.push(op)\n break\n } else if (Y.utils.matchesId(o, op.origin)) {\n // case 3. o is op.origin\n op.left = op.origin\n send.push(op)\n op = Y.Struct[op.struct].encode(o)\n op.right = newright\n if (missing_origins.length > 0) {\n console.log('This should not happen .. :( please report this')\n }\n missing_origins = [op]\n } else {\n // case 4. send o, continue to find op.origin\n var s = Y.Struct[op.struct].encode(o)\n s.right = missing_origins[missing_origins.length - 1].id\n s.left = s.origin\n send.push(s)\n missing_origins.push(o)\n }\n }\n }\n })\n }\n return send.reverse()\n }\n /*\n * Get the plain untransformed operations from the database.\n * You can apply these operations using .applyOperationsUntransformed(ops)\n *\n */\n * getOperationsUntransformed () {\n var ops = []\n yield* this.os.iterate(this, null, null, function * (op) {\n if (op.id[0] !== '_') {\n ops.push(op)\n }\n })\n return {\n untransformed: ops\n }\n }\n * applyOperationsUntransformed (m, stateSet) {\n var ops = m.untransformed\n for (var i = 0; i < ops.length; i++) {\n var op = ops[i]\n // create, and modify parent, if it is created implicitly\n if (op.parent != null && op.parent[0] === '_') {\n if (op.struct === 'Insert') {\n // update parents .map/start/end properties\n if (op.parentSub != null && op.left == null) {\n // op is child of Map\n let parent = yield* this.getOperation(op.parent)\n parent.map[op.parentSub] = op.id\n yield* this.setOperation(parent)\n } else if (op.right == null || op.left == null) {\n let parent = yield* this.getOperation(op.parent)\n if (op.right == null) {\n parent.end = Y.utils.getLastId(op)\n }\n if (op.left == null) {\n parent.start = op.id\n }\n yield* this.setOperation(parent)\n }\n }\n }\n yield* this.os.put(op)\n }\n for (var user in stateSet) {\n yield* this.ss.put({\n id: [user],\n clock: stateSet[user]\n })\n }\n }\n /* this is what we used before.. use this as a reference..\n * makeOperationReady (startSS, op) {\n op = Y.Struct[op.struct].encode(op)\n op = Y.utils.copyObject(op) -- use copyoperation instead now!\n var o = op\n var ids = [op.id]\n // search for the new op.right\n // it is either the first known op (according to startSS)\n // or the o that has no origin to the right of op\n // (this is why we use the ids array)\n while (o.right != null) {\n var right = yield* this.getOperation(o.right)\n if (o.right[1] < (startSS[o.right[0]] || 0) || !ids.some(function (id) {\n return Y.utils.compareIds(id, right.origin)\n })) {\n break\n }\n ids.push(o.right)\n o = right\n }\n op.right = o.right\n op.left = op.origin\n return op\n }\n */\n * flush () {\n yield* this.os.flush()\n yield* this.ss.flush()\n yield* this.ds.flush()\n }\n }\n Y.Transaction = TransactionInterface\n}\n","/* @flow */\n'use strict'\n\n/*\n EventHandler is an helper class for constructing custom types.\n\n Why: When constructing custom types, you sometimes want your types to work\n synchronous: E.g.\n ``` Synchronous\n mytype.setSomething(\"yay\")\n mytype.getSomething() === \"yay\"\n ```\n versus\n ``` Asynchronous\n mytype.setSomething(\"yay\")\n mytype.getSomething() === undefined\n mytype.waitForSomething().then(function(){\n mytype.getSomething() === \"yay\"\n })\n ```\n\n The structures usually work asynchronously (you have to wait for the\n database request to finish). EventHandler helps you to make your type\n synchronous.\n*/\nmodule.exports = function (Y /* : any*/) {\n Y.utils = {}\n\n Y.utils.bubbleEvent = function (type, event) {\n type.eventHandler.callEventListeners(event)\n event.path = []\n while (type != null && type._deepEventHandler != null) {\n type._deepEventHandler.callEventListeners(event)\n var parent = null\n if (type._parent != null) {\n parent = type.os.getType(type._parent)\n }\n if (parent != null && parent._getPathToChild != null) {\n event.path = [parent._getPathToChild(type._model)].concat(event.path)\n type = parent\n } else {\n type = null\n }\n }\n }\n\n class EventListenerHandler {\n constructor () {\n this.eventListeners = []\n }\n destroy () {\n this.eventListeners = null\n }\n /*\n Basic event listener boilerplate...\n */\n addEventListener (f) {\n this.eventListeners.push(f)\n }\n removeEventListener (f) {\n this.eventListeners = this.eventListeners.filter(function (g) {\n return f !== g\n })\n }\n removeAllEventListeners () {\n this.eventListeners = []\n }\n callEventListeners (event) {\n for (var i = 0; i < this.eventListeners.length; i++) {\n try {\n var _event = {}\n for (var name in event) {\n _event[name] = event[name]\n }\n this.eventListeners[i](_event)\n } catch (e) {\n console.error('Your observer threw an error. This error was caught so that Yjs still can ensure data consistency! In order to debug this error you have to check \"Pause On Caught Exceptions\"', e)\n }\n }\n }\n }\n Y.utils.EventListenerHandler = EventListenerHandler\n\n class EventHandler extends EventListenerHandler {\n /* ::\n waiting: Array;\n awaiting: number;\n onevent: Function;\n eventListeners: Array;\n */\n /*\n onevent: is called when the structure changes.\n\n Note: \"awaiting opertations\" is used to denote operations that were\n prematurely called. Events for received operations can not be executed until\n all prematurely called operations were executed (\"waiting operations\")\n */\n constructor (onevent /* : Function */) {\n super()\n this.waiting = []\n this.awaiting = 0\n this.onevent = onevent\n }\n destroy () {\n super.destroy()\n this.waiting = null\n this.onevent = null\n }\n /*\n Call this when a new operation arrives. It will be executed right away if\n there are no waiting operations, that you prematurely executed\n */\n receivedOp (op) {\n if (this.awaiting <= 0) {\n this.onevent(op)\n } else if (op.struct === 'Delete') {\n var self = this\n var checkDelete = function checkDelete (d) {\n if (d.length == null) {\n throw new Error('This shouldn\\'t happen! d.length must be defined!')\n }\n // we check if o deletes something in self.waiting\n // if so, we remove the deleted operation\n for (var w = 0; w < self.waiting.length; w++) {\n var i = self.waiting[w]\n if (i.struct === 'Insert' && i.id[0] === d.target[0]) {\n var iLength = i.hasOwnProperty('content') ? i.content.length : 1\n var dStart = d.target[1]\n var dEnd = d.target[1] + (d.length || 1)\n var iStart = i.id[1]\n var iEnd = i.id[1] + iLength\n // Check if they don't overlap\n if (iEnd <= dStart || dEnd <= iStart) {\n // no overlapping\n continue\n }\n // we check all overlapping cases. All cases:\n /*\n 1) iiiii\n ddddd\n --> modify i and d\n 2) iiiiiii\n ddddd\n --> modify i, remove d\n 3) iiiiiii\n ddd\n --> remove d, modify i, and create another i (for the right hand side)\n 4) iiiii\n ddddddd\n --> remove i, modify d\n 5) iiiiiii\n ddddddd\n --> remove both i and d (**)\n 6) iiiiiii\n ddddd\n --> modify i, remove d\n 7) iii\n ddddddd\n --> remove i, create and apply two d with checkDelete(d) (**)\n 8) iiiii\n ddddddd\n --> remove i, modify d (**)\n 9) iiiii\n ddddd\n --> modify i and d\n (**) (also check if i contains content or type)\n */\n // TODO: I left some debugger statements, because I want to debug all cases once in production. REMEMBER END TODO\n if (iStart < dStart) {\n if (dStart < iEnd) {\n if (iEnd < dEnd) {\n // Case 1\n // remove the right part of i's content\n i.content.splice(dStart - iStart)\n // remove the start of d's deletion\n d.length = dEnd - iEnd\n d.target = [d.target[0], iEnd]\n continue\n } else if (iEnd === dEnd) {\n // Case 2\n i.content.splice(dStart - iStart)\n // remove d, we do that by simply ending this function\n return\n } else { // (dEnd < iEnd)\n // Case 3\n var newI = {\n id: [i.id[0], dEnd],\n content: i.content.slice(dEnd - iStart),\n struct: 'Insert'\n }\n self.waiting.push(newI)\n i.content.splice(dStart - iStart)\n return\n }\n }\n } else if (dStart === iStart) {\n if (iEnd < dEnd) {\n // Case 4\n d.length = dEnd - iEnd\n d.target = [d.target[0], iEnd]\n i.content = []\n continue\n } else if (iEnd === dEnd) {\n // Case 5\n self.waiting.splice(w, 1)\n return\n } else { // (dEnd < iEnd)\n // Case 6\n i.content = i.content.slice(dEnd - iStart)\n i.id = [i.id[0], dEnd]\n return\n }\n } else { // (dStart < iStart)\n if (iStart < dEnd) {\n // they overlap\n /*\n 7) iii\n ddddddd\n --> remove i, create and apply two d with checkDelete(d) (**)\n 8) iiiii\n ddddddd\n --> remove i, modify d (**)\n 9) iiiii\n ddddd\n --> modify i and d\n */\n if (iEnd < dEnd) {\n // Case 7\n // debugger // TODO: You did not test this case yet!!!! (add the debugger here)\n self.waiting.splice(w, 1)\n checkDelete({\n target: [d.target[0], dStart],\n length: iStart - dStart,\n struct: 'Delete'\n })\n checkDelete({\n target: [d.target[0], iEnd],\n length: iEnd - dEnd,\n struct: 'Delete'\n })\n return\n } else if (iEnd === dEnd) {\n // Case 8\n self.waiting.splice(w, 1)\n w--\n d.length -= iLength\n continue\n } else { // dEnd < iEnd\n // Case 9\n d.length = iStart - dStart\n i.content.splice(0, dEnd - iStart)\n i.id = [i.id[0], dEnd]\n continue\n }\n }\n }\n }\n }\n // finished with remaining operations\n self.waiting.push(d)\n }\n if (op.key == null) {\n // deletes in list\n checkDelete(op)\n } else {\n // deletes in map\n this.waiting.push(op)\n }\n } else {\n this.waiting.push(op)\n }\n }\n /*\n You created some operations, and you want the `onevent` function to be\n called right away. Received operations will not be executed untill all\n prematurely called operations are executed\n */\n awaitAndPrematurelyCall (ops) {\n this.awaiting++\n ops.map(Y.utils.copyOperation).forEach(this.onevent)\n }\n * awaitOps (transaction, f, args) {\n function notSoSmartSort (array) {\n // this function sorts insertions in a executable order\n var result = []\n while (array.length > 0) {\n for (var i = 0; i < array.length; i++) {\n var independent = true\n for (var j = 0; j < array.length; j++) {\n if (Y.utils.matchesId(array[j], array[i].left)) {\n // array[i] depends on array[j]\n independent = false\n break\n }\n }\n if (independent) {\n result.push(array.splice(i, 1)[0])\n i--\n }\n }\n }\n return result\n }\n var before = this.waiting.length\n // somehow create new operations\n yield* f.apply(transaction, args)\n // remove all appended ops / awaited ops\n this.waiting.splice(before)\n if (this.awaiting > 0) this.awaiting--\n // if there are no awaited ops anymore, we can update all waiting ops, and send execute them (if there are still no awaited ops)\n if (this.awaiting === 0 && this.waiting.length > 0) {\n // update all waiting ops\n for (let i = 0; i < this.waiting.length; i++) {\n var o = this.waiting[i]\n if (o.struct === 'Insert') {\n var _o = yield* transaction.getInsertion(o.id)\n if (_o.parentSub != null && _o.left != null) {\n // if o is an insertion of a map struc (parentSub is defined), then it shouldn't be necessary to compute left\n this.waiting.splice(i, 1)\n i-- // update index\n } else if (!Y.utils.compareIds(_o.id, o.id)) {\n // o got extended\n o.left = [o.id[0], o.id[1] - 1]\n } else if (_o.left == null) {\n o.left = null\n } else {\n // find next undeleted op\n var left = yield* transaction.getInsertion(_o.left)\n while (left.deleted != null) {\n if (left.left != null) {\n left = yield* transaction.getInsertion(left.left)\n } else {\n left = null\n break\n }\n }\n o.left = left != null ? Y.utils.getLastId(left) : null\n }\n }\n }\n // the previous stuff was async, so we have to check again!\n // We also pull changes from the bindings, if there exists such a method, this could increase awaiting too\n if (this._pullChanges != null) {\n this._pullChanges()\n }\n if (this.awaiting === 0) {\n // sort by type, execute inserts first\n var ins = []\n var dels = []\n this.waiting.forEach(function (o) {\n if (o.struct === 'Delete') {\n dels.push(o)\n } else {\n ins.push(o)\n }\n })\n this.waiting = []\n // put in executable order\n ins = notSoSmartSort(ins)\n // this.onevent can trigger the creation of another operation\n // -> check if this.awaiting increased & stop computation if it does\n for (var i = 0; i < ins.length; i++) {\n if (this.awaiting === 0) {\n this.onevent(ins[i])\n } else {\n this.waiting = this.waiting.concat(ins.slice(i))\n break\n }\n }\n for (i = 0; i < dels.length; i++) {\n if (this.awaiting === 0) {\n this.onevent(dels[i])\n } else {\n this.waiting = this.waiting.concat(dels.slice(i))\n break\n }\n }\n }\n }\n }\n // TODO: Remove awaitedInserts and awaitedDeletes in favor of awaitedOps, as they are deprecated and do not always work\n // Do this in one of the coming releases that are breaking anyway\n /*\n Call this when you successfully awaited the execution of n Insert operations\n */\n awaitedInserts (n) {\n var ops = this.waiting.splice(this.waiting.length - n)\n for (var oid = 0; oid < ops.length; oid++) {\n var op = ops[oid]\n if (op.struct === 'Insert') {\n for (var i = this.waiting.length - 1; i >= 0; i--) {\n let w = this.waiting[i]\n // TODO: do I handle split operations correctly here? Super unlikely, but yeah..\n // Also: can this case happen? Can op be inserted in the middle of a larger op that is in $waiting?\n if (w.struct === 'Insert') {\n if (Y.utils.matchesId(w, op.left)) {\n // include the effect of op in w\n w.right = op.id\n // exclude the effect of w in op\n op.left = w.left\n } else if (Y.utils.compareIds(w.id, op.right)) {\n // similar..\n w.left = Y.utils.getLastId(op)\n op.right = w.right\n }\n }\n }\n } else {\n throw new Error('Expected Insert Operation!')\n }\n }\n this._tryCallEvents(n)\n }\n /*\n Call this when you successfully awaited the execution of n Delete operations\n */\n awaitedDeletes (n, newLeft) {\n var ops = this.waiting.splice(this.waiting.length - n)\n for (var j = 0; j < ops.length; j++) {\n var del = ops[j]\n if (del.struct === 'Delete') {\n if (newLeft != null) {\n for (var i = 0; i < this.waiting.length; i++) {\n let w = this.waiting[i]\n // We will just care about w.left\n if (w.struct === 'Insert' && Y.utils.compareIds(del.target, w.left)) {\n w.left = newLeft\n }\n }\n }\n } else {\n throw new Error('Expected Delete Operation!')\n }\n }\n this._tryCallEvents(n)\n }\n /* (private)\n Try to execute the events for the waiting operations\n */\n _tryCallEvents () {\n function notSoSmartSort (array) {\n var result = []\n while (array.length > 0) {\n for (var i = 0; i < array.length; i++) {\n var independent = true\n for (var j = 0; j < array.length; j++) {\n if (Y.utils.matchesId(array[j], array[i].left)) {\n // array[i] depends on array[j]\n independent = false\n break\n }\n }\n if (independent) {\n result.push(array.splice(i, 1)[0])\n i--\n }\n }\n }\n return result\n }\n if (this.awaiting > 0) this.awaiting--\n if (this.awaiting === 0 && this.waiting.length > 0) {\n var ins = []\n var dels = []\n this.waiting.forEach(function (o) {\n if (o.struct === 'Delete') {\n dels.push(o)\n } else {\n ins.push(o)\n }\n })\n ins = notSoSmartSort(ins)\n ins.forEach(this.onevent)\n dels.forEach(this.onevent)\n this.waiting = []\n }\n }\n }\n Y.utils.EventHandler = EventHandler\n\n /*\n Default class of custom types!\n */\n class CustomType {\n getPath () {\n var parent = null\n if (this._parent != null) {\n parent = this.os.getType(this._parent)\n }\n if (parent != null && parent._getPathToChild != null) {\n var firstKey = parent._getPathToChild(this._model)\n var parentKeys = parent.getPath()\n parentKeys.push(firstKey)\n return parentKeys\n } else {\n return []\n }\n }\n }\n Y.utils.CustomType = CustomType\n\n /*\n A wrapper for the definition of a custom type.\n Every custom type must have three properties:\n\n * struct\n - Structname of this type\n * initType\n - Given a model, creates a custom type\n * class\n - the constructor of the custom type (e.g. in order to inherit from a type)\n */\n class CustomTypeDefinition { // eslint-disable-line\n /* ::\n struct: any;\n initType: any;\n class: Function;\n name: String;\n */\n constructor (def) {\n if (def.struct == null ||\n def.initType == null ||\n def.class == null ||\n def.name == null ||\n def.createType == null\n ) {\n throw new Error('Custom type was not initialized correctly!')\n }\n this.struct = def.struct\n this.initType = def.initType\n this.createType = def.createType\n this.class = def.class\n this.name = def.name\n if (def.appendAdditionalInfo != null) {\n this.appendAdditionalInfo = def.appendAdditionalInfo\n }\n this.parseArguments = (def.parseArguments || function () {\n return [this]\n }).bind(this)\n this.parseArguments.typeDefinition = this\n }\n }\n Y.utils.CustomTypeDefinition = CustomTypeDefinition\n\n Y.utils.isTypeDefinition = function isTypeDefinition (v) {\n if (v != null) {\n if (v instanceof Y.utils.CustomTypeDefinition) return [v]\n else if (v.constructor === Array && v[0] instanceof Y.utils.CustomTypeDefinition) return v\n else if (v instanceof Function && v.typeDefinition instanceof Y.utils.CustomTypeDefinition) return [v.typeDefinition]\n }\n return false\n }\n\n /*\n Make a flat copy of an object\n (just copy properties)\n */\n function copyObject (o) {\n var c = {}\n for (var key in o) {\n c[key] = o[key]\n }\n return c\n }\n Y.utils.copyObject = copyObject\n\n /*\n Copy an operation, so that it can be manipulated.\n Note: You must not change subproperties (except o.content)!\n */\n function copyOperation (o) {\n o = copyObject(o)\n if (o.content != null) {\n o.content = o.content.map(function (c) { return c })\n }\n return o\n }\n\n Y.utils.copyOperation = copyOperation\n\n /*\n Defines a smaller relation on Id's\n */\n function smaller (a, b) {\n return a[0] < b[0] || (a[0] === b[0] && (a[1] < b[1] || typeof a[1] < typeof b[1]))\n }\n Y.utils.smaller = smaller\n\n function inDeletionRange (del, ins) {\n return del.target[0] === ins[0] && del.target[1] <= ins[1] && ins[1] < del.target[1] + (del.length || 1)\n }\n Y.utils.inDeletionRange = inDeletionRange\n\n function compareIds (id1, id2) {\n if (id1 == null || id2 == null) {\n return id1 === id2\n } else {\n return id1[0] === id2[0] && id1[1] === id2[1]\n }\n }\n Y.utils.compareIds = compareIds\n\n function matchesId (op, id) {\n if (id == null || op == null) {\n return id === op\n } else {\n if (id[0] === op.id[0]) {\n if (op.content == null) {\n return id[1] === op.id[1]\n } else {\n return id[1] >= op.id[1] && id[1] < op.id[1] + op.content.length\n }\n }\n }\n }\n Y.utils.matchesId = matchesId\n\n function getLastId (op) {\n if (op.content == null || op.content.length === 1) {\n return op.id\n } else {\n return [op.id[0], op.id[1] + op.content.length - 1]\n }\n }\n Y.utils.getLastId = getLastId\n\n function createEmptyOpsArray (n) {\n var a = new Array(n)\n for (var i = 0; i < a.length; i++) {\n a[i] = {\n id: [null, null]\n }\n }\n return a\n }\n\n function createSmallLookupBuffer (Store) {\n /*\n This buffer implements a very small buffer that temporarily stores operations\n after they are read / before they are written.\n The buffer basically implements FIFO. Often requested lookups will be re-queued every time they are looked up / written.\n\n It can speed up lookups on Operation Stores and State Stores. But it does not require notable use of memory or processing power.\n\n Good for os and ss, bot not for ds (because it often uses methods that require a flush)\n\n I tried to optimize this for performance, therefore no highlevel operations.\n */\n class SmallLookupBuffer extends Store {\n constructor (arg1, arg2) {\n // super(...arguments) -- do this when this is supported by stable nodejs\n super(arg1, arg2)\n this.writeBuffer = createEmptyOpsArray(5)\n this.readBuffer = createEmptyOpsArray(10)\n }\n * find (id, noSuperCall) {\n var i, r\n for (i = this.readBuffer.length - 1; i >= 0; i--) {\n r = this.readBuffer[i]\n // we don't have to use compareids, because id is always defined!\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n // found r\n // move r to the end of readBuffer\n for (; i < this.readBuffer.length - 1; i++) {\n this.readBuffer[i] = this.readBuffer[i + 1]\n }\n this.readBuffer[this.readBuffer.length - 1] = r\n return r\n }\n }\n var o\n for (i = this.writeBuffer.length - 1; i >= 0; i--) {\n r = this.writeBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n o = r\n break\n }\n }\n if (i < 0 && noSuperCall === undefined) {\n // did not reach break in last loop\n // read id and put it to the end of readBuffer\n o = yield* super.find(id)\n }\n if (o != null) {\n for (i = 0; i < this.readBuffer.length - 1; i++) {\n this.readBuffer[i] = this.readBuffer[i + 1]\n }\n this.readBuffer[this.readBuffer.length - 1] = o\n }\n return o\n }\n * put (o) {\n var id = o.id\n var i, r // helper variables\n for (i = this.writeBuffer.length - 1; i >= 0; i--) {\n r = this.writeBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n // is already in buffer\n // forget r, and move o to the end of writeBuffer\n for (; i < this.writeBuffer.length - 1; i++) {\n this.writeBuffer[i] = this.writeBuffer[i + 1]\n }\n this.writeBuffer[this.writeBuffer.length - 1] = o\n break\n }\n }\n if (i < 0) {\n // did not reach break in last loop\n // write writeBuffer[0]\n var write = this.writeBuffer[0]\n if (write.id[0] !== null) {\n yield* super.put(write)\n }\n // put o to the end of writeBuffer\n for (i = 0; i < this.writeBuffer.length - 1; i++) {\n this.writeBuffer[i] = this.writeBuffer[i + 1]\n }\n this.writeBuffer[this.writeBuffer.length - 1] = o\n }\n // check readBuffer for every occurence of o.id, overwrite if found\n // whether found or not, we'll append o to the readbuffer\n for (i = 0; i < this.readBuffer.length - 1; i++) {\n r = this.readBuffer[i + 1]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n this.readBuffer[i] = o\n } else {\n this.readBuffer[i] = r\n }\n }\n this.readBuffer[this.readBuffer.length - 1] = o\n }\n * delete (id) {\n var i, r\n for (i = 0; i < this.readBuffer.length; i++) {\n r = this.readBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n this.readBuffer[i] = {\n id: [null, null]\n }\n }\n }\n yield* this.flush()\n yield* super.delete(id)\n }\n * findWithLowerBound (id) {\n var o = yield* this.find(id, true)\n if (o != null) {\n return o\n } else {\n yield* this.flush()\n return yield* super.findWithLowerBound.apply(this, arguments)\n }\n }\n * findWithUpperBound (id) {\n var o = yield* this.find(id, true)\n if (o != null) {\n return o\n } else {\n yield* this.flush()\n return yield* super.findWithUpperBound.apply(this, arguments)\n }\n }\n * findNext () {\n yield* this.flush()\n return yield* super.findNext.apply(this, arguments)\n }\n * findPrev () {\n yield* this.flush()\n return yield* super.findPrev.apply(this, arguments)\n }\n * iterate () {\n yield* this.flush()\n yield* super.iterate.apply(this, arguments)\n }\n * flush () {\n for (var i = 0; i < this.writeBuffer.length; i++) {\n var write = this.writeBuffer[i]\n if (write.id[0] !== null) {\n yield* super.put(write)\n this.writeBuffer[i] = {\n id: [null, null]\n }\n }\n }\n }\n }\n return SmallLookupBuffer\n }\n Y.utils.createSmallLookupBuffer = createSmallLookupBuffer\n\n // Generates a unique id, for use as a user id.\n // Thx to @jed for this script https://gist.github.com/jed/982883\n function generateGuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,generateGuid)} // eslint-disable-line\n Y.utils.generateGuid = generateGuid\n}\n","/* @flow */\n'use strict'\n\nrequire('./Connector.js')(Y)\nrequire('./Database.js')(Y)\nrequire('./Transaction.js')(Y)\nrequire('./Struct.js')(Y)\nrequire('./Utils.js')(Y)\nrequire('./Connectors/Test.js')(Y)\n\nY.debug = require('debug')\n\nvar requiringModules = {}\n\nmodule.exports = Y\nY.requiringModules = requiringModules\n\nY.extend = function (name, value) {\n if (arguments.length === 2 && typeof name === 'string') {\n if (value instanceof Y.utils.CustomTypeDefinition) {\n Y[name] = value.parseArguments\n } else {\n Y[name] = value\n }\n if (requiringModules[name] != null) {\n requiringModules[name].resolve()\n delete requiringModules[name]\n }\n } else {\n for (var i = 0; i < arguments.length; i++) {\n var f = arguments[i]\n if (typeof f === 'function') {\n f(Y)\n } else {\n throw new Error('Expected function!')\n }\n }\n }\n}\n\nY.requestModules = requestModules\nfunction requestModules (modules) {\n var sourceDir\n if (Y.sourceDir === null) {\n sourceDir = null\n } else {\n sourceDir = Y.sourceDir || '/bower_components'\n }\n // determine if this module was compiled for es5 or es6 (y.js vs. y.es6)\n // if Insert.execute is a Function, then it isnt a generator..\n // then load the es5(.js) files..\n var extention = typeof regeneratorRuntime !== 'undefined' ? '.js' : '.es6'\n var promises = []\n for (var i = 0; i < modules.length; i++) {\n var module = modules[i].split('(')[0]\n var modulename = 'y-' + module.toLowerCase()\n if (Y[module] == null) {\n if (requiringModules[module] == null) {\n // module does not exist\n if (typeof window !== 'undefined' && window.Y !== 'undefined') {\n if (sourceDir != null) {\n var imported = document.createElement('script')\n imported.src = sourceDir + '/' + modulename + '/' + modulename + extention\n document.head.appendChild(imported)\n }\n let requireModule = {}\n requiringModules[module] = requireModule\n requireModule.promise = new Promise(function (resolve) {\n requireModule.resolve = resolve\n })\n promises.push(requireModule.promise)\n } else {\n console.info('YJS: Please do not depend on automatic requiring of modules anymore! Extend modules as follows `require(\\'y-modulename\\')(Y)`')\n require(modulename)(Y)\n }\n } else {\n promises.push(requiringModules[modules[i]].promise)\n }\n }\n }\n return Promise.all(promises)\n}\n\n/* ::\ntype MemoryOptions = {\n name: 'memory'\n}\ntype IndexedDBOptions = {\n name: 'indexeddb',\n namespace: string\n}\ntype DbOptions = MemoryOptions | IndexedDBOptions\n\ntype WebRTCOptions = {\n name: 'webrtc',\n room: string\n}\ntype WebsocketsClientOptions = {\n name: 'websockets-client',\n room: string\n}\ntype ConnectionOptions = WebRTCOptions | WebsocketsClientOptions\n\ntype YOptions = {\n connector: ConnectionOptions,\n db: DbOptions,\n types: Array,\n sourceDir: string,\n share: {[key: string]: TypeName}\n}\n*/\n\nfunction Y (opts/* :YOptions */) /* :Promise */ {\n if (opts.hasOwnProperty('sourceDir')) {\n Y.sourceDir = opts.sourceDir\n }\n opts.types = opts.types != null ? opts.types : []\n var modules = [opts.db.name, opts.connector.name].concat(opts.types)\n for (var name in opts.share) {\n modules.push(opts.share[name])\n }\n return new Promise(function (resolve, reject) {\n if (opts == null) reject('An options object is expected! ')\n else if (opts.connector == null) reject('You must specify a connector! (missing connector property)')\n else if (opts.connector.name == null) reject('You must specify connector name! (missing connector.name property)')\n else if (opts.db == null) reject('You must specify a database! (missing db property)')\n else if (opts.connector.name == null) reject('You must specify db name! (missing db.name property)')\n else {\n opts = Y.utils.copyObject(opts)\n opts.connector = Y.utils.copyObject(opts.connector)\n opts.db = Y.utils.copyObject(opts.db)\n opts.share = Y.utils.copyObject(opts.share)\n setTimeout(function () {\n Y.requestModules(modules).then(function () {\n var yconfig = new YConfig(opts)\n yconfig.db.whenUserIdSet(function () {\n yconfig.init(function () {\n resolve(yconfig)\n })\n })\n }).catch(reject)\n }, 0)\n }\n })\n}\n\nclass YConfig {\n /* ::\n db: Y.AbstractDatabase;\n connector: Y.AbstractConnector;\n share: {[key: string]: any};\n options: Object;\n */\n constructor (opts, callback) {\n this.options = opts\n this.db = new Y[opts.db.name](this, opts.db)\n this.connector = new Y[opts.connector.name](this, opts.connector)\n this.connected = true\n }\n init (callback) {\n var opts = this.options\n var share = {}\n this.share = share\n this.db.requestTransaction(function * requestTransaction () {\n // create shared object\n for (var propertyname in opts.share) {\n var typeConstructor = opts.share[propertyname].split('(')\n var typeName = typeConstructor.splice(0, 1)\n var type = Y[typeName]\n var typedef = type.typeDefinition\n var id = ['_', typedef.struct + '_' + typeName + '_' + propertyname + '_' + typeConstructor]\n var args = []\n if (typeConstructor.length === 1) {\n try {\n args = JSON.parse('[' + typeConstructor[0].split(')')[0] + ']')\n } catch (e) {\n throw new Error('Was not able to parse type definition! (share.' + propertyname + ')')\n }\n if (type.typeDefinition.parseArguments == null) {\n throw new Error(typeName + ' does not expect arguments!')\n } else {\n args = typedef.parseArguments(args[0])[1]\n }\n }\n share[propertyname] = yield* this.store.initType.call(this, id, args)\n }\n this.store.whenTransactionsFinished()\n .then(callback)\n })\n }\n isConnected () {\n return this.connector.isSynced\n }\n disconnect () {\n if (this.connected) {\n this.connected = false\n return this.connector.disconnect()\n } else {\n return Promise.resolve()\n }\n }\n reconnect () {\n if (!this.connected) {\n this.connected = true\n return this.connector.reconnect()\n } else {\n return Promise.resolve()\n }\n }\n destroy () {\n var self = this\n return this.close().then(function () {\n if (self.db.deleteDB != null) {\n return self.db.deleteDB()\n } else {\n return Promise.resolve()\n }\n })\n }\n close () {\n var self = this\n this.share = null\n if (this.connector.destroy != null) {\n this.connector.destroy()\n } else {\n this.connector.disconnect()\n }\n return this.db.whenTransactionsFinished(function () {\n this.db.destroyTypes()\n // make sure to wait for all transactions before destroying the db\n this.db.requestTransaction(function * () {\n yield* self.db.destroy()\n })\n return this.db.whenTransactionsFinished()\n })\n }\n}\n"]} \ No newline at end of file diff --git a/y.js b/y.js index aa754e97..677e975f 100644 --- a/y.js +++ b/y.js @@ -1,10 +1,10 @@ /** * yjs - A framework for real-time p2p shared editing on any data - * @version v12.3.1 + * @version v12.3.2 * @link http://y-js.org * @license MIT */ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.Y=e()}}(function(){return function e(t,r,n){function i(s,o){if(!r[s]){if(!t[s]){var u="function"==typeof require&&require;if(!o&&u)return u(s,!0);if(a)return a(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=r[s]={exports:{}};t[s][0].call(l.exports,function(e){var r=t[s][1][e];return i(r||e)},l,l.exports,e,t,r,n)}return r[s].exports}for(var a="function"==typeof require&&require,s=0;s=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function a(e){var t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+r.humanize(this.diff),t){var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var i=0,a=0;e[0].replace(/%[a-zA-Z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(a=i))}),e.splice(a,0,n)}}function s(){return"object"===("undefined"==typeof console?"undefined":c(console))&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function o(e){try{null==e?r.storage.removeItem("debug"):r.storage.debug=e}catch(e){}}function u(){var e;try{e=r.storage.debug}catch(e){}return!e&&void 0!==n&&"env"in n&&(e=n.env.DEBUG),e}var c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};r=t.exports=e("./debug"),r.log=s,r.formatArgs=a,r.save=o,r.load=u,r.useColors=i,r.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],r.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},r.enable(u())}).call(this,e("_process"))},{"./debug":2,_process:4}],2:[function(e,t,r){"use strict";function n(e){var t,n=0;for(t in e)n=(n<<5)-n+e.charCodeAt(t),n|=0;return r.colors[Math.abs(n)%r.colors.length]}function i(e){function t(){if(t.enabled){var e=t,n=+new Date,i=n-(c||n);e.diff=i,e.prev=c,e.curr=n,c=n;for(var a=new Array(arguments.length),s=0;s100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*f;case"days":case"day":case"d":return r*d;case"hours":case"hour":case"hrs":case"hr":case"h":return r*l;case"minutes":case"minute":case"mins":case"min":case"m":return r*c;case"seconds":case"second":case"secs":case"sec":case"s":return r*u;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function i(e){return e>=d?Math.round(e/d)+"d":e>=l?Math.round(e/l)+"h":e>=c?Math.round(e/c)+"m":e>=u?Math.round(e/u)+"s":e+"ms"}function a(e){return s(e,d,"day")||s(e,l,"hour")||s(e,c,"minute")||s(e,u,"second")||e+" ms"}function s(e,t,r){if(!(e0)return n(e);if("number"===r&&!1===isNaN(e))return t.long?a(e):i(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],4:[function(e,t,r){function n(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function a(e){if(d===setTimeout)return setTimeout(e,0);if((d===n||!d)&&setTimeout)return d=setTimeout,setTimeout(e,0);try{return d(e,0)}catch(t){try{return d.call(null,e,0)}catch(t){return d.call(this,e,0)}}}function s(e){if(f===clearTimeout)return clearTimeout(e);if((f===i||!f)&&clearTimeout)return f=clearTimeout,clearTimeout(e);try{return f(e)}catch(t){try{return f.call(null,e)}catch(t){return f.call(this,e)}}}function o(){y&&p&&(y=!1,p.length?g=p.concat(g):b=-1,g.length&&u())}function u(){if(!y){var e=a(o);y=!0;for(var t=g.length;t;){for(p=g,g=[];++b1)for(var r=1;r=0;--n){var i=this.tryEntries[n],a=i.completion;if("root"===i.tryLoc)return t("end");if(i.tryLoc<=this.prev){var s=v.call(i,"catchLoc"),o=v.call(i,"finallyLoc");if(s&&o){if(this.prev=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&v.call(n,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),h(r),T}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;h(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:g(e),resultName:t,nextLoc:r},T}}}("object"==typeof r?r:"object"==typeof window?window:"object"==typeof self?self:this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:4}],6:[function(e,t,r){"use strict";console.warn("The regenerator/runtime module is deprecated; please import regenerator-runtime/runtime instead."),t.exports=e("regenerator-runtime/runtime")},{"regenerator-runtime/runtime":5}],7:[function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){return"read"===e||"write"===e}function a(e){return"write"===e}var s=function(){function e(e,t){for(var r=0;r0&&(n.broadcast({type:"update",ops:n.broadcastOpBuffer}),n.broadcastOpBuffer=[])}t=t.map(function(t){return e.Struct[t.struct].encode(t)});var n=this;0===this.broadcastOpBuffer.length?(this.broadcastOpBuffer=t,this.y.db.transactionInProgress?this.y.db.whenTransactionsFinished().then(r):setTimeout(r,0)):this.broadcastOpBuffer=this.broadcastOpBuffer.concat(t)}},{key:"receiveMessage",value:function(e,t){var r=this;if(e===this.userId)return Promise.resolve();if(this.log("Receive '%s' from %s",t.type,e),this.logMessage("Message: %j",t),null!=t.protocolVersion&&t.protocolVersion!==this.protocolVersion)return this.log("You tried to sync with a yjs instance that has a different protocol version\n (You: "+this.protocolVersion+", Client: "+t.protocolVersion+").\n The sync was stopped. You need to upgrade your dependencies (especially Yjs & the Connector)!\n "),this.send(e,{type:"sync stop",protocolVersion:this.protocolVersion}),Promise.reject("Incompatible protocol version");if(null!=t.auth&&null!=this.connections[e]){var n=this.checkAuth(t.auth,this.y,e);this.connections[e].auth=n,n.then(function(t){var n=!0,i=!1,a=void 0;try{for(var s,o=r.userEventListeners[Symbol.iterator]();!(n=(s=o.next()).done);n=!0){(0,s.value)({action:"userAuthenticated",user:e,auth:t})}}catch(e){i=!0,a=e}finally{try{!n&&o.return&&o.return()}finally{if(i)throw a}}})}else null!=this.connections[e]&&null==this.connections[e].auth&&(this.connections[e].auth=this.checkAuth(null,this.y,e));return null!=this.connections[e]&&null!=this.connections[e].auth?this.connections[e].auth.then(function(n){if("sync step 1"===t.type&&i(n)){var s=r,o=t;r.y.db.requestTransaction(regeneratorRuntime.mark(function r(){var i,u,c;return regeneratorRuntime.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return r.delegateYield(this.getStateSet(),"t0",1);case 1:if(i=r.t0,!a(n)){r.next=4;break}return r.delegateYield(this.applyDeleteSet(o.deleteSet),"t1",4);case 4:return r.delegateYield(this.getDeleteSet(),"t2",5);case 5:if(u=r.t2,c={type:"sync step 2",stateSet:i,deleteSet:u,protocolVersion:this.protocolVersion,auth:this.authInfo},!0!==t.preferUntransformed||0!==Object.keys(o.stateSet).length){r.next=12;break}return r.delegateYield(this.getOperationsUntransformed(),"t3",9);case 9:c.osUntransformed=r.t3,r.next=14;break;case 12:return r.delegateYield(this.getOperations(o.stateSet),"t4",13);case 13:c.os=r.t4;case 14:s.send(e,c),this.forwardToSyncingClients?(s.syncingClients.push(e),setTimeout(function(){s.syncingClients=s.syncingClients.filter(function(t){return t!==e}),s.send(e,{type:"sync done"})},5e3)):s.send(e,{type:"sync done"});case 16:case"end":return r.stop()}},r,this)}))}else if("sync step 2"===t.type&&a(n)){var u=r.y.db,c={};c.promise=new Promise(function(e){c.resolve=e}),r.syncStep2=c.promise;var l=t;u.requestTransaction(regeneratorRuntime.mark(function e(){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.applyDeleteSet(l.deleteSet),"t0",1);case 1:if(null==l.osUntransformed){e.next=5;break}return e.delegateYield(this.applyOperationsUntransformed(l.osUntransformed,l.stateSet),"t1",3);case 3:e.next=6;break;case 5:this.store.apply(l.os);case 6:c.resolve();case 7:case"end":return e.stop()}},e,this)}))}else if("sync done"===t.type){var d=r;r.syncStep2.then(function(){d._setSyncedWith(e)})}else if("update"===t.type&&a(n)){if(r.forwardToSyncingClients){var f=!0,h=!1,p=void 0;try{for(var g,y=r.syncingClients[Symbol.iterator]();!(f=(g=y.next()).done);f=!0){var b=g.value;r.send(b,t)}}catch(e){h=!0,p=e}finally{try{!f&&y.return&&y.return()}finally{if(h)throw p}}}if(r.y.db.forwardAppliedOperations){var v=t.ops.filter(function(e){return"Delete"===e.struct});v.length>0&&r.broadcastOps(v)}r.y.db.apply(t.ops)}}):Promise.reject("Unable to deliver message")}},{key:"_setSyncedWith",value:function(e){var t=this.connections[e];null!=t&&(t.isSynced=!0),e===this.currentSyncTarget&&(this.currentSyncTarget=null,this.findNextSyncTarget())}},{key:"parseMessageFromXml",value:function(e){function t(e){var n=!0,i=!1,a=void 0;try{for(var s,o=e.children[Symbol.iterator]();!(n=(s=o.next()).done);n=!0){var u=s.value;return"true"===u.getAttribute("isArray")?t(u):r(u)}}catch(e){i=!0,a=e}finally{try{!n&&o.return&&o.return()}finally{if(i)throw a}}}function r(e){var n={};for(var i in e.attrs){var a=e.attrs[i],s=parseInt(a,10);isNaN(s)||""+s!==a?n[i]=a:n[i]=s}for(var o in e.children){var u=o.name;"true"===o.getAttribute("isArray")?n[u]=t(o):n[u]=r(o)}return n}r(e)}},{key:"encodeMessageToXml",value:function(e,t){function r(e,t){for(var i in t){var a=t[i];null==i||(a.constructor===Object?r(e.c(i),a):a.constructor===Array?n(e.c(i),a):e.setAttribute(i,a))}}function n(e,t){e.setAttribute("isArray","true");var i=!0,a=!1,s=void 0;try{for(var o,u=t[Symbol.iterator]();!(i=(o=u.next()).done);i=!0){var c=o.value;c.constructor===Object?r(e.c("array-element"),c):n(e.c("array-element"),c)}}catch(e){a=!0,s=e}finally{try{!i&&u.return&&u.return()}finally{if(a)throw s}}}if(t.constructor===Object)r(e.c("y",{xmlns:"http://y.ninja/connector-stanza"}),t);else{if(t.constructor!==Array)throw new Error("I can't encode this json!");n(e.c("y",{xmlns:"http://y.ninja/connector-stanza"}),t)}}}]),t}();e.AbstractConnector=t}},{}],8:[function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var s=function(){function e(e,t){for(var r=0;r0){i=!0;break}i&&e.push(r)}if(e.length>0){var s=getRandom(e),o=t.buffers[s],u=getRandom(Object.keys(o)),c=o[u].shift();0===o[u].length&&delete o[u];var l=t.users[s];return l.receiveMessage(c[0],c[1]).then(function(){return l.y.db.whenTransactionsFinished()},function(){})}return!1},flushAll:function(){return new Promise(function(e){function r(){var n=t.flushOne();if(n){for(;n;)n=t.flushOne();t.whenTransactionsFinished().then(r)}else n=t.flushOne(),n?n.then(function(){t.whenTransactionsFinished().then(r)}):e()}t.whenTransactionsFinished().then(r)})}};e.utils.globalRoom=t;var r=0,u=function(u){function c(e,a){if(n(this,c),void 0===a)throw new Error("Options must not be undefined!");a.role="master",a.forwardToSyncingClients=!1;var s=i(this,(c.__proto__||Object.getPrototypeOf(c)).call(this,e,a));return s.setUserId(r+++"").then(function(){t.addUser(s)}),s.globalRoom=t,s.syncingClientDuration=0,s}return a(c,u),s(c,[{key:"receiveMessage",value:function(e,t){return o(c.prototype.__proto__||Object.getPrototypeOf(c.prototype),"receiveMessage",this).call(this,e,JSON.parse(JSON.stringify(t)))}},{key:"send",value:function(e,r){var n=t.buffers[e];null!=n&&(null==n[this.userId]&&(n[this.userId]=[]),n[this.userId].push(JSON.parse(JSON.stringify([this.userId,r]))))}},{key:"broadcast",value:function(e){for(var r in t.buffers){var n=t.buffers[r];null==n[this.userId]&&(n[this.userId]=[]),n[this.userId].push(JSON.parse(JSON.stringify([this.userId,e])))}}},{key:"isDisconnected",value:function(){return null==t.users[this.userId]}},{key:"reconnect",value:function(){return this.isDisconnected()&&(t.addUser(this),o(c.prototype.__proto__||Object.getPrototypeOf(c.prototype),"reconnect",this).call(this)),e.utils.globalRoom.flushAll()}},{key:"disconnect",value:function(){var e=Promise.resolve();this.isDisconnected()||(t.removeUser(this.userId),e=o(c.prototype.__proto__||Object.getPrototypeOf(c.prototype),"disconnect",this).call(this));var r=this;return e.then(function(){return r.y.db.whenTransactionsFinished()})}},{key:"flush",value:function(){var e=this;return async(regeneratorRuntime.mark(function r(){var n,i,a;return regeneratorRuntime.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:n=t.buffers[e.userId];case 1:if(!(Object.keys(n).length>0)){r.next=9;break}return i=getRandom(Object.keys(n)),a=n[i].shift(),0===n[i].length&&delete n[i],r.next=7,this.receiveMessage(a[0],a[1]);case 7:r.next=1;break;case 9:return r.next=11,e.whenTransactionsFinished();case 11:case"end":return r.stop()}},r,this)}))}}]),c}(e.AbstractConnector);e.Test=u}},{}],9:[function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function e(e,t){for(var r=0;r0||a.gc2.length>0?(a.y.connector.isSynced||console.warn("gc should be empty when not synced!"),new Promise(function(e){a.requestTransaction(regeneratorRuntime.mark(function t(){var r,n;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(null==a.y.connector||!a.y.connector.isSynced){t.next=10;break}r=0;case 2:if(!(r0&&(a.gcInterval=setTimeout(i,a.gcTimeout)),e();case 12:case"end":return t.stop()}},t,this)}))})):(a.gcTimeout>0&&(a.gcInterval=setTimeout(i,a.gcTimeout)),Promise.resolve())})}n(this,t),this.y=e,this.dbOpts=r;var a=this;this.userId=null;var s;this.userIdPromise=new Promise(function(e){s=e}),this.userIdPromise.resolve=s,this.forwardAppliedOperations=!1,this.listenersById={},this.listenersByIdExecuteNow=[],this.listenersByIdRequestPending=!1,this.initializedTypes={},this.waitingTransactions=[],this.transactionInProgress=!1,this.transactionIsFlushed=!1,"undefined"!=typeof YConcurrency_TestingMode&&(this.executeOrder=[]),this.gc1=[],this.gc2=[],this.garbageCollect=i,this.startGarbageCollector(),this.repairCheckInterval=r.repairCheckInterval?r.repairCheckInterval:6e3,this.opsReceivedTimestamp=new Date,this.startRepairCheck()}return i(t,[{key:"startGarbageCollector",value:function(){this.gc=null==this.dbOpts.gc||this.dbOpts.gc,this.gc?this.gcTimeout=this.dbOpts.gcTimeout?this.dbOpts.gcTimeout:5e4:this.gcTimeout=-1,this.gcTimeout>0&&this.garbageCollect()}},{key:"startRepairCheck",value:function(){var e=this;this.repairCheckInterval>0&&(this.repairCheckIntervalHandler=setInterval(function(){new Date-e.opsReceivedTimestamp>e.repairCheckInterval&&Object.keys(e.listenersById).length>0&&(e.listenersById={},e.opsReceivedTimestamp=new Date,e.y.connector.repair())},this.repairCheckInterval))}},{key:"stopRepairCheck",value:function(){clearInterval(this.repairCheckIntervalHandler)}},{key:"queueGarbageCollector",value:function(e){this.y.connector.isSynced&&this.gc&&this.gc1.push(e)}},{key:"emptyGarbageCollector",value:function(){var e=this;return new Promise(function(t){var r=function r(){e.gc1.length>0||e.gc2.length>0?e.garbageCollect().then(r):t()};setTimeout(r,0)})}},{key:"addToDebug",value:function(){if("undefined"!=typeof YConcurrency_TestingMode){var e=Array.prototype.map.call(arguments,function(e){return"string"==typeof e?e:JSON.stringify(e)}).join("").replace(/"/g,"'").replace(/,/g,", ").replace(/:/g,": ");this.executeOrder.push(e)}}},{key:"getDebugData",value:function(){console.log(this.executeOrder.join("\n"))}},{key:"stopGarbageCollector",value:function(){var e=this;return this.gc=!1,this.gcTimeout=-1,new Promise(function(t){e.requestTransaction(regeneratorRuntime.mark(function r(){var n,i,a;return regeneratorRuntime.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:n=e.gc1.concat(e.gc2),e.gc1=[],e.gc2=[],i=0;case 4: -if(!(i1)){e.next=10;break}return e.delegateYield(this.getInsertionCleanStart([t.id[0],t.id[1]+1]),"t0",8);case 8:t=e.t0,n=!0;case 10:if(!n){e.next=15;break}return t.gc=!0,e.delegateYield(this.setOperation(t),"t1",13);case 13:return this.store.queueGarbageCollector(t.id),e.abrupt("return",!0);case 15:return e.abrupt("return",!1);case 16:case"end":return e.stop()}},e,this)})},{key:"removeFromGarbageCollector",value:function(t){function r(r){return!e.utils.compareIds(r,t.id)}this.gc1=this.gc1.filter(r),this.gc2=this.gc2.filter(r),delete t.gc}},{key:"destroyTypes",value:function(){for(var e in this.initializedTypes){var t=this.initializedTypes[e];null!=t._destroy?t._destroy():console.error("The type you included does not provide destroy functionality, it will remain in memory (updating your packages will help).")}}},{key:"destroy",value:regeneratorRuntime.mark(function e(){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:clearInterval(this.gcInterval),this.gcInterval=null,this.stopRepairCheck();case 3:case"end":return e.stop()}},e,this)})},{key:"setUserId",value:function(e){if(!this.userIdPromise.inProgress){this.userIdPromise.inProgress=!0;var t=this;t.requestTransaction(regeneratorRuntime.mark(function r(){var n;return regeneratorRuntime.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return t.userId=e,r.delegateYield(this.getState(e),"t0",2);case 2:n=r.t0,t.opClock=n.clock,t.userIdPromise.resolve(e);case 5:case"end":return r.stop()}},r,this)}))}return this.userIdPromise}},{key:"whenUserIdSet",value:function(e){this.userIdPromise.then(e)}},{key:"getNextOpId",value:function(e){if(null==e)throw new Error("getNextOpId expects the number of created ids to create!");if(null==this.userId)throw new Error("OperationStore not yet initialized!");var t=[this.userId,this.opClock];return this.opClock+=e,t}},{key:"apply",value:function(t){this.opsReceivedTimestamp=new Date;for(var r=0;r0)for(var r={op:t,missing:e.length},n=0;n1)){r.next=84;break}return r.delegateYield(this.getInsertionCleanEnd(p.id),"t16",83);case 83:p=r.t16;case 84:this.store.removeFromGarbageCollector(p);case 85:return r.delegateYield(this.setOperation(p),"t17",86);case 86:if(null==n.parentSub){r.next=96;break}if(null!=h){r.next=90;break}return c.map[n.parentSub]=n.id,r.delegateYield(this.setOperation(c),"t18",90);case 90:if(null==n.right){r.next=92;break}return r.delegateYield(this.deleteOperation(n.right,1,!0),"t19",92);case 92:if(null==n.left){r.next=94;break}return r.delegateYield(this.deleteOperation(n.id,1,!0),"t20",94);case 94:r.next=100;break;case 96:if(null!=p&&null!=h){r.next=100;break}return null==p&&(c.end=e.utils.getLastId(n)),null==h&&(c.start=n.id),r.delegateYield(this.setOperation(c),"t21",100);case 100:i=0;case 101:if(!(i=0&&null!=i.right)){e.next=12;break}return e.delegateYield(this.getOperation(i.right),"t1",9);case 9:i=e.t1,e.next=13;break;case 12:return e.abrupt("break",15);case 13:e.next=5;break;case 15:return e.abrupt("return",n);case 16:case"end":return e.stop()}},e,this)}),map:regeneratorRuntime.mark(function e(t,r){var n,i;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=t.start,n=[];case 2:if(null==t){e.next=9;break}return e.delegateYield(this.getOperation(t),"t0",4);case 4:i=e.t0,i.deleted||n.push(r(i)),t=i.right,e.next=2;break;case 9:return e.abrupt("return",n);case 10:case"end":return e.stop()}},e,this)})},Map:{create:function(e){return{id:e,map:{},struct:"Map"}},encode:function(e){var t={struct:"Map",type:e.type,id:e.id,map:{}};return null!=e.requires&&(t.requires=e.requires),null!=e.info&&(t.info=e.info),t},requiredOps:function(){return[]},execute:regeneratorRuntime.mark(function e(){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}},e,this)}),get:regeneratorRuntime.mark(function e(t,r){var n,i;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(null==(n=t.map[r])){e.next=14;break}return e.delegateYield(this.getOperation(n),"t0",3);case 3:if(null!=(i=e.t0)&&!i.deleted){e.next=8;break}return e.abrupt("return",void 0);case 8:if(null!=i.opContent){e.next=12;break}return e.abrupt("return",i.content[0]);case 12:return e.delegateYield(this.getType(i.opContent),"t1",13);case 13:return e.abrupt("return",e.t1);case 14:case"end":return e.stop()}},e,this)})}};e.Struct=t}},{}],11:[function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function e(e,t){for(var r=0;r0&&this.store.y.connector.broadcastOps(n);case 10:case"end":return t.stop()}},t,this)})},{key:"deleteList",value:regeneratorRuntime.mark(function e(t){var r;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(null==t){e.next=15;break}return e.delegateYield(this.getOperation(t),"t0",2);case 2:if(t=e.t0,t.gc){e.next=12;break}return t.gc=!0,t.deleted=!0,e.delegateYield(this.setOperation(t),"t1",7);case 7:return r=null!=t.content?t.content.length:1,e.delegateYield(this.markDeleted(t.id,r),"t2",9);case 9:if(null==t.opContent){e.next=11;break}return e.delegateYield(this.deleteOperation(t.opContent),"t3",11);case 11:this.store.queueGarbageCollector(t.id);case 12:t=t.right,e.next=0;break;case 15:case"end":return e.stop()}},e,this)})},{key:"deleteOperation",value:regeneratorRuntime.mark(function e(t,r,n){var i,a,s,o,u,c,l;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return null==r&&(r=1),e.delegateYield(this.markDeleted(t,r),"t0",2);case 2:if(!(r>0)){e.next=64;break}return i=!1,e.delegateYield(this.os.findWithUpperBound([t[0],t[1]+r-1]),"t1",5);case 5:if(a=e.t1,s=null!=a&&null!=a.content?a.content.length:1,!(null==a||a.id[0]!==t[0]||a.id[1]+s<=t[1])){e.next=12;break}a=null,r=0,e.next=22;break;case 12:if(a.deleted){e.next=21;break}if(!(a.id[1]t[1]+r)){e.next=21;break}return e.delegateYield(this.getInsertionCleanEnd([t[0],t[1]+r-1]),"t3",19);case 19:a=e.t3,s=a.content.length;case 21:r=a.id[1]-t[1];case 22:if(null==a){e.next=62;break}if(a.deleted){e.next=44;break}if(i=!0,a.deleted=!0,null==a.start){e.next=28;break}return e.delegateYield(this.deleteList(a.start),"t4",28);case 28:if(null==a.map){e.next=35;break}e.t5=regeneratorRuntime.keys(a.map);case 30:if((e.t6=e.t5()).done){e.next=35;break}return o=e.t6.value,e.delegateYield(this.deleteList(a.map[o]),"t7",33);case 33:e.next=30;break;case 35:if(null==a.opContent){e.next=37;break}return e.delegateYield(this.deleteOperation(a.opContent),"t8",37);case 37:if(null==a.requires){e.next=44;break}u=0;case 39:if(!(u0)){e.next=20;break}if(n.gc){e.next=11;break}n.len+=i,e.next=18;break;case 11:if(!((i=n.id[1]+n.len-t[1])=a.id[1])){e.next=61;break}i=n.id[1]+n.len-a.id[1];case 33:if(!(i>=0)){e.next=61;break}if(!a.gc){e.next=44;break}if(n.len-=i,!(i>=a.len)){e.next=41;break}if(!((i-=a.len)>0)){e.next=41;break}return e.delegateYield(this.ds.put(n),"t5",40);case 40:return e.delegateYield(this.markDeleted([a.id[0],a.id[1]+a.len],i),"t6",41);case 41:return e.abrupt("break",61);case 44:if(!(i>a.len)){e.next=56;break}return e.delegateYield(this.ds.findNext(a.id),"t7",46);case 46:return s=e.t7,e.delegateYield(this.ds.delete(a.id),"t8",48);case 48:if(null!=s&&n.id[0]===s.id[0]){e.next=52;break}return e.abrupt("break",61);case 52:a=s,i=n.id[1]+n.len-a.id[1];case 54:e.next=59;break;case 56:return n.len+=a.len-i,e.delegateYield(this.ds.delete(a.id),"t9",58);case 58:return e.abrupt("break",61);case 59:e.next=33;break;case 61:return e.delegateYield(this.ds.put(n),"t10",62);case 62:return e.abrupt("return",n);case 63:case"end":return e.stop()}},e,this)})},{key:"garbageCollectAfterSync",value:regeneratorRuntime.mark(function e(){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((this.store.gc1.length>0||this.store.gc2.length>0)&&console.warn("gc should be empty after sync"),this.store.gc){e.next=3;break}return e.abrupt("return");case 3:return e.delegateYield(this.os.iterate(this,null,null,regeneratorRuntime.mark(function e(t){var r,n,i;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.gc){e.next=3;break}return delete t.gc,e.delegateYield(this.setOperation(t),"t0",3);case 3:if(null==t.parent){e.next=23;break}return e.delegateYield(this.isDeleted(t.parent),"t1",5);case 5:if(!(r=e.t1)){e.next=23;break}if(t.gc=!0,t.deleted){e.next=20;break}return e.delegateYield(this.markDeleted(t.id,null!=t.content?t.content.length:1),"t2",10);case 10:if(t.deleted=!0,null==t.opContent){e.next=13;break}return e.delegateYield(this.deleteOperation(t.opContent),"t3",13);case 13:if(null==t.requires){e.next=20;break}n=0;case 15:if(!(n0)){t.next=60;break}c=n.left,l=null;case 39:if(null==c){t.next=47;break}return t.delegateYield(this.getInsertion(c),"t11",41);case 41:if(l=t.t11,!l.deleted){t.next=44;break}return t.abrupt("break",47);case 44:c=l.left,t.next=39;break;case 47:t.t12=regeneratorRuntime.keys(n.originOf);case 48:if((t.t13=t.t12()).done){t.next=57;break}return d=t.t13.value,t.delegateYield(this.getOperation(n.originOf[d]),"t14",51);case 51:if(null==(f=t.t14)){t.next=55;break}return f.origin=c,t.delegateYield(this.setOperation(f),"t15",55);case 55:t.next=48;break;case 57:if(null==c){t.next=60;break}return null==l.originOf?l.originOf=n.originOf:l.originOf=n.originOf.concat(l.originOf),t.delegateYield(this.setOperation(l),"t16",60);case 60:if(null==n.origin){t.next=65;break}return t.delegateYield(this.getInsertion(n.origin),"t17",62);case 62:return h=t.t17,h.originOf=h.originOf.filter(function(t){return!e.utils.compareIds(r,t)}),t.delegateYield(this.setOperation(h),"t18",65);case 65:if(null==n.parent){t.next=68;break}return t.delegateYield(this.getOperation(n.parent),"t19",67);case 67:p=t.t19;case 68:if(null==p){t.next=73;break}if(g=!1,null!=n.parentSub?e.utils.compareIds(p.map[n.parentSub],n.id)&&(g=!0,null!=n.right?p.map[n.parentSub]=n.right:delete p.map[n.parentSub]):(e.utils.compareIds(p.start,n.id)&&(g=!0,p.start=n.right),e.utils.matchesId(n,p.end)&&(g=!0,p.end=n.left)),!g){t.next=73;break}return t.delegateYield(this.setOperation(p),"t20",73);case 73:return t.delegateYield(this.removeOperation(n.id),"t21",74);case 74:case"end":return t.stop()}},t,this)})},{key:"checkDeleteStoreForState",value:regeneratorRuntime.mark(function e(t){var r;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.ds.findWithUpperBound([t.user,t.clock]),"t0",1);case 1:r=e.t0,null!=r&&r.id[0]===t.user&&r.gc&&(t.clock=Math.max(t.clock,r.id[1]+r.len));case 3:case"end":return e.stop()}},e,this)})},{key:"updateState",value:regeneratorRuntime.mark(function e(t){var r,n,i;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.getState(t),"t0",1);case 1:return r=e.t0,e.delegateYield(this.checkDeleteStoreForState(r),"t1",3);case 3:return e.delegateYield(this.getInsertion([t,r.clock]),"t2",4);case 4:n=e.t2,i=null!=n&&null!=n.content?n.content.length:1;case 6:if(!(null!=n&&t===n.id[0]&&n.id[1]<=r.clock&&n.id[1]+i>r.clock)){e.next=14;break}return r.clock+=i,e.delegateYield(this.checkDeleteStoreForState(r),"t3",9);case 9:return e.delegateYield(this.os.findNext(n.id),"t4",10);case 10:n=e.t4,i=null!=n&&null!=n.content?n.content.length:1,e.next=6;break;case 14:return e.delegateYield(this.setState(r),"t5",15);case 15:case"end":return e.stop()}},e,this)})},{key:"applyDeleteSet",value:regeneratorRuntime.mark(function e(t){var r,n,i,a,s,o,u,c,l,d,f;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r=[],e.t0=regeneratorRuntime.keys(t);case 2:if((e.t1=e.t0()).done){e.next=11;break}return n=e.t1.value,i=t[n],a=0,s=i[a],e.delegateYield(this.ds.iterate(this,[n,0],[n,Number.MAX_VALUE],regeneratorRuntime.mark(function e(t){var o;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(null==s){e.next=10;break}if(o=0,!(t.id[1]+t.len<=s[0])){e.next=6;break}return e.abrupt("break",10);case 6:s[0]=u[1])){e.next=36;break}return e.delegateYield(this.os.findWithUpperBound([u[0],c-1]),"t5",20);case 20:if(null!=(l=e.t5)){e.next=23;break}return e.abrupt("break",36);case 23:if(d=null!=l.content?l.content.length:1,!(l.id[0]!==u[0]||l.id[1]+d<=u[1])){e.next=26;break}return e.abrupt("break",36);case 26:if(!(l.id[1]+d>u[1]+u[2])){e.next=29;break}return e.delegateYield(this.getInsertionCleanEnd([u[0],u[1]+u[2]-1]),"t6",28);case 28:l=e.t6;case 29:if(!(l.id[1]1)){t.next=15;break}return a=i[0],s=e.Struct[a].create(r),s.type=i[1],t.delegateYield(this.setOperation(s),"t1",12);case 12:return t.abrupt("return",s);case 15:return console.error("Unexpected case. How can this happen?"),t.abrupt("return",null);case 18:case"end":return t.stop()}},t,this)})},{key:"removeOperation",value:regeneratorRuntime.mark(function e(t){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.os.delete(t),"t0",1);case 1:case"end":return e.stop()}},e,this)})},{key:"setState",value:regeneratorRuntime.mark(function e(t){var r;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r={id:[t.user],clock:t.clock},e.delegateYield(this.ss.put(r),"t0",2);case 2:case"end":return e.stop()}},e,this)})},{key:"getState",value:regeneratorRuntime.mark(function e(t){var r,n;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.ss.find([t]),"t0",1);case 1:return r=e.t0,n=null==r?null:r.clock,null==n&&(n=0),e.abrupt("return",{user:t,clock:n});case 5:case"end":return e.stop()}},e,this)})},{key:"getStateVector",value:regeneratorRuntime.mark(function e(){var t;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],e.delegateYield(this.ss.iterate(this,null,null,regeneratorRuntime.mark(function e(r){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t.push({user:r.id[0],clock:r.clock});case 1:case"end":return e.stop()}},e,this)})),"t0",2);case 2:return e.abrupt("return",t);case 3:case"end":return e.stop()}},e,this)})},{key:"getStateSet",value:regeneratorRuntime.mark(function e(){var t;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t={},e.delegateYield(this.ss.iterate(this,null,null,regeneratorRuntime.mark(function e(r){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t[r.id[0]]=r.clock;case 1:case"end":return e.stop()}},e,this)})),"t0",2);case 2:return e.abrupt("return",t);case 3:case"end":return e.stop()}},e,this)})},{key:"getOperations",value:regeneratorRuntime.mark(function t(r){var n,i,a,s,o,u,c,l,d,f,h;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return null==r&&(r={}),n=[],t.delegateYield(this.getStateVector(),"t0",3);case 3:i=t.t0,a=!0,s=!1,o=void 0,t.prev=7,u=i[Symbol.iterator]();case 9:if(a=(c=u.next()).done){t.next=23;break}if(l=c.value,"_"!==(d=l.user)){t.next=14;break}return t.abrupt("continue",20);case 14:if(!((f=r[d]||0)>0)){t.next=19;break}return t.delegateYield(this.getInsertion([d,f]),"t1",17);case 17:h=t.t1,null!=h&&(f=h.id[1],r[d]=f);case 19:return t.delegateYield(this.os.iterate(this,[d,f],[d,Number.MAX_VALUE],regeneratorRuntime.mark(function t(i){var a,s,o,u;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=e.Struct[i.struct].encode(i),"Insert"===i.struct){t.next=5;break}n.push(i),t.next=27;break;case 5:if(!(null==i.right||i.right[1]<(r[i.right[0]]||0))){t.next=27;break}a=i,s=[i],o=i.right;case 9:if(null!=a.left){t.next=15;break}return i.left=null,n.push(i),e.utils.compareIds(a.id,i.id)||(a=e.Struct[i.struct].encode(a),a.right=s[s.length-1].id,n.push(a)),t.abrupt("break",27);case 15:return t.delegateYield(this.getInsertion(a.left),"t0",16);case 16:for(a=t.t0;s.length>0&&e.utils.matchesId(a,s[s.length-1].origin);)s.pop();if(!(a.id[1]<(r[a.id[0]]||0))){t.next=24;break}return i.left=e.utils.getLastId(a),n.push(i),t.abrupt("break",27);case 24:e.utils.matchesId(a,i.origin)?(i.left=i.origin,n.push(i),i=e.Struct[i.struct].encode(a),i.right=o,s.length>0&&console.log("This should not happen .. :( please report this"),s=[i]):(u=e.Struct[i.struct].encode(a),u.right=s[s.length-1].id,u.left=u.origin,n.push(u),s.push(a));case 25:t.next=9;break;case 27:case"end":return t.stop()}},t,this)})),"t2",20);case 20:a=!0,t.next=9;break;case 23:t.next=29;break;case 25:t.prev=25,t.t3=t.catch(7),s=!0,o=t.t3;case 29:t.prev=29,t.prev=30,!a&&u.return&&u.return();case 32:if(t.prev=32,!s){t.next=35;break}throw o;case 35:return t.finish(32);case 36:return t.finish(29);case 37:return t.abrupt("return",n.reverse());case 38:case"end":return t.stop()}},t,this,[[7,25,29,37],[30,,32,36]])})},{key:"getOperationsUntransformed",value:regeneratorRuntime.mark(function e(){var t;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],e.delegateYield(this.os.iterate(this,null,null,regeneratorRuntime.mark(function e(r){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:"_"!==r.id[0]&&t.push(r);case 1:case"end":return e.stop()}},e,this)})),"t0",2);case 2:return e.abrupt("return",{untransformed:t});case 3:case"end":return e.stop()}},e,this)})},{key:"applyOperationsUntransformed",value:regeneratorRuntime.mark(function t(r,n){var i,a,s,o,u,c;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:i=r.untransformed,a=0;case 2:if(!(a=e.id[1]&&t[1]=0)){e.next=10;break}if(a=this.readBuffer[i],a.id[1]!==r[1]||a.id[0]!==r[0]){e.next=7;break}for(;i=0)){e.next=19;break}if(a=this.writeBuffer[i],a.id[1]!==r[1]||a.id[0]!==r[0]){e.next=16;break}return s=a,e.abrupt("break",19);case 16:i--,e.next=11;break;case 19:if(!(i<0&&void 0===n)){e.next=22;break}return e.delegateYield(o(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"find",this).call(this,r),"t0",21);case 21:s=e.t0;case 22:if(null!=s){for(i=0;i=0)){e.next=11;break}if(a=this.writeBuffer[i],a.id[1]!==n[1]||a.id[0]!==n[0]){e.next=8;break}for(;i>e/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,y)}e.utils={},e.utils.bubbleEvent=function(e,t){for(e.eventHandler.callEventListeners(t),t.path=[];null!=e&&null!=e._deepEventHandler;){e._deepEventHandler.callEventListeners(t);var r=null;null!=e._parent&&(r=e.os.getType(e._parent)),null!=r&&null!=r._getPathToChild?(t.path=[r._getPathToChild(e._model)].concat(t.path),e=r):e=null}};var b=function(){function e(){a(this,e),this.eventListeners=[]}return u(e,[{key:"destroy",value:function(){this.eventListeners=null}},{key:"addEventListener",value:function(e){this.eventListeners.push(e)}},{key:"removeEventListener",value:function(e){this.eventListeners=this.eventListeners.filter(function(t){return e!==t})}},{key:"removeAllEventListeners",value:function(){this.eventListeners=[]}},{key:"callEventListeners",value:function(e){for(var t=0;t0;)for(var n=0;n0&&this.awaiting--,!(0===this.awaiting&&this.waiting.length>0)){t.next=70;break}o=0;case 7:if(!(o=0;a--){var s=this.waiting[a];"Insert"===s.struct&&(e.utils.matchesId(s,i.left)?(s.right=i.id,i.left=s.left):e.utils.compareIds(s.id,i.right)&&(s.left=e.utils.getLastId(i),i.right=s.right))}}this._tryCallEvents(t)}},{key:"awaitedDeletes",value:function(t,r){for(var n=this.waiting.splice(this.waiting.length-t),i=0;i0&&this.awaiting--,0===this.awaiting&&this.waiting.length>0){var t=[],r=[];this.waiting.forEach(function(e){"Delete"===e.struct?r.push(e):t.push(e)}),t=function(t){for(var r=[];t.length>0;)for(var n=0;n=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function a(e){var t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+r.humanize(this.diff),t){var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var i=0,a=0;e[0].replace(/%[a-zA-Z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(a=i))}),e.splice(a,0,n)}}function s(){return"object"===("undefined"==typeof console?"undefined":c(console))&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function o(e){try{null==e?r.storage.removeItem("debug"):r.storage.debug=e}catch(e){}}function u(){var e;try{e=r.storage.debug}catch(e){}return!e&&void 0!==n&&"env"in n&&(e=n.env.DEBUG),e}var c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};r=t.exports=e("./debug"),r.log=s,r.formatArgs=a,r.save=o,r.load=u,r.useColors=i,r.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],r.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},r.enable(u())}).call(this,e("_process"))},{"./debug":2,_process:4}],2:[function(e,t,r){"use strict";function n(e){var t,n=0;for(t in e)n=(n<<5)-n+e.charCodeAt(t),n|=0;return r.colors[Math.abs(n)%r.colors.length]}function i(e){function t(){if(t.enabled){var e=t,n=+new Date,i=n-(c||n);e.diff=i,e.prev=c,e.curr=n,c=n;for(var a=new Array(arguments.length),s=0;s100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*f;case"days":case"day":case"d":return r*d;case"hours":case"hour":case"hrs":case"hr":case"h":return r*l;case"minutes":case"minute":case"mins":case"min":case"m":return r*c;case"seconds":case"second":case"secs":case"sec":case"s":return r*u;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function i(e){return e>=d?Math.round(e/d)+"d":e>=l?Math.round(e/l)+"h":e>=c?Math.round(e/c)+"m":e>=u?Math.round(e/u)+"s":e+"ms"}function a(e){return s(e,d,"day")||s(e,l,"hour")||s(e,c,"minute")||s(e,u,"second")||e+" ms"}function s(e,t,r){if(!(e0)return n(e);if("number"===r&&!1===isNaN(e))return t.long?a(e):i(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],4:[function(e,t,r){function n(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function a(e){if(d===setTimeout)return setTimeout(e,0);if((d===n||!d)&&setTimeout)return d=setTimeout,setTimeout(e,0);try{return d(e,0)}catch(t){try{return d.call(null,e,0)}catch(t){return d.call(this,e,0)}}}function s(e){if(f===clearTimeout)return clearTimeout(e);if((f===i||!f)&&clearTimeout)return f=clearTimeout,clearTimeout(e);try{return f(e)}catch(t){try{return f.call(null,e)}catch(t){return f.call(this,e)}}}function o(){y&&p&&(y=!1,p.length?g=p.concat(g):b=-1,g.length&&u())}function u(){if(!y){var e=a(o);y=!0;for(var t=g.length;t;){for(p=g,g=[];++b1)for(var r=1;r=0;--n){var i=this.tryEntries[n],a=i.completion;if("root"===i.tryLoc)return t("end");if(i.tryLoc<=this.prev){var s=v.call(i,"catchLoc"),o=v.call(i,"finallyLoc");if(s&&o){if(this.prev=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&v.call(n,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),h(r),T}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;h(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:g(e),resultName:t,nextLoc:r},T}}}("object"==typeof r?r:"object"==typeof window?window:"object"==typeof self?self:this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:4}],6:[function(e,t,r){"use strict";console.warn("The regenerator/runtime module is deprecated; please import regenerator-runtime/runtime instead."),t.exports=e("regenerator-runtime/runtime")},{"regenerator-runtime/runtime":5}],7:[function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){return"read"===e||"write"===e}function a(e){return"write"===e}var s=function(){function e(e,t){for(var r=0;r0&&(n.broadcast({type:"update",ops:n.broadcastOpBuffer}),n.broadcastOpBuffer=[])}t=t.map(function(t){return e.Struct[t.struct].encode(t)});var n=this;0===this.broadcastOpBuffer.length?(this.broadcastOpBuffer=t,this.y.db.transactionInProgress?this.y.db.whenTransactionsFinished().then(r):setTimeout(r,0)):this.broadcastOpBuffer=this.broadcastOpBuffer.concat(t)}},{key:"receiveMessage",value:function(e,t){var r=this;if(e===this.userId)return Promise.resolve();if(this.log("Receive '%s' from %s",t.type,e),this.logMessage("Message: %j",t),null!=t.protocolVersion&&t.protocolVersion!==this.protocolVersion)return this.log("You tried to sync with a yjs instance that has a different protocol version\n (You: "+this.protocolVersion+", Client: "+t.protocolVersion+").\n The sync was stopped. You need to upgrade your dependencies (especially Yjs & the Connector)!\n "),this.send(e,{type:"sync stop",protocolVersion:this.protocolVersion}),Promise.reject("Incompatible protocol version");if(null!=t.auth&&null!=this.connections[e]){var n=this.checkAuth(t.auth,this.y,e);this.connections[e].auth=n,n.then(function(t){var n=!0,i=!1,a=void 0;try{for(var s,o=r.userEventListeners[Symbol.iterator]();!(n=(s=o.next()).done);n=!0){(0,s.value)({action:"userAuthenticated",user:e,auth:t})}}catch(e){i=!0,a=e}finally{try{!n&&o.return&&o.return()}finally{if(i)throw a}}})}else null!=this.connections[e]&&null==this.connections[e].auth&&(this.connections[e].auth=this.checkAuth(null,this.y,e));return null!=this.connections[e]&&null!=this.connections[e].auth?this.connections[e].auth.then(function(n){if("sync step 1"===t.type&&i(n)){var s=r,o=t;r.y.db.requestTransaction(regeneratorRuntime.mark(function t(){var r,i,u;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.delegateYield(this.getStateSet(),"t0",1);case 1:if(r=t.t0,!a(n)){t.next=4;break}return t.delegateYield(this.applyDeleteSet(o.deleteSet),"t1",4);case 4:return t.delegateYield(this.getDeleteSet(),"t2",5);case 5:return i=t.t2,u={type:"sync step 2",stateSet:r,deleteSet:i,protocolVersion:this.protocolVersion,auth:this.authInfo},t.delegateYield(this.getOperations(o.stateSet),"t3",8);case 8:u.os=t.t3,s.send(e,u),this.forwardToSyncingClients?(s.syncingClients.push(e),setTimeout(function(){s.syncingClients=s.syncingClients.filter(function(t){return t!==e}),s.send(e,{type:"sync done"})},5e3)):s.send(e,{type:"sync done"});case 11:case"end":return t.stop()}},t,this)}))}else if("sync step 2"===t.type&&a(n)){var u=r.y.db,c={};c.promise=new Promise(function(e){c.resolve=e}),r.syncStep2=c.promise;var l=t;u.requestTransaction(regeneratorRuntime.mark(function e(){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.applyDeleteSet(l.deleteSet),"t0",1);case 1:if(null==l.osUntransformed){e.next=5;break}return e.delegateYield(this.applyOperationsUntransformed(l.osUntransformed,l.stateSet),"t1",3);case 3:e.next=6;break;case 5:this.store.apply(l.os);case 6:c.resolve();case 7:case"end":return e.stop()}},e,this)}))}else if("sync done"===t.type){var d=r;r.syncStep2.then(function(){d._setSyncedWith(e)})}else if("update"===t.type&&a(n)){if(r.forwardToSyncingClients){var f=!0,h=!1,p=void 0;try{for(var g,y=r.syncingClients[Symbol.iterator]();!(f=(g=y.next()).done);f=!0){var b=g.value;r.send(b,t)}}catch(e){h=!0,p=e}finally{try{!f&&y.return&&y.return()}finally{if(h)throw p}}}if(r.y.db.forwardAppliedOperations){var v=t.ops.filter(function(e){return"Delete"===e.struct});v.length>0&&r.broadcastOps(v)}r.y.db.apply(t.ops)}}):Promise.reject("Unable to deliver message")}},{key:"_setSyncedWith",value:function(e){var t=this.connections[e];null!=t&&(t.isSynced=!0),e===this.currentSyncTarget&&(this.currentSyncTarget=null,this.findNextSyncTarget())}},{key:"parseMessageFromXml",value:function(e){function t(e){var n=!0,i=!1,a=void 0;try{for(var s,o=e.children[Symbol.iterator]();!(n=(s=o.next()).done);n=!0){var u=s.value;return"true"===u.getAttribute("isArray")?t(u):r(u)}}catch(e){i=!0,a=e}finally{try{!n&&o.return&&o.return()}finally{if(i)throw a}}}function r(e){var n={};for(var i in e.attrs){var a=e.attrs[i],s=parseInt(a,10);isNaN(s)||""+s!==a?n[i]=a:n[i]=s}for(var o in e.children){var u=o.name;"true"===o.getAttribute("isArray")?n[u]=t(o):n[u]=r(o)}return n}r(e)}},{key:"encodeMessageToXml",value:function(e,t){function r(e,t){for(var i in t){var a=t[i];null==i||(a.constructor===Object?r(e.c(i),a):a.constructor===Array?n(e.c(i),a):e.setAttribute(i,a))}}function n(e,t){e.setAttribute("isArray","true");var i=!0,a=!1,s=void 0;try{for(var o,u=t[Symbol.iterator]();!(i=(o=u.next()).done);i=!0){var c=o.value;c.constructor===Object?r(e.c("array-element"),c):n(e.c("array-element"),c)}}catch(e){a=!0,s=e}finally{try{!i&&u.return&&u.return()}finally{if(a)throw s}}}if(t.constructor===Object)r(e.c("y",{xmlns:"http://y.ninja/connector-stanza"}),t);else{if(t.constructor!==Array)throw new Error("I can't encode this json!");n(e.c("y",{xmlns:"http://y.ninja/connector-stanza"}),t)}}}]),t}();e.AbstractConnector=t}},{}],8:[function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var s=function(){function e(e,t){for(var r=0;r0){i=!0;break}i&&e.push(r)}if(e.length>0){var s=getRandom(e),o=t.buffers[s],u=getRandom(Object.keys(o)),c=o[u].shift();0===o[u].length&&delete o[u];var l=t.users[s];return l.receiveMessage(c[0],c[1]).then(function(){return l.y.db.whenTransactionsFinished()},function(){})}return!1},flushAll:function(){return new Promise(function(e){function r(){var n=t.flushOne();if(n){for(;n;)n=t.flushOne();t.whenTransactionsFinished().then(r)}else n=t.flushOne(),n?n.then(function(){t.whenTransactionsFinished().then(r)}):e()}t.whenTransactionsFinished().then(r)})}};e.utils.globalRoom=t;var r=0,u=function(u){function c(e,a){if(n(this,c),void 0===a)throw new Error("Options must not be undefined!");a.role="master",a.forwardToSyncingClients=!1;var s=i(this,(c.__proto__||Object.getPrototypeOf(c)).call(this,e,a));return s.setUserId(r+++"").then(function(){t.addUser(s)}),s.globalRoom=t,s.syncingClientDuration=0,s}return a(c,u),s(c,[{key:"receiveMessage",value:function(e,t){return o(c.prototype.__proto__||Object.getPrototypeOf(c.prototype),"receiveMessage",this).call(this,e,JSON.parse(JSON.stringify(t)))}},{key:"send",value:function(e,r){var n=t.buffers[e];null!=n&&(null==n[this.userId]&&(n[this.userId]=[]),n[this.userId].push(JSON.parse(JSON.stringify([this.userId,r]))))}},{key:"broadcast",value:function(e){for(var r in t.buffers){var n=t.buffers[r];null==n[this.userId]&&(n[this.userId]=[]),n[this.userId].push(JSON.parse(JSON.stringify([this.userId,e])))}}},{key:"isDisconnected",value:function(){return null==t.users[this.userId]}},{key:"reconnect",value:function(){return this.isDisconnected()&&(t.addUser(this),o(c.prototype.__proto__||Object.getPrototypeOf(c.prototype),"reconnect",this).call(this)),e.utils.globalRoom.flushAll()}},{key:"disconnect",value:function(){var e=Promise.resolve();this.isDisconnected()||(t.removeUser(this.userId),e=o(c.prototype.__proto__||Object.getPrototypeOf(c.prototype),"disconnect",this).call(this));var r=this;return e.then(function(){return r.y.db.whenTransactionsFinished()})}},{key:"flush",value:function(){var e=this;return async(regeneratorRuntime.mark(function r(){var n,i,a;return regeneratorRuntime.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:n=t.buffers[e.userId];case 1:if(!(Object.keys(n).length>0)){r.next=9;break}return i=getRandom(Object.keys(n)),a=n[i].shift(),0===n[i].length&&delete n[i],r.next=7,this.receiveMessage(a[0],a[1]);case 7:r.next=1;break;case 9:return r.next=11,e.whenTransactionsFinished();case 11:case"end":return r.stop()}},r,this)}))}}]),c}(e.AbstractConnector);e.Test=u}},{}],9:[function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function e(e,t){for(var r=0;r0||a.gc2.length>0?(a.y.connector.isSynced||console.warn("gc should be empty when not synced!"),new Promise(function(e){a.requestTransaction(regeneratorRuntime.mark(function t(){var r,n;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(null==a.y.connector||!a.y.connector.isSynced){t.next=10;break}r=0;case 2:if(!(r0&&(a.gcInterval=setTimeout(i,a.gcTimeout)),e();case 12:case"end":return t.stop()}},t,this)}))})):(a.gcTimeout>0&&(a.gcInterval=setTimeout(i,a.gcTimeout)),Promise.resolve())})}n(this,t),this.y=e,this.dbOpts=r;var a=this;this.userId=null;var s;this.userIdPromise=new Promise(function(e){s=e}),this.userIdPromise.resolve=s,this.forwardAppliedOperations=!1,this.listenersById={},this.listenersByIdExecuteNow=[],this.listenersByIdRequestPending=!1,this.initializedTypes={},this.waitingTransactions=[],this.transactionInProgress=!1,this.transactionIsFlushed=!1,"undefined"!=typeof YConcurrency_TestingMode&&(this.executeOrder=[]),this.gc1=[],this.gc2=[],this.garbageCollect=i,this.startGarbageCollector(),this.repairCheckInterval=r.repairCheckInterval?r.repairCheckInterval:6e3,this.opsReceivedTimestamp=new Date,this.startRepairCheck()}return i(t,[{key:"startGarbageCollector",value:function(){this.gc=null==this.dbOpts.gc||this.dbOpts.gc,this.gc?this.gcTimeout=this.dbOpts.gcTimeout?this.dbOpts.gcTimeout:5e4:this.gcTimeout=-1,this.gcTimeout>0&&this.garbageCollect()}},{key:"startRepairCheck",value:function(){var e=this;this.repairCheckInterval>0&&(this.repairCheckIntervalHandler=setInterval(function(){new Date-e.opsReceivedTimestamp>e.repairCheckInterval&&Object.keys(e.listenersById).length>0&&(e.listenersById={},e.opsReceivedTimestamp=new Date,e.y.connector.repair())},this.repairCheckInterval))}},{key:"stopRepairCheck",value:function(){clearInterval(this.repairCheckIntervalHandler)}},{key:"queueGarbageCollector",value:function(e){this.y.connector.isSynced&&this.gc&&this.gc1.push(e)}},{key:"emptyGarbageCollector",value:function(){var e=this;return new Promise(function(t){var r=function r(){e.gc1.length>0||e.gc2.length>0?e.garbageCollect().then(r):t()};setTimeout(r,0)})}},{key:"addToDebug",value:function(){if("undefined"!=typeof YConcurrency_TestingMode){var e=Array.prototype.map.call(arguments,function(e){return"string"==typeof e?e:JSON.stringify(e)}).join("").replace(/"/g,"'").replace(/,/g,", ").replace(/:/g,": ");this.executeOrder.push(e)}}},{key:"getDebugData",value:function(){console.log(this.executeOrder.join("\n"))}},{key:"stopGarbageCollector",value:function(){var e=this;return this.gc=!1,this.gcTimeout=-1,new Promise(function(t){e.requestTransaction(regeneratorRuntime.mark(function r(){var n,i,a;return regeneratorRuntime.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:n=e.gc1.concat(e.gc2),e.gc1=[],e.gc2=[],i=0;case 4:if(!(i1)){e.next=10;break}return e.delegateYield(this.getInsertionCleanStart([t.id[0],t.id[1]+1]),"t0",8);case 8:t=e.t0,n=!0;case 10:if(!n){e.next=15;break}return t.gc=!0,e.delegateYield(this.setOperation(t),"t1",13);case 13:return this.store.queueGarbageCollector(t.id),e.abrupt("return",!0);case 15:return e.abrupt("return",!1);case 16:case"end":return e.stop()}},e,this)})},{key:"removeFromGarbageCollector",value:function(t){function r(r){return!e.utils.compareIds(r,t.id)}this.gc1=this.gc1.filter(r),this.gc2=this.gc2.filter(r),delete t.gc}},{key:"destroyTypes",value:function(){for(var e in this.initializedTypes){var t=this.initializedTypes[e];null!=t._destroy?t._destroy():console.error("The type you included does not provide destroy functionality, it will remain in memory (updating your packages will help).")}}},{key:"destroy",value:regeneratorRuntime.mark(function e(){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:clearInterval(this.gcInterval),this.gcInterval=null,this.stopRepairCheck();case 3:case"end":return e.stop()}},e,this)})},{key:"setUserId",value:function(e){if(!this.userIdPromise.inProgress){this.userIdPromise.inProgress=!0;var t=this;t.requestTransaction(regeneratorRuntime.mark(function r(){var n;return regeneratorRuntime.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return t.userId=e,r.delegateYield(this.getState(e),"t0",2);case 2:n=r.t0,t.opClock=n.clock,t.userIdPromise.resolve(e);case 5:case"end":return r.stop()}},r,this)}))}return this.userIdPromise}},{key:"whenUserIdSet",value:function(e){this.userIdPromise.then(e)}},{key:"getNextOpId",value:function(e){if(null==e)throw new Error("getNextOpId expects the number of created ids to create!");if(null==this.userId)throw new Error("OperationStore not yet initialized!");var t=[this.userId,this.opClock];return this.opClock+=e,t}},{key:"apply",value:function(t){this.opsReceivedTimestamp=new Date;for(var r=0;r0)for(var r={op:t,missing:e.length},n=0;n1)){r.next=84;break}return r.delegateYield(this.getInsertionCleanEnd(p.id),"t16",83);case 83:p=r.t16;case 84:this.store.removeFromGarbageCollector(p);case 85:return r.delegateYield(this.setOperation(p),"t17",86);case 86:if(null==n.parentSub){r.next=96;break}if(null!=h){r.next=90;break}return c.map[n.parentSub]=n.id,r.delegateYield(this.setOperation(c),"t18",90);case 90:if(null==n.right){r.next=92;break}return r.delegateYield(this.deleteOperation(n.right,1,!0),"t19",92);case 92:if(null==n.left){r.next=94;break}return r.delegateYield(this.deleteOperation(n.id,1,!0),"t20",94);case 94:r.next=100;break;case 96:if(null!=p&&null!=h){r.next=100;break}return null==p&&(c.end=e.utils.getLastId(n)),null==h&&(c.start=n.id),r.delegateYield(this.setOperation(c),"t21",100);case 100:i=0;case 101:if(!(i=0&&null!=i.right)){e.next=12;break}return e.delegateYield(this.getOperation(i.right),"t1",9);case 9:i=e.t1,e.next=13;break;case 12:return e.abrupt("break",15);case 13:e.next=5;break;case 15:return e.abrupt("return",n);case 16:case"end":return e.stop()}},e,this)}),map:regeneratorRuntime.mark(function e(t,r){var n,i;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=t.start,n=[];case 2:if(null==t){e.next=9;break}return e.delegateYield(this.getOperation(t),"t0",4);case 4:i=e.t0,i.deleted||n.push(r(i)),t=i.right,e.next=2;break;case 9:return e.abrupt("return",n);case 10:case"end":return e.stop()}},e,this)})},Map:{create:function(e){return{id:e,map:{},struct:"Map"}},encode:function(e){var t={struct:"Map",type:e.type,id:e.id,map:{}};return null!=e.requires&&(t.requires=e.requires),null!=e.info&&(t.info=e.info),t},requiredOps:function(){return[]},execute:regeneratorRuntime.mark(function e(){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}},e,this)}),get:regeneratorRuntime.mark(function e(t,r){var n,i;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(null==(n=t.map[r])){e.next=14;break}return e.delegateYield(this.getOperation(n),"t0",3);case 3:if(null!=(i=e.t0)&&!i.deleted){e.next=8;break}return e.abrupt("return",void 0);case 8:if(null!=i.opContent){e.next=12;break}return e.abrupt("return",i.content[0]);case 12:return e.delegateYield(this.getType(i.opContent),"t1",13);case 13:return e.abrupt("return",e.t1);case 14:case"end":return e.stop()}},e,this)})}};e.Struct=t}},{}],11:[function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function e(e,t){for(var r=0;r0&&this.store.y.connector.broadcastOps(n);case 10:case"end":return t.stop()}},t,this)})},{key:"deleteList",value:regeneratorRuntime.mark(function e(t){var r;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(null==t){e.next=15;break}return e.delegateYield(this.getOperation(t),"t0",2);case 2:if(t=e.t0,t.gc){e.next=12;break}return t.gc=!0,t.deleted=!0,e.delegateYield(this.setOperation(t),"t1",7);case 7:return r=null!=t.content?t.content.length:1,e.delegateYield(this.markDeleted(t.id,r),"t2",9);case 9:if(null==t.opContent){e.next=11;break}return e.delegateYield(this.deleteOperation(t.opContent),"t3",11);case 11:this.store.queueGarbageCollector(t.id);case 12:t=t.right,e.next=0;break;case 15:case"end":return e.stop()}},e,this)})},{key:"deleteOperation",value:regeneratorRuntime.mark(function e(t,r,n){var i,a,s,o,u,c,l;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return null==r&&(r=1),e.delegateYield(this.markDeleted(t,r),"t0",2);case 2:if(!(r>0)){e.next=64;break}return i=!1,e.delegateYield(this.os.findWithUpperBound([t[0],t[1]+r-1]),"t1",5);case 5:if(a=e.t1,s=null!=a&&null!=a.content?a.content.length:1,!(null==a||a.id[0]!==t[0]||a.id[1]+s<=t[1])){e.next=12;break}a=null,r=0,e.next=22;break;case 12:if(a.deleted){e.next=21;break}if(!(a.id[1]t[1]+r)){e.next=21;break}return e.delegateYield(this.getInsertionCleanEnd([t[0],t[1]+r-1]),"t3",19);case 19:a=e.t3,s=a.content.length;case 21:r=a.id[1]-t[1];case 22:if(null==a){e.next=62;break}if(a.deleted){e.next=44;break}if(i=!0,a.deleted=!0,null==a.start){e.next=28;break}return e.delegateYield(this.deleteList(a.start),"t4",28);case 28:if(null==a.map){e.next=35;break}e.t5=regeneratorRuntime.keys(a.map);case 30:if((e.t6=e.t5()).done){e.next=35;break}return o=e.t6.value,e.delegateYield(this.deleteList(a.map[o]),"t7",33);case 33:e.next=30;break;case 35:if(null==a.opContent){e.next=37;break}return e.delegateYield(this.deleteOperation(a.opContent),"t8",37);case 37:if(null==a.requires){e.next=44;break}u=0;case 39:if(!(u0)){e.next=20;break}if(n.gc){e.next=11;break}n.len+=i,e.next=18;break;case 11:if(!((i=n.id[1]+n.len-t[1])=a.id[1])){e.next=61;break}i=n.id[1]+n.len-a.id[1];case 33:if(!(i>=0)){e.next=61;break}if(!a.gc){e.next=44;break}if(n.len-=i,!(i>=a.len)){e.next=41;break}if(!((i-=a.len)>0)){e.next=41;break}return e.delegateYield(this.ds.put(n),"t5",40);case 40:return e.delegateYield(this.markDeleted([a.id[0],a.id[1]+a.len],i),"t6",41);case 41:return e.abrupt("break",61);case 44:if(!(i>a.len)){e.next=56;break}return e.delegateYield(this.ds.findNext(a.id),"t7",46);case 46:return s=e.t7,e.delegateYield(this.ds.delete(a.id),"t8",48);case 48:if(null!=s&&n.id[0]===s.id[0]){e.next=52;break}return e.abrupt("break",61);case 52:a=s,i=n.id[1]+n.len-a.id[1];case 54:e.next=59;break;case 56:return n.len+=a.len-i,e.delegateYield(this.ds.delete(a.id),"t9",58);case 58:return e.abrupt("break",61);case 59:e.next=33;break;case 61:return e.delegateYield(this.ds.put(n),"t10",62);case 62:return e.abrupt("return",n);case 63:case"end":return e.stop()}},e,this)})},{key:"garbageCollectAfterSync",value:regeneratorRuntime.mark(function e(){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((this.store.gc1.length>0||this.store.gc2.length>0)&&console.warn("gc should be empty after sync"),this.store.gc){e.next=3;break}return e.abrupt("return");case 3:return e.delegateYield(this.os.iterate(this,null,null,regeneratorRuntime.mark(function e(t){var r,n,i;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.gc){e.next=3;break}return delete t.gc,e.delegateYield(this.setOperation(t),"t0",3);case 3:if(null==t.parent){e.next=23;break}return e.delegateYield(this.isDeleted(t.parent),"t1",5);case 5:if(!(r=e.t1)){e.next=23;break}if(t.gc=!0,t.deleted){e.next=20;break}return e.delegateYield(this.markDeleted(t.id,null!=t.content?t.content.length:1),"t2",10);case 10:if(t.deleted=!0,null==t.opContent){e.next=13;break}return e.delegateYield(this.deleteOperation(t.opContent),"t3",13);case 13:if(null==t.requires){e.next=20;break}n=0;case 15:if(!(n0)){t.next=60;break}c=n.left,l=null;case 39:if(null==c){t.next=47;break}return t.delegateYield(this.getInsertion(c),"t11",41);case 41:if(l=t.t11,!l.deleted){t.next=44;break}return t.abrupt("break",47);case 44:c=l.left,t.next=39;break;case 47:t.t12=regeneratorRuntime.keys(n.originOf);case 48:if((t.t13=t.t12()).done){t.next=57;break}return d=t.t13.value,t.delegateYield(this.getOperation(n.originOf[d]),"t14",51);case 51:if(null==(f=t.t14)){t.next=55;break}return f.origin=c,t.delegateYield(this.setOperation(f),"t15",55);case 55:t.next=48;break;case 57:if(null==c){t.next=60;break}return null==l.originOf?l.originOf=n.originOf:l.originOf=n.originOf.concat(l.originOf),t.delegateYield(this.setOperation(l),"t16",60);case 60:if(null==n.origin){t.next=65;break}return t.delegateYield(this.getInsertion(n.origin),"t17",62);case 62:return h=t.t17,h.originOf=h.originOf.filter(function(t){return!e.utils.compareIds(r,t)}),t.delegateYield(this.setOperation(h),"t18",65);case 65:if(null==n.parent){t.next=68;break}return t.delegateYield(this.getOperation(n.parent),"t19",67);case 67:p=t.t19;case 68:if(null==p){t.next=73;break}if(g=!1,null!=n.parentSub?e.utils.compareIds(p.map[n.parentSub],n.id)&&(g=!0,null!=n.right?p.map[n.parentSub]=n.right:delete p.map[n.parentSub]):(e.utils.compareIds(p.start,n.id)&&(g=!0,p.start=n.right),e.utils.matchesId(n,p.end)&&(g=!0,p.end=n.left)),!g){t.next=73;break}return t.delegateYield(this.setOperation(p),"t20",73);case 73:return t.delegateYield(this.removeOperation(n.id),"t21",74);case 74:case"end":return t.stop()}},t,this)})},{key:"checkDeleteStoreForState",value:regeneratorRuntime.mark(function e(t){var r;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.ds.findWithUpperBound([t.user,t.clock]),"t0",1);case 1:r=e.t0,null!=r&&r.id[0]===t.user&&r.gc&&(t.clock=Math.max(t.clock,r.id[1]+r.len));case 3:case"end":return e.stop()}},e,this)})},{key:"updateState",value:regeneratorRuntime.mark(function e(t){var r,n,i;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.getState(t),"t0",1);case 1:return r=e.t0,e.delegateYield(this.checkDeleteStoreForState(r),"t1",3);case 3:return e.delegateYield(this.getInsertion([t,r.clock]),"t2",4);case 4:n=e.t2,i=null!=n&&null!=n.content?n.content.length:1;case 6:if(!(null!=n&&t===n.id[0]&&n.id[1]<=r.clock&&n.id[1]+i>r.clock)){e.next=14;break}return r.clock+=i,e.delegateYield(this.checkDeleteStoreForState(r),"t3",9);case 9:return e.delegateYield(this.os.findNext(n.id),"t4",10);case 10:n=e.t4,i=null!=n&&null!=n.content?n.content.length:1,e.next=6;break;case 14:return e.delegateYield(this.setState(r),"t5",15);case 15:case"end":return e.stop()}},e,this)})},{key:"applyDeleteSet",value:regeneratorRuntime.mark(function e(t){var r,n,i,a,s,o,u,c,l,d,f;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r=[],e.t0=regeneratorRuntime.keys(t);case 2:if((e.t1=e.t0()).done){e.next=11;break}return n=e.t1.value,i=t[n],a=0,s=i[a],e.delegateYield(this.ds.iterate(this,[n,0],[n,Number.MAX_VALUE],regeneratorRuntime.mark(function e(t){var o;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(null==s){e.next=10;break}if(o=0,!(t.id[1]+t.len<=s[0])){e.next=6;break}return e.abrupt("break",10);case 6:s[0]=u[1])){e.next=36;break}return e.delegateYield(this.os.findWithUpperBound([u[0],c-1]),"t5",20);case 20:if(null!=(l=e.t5)){e.next=23;break}return e.abrupt("break",36);case 23:if(d=null!=l.content?l.content.length:1,!(l.id[0]!==u[0]||l.id[1]+d<=u[1])){e.next=26;break}return e.abrupt("break",36);case 26:if(!(l.id[1]+d>u[1]+u[2])){e.next=29;break}return e.delegateYield(this.getInsertionCleanEnd([u[0],u[1]+u[2]-1]),"t6",28);case 28:l=e.t6;case 29:if(!(l.id[1]1)){t.next=15;break}return a=i[0],s=e.Struct[a].create(r),s.type=i[1],t.delegateYield(this.setOperation(s),"t1",12);case 12:return t.abrupt("return",s);case 15:return console.error("Unexpected case. How can this happen?"),t.abrupt("return",null);case 18:case"end":return t.stop()}},t,this)})},{key:"removeOperation",value:regeneratorRuntime.mark(function e(t){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.os.delete(t),"t0",1);case 1:case"end":return e.stop()}},e,this)})},{key:"setState",value:regeneratorRuntime.mark(function e(t){var r;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r={id:[t.user],clock:t.clock},e.delegateYield(this.ss.put(r),"t0",2);case 2:case"end":return e.stop()}},e,this)})},{key:"getState",value:regeneratorRuntime.mark(function e(t){var r,n;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.ss.find([t]),"t0",1);case 1:return r=e.t0,n=null==r?null:r.clock,null==n&&(n=0),e.abrupt("return",{user:t,clock:n});case 5:case"end":return e.stop()}},e,this)})},{key:"getStateVector",value:regeneratorRuntime.mark(function e(){var t;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],e.delegateYield(this.ss.iterate(this,null,null,regeneratorRuntime.mark(function e(r){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t.push({user:r.id[0],clock:r.clock});case 1:case"end":return e.stop()}},e,this)})),"t0",2);case 2:return e.abrupt("return",t);case 3:case"end":return e.stop()}},e,this)})},{key:"getStateSet",value:regeneratorRuntime.mark(function e(){var t;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t={},e.delegateYield(this.ss.iterate(this,null,null,regeneratorRuntime.mark(function e(r){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t[r.id[0]]=r.clock;case 1:case"end":return e.stop()}},e,this)})),"t0",2);case 2:return e.abrupt("return",t);case 3:case"end":return e.stop()}},e,this)})},{key:"getOperations",value:regeneratorRuntime.mark(function t(r){var n,i,a,s,o,u,c,l,d,f,h;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return null==r&&(r={}),n=[],t.delegateYield(this.getStateVector(),"t0",3);case 3:i=t.t0,a=!0,s=!1,o=void 0,t.prev=7,u=i[Symbol.iterator]();case 9:if(a=(c=u.next()).done){t.next=23;break}if(l=c.value,"_"!==(d=l.user)){t.next=14;break}return t.abrupt("continue",20);case 14:if(!((f=r[d]||0)>0)){t.next=19;break}return t.delegateYield(this.getInsertion([d,f]),"t1",17);case 17:h=t.t1,null!=h&&(f=h.id[1],r[d]=f);case 19:return t.delegateYield(this.os.iterate(this,[d,f],[d,Number.MAX_VALUE],regeneratorRuntime.mark(function t(i){var a,s,o,u;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=e.Struct[i.struct].encode(i),"Insert"===i.struct){t.next=5;break}n.push(i),t.next=27;break;case 5:if(!(null==i.right||i.right[1]<(r[i.right[0]]||0))){t.next=27;break}a=i,s=[i],o=i.right;case 9:if(null!=a.left){t.next=15;break}return i.left=null,n.push(i),e.utils.compareIds(a.id,i.id)||(a=e.Struct[i.struct].encode(a),a.right=s[s.length-1].id,n.push(a)),t.abrupt("break",27);case 15:return t.delegateYield(this.getInsertion(a.left),"t0",16);case 16:for(a=t.t0;s.length>0&&e.utils.matchesId(a,s[s.length-1].origin);)s.pop();if(!(a.id[1]<(r[a.id[0]]||0))){t.next=24;break}return i.left=e.utils.getLastId(a),n.push(i),t.abrupt("break",27);case 24:e.utils.matchesId(a,i.origin)?(i.left=i.origin,n.push(i),i=e.Struct[i.struct].encode(a),i.right=o,s.length>0&&console.log("This should not happen .. :( please report this"),s=[i]):(u=e.Struct[i.struct].encode(a),u.right=s[s.length-1].id,u.left=u.origin,n.push(u),s.push(a));case 25:t.next=9;break;case 27:case"end":return t.stop()}},t,this)})),"t2",20);case 20:a=!0,t.next=9;break;case 23:t.next=29;break;case 25:t.prev=25,t.t3=t.catch(7),s=!0,o=t.t3;case 29:t.prev=29,t.prev=30,!a&&u.return&&u.return();case 32:if(t.prev=32,!s){t.next=35;break}throw o;case 35:return t.finish(32);case 36:return t.finish(29);case 37:return t.abrupt("return",n.reverse());case 38:case"end":return t.stop()}},t,this,[[7,25,29,37],[30,,32,36]])})},{key:"getOperationsUntransformed",value:regeneratorRuntime.mark(function e(){var t;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],e.delegateYield(this.os.iterate(this,null,null,regeneratorRuntime.mark(function e(r){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:"_"!==r.id[0]&&t.push(r);case 1:case"end":return e.stop()}},e,this)})),"t0",2);case 2:return e.abrupt("return",{untransformed:t});case 3:case"end":return e.stop()}},e,this)})},{key:"applyOperationsUntransformed",value:regeneratorRuntime.mark(function t(r,n){var i,a,s,o,u,c;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:i=r.untransformed,a=0;case 2:if(!(a=e.id[1]&&t[1]=0)){e.next=10;break}if(a=this.readBuffer[i],a.id[1]!==r[1]||a.id[0]!==r[0]){e.next=7;break}for(;i=0)){e.next=19;break}if(a=this.writeBuffer[i],a.id[1]!==r[1]||a.id[0]!==r[0]){e.next=16;break}return s=a,e.abrupt("break",19);case 16:i--,e.next=11;break;case 19:if(!(i<0&&void 0===n)){e.next=22;break}return e.delegateYield(o(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"find",this).call(this,r),"t0",21);case 21:s=e.t0;case 22:if(null!=s){for(i=0;i=0)){e.next=11;break}if(a=this.writeBuffer[i],a.id[1]!==n[1]||a.id[0]!==n[0]){e.next=8;break}for(;i>e/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,y)}e.utils={},e.utils.bubbleEvent=function(e,t){for(e.eventHandler.callEventListeners(t),t.path=[];null!=e&&null!=e._deepEventHandler;){e._deepEventHandler.callEventListeners(t);var r=null;null!=e._parent&&(r=e.os.getType(e._parent)),null!=r&&null!=r._getPathToChild?(t.path=[r._getPathToChild(e._model)].concat(t.path),e=r):e=null}};var b=function(){function e(){a(this,e),this.eventListeners=[]}return u(e,[{key:"destroy",value:function(){this.eventListeners=null}},{key:"addEventListener",value:function(e){this.eventListeners.push(e)}},{key:"removeEventListener",value:function(e){this.eventListeners=this.eventListeners.filter(function(t){return e!==t})}},{key:"removeAllEventListeners",value:function(){this.eventListeners=[]}},{key:"callEventListeners",value:function(e){for(var t=0;t0;)for(var n=0;n0&&this.awaiting--,!(0===this.awaiting&&this.waiting.length>0)){t.next=70;break}o=0;case 7:if(!(o=0;a--){var s=this.waiting[a];"Insert"===s.struct&&(e.utils.matchesId(s,i.left)?(s.right=i.id,i.left=s.left):e.utils.compareIds(s.id,i.right)&&(s.left=e.utils.getLastId(i),i.right=s.right))}}this._tryCallEvents(t)}},{key:"awaitedDeletes",value:function(t,r){for(var n=this.waiting.splice(this.waiting.length-t),i=0;i0&&this.awaiting--,0===this.awaiting&&this.waiting.length>0){var t=[],r=[];this.waiting.forEach(function(e){"Delete"===e.struct?r.push(e):t.push(e)}),t=function(t){for(var r=[];t.length>0;)for(var n=0;n= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return;\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name;\n }\n return Math.ceil(ms / n) + ' ' + name + 's';\n}\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","/**\n * Copyright (c) 2014, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * https://raw.github.com/facebook/regenerator/master/LICENSE file. An\n * additional grant of patent rights can be found in the PATENTS file in\n * the same directory.\n */\n\n!(function(global) {\n \"use strict\";\n\n var hasOwn = Object.prototype.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n var inModule = typeof module === \"object\";\n var runtime = global.regeneratorRuntime;\n if (runtime) {\n if (inModule) {\n // If regeneratorRuntime is defined globally and we're in a module,\n // make the exports object identical to regeneratorRuntime.\n module.exports = runtime;\n }\n // Don't bother evaluating the rest of this file if the runtime was\n // already defined globally.\n return;\n }\n\n // Define the runtime globally (as expected by generated code) as either\n // module.exports (if we're in a module) or a new, empty object.\n runtime = global.regeneratorRuntime = inModule ? module.exports : {};\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n runtime.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype;\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = \"GeneratorFunction\";\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n prototype[method] = function(arg) {\n return this._invoke(method, arg);\n };\n });\n }\n\n runtime.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n runtime.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n if (!(toStringTagSymbol in genFun)) {\n genFun[toStringTagSymbol] = \"GeneratorFunction\";\n }\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `value instanceof AwaitArgument` to determine if the yielded value is\n // meant to be awaited. Some may consider the name of this method too\n // cutesy, but they are curmudgeons.\n runtime.awrap = function(arg) {\n return new AwaitArgument(arg);\n };\n\n function AwaitArgument(arg) {\n this.arg = arg;\n }\n\n function AsyncIterator(generator) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value instanceof AwaitArgument) {\n return Promise.resolve(value.arg).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return Promise.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration. If the Promise is rejected, however, the\n // result for this iteration will be rejected with the same\n // reason. Note that rejections of yielded Promises are not\n // thrown back into the generator function, as is the case\n // when an awaited Promise is rejected. This difference in\n // behavior between yield and await is important, because it\n // allows the consumer to decide what to do with the yielded\n // rejection (swallow it and continue, manually .throw it back\n // into the generator, abandon iteration, whatever). With\n // await, by contrast, there is no opportunity to examine the\n // rejection reason outside the generator function, so the\n // only option is to throw it from the await expression, and\n // let the generator function handle the exception.\n result.value = unwrapped;\n resolve(result);\n }, reject);\n }\n }\n\n if (typeof process === \"object\" && process.domain) {\n invoke = process.domain.bind(invoke);\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new Promise(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n runtime.async = function(innerFn, outerFn, self, tryLocsList) {\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList)\n );\n\n return runtime.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n if (method === \"return\" ||\n (method === \"throw\" && delegate.iterator[method] === undefined)) {\n // A return or throw (when the delegate iterator has no throw\n // method) always terminates the yield* loop.\n context.delegate = null;\n\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n var returnMethod = delegate.iterator[\"return\"];\n if (returnMethod) {\n var record = tryCatch(returnMethod, delegate.iterator, arg);\n if (record.type === \"throw\") {\n // If the return method threw an exception, let that\n // exception prevail over the original return or throw.\n method = \"throw\";\n arg = record.arg;\n continue;\n }\n }\n\n if (method === \"return\") {\n // Continue with the outer return, now that the delegate\n // iterator has been terminated.\n continue;\n }\n }\n\n var record = tryCatch(\n delegate.iterator[method],\n delegate.iterator,\n arg\n );\n\n if (record.type === \"throw\") {\n context.delegate = null;\n\n // Like returning generator.throw(uncaught), but without the\n // overhead of an extra function call.\n method = \"throw\";\n arg = record.arg;\n continue;\n }\n\n // Delegate generator ran and handled its own exceptions so\n // regardless of what the method was, we continue as if it is\n // \"next\" with an undefined arg.\n method = \"next\";\n arg = undefined;\n\n var info = record.arg;\n if (info.done) {\n context[delegate.resultName] = info.value;\n context.next = delegate.nextLoc;\n } else {\n state = GenStateSuspendedYield;\n return info;\n }\n\n context.delegate = null;\n }\n\n if (method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = arg;\n\n } else if (method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw arg;\n }\n\n if (context.dispatchException(arg)) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n method = \"next\";\n arg = undefined;\n }\n\n } else if (method === \"return\") {\n context.abrupt(\"return\", arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n var info = {\n value: record.arg,\n done: context.done\n };\n\n if (record.arg === ContinueSentinel) {\n if (context.delegate && method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n arg = undefined;\n }\n } else {\n return info;\n }\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(arg) call above.\n method = \"throw\";\n arg = record.arg;\n }\n }\n };\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp[toStringTagSymbol] = \"Generator\";\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n runtime.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n runtime.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n return !!caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.next = finallyEntry.finallyLoc;\n } else {\n this.complete(record);\n }\n\n return ContinueSentinel;\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = record.arg;\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n return ContinueSentinel;\n }\n };\n})(\n // Among the various tricks for obtaining a reference to the global\n // object, this seems to be the most reliable technique that does not\n // use indirect eval (which violates Content Security Policy).\n typeof global === \"object\" ? global :\n typeof window === \"object\" ? window :\n typeof self === \"object\" ? self : this\n);\n","console.warn(\n \"The regenerator/runtime module is deprecated; \" +\n \"please import regenerator-runtime/runtime instead.\"\n);\n\nmodule.exports = require(\"regenerator-runtime/runtime\");\n","function canRead (auth) { return auth === 'read' || auth === 'write' }\nfunction canWrite (auth) { return auth === 'write' }\n\nmodule.exports = function (Y/* :any */) {\n class AbstractConnector {\n /* ::\n y: YConfig;\n role: SyncRole;\n connections: Object;\n isSynced: boolean;\n userEventListeners: Array;\n whenSyncedListeners: Array;\n currentSyncTarget: ?UserId;\n syncingClients: Array;\n forwardToSyncingClients: boolean;\n debug: boolean;\n syncStep2: Promise;\n userId: UserId;\n send: Function;\n broadcast: Function;\n broadcastOpBuffer: Array;\n protocolVersion: number;\n */\n /*\n opts contains the following information:\n role : String Role of this client (\"master\" or \"slave\")\n userId : String Uniquely defines the user.\n debug: Boolean Whether to print debug messages (optional)\n */\n constructor (y, opts) {\n this.y = y\n if (opts == null) {\n opts = {}\n }\n // Prefer to receive untransformed operations. This does only work if\n // this client receives operations from only one other client.\n // In particular, this does not work with y-webrtc.\n // It will work with y-websockets-client\n this.preferUntransformed = opts.preferUntransformed || false\n if (opts.role == null || opts.role === 'master') {\n this.role = 'master'\n } else if (opts.role === 'slave') {\n this.role = 'slave'\n } else {\n throw new Error(\"Role must be either 'master' or 'slave'!\")\n }\n this.log = Y.debug('y:connector')\n this.logMessage = Y.debug('y:connector-message')\n this.y.db.forwardAppliedOperations = opts.forwardAppliedOperations || false\n this.role = opts.role\n this.connections = {}\n this.isSynced = false\n this.userEventListeners = []\n this.whenSyncedListeners = []\n this.currentSyncTarget = null\n this.syncingClients = []\n this.forwardToSyncingClients = opts.forwardToSyncingClients !== false\n this.debug = opts.debug === true\n this.syncStep2 = Promise.resolve()\n this.broadcastOpBuffer = []\n this.protocolVersion = 11\n this.authInfo = opts.auth || null\n this.checkAuth = opts.checkAuth || function () { return Promise.resolve('write') } // default is everyone has write access\n if (opts.generateUserId === true) {\n this.setUserId(Y.utils.generateGuid())\n }\n }\n resetAuth (auth) {\n if (this.authInfo !== auth) {\n this.authInfo = auth\n this.broadcast({\n type: 'auth',\n auth: this.authInfo\n })\n }\n }\n reconnect () {\n this.log('reconnecting..')\n return this.y.db.startGarbageCollector()\n }\n disconnect () {\n this.log('discronnecting..')\n this.connections = {}\n this.isSynced = false\n this.currentSyncTarget = null\n this.syncingClients = []\n this.whenSyncedListeners = []\n this.y.db.stopGarbageCollector()\n return this.y.db.whenTransactionsFinished()\n }\n repair () {\n this.log('Repairing the state of Yjs. This can happen if messages get lost, and Yjs detects that something is wrong. If this happens often, please report an issue here: https://github.com/y-js/yjs/issues')\n for (var name in this.connections) {\n this.connections[name].isSynced = false\n }\n this.isSynced = false\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n setUserId (userId) {\n if (this.userId == null) {\n this.log('Set userId to \"%s\"', userId)\n this.userId = userId\n return this.y.db.setUserId(userId)\n } else {\n return null\n }\n }\n onUserEvent (f) {\n this.userEventListeners.push(f)\n }\n removeUserEventListener (f) {\n this.userEventListeners = this.userEventListeners.filter(g => { f !== g })\n }\n userLeft (user) {\n if (this.connections[user] != null) {\n this.log('User left: %s', user)\n delete this.connections[user]\n if (user === this.currentSyncTarget) {\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n this.syncingClients = this.syncingClients.filter(function (cli) {\n return cli !== user\n })\n for (var f of this.userEventListeners) {\n f({\n action: 'userLeft',\n user: user\n })\n }\n }\n }\n userJoined (user, role) {\n if (role == null) {\n throw new Error('You must specify the role of the joined user!')\n }\n if (this.connections[user] != null) {\n throw new Error('This user already joined!')\n }\n this.log('User joined: %s', user)\n this.connections[user] = {\n isSynced: false,\n role: role\n }\n for (var f of this.userEventListeners) {\n f({\n action: 'userJoined',\n user: user,\n role: role\n })\n }\n if (this.currentSyncTarget == null) {\n this.findNextSyncTarget()\n }\n }\n // Execute a function _when_ we are connected.\n // If not connected, wait until connected\n whenSynced (f) {\n if (this.isSynced) {\n f()\n } else {\n this.whenSyncedListeners.push(f)\n }\n }\n findNextSyncTarget () {\n if (this.currentSyncTarget != null) {\n return // \"The current sync has not finished!\"\n }\n\n var syncUser = null\n for (var uid in this.connections) {\n if (!this.connections[uid].isSynced) {\n syncUser = uid\n break\n }\n }\n var conn = this\n if (syncUser != null) {\n this.currentSyncTarget = syncUser\n this.y.db.requestTransaction(function *() {\n var stateSet = yield* this.getStateSet()\n var deleteSet = yield* this.getDeleteSet()\n var answer = {\n type: 'sync step 1',\n stateSet: stateSet,\n deleteSet: deleteSet,\n protocolVersion: conn.protocolVersion,\n auth: conn.authInfo\n }\n if (conn.preferUntransformed && Object.keys(stateSet).length === 0) {\n answer.preferUntransformed = true\n }\n conn.send(syncUser, answer)\n })\n } else {\n if (!conn.isSynced) {\n this.y.db.requestTransaction(function *() {\n if (!conn.isSynced) {\n // it is crucial that isSynced is set at the time garbageCollectAfterSync is called\n conn.isSynced = true\n yield* this.garbageCollectAfterSync()\n // call whensynced listeners\n for (var f of conn.whenSyncedListeners) {\n f()\n }\n conn.whenSyncedListeners = []\n }\n })\n }\n }\n }\n send (uid, message) {\n this.log('Send \\'%s\\' to %s', message.type, uid)\n this.logMessage('Message: %j', message)\n }\n broadcast (message) {\n this.log('Broadcast \\'%s\\'', message.type)\n this.logMessage('Message: %j', message)\n }\n /*\n Buffer operations, and broadcast them when ready.\n */\n broadcastOps (ops) {\n ops = ops.map(function (op) {\n return Y.Struct[op.struct].encode(op)\n })\n var self = this\n function broadcastOperations () {\n if (self.broadcastOpBuffer.length > 0) {\n self.broadcast({\n type: 'update',\n ops: self.broadcastOpBuffer\n })\n self.broadcastOpBuffer = []\n }\n }\n if (this.broadcastOpBuffer.length === 0) {\n this.broadcastOpBuffer = ops\n if (this.y.db.transactionInProgress) {\n this.y.db.whenTransactionsFinished().then(broadcastOperations)\n } else {\n setTimeout(broadcastOperations, 0)\n }\n } else {\n this.broadcastOpBuffer = this.broadcastOpBuffer.concat(ops)\n }\n }\n /*\n You received a raw message, and you know that it is intended for Yjs. Then call this function.\n */\n receiveMessage (sender/* :UserId */, message/* :Message */) {\n if (sender === this.userId) {\n return Promise.resolve()\n }\n this.log('Receive \\'%s\\' from %s', message.type, sender)\n this.logMessage('Message: %j', message)\n if (message.protocolVersion != null && message.protocolVersion !== this.protocolVersion) {\n this.log(\n `You tried to sync with a yjs instance that has a different protocol version\n (You: ${this.protocolVersion}, Client: ${message.protocolVersion}).\n The sync was stopped. You need to upgrade your dependencies (especially Yjs & the Connector)!\n `)\n this.send(sender, {\n type: 'sync stop',\n protocolVersion: this.protocolVersion\n })\n return Promise.reject('Incompatible protocol version')\n }\n if (message.auth != null && this.connections[sender] != null) {\n // authenticate using auth in message\n var auth = this.checkAuth(message.auth, this.y, sender)\n this.connections[sender].auth = auth\n auth.then(auth => {\n for (var f of this.userEventListeners) {\n f({\n action: 'userAuthenticated',\n user: sender,\n auth: auth\n })\n }\n })\n } else if (this.connections[sender] != null && this.connections[sender].auth == null) {\n // authenticate without otherwise\n this.connections[sender].auth = this.checkAuth(null, this.y, sender)\n }\n if (this.connections[sender] != null && this.connections[sender].auth != null) {\n return this.connections[sender].auth.then((auth) => {\n if (message.type === 'sync step 1' && canRead(auth)) {\n let conn = this\n let m = message\n\n this.y.db.requestTransaction(function *() {\n var currentStateSet = yield* this.getStateSet()\n if (canWrite(auth)) {\n yield* this.applyDeleteSet(m.deleteSet)\n }\n\n var ds = yield* this.getDeleteSet()\n var answer = {\n type: 'sync step 2',\n stateSet: currentStateSet,\n deleteSet: ds,\n protocolVersion: this.protocolVersion,\n auth: this.authInfo\n }\n if (message.preferUntransformed === true && Object.keys(m.stateSet).length === 0) {\n answer.osUntransformed = yield* this.getOperationsUntransformed()\n } else {\n answer.os = yield* this.getOperations(m.stateSet)\n }\n conn.send(sender, answer)\n if (this.forwardToSyncingClients) {\n conn.syncingClients.push(sender)\n setTimeout(function () {\n conn.syncingClients = conn.syncingClients.filter(function (cli) {\n return cli !== sender\n })\n conn.send(sender, {\n type: 'sync done'\n })\n }, 5000) // TODO: conn.syncingClientDuration)\n } else {\n conn.send(sender, {\n type: 'sync done'\n })\n }\n })\n } else if (message.type === 'sync step 2' && canWrite(auth)) {\n var db = this.y.db\n var defer = {}\n defer.promise = new Promise(function (resolve) {\n defer.resolve = resolve\n })\n this.syncStep2 = defer.promise\n let m /* :MessageSyncStep2 */ = message\n db.requestTransaction(function * () {\n yield* this.applyDeleteSet(m.deleteSet)\n if (m.osUntransformed != null) {\n yield* this.applyOperationsUntransformed(m.osUntransformed, m.stateSet)\n } else {\n this.store.apply(m.os)\n }\n /*\n * This just sends the complete hb after some time\n * Mostly for debugging..\n *\n db.requestTransaction(function * () {\n var ops = yield* this.getOperations(m.stateSet)\n if (ops.length > 0) {\n if (!broadcastHB) { // TODO: consider to broadcast here..\n conn.send(sender, {\n type: 'update',\n ops: ops\n })\n } else {\n // broadcast only once!\n conn.broadcastOps(ops)\n }\n }\n })\n */\n defer.resolve()\n })\n } else if (message.type === 'sync done') {\n var self = this\n this.syncStep2.then(function () {\n self._setSyncedWith(sender)\n })\n } else if (message.type === 'update' && canWrite(auth)) {\n if (this.forwardToSyncingClients) {\n for (var client of this.syncingClients) {\n this.send(client, message)\n }\n }\n if (this.y.db.forwardAppliedOperations) {\n var delops = message.ops.filter(function (o) {\n return o.struct === 'Delete'\n })\n if (delops.length > 0) {\n this.broadcastOps(delops)\n }\n }\n this.y.db.apply(message.ops)\n }\n })\n } else {\n return Promise.reject('Unable to deliver message')\n }\n }\n _setSyncedWith (user) {\n var conn = this.connections[user]\n if (conn != null) {\n conn.isSynced = true\n }\n if (user === this.currentSyncTarget) {\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n }\n /*\n Currently, the HB encodes operations as JSON. For the moment I want to keep it\n that way. Maybe we support encoding in the HB as XML in the future, but for now I don't want\n too much overhead. Y is very likely to get changed a lot in the future\n\n Because we don't want to encode JSON as string (with character escaping, wich makes it pretty much unreadable)\n we encode the JSON as XML.\n\n When the HB support encoding as XML, the format should look pretty much like this.\n\n does not support primitive values as array elements\n expects an ltx (less than xml) object\n */\n parseMessageFromXml (m/* :any */) {\n function parseArray (node) {\n for (var n of node.children) {\n if (n.getAttribute('isArray') === 'true') {\n return parseArray(n)\n } else {\n return parseObject(n)\n }\n }\n }\n function parseObject (node/* :any */) {\n var json = {}\n for (var attrName in node.attrs) {\n var value = node.attrs[attrName]\n var int = parseInt(value, 10)\n if (isNaN(int) || ('' + int) !== value) {\n json[attrName] = value\n } else {\n json[attrName] = int\n }\n }\n for (var n/* :any */ in node.children) {\n var name = n.name\n if (n.getAttribute('isArray') === 'true') {\n json[name] = parseArray(n)\n } else {\n json[name] = parseObject(n)\n }\n }\n return json\n }\n parseObject(m)\n }\n /*\n encode message in xml\n we use string because Strophe only accepts an \"xml-string\"..\n So {a:4,b:{c:5}} will look like\n \n \n \n m - ltx element\n json - Object\n */\n encodeMessageToXml (msg, obj) {\n // attributes is optional\n function encodeObject (m, json) {\n for (var name in json) {\n var value = json[name]\n if (name == null) {\n // nop\n } else if (value.constructor === Object) {\n encodeObject(m.c(name), value)\n } else if (value.constructor === Array) {\n encodeArray(m.c(name), value)\n } else {\n m.setAttribute(name, value)\n }\n }\n }\n function encodeArray (m, array) {\n m.setAttribute('isArray', 'true')\n for (var e of array) {\n if (e.constructor === Object) {\n encodeObject(m.c('array-element'), e)\n } else {\n encodeArray(m.c('array-element'), e)\n }\n }\n }\n if (obj.constructor === Object) {\n encodeObject(msg.c('y', { xmlns: 'http://y.ninja/connector-stanza' }), obj)\n } else if (obj.constructor === Array) {\n encodeArray(msg.c('y', { xmlns: 'http://y.ninja/connector-stanza' }), obj)\n } else {\n throw new Error(\"I can't encode this json!\")\n }\n }\n }\n Y.AbstractConnector = AbstractConnector\n}\n","/* global getRandom, async */\n'use strict'\n\nmodule.exports = function (Y) {\n var globalRoom = {\n users: {},\n buffers: {},\n removeUser: function (user) {\n for (var i in this.users) {\n this.users[i].userLeft(user)\n }\n delete this.users[user]\n delete this.buffers[user]\n },\n addUser: function (connector) {\n this.users[connector.userId] = connector\n this.buffers[connector.userId] = {}\n for (var uname in this.users) {\n if (uname !== connector.userId) {\n var u = this.users[uname]\n u.userJoined(connector.userId, 'master')\n connector.userJoined(u.userId, 'master')\n }\n }\n },\n whenTransactionsFinished: function () {\n var self = this\n return new Promise(function (resolve, reject) {\n // The connector first has to send the messages to the db.\n // Wait for the checkAuth-function to resolve\n // The test lib only has a simple checkAuth function: `() => Promise.resolve()`\n // Just add a function to the event-queue, in order to wait for the event.\n // TODO: this may be buggy in test applications (but it isn't be for real-life apps)\n setTimeout(function () {\n var ps = []\n for (var name in self.users) {\n ps.push(self.users[name].y.db.whenTransactionsFinished())\n }\n Promise.all(ps).then(resolve, reject)\n }, 10)\n })\n },\n flushOne: function flushOne () {\n var bufs = []\n for (var receiver in globalRoom.buffers) {\n let buff = globalRoom.buffers[receiver]\n var push = false\n for (let sender in buff) {\n if (buff[sender].length > 0) {\n push = true\n break\n }\n }\n if (push) {\n bufs.push(receiver)\n }\n }\n if (bufs.length > 0) {\n var userId = getRandom(bufs)\n let buff = globalRoom.buffers[userId]\n let sender = getRandom(Object.keys(buff))\n var m = buff[sender].shift()\n if (buff[sender].length === 0) {\n delete buff[sender]\n }\n var user = globalRoom.users[userId]\n return user.receiveMessage(m[0], m[1]).then(function () {\n return user.y.db.whenTransactionsFinished()\n }, function () {})\n } else {\n return false\n }\n },\n flushAll: function () {\n return new Promise(function (resolve) {\n // flushes may result in more created operations,\n // flush until there is nothing more to flush\n function nextFlush () {\n var c = globalRoom.flushOne()\n if (c) {\n while (c) {\n c = globalRoom.flushOne()\n }\n globalRoom.whenTransactionsFinished().then(nextFlush)\n } else {\n c = globalRoom.flushOne()\n if (c) {\n c.then(function () {\n globalRoom.whenTransactionsFinished().then(nextFlush)\n })\n } else {\n resolve()\n }\n }\n }\n globalRoom.whenTransactionsFinished().then(nextFlush)\n })\n }\n }\n Y.utils.globalRoom = globalRoom\n\n var userIdCounter = 0\n\n class Test extends Y.AbstractConnector {\n constructor (y, options) {\n if (options === undefined) {\n throw new Error('Options must not be undefined!')\n }\n options.role = 'master'\n options.forwardToSyncingClients = false\n super(y, options)\n this.setUserId((userIdCounter++) + '').then(() => {\n globalRoom.addUser(this)\n })\n this.globalRoom = globalRoom\n this.syncingClientDuration = 0\n }\n receiveMessage (sender, m) {\n return super.receiveMessage(sender, JSON.parse(JSON.stringify(m)))\n }\n send (userId, message) {\n var buffer = globalRoom.buffers[userId]\n if (buffer != null) {\n if (buffer[this.userId] == null) {\n buffer[this.userId] = []\n }\n buffer[this.userId].push(JSON.parse(JSON.stringify([this.userId, message])))\n }\n }\n broadcast (message) {\n for (var key in globalRoom.buffers) {\n var buff = globalRoom.buffers[key]\n if (buff[this.userId] == null) {\n buff[this.userId] = []\n }\n buff[this.userId].push(JSON.parse(JSON.stringify([this.userId, message])))\n }\n }\n isDisconnected () {\n return globalRoom.users[this.userId] == null\n }\n reconnect () {\n if (this.isDisconnected()) {\n globalRoom.addUser(this)\n super.reconnect()\n }\n return Y.utils.globalRoom.flushAll()\n }\n disconnect () {\n var waitForMe = Promise.resolve()\n if (!this.isDisconnected()) {\n globalRoom.removeUser(this.userId)\n waitForMe = super.disconnect()\n }\n var self = this\n return waitForMe.then(function () {\n return self.y.db.whenTransactionsFinished()\n })\n }\n flush () {\n var self = this\n return async(function * () {\n var buff = globalRoom.buffers[self.userId]\n while (Object.keys(buff).length > 0) {\n var sender = getRandom(Object.keys(buff))\n var m = buff[sender].shift()\n if (buff[sender].length === 0) {\n delete buff[sender]\n }\n yield this.receiveMessage(m[0], m[1])\n }\n yield self.whenTransactionsFinished()\n })\n }\n }\n\n Y.Test = Test\n}\n","/* @flow */\n'use strict'\n\nmodule.exports = function (Y /* :any */) {\n /*\n Partial definition of an OperationStore.\n TODO: name it Database, operation store only holds operations.\n\n A database definition must alse define the following methods:\n * logTable() (optional)\n - show relevant information information in a table\n * requestTransaction(makeGen)\n - request a transaction\n * destroy()\n - destroy the database\n */\n class AbstractDatabase {\n /* ::\n y: YConfig;\n forwardAppliedOperations: boolean;\n listenersById: Object;\n listenersByIdExecuteNow: Array;\n listenersByIdRequestPending: boolean;\n initializedTypes: Object;\n whenUserIdSetListener: ?Function;\n waitingTransactions: Array;\n transactionInProgress: boolean;\n executeOrder: Array;\n gc1: Array;\n gc2: Array;\n gcTimeout: number;\n gcInterval: any;\n garbageCollect: Function;\n executeOrder: Array; // for debugging only\n userId: UserId;\n opClock: number;\n transactionsFinished: ?{promise: Promise, resolve: any};\n transact: (x: ?Generator) => any;\n */\n constructor (y, opts) {\n this.y = y\n this.dbOpts = opts\n var os = this\n this.userId = null\n var resolve\n this.userIdPromise = new Promise(function (r) {\n resolve = r\n })\n this.userIdPromise.resolve = resolve\n // whether to broadcast all applied operations (insert & delete hook)\n this.forwardAppliedOperations = false\n // E.g. this.listenersById[id] : Array\n this.listenersById = {}\n // Execute the next time a transaction is requested\n this.listenersByIdExecuteNow = []\n // A transaction is requested\n this.listenersByIdRequestPending = false\n /* To make things more clear, the following naming conventions:\n * ls : we put this.listenersById on ls\n * l : Array\n * id : Id (can't use as property name)\n * sid : String (converted from id via JSON.stringify\n so we can use it as a property name)\n\n Always remember to first overwrite\n a property before you iterate over it!\n */\n // TODO: Use ES7 Weak Maps. This way types that are no longer user,\n // wont be kept in memory.\n this.initializedTypes = {}\n this.waitingTransactions = []\n this.transactionInProgress = false\n this.transactionIsFlushed = false\n if (typeof YConcurrency_TestingMode !== 'undefined') {\n this.executeOrder = []\n }\n this.gc1 = [] // first stage\n this.gc2 = [] // second stage -> after that, remove the op\n\n function garbageCollect () {\n return os.whenTransactionsFinished().then(function () {\n if (os.gc1.length > 0 || os.gc2.length > 0) {\n if (!os.y.connector.isSynced) {\n console.warn('gc should be empty when not synced!')\n }\n return new Promise((resolve) => {\n os.requestTransaction(function * () {\n if (os.y.connector != null && os.y.connector.isSynced) {\n for (var i = 0; i < os.gc2.length; i++) {\n var oid = os.gc2[i]\n yield* this.garbageCollectOperation(oid)\n }\n os.gc2 = os.gc1\n os.gc1 = []\n }\n // TODO: Use setInterval here instead (when garbageCollect is called several times there will be several timeouts..)\n if (os.gcTimeout > 0) {\n os.gcInterval = setTimeout(garbageCollect, os.gcTimeout)\n }\n resolve()\n })\n })\n } else {\n // TODO: see above\n if (os.gcTimeout > 0) {\n os.gcInterval = setTimeout(garbageCollect, os.gcTimeout)\n }\n return Promise.resolve()\n }\n })\n }\n this.garbageCollect = garbageCollect\n this.startGarbageCollector()\n\n this.repairCheckInterval = !opts.repairCheckInterval ? 6000 : opts.repairCheckInterval\n this.opsReceivedTimestamp = new Date()\n this.startRepairCheck()\n }\n startGarbageCollector () {\n this.gc = this.dbOpts.gc == null || this.dbOpts.gc\n if (this.gc) {\n this.gcTimeout = !this.dbOpts.gcTimeout ? 50000 : this.dbOpts.gcTimeout\n } else {\n this.gcTimeout = -1\n }\n if (this.gcTimeout > 0) {\n this.garbageCollect()\n }\n }\n startRepairCheck () {\n var os = this\n if (this.repairCheckInterval > 0) {\n this.repairCheckIntervalHandler = setInterval(function repairOnMissingOperations () {\n /*\n Case 1. No ops have been received in a while (new Date() - os.opsReceivedTimestamp > os.repairCheckInterval)\n - 1.1 os.listenersById is empty. Then the state was correct the whole time. -> Nothing to do (nor to update)\n - 1.2 os.listenersById is not empty.\n * Then the state was incorrect for at least {os.repairCheckInterval} seconds.\n * -> Remove everything in os.listenersById and sync again (connector.repair())\n Case 2. An op has been received in the last {os.repairCheckInterval } seconds.\n It is not yet necessary to check for faulty behavior. Everything can still resolve itself. Wait for more messages.\n If nothing was received for a while and os.listenersById is still not emty, we are in case 1.2\n -> Do nothing\n\n Baseline here is: we really only have to catch case 1.2..\n */\n if (\n new Date() - os.opsReceivedTimestamp > os.repairCheckInterval &&\n Object.keys(os.listenersById).length > 0 // os.listenersById is not empty\n ) {\n // haven't received operations for over {os.repairCheckInterval} seconds, resend state vector\n os.listenersById = {}\n os.opsReceivedTimestamp = new Date() // update so you don't send repair several times in a row\n os.y.connector.repair()\n }\n }, this.repairCheckInterval)\n }\n }\n stopRepairCheck () {\n clearInterval(this.repairCheckIntervalHandler)\n }\n queueGarbageCollector (id) {\n if (this.y.connector.isSynced && this.gc) {\n this.gc1.push(id)\n }\n }\n emptyGarbageCollector () {\n return new Promise(resolve => {\n var check = () => {\n if (this.gc1.length > 0 || this.gc2.length > 0) {\n this.garbageCollect().then(check)\n } else {\n resolve()\n }\n }\n setTimeout(check, 0)\n })\n }\n addToDebug () {\n if (typeof YConcurrency_TestingMode !== 'undefined') {\n var command /* :string */ = Array.prototype.map.call(arguments, function (s) {\n if (typeof s === 'string') {\n return s\n } else {\n return JSON.stringify(s)\n }\n }).join('').replace(/\"/g, \"'\").replace(/,/g, ', ').replace(/:/g, ': ')\n this.executeOrder.push(command)\n }\n }\n getDebugData () {\n console.log(this.executeOrder.join('\\n'))\n }\n stopGarbageCollector () {\n var self = this\n this.gc = false\n this.gcTimeout = -1\n return new Promise(function (resolve) {\n self.requestTransaction(function * () {\n var ungc /* :Array */ = self.gc1.concat(self.gc2)\n self.gc1 = []\n self.gc2 = []\n for (var i = 0; i < ungc.length; i++) {\n var op = yield* this.getOperation(ungc[i])\n if (op != null) {\n delete op.gc\n yield* this.setOperation(op)\n }\n }\n resolve()\n })\n })\n }\n /*\n Try to add to GC.\n\n TODO: rename this function\n\n Rulez:\n * Only gc if this user is online & gc turned on\n * The most left element in a list must not be gc'd.\n => There is at least one element in the list\n\n returns true iff op was added to GC\n */\n * addToGarbageCollector (op, left) {\n if (\n op.gc == null &&\n op.deleted === true &&\n this.store.gc &&\n this.store.y.connector.isSynced\n ) {\n var gc = false\n if (left != null && left.deleted === true) {\n gc = true\n } else if (op.content != null && op.content.length > 1) {\n op = yield* this.getInsertionCleanStart([op.id[0], op.id[1] + 1])\n gc = true\n }\n if (gc) {\n op.gc = true\n yield* this.setOperation(op)\n this.store.queueGarbageCollector(op.id)\n return true\n }\n }\n return false\n }\n removeFromGarbageCollector (op) {\n function filter (o) {\n return !Y.utils.compareIds(o, op.id)\n }\n this.gc1 = this.gc1.filter(filter)\n this.gc2 = this.gc2.filter(filter)\n delete op.gc\n }\n destroyTypes () {\n for (var key in this.initializedTypes) {\n var type = this.initializedTypes[key]\n if (type._destroy != null) {\n type._destroy()\n } else {\n console.error('The type you included does not provide destroy functionality, it will remain in memory (updating your packages will help).')\n }\n }\n }\n * destroy () {\n clearInterval(this.gcInterval)\n this.gcInterval = null\n this.stopRepairCheck()\n }\n setUserId (userId) {\n if (!this.userIdPromise.inProgress) {\n this.userIdPromise.inProgress = true\n var self = this\n self.requestTransaction(function * () {\n self.userId = userId\n var state = yield* this.getState(userId)\n self.opClock = state.clock\n self.userIdPromise.resolve(userId)\n })\n }\n return this.userIdPromise\n }\n whenUserIdSet (f) {\n this.userIdPromise.then(f)\n }\n getNextOpId (numberOfIds) {\n if (numberOfIds == null) {\n throw new Error('getNextOpId expects the number of created ids to create!')\n } else if (this.userId == null) {\n throw new Error('OperationStore not yet initialized!')\n } else {\n var id = [this.userId, this.opClock]\n this.opClock += numberOfIds\n return id\n }\n }\n /*\n Apply a list of operations.\n\n * we save a timestamp, because we received new operations that could resolve ops in this.listenersById (see this.startRepairCheck)\n * get a transaction\n * check whether all Struct.*.requiredOps are in the OS\n * check if it is an expected op (otherwise wait for it)\n * check if was deleted, apply a delete operation after op was applied\n */\n apply (ops) {\n this.opsReceivedTimestamp = new Date()\n for (var i = 0; i < ops.length; i++) {\n var o = ops[i]\n if (o.id == null || o.id[0] !== this.y.connector.userId) {\n var required = Y.Struct[o.struct].requiredOps(o)\n if (o.requires != null) {\n required = required.concat(o.requires)\n }\n this.whenOperationsExist(required, o)\n }\n }\n }\n /*\n op is executed as soon as every operation requested is available.\n Note that Transaction can (and should) buffer requests.\n */\n whenOperationsExist (ids, op) {\n if (ids.length > 0) {\n let listener = {\n op: op,\n missing: ids.length\n }\n\n for (let i = 0; i < ids.length; i++) {\n let id = ids[i]\n let sid = JSON.stringify(id)\n let l = this.listenersById[sid]\n if (l == null) {\n l = []\n this.listenersById[sid] = l\n }\n l.push(listener)\n }\n } else {\n this.listenersByIdExecuteNow.push({\n op: op\n })\n }\n\n if (this.listenersByIdRequestPending) {\n return\n }\n\n this.listenersByIdRequestPending = true\n var store = this\n\n this.requestTransaction(function * () {\n var exeNow = store.listenersByIdExecuteNow\n store.listenersByIdExecuteNow = []\n\n var ls = store.listenersById\n store.listenersById = {}\n\n store.listenersByIdRequestPending = false\n\n for (let key = 0; key < exeNow.length; key++) {\n let o = exeNow[key].op\n yield* store.tryExecute.call(this, o)\n }\n\n for (var sid in ls) {\n var l = ls[sid]\n var id = JSON.parse(sid)\n var op\n if (typeof id[1] === 'string') {\n op = yield* this.getOperation(id)\n } else {\n op = yield* this.getInsertion(id)\n }\n if (op == null) {\n store.listenersById[sid] = l\n } else {\n for (let i = 0; i < l.length; i++) {\n let listener = l[i]\n let o = listener.op\n if (--listener.missing === 0) {\n yield* store.tryExecute.call(this, o)\n }\n }\n }\n }\n })\n }\n /*\n Actually execute an operation, when all expected operations are available.\n */\n /* :: // TODO: this belongs somehow to transaction\n store: Object;\n getOperation: any;\n isGarbageCollected: any;\n addOperation: any;\n whenOperationsExist: any;\n */\n * tryExecute (op) {\n this.store.addToDebug('yield* this.store.tryExecute.call(this, ', JSON.stringify(op), ')')\n if (op.struct === 'Delete') {\n yield* Y.Struct.Delete.execute.call(this, op)\n // this is now called in Transaction.deleteOperation!\n // yield* this.store.operationAdded(this, op)\n } else {\n // check if this op was defined\n var defined = yield* this.getInsertion(op.id)\n while (defined != null && defined.content != null) {\n // check if this op has a longer content in the case it is defined\n if (defined.id[1] + defined.content.length < op.id[1] + op.content.length) {\n var overlapSize = defined.content.length - (op.id[1] - defined.id[1])\n op.content.splice(0, overlapSize)\n op.id = [op.id[0], op.id[1] + overlapSize]\n op.left = Y.utils.getLastId(defined)\n op.origin = op.left\n defined = yield* this.getOperation(op.id) // getOperation suffices here\n } else {\n break\n }\n }\n if (defined == null) {\n var opid = op.id\n var isGarbageCollected = yield* this.isGarbageCollected(opid)\n if (!isGarbageCollected) {\n // TODO: reduce number of get / put calls for op ..\n yield* Y.Struct[op.struct].execute.call(this, op)\n yield* this.addOperation(op)\n yield* this.store.operationAdded(this, op)\n // operationAdded can change op..\n op = yield* this.getOperation(opid)\n // if insertion, try to combine with left\n yield* this.tryCombineWithLeft(op)\n }\n }\n }\n }\n /*\n * Called by a transaction when an operation is added.\n * This function is especially important for y-indexeddb, where several instances may share a single database.\n * Every time an operation is created by one instance, it is send to all other instances and operationAdded is called\n *\n * If it's not a Delete operation:\n * * Checks if another operation is executable (listenersById)\n * * Update state, if possible\n *\n * Always:\n * * Call type\n */\n * operationAdded (transaction, op) {\n if (op.struct === 'Delete') {\n var type = this.initializedTypes[JSON.stringify(op.targetParent)]\n if (type != null) {\n yield* type._changed(transaction, op)\n }\n } else {\n // increase SS\n yield* transaction.updateState(op.id[0])\n var opLen = op.content != null ? op.content.length : 1\n for (let i = 0; i < opLen; i++) {\n // notify whenOperation listeners (by id)\n var sid = JSON.stringify([op.id[0], op.id[1] + i])\n var l = this.listenersById[sid]\n delete this.listenersById[sid]\n if (l != null) {\n for (var key in l) {\n var listener = l[key]\n if (--listener.missing === 0) {\n this.whenOperationsExist([], listener.op)\n }\n }\n }\n }\n var t = this.initializedTypes[JSON.stringify(op.parent)]\n\n // if parent is deleted, mark as gc'd and return\n if (op.parent != null) {\n var parentIsDeleted = yield* transaction.isDeleted(op.parent)\n if (parentIsDeleted) {\n yield* transaction.deleteList(op.id)\n return\n }\n }\n\n // notify parent, if it was instanciated as a custom type\n if (t != null) {\n let o = Y.utils.copyOperation(op)\n yield* t._changed(transaction, o)\n }\n if (!op.deleted) {\n // Delete if DS says this is actually deleted\n var len = op.content != null ? op.content.length : 1\n var startId = op.id // You must not use op.id in the following loop, because op will change when deleted\n // TODO: !! console.log('TODO: change this before commiting')\n for (let i = 0; i < len; i++) {\n var id = [startId[0], startId[1] + i]\n var opIsDeleted = yield* transaction.isDeleted(id)\n if (opIsDeleted) {\n var delop = {\n struct: 'Delete',\n target: id\n }\n yield* this.tryExecute.call(transaction, delop)\n }\n }\n }\n }\n }\n whenTransactionsFinished () {\n if (this.transactionInProgress) {\n if (this.transactionsFinished == null) {\n var resolve\n var promise = new Promise(function (r) {\n resolve = r\n })\n this.transactionsFinished = {\n resolve: resolve,\n promise: promise\n }\n }\n return this.transactionsFinished.promise\n } else {\n return Promise.resolve()\n }\n }\n // Check if there is another transaction request.\n // * the last transaction is always a flush :)\n getNextRequest () {\n if (this.waitingTransactions.length === 0) {\n if (this.transactionIsFlushed) {\n this.transactionInProgress = false\n this.transactionIsFlushed = false\n if (this.transactionsFinished != null) {\n this.transactionsFinished.resolve()\n this.transactionsFinished = null\n }\n return null\n } else {\n this.transactionIsFlushed = true\n return function * () {\n yield* this.flush()\n }\n }\n } else {\n this.transactionIsFlushed = false\n return this.waitingTransactions.shift()\n }\n }\n requestTransaction (makeGen/* :any */, callImmediately) {\n this.waitingTransactions.push(makeGen)\n if (!this.transactionInProgress) {\n this.transactionInProgress = true\n setTimeout(() => {\n this.transact(this.getNextRequest())\n }, 0)\n }\n }\n /*\n Get a created/initialized type.\n */\n getType (id) {\n return this.initializedTypes[JSON.stringify(id)]\n }\n /*\n Init type. This is called when a remote operation is retrieved, and transformed to a type\n TODO: delete type from store.initializedTypes[id] when corresponding id was deleted!\n */\n * initType (id, args) {\n var sid = JSON.stringify(id)\n var t = this.store.initializedTypes[sid]\n if (t == null) {\n var op/* :MapStruct | ListStruct */ = yield* this.getOperation(id)\n if (op != null) {\n t = yield* Y[op.type].typeDefinition.initType.call(this, this.store, op, args)\n this.store.initializedTypes[sid] = t\n }\n }\n return t\n }\n /*\n Create type. This is called when the local user creates a type (which is a synchronous action)\n */\n createType (typedefinition, id) {\n var structname = typedefinition[0].struct\n id = id || this.getNextOpId(1)\n var op = Y.Struct[structname].create(id)\n op.type = typedefinition[0].name\n\n this.requestTransaction(function * () {\n if (op.id[0] === '_') {\n yield* this.setOperation(op)\n } else {\n yield* this.applyCreatedOperations([op])\n }\n })\n var t = Y[op.type].typeDefinition.createType(this, op, typedefinition[1])\n this.initializedTypes[JSON.stringify(op.id)] = t\n return t\n }\n }\n Y.AbstractDatabase = AbstractDatabase\n}\n","/* @flow */\n'use strict'\n\n/*\n An operation also defines the structure of a type. This is why operation and\n structure are used interchangeably here.\n\n It must be of the type Object. I hope to achieve some performance\n improvements when working on databases that support the json format.\n\n An operation must have the following properties:\n\n * encode\n - Encode the structure in a readable format (preferably string- todo)\n * decode (todo)\n - decode structure to json\n * execute\n - Execute the semantics of an operation.\n * requiredOps\n - Operations that are required to execute this operation.\n*/\nmodule.exports = function (Y/* :any */) {\n var Struct = {\n /* This is the only operation that is actually not a structure, because\n it is not stored in the OS. This is why it _does not_ have an id\n\n op = {\n target: Id\n }\n */\n Delete: {\n encode: function (op) {\n return {\n target: op.target,\n length: op.length || 0,\n struct: 'Delete'\n }\n },\n requiredOps: function (op) {\n return [] // [op.target]\n },\n execute: function * (op) {\n return yield* this.deleteOperation(op.target, op.length || 1)\n }\n },\n Insert: {\n /* {\n content: [any],\n opContent: Id,\n id: Id,\n left: Id,\n origin: Id,\n right: Id,\n parent: Id,\n parentSub: string (optional), // child of Map type\n }\n */\n encode: function (op/* :Insertion */) /* :Insertion */ {\n // TODO: you could not send the \"left\" property, then you also have to\n // \"op.left = null\" in $execute or $decode\n var e/* :any */ = {\n id: op.id,\n left: op.left,\n right: op.right,\n origin: op.origin,\n parent: op.parent,\n struct: op.struct\n }\n if (op.parentSub != null) {\n e.parentSub = op.parentSub\n }\n if (op.hasOwnProperty('opContent')) {\n e.opContent = op.opContent\n } else {\n e.content = op.content.slice()\n }\n\n return e\n },\n requiredOps: function (op) {\n var ids = []\n if (op.left != null) {\n ids.push(op.left)\n }\n if (op.right != null) {\n ids.push(op.right)\n }\n if (op.origin != null && !Y.utils.compareIds(op.left, op.origin)) {\n ids.push(op.origin)\n }\n // if (op.right == null && op.left == null) {\n ids.push(op.parent)\n\n if (op.opContent != null) {\n ids.push(op.opContent)\n }\n return ids\n },\n getDistanceToOrigin: function * (op) {\n if (op.left == null) {\n return 0\n } else {\n var d = 0\n var o = yield* this.getInsertion(op.left)\n while (!Y.utils.matchesId(o, op.origin)) {\n d++\n if (o.left == null) {\n break\n } else {\n o = yield* this.getInsertion(o.left)\n }\n }\n return d\n }\n },\n /*\n # $this has to find a unique position between origin and the next known character\n # case 1: $origin equals $o.origin: the $creator parameter decides if left or right\n # let $OL= [o1,o2,o3,o4], whereby $this is to be inserted between o1 and o4\n # o2,o3 and o4 origin is 1 (the position of o2)\n # there is the case that $this.creator < o2.creator, but o3.creator < $this.creator\n # then o2 knows o3. Since on another client $OL could be [o1,o3,o4] the problem is complex\n # therefore $this would be always to the right of o3\n # case 2: $origin < $o.origin\n # if current $this insert_position > $o origin: $this ins\n # else $insert_position will not change\n # (maybe we encounter case 1 later, then this will be to the right of $o)\n # case 3: $origin > $o.origin\n # $this insert_position is to the left of $o (forever!)\n */\n execute: function * (op) {\n var i // loop counter\n\n // during this function some ops may get split into two pieces (e.g. with getInsertionCleanEnd)\n // We try to merge them later, if possible\n var tryToRemergeLater = []\n\n if (op.origin != null) { // TODO: !== instead of !=\n // we save in origin that op originates in it\n // we need that later when we eventually garbage collect origin (see transaction)\n var origin = yield* this.getInsertionCleanEnd(op.origin)\n if (origin.originOf == null) {\n origin.originOf = []\n }\n origin.originOf.push(op.id)\n yield* this.setOperation(origin)\n if (origin.right != null) {\n tryToRemergeLater.push(origin.right)\n }\n }\n var distanceToOrigin = i = yield* Struct.Insert.getDistanceToOrigin.call(this, op) // most cases: 0 (starts from 0)\n\n // now we begin to insert op in the list of insertions..\n var o\n var parent\n var start\n\n // find o. o is the first conflicting operation\n if (op.left != null) {\n o = yield* this.getInsertionCleanEnd(op.left)\n if (!Y.utils.compareIds(op.left, op.origin) && o.right != null) {\n // only if not added previously\n tryToRemergeLater.push(o.right)\n }\n o = (o.right == null) ? null : yield* this.getOperation(o.right)\n } else { // left == null\n parent = yield* this.getOperation(op.parent)\n let startId = op.parentSub ? parent.map[op.parentSub] : parent.start\n start = startId == null ? null : yield* this.getOperation(startId)\n o = start\n }\n\n // make sure to split op.right if necessary (also add to tryCombineWithLeft)\n if (op.right != null) {\n tryToRemergeLater.push(op.right)\n yield* this.getInsertionCleanStart(op.right)\n }\n\n // handle conflicts\n while (true) {\n if (o != null && !Y.utils.compareIds(o.id, op.right)) {\n var oOriginDistance = yield* Struct.Insert.getDistanceToOrigin.call(this, o)\n if (oOriginDistance === i) {\n // case 1\n if (o.id[0] < op.id[0]) {\n op.left = Y.utils.getLastId(o)\n distanceToOrigin = i + 1 // just ignore o.content.length, doesn't make a difference\n }\n } else if (oOriginDistance < i) {\n // case 2\n if (i - distanceToOrigin <= oOriginDistance) {\n op.left = Y.utils.getLastId(o)\n distanceToOrigin = i + 1 // just ignore o.content.length, doesn't make a difference\n }\n } else {\n break\n }\n i++\n if (o.right != null) {\n o = yield* this.getInsertion(o.right)\n } else {\n o = null\n }\n } else {\n break\n }\n }\n\n // reconnect..\n var left = null\n var right = null\n if (parent == null) {\n parent = yield* this.getOperation(op.parent)\n }\n\n // reconnect left and set right of op\n if (op.left != null) {\n left = yield* this.getInsertion(op.left)\n // link left\n op.right = left.right\n left.right = op.id\n\n yield* this.setOperation(left)\n } else {\n // set op.right from parent, if necessary\n op.right = op.parentSub ? parent.map[op.parentSub] || null : parent.start\n }\n // reconnect right\n if (op.right != null) {\n // TODO: wanna connect right too?\n right = yield* this.getOperation(op.right)\n right.left = Y.utils.getLastId(op)\n\n // if right exists, and it is supposed to be gc'd. Remove it from the gc\n if (right.gc != null) {\n if (right.content != null && right.content.length > 1) {\n right = yield* this.getInsertionCleanEnd(right.id)\n }\n this.store.removeFromGarbageCollector(right)\n }\n yield* this.setOperation(right)\n }\n\n // update parents .map/start/end properties\n if (op.parentSub != null) {\n if (left == null) {\n parent.map[op.parentSub] = op.id\n yield* this.setOperation(parent)\n }\n // is a child of a map struct.\n // Then also make sure that only the most left element is not deleted\n // We do not call the type in this case (this is what the third parameter is for)\n if (op.right != null) {\n yield* this.deleteOperation(op.right, 1, true)\n }\n if (op.left != null) {\n yield* this.deleteOperation(op.id, 1, true)\n }\n } else {\n if (right == null || left == null) {\n if (right == null) {\n parent.end = Y.utils.getLastId(op)\n }\n if (left == null) {\n parent.start = op.id\n }\n yield* this.setOperation(parent)\n }\n }\n\n // try to merge original op.left and op.origin\n for (i = 0; i < tryToRemergeLater.length; i++) {\n var m = yield* this.getOperation(tryToRemergeLater[i])\n yield* this.tryCombineWithLeft(m)\n }\n }\n },\n List: {\n /*\n {\n start: null,\n end: null,\n struct: \"List\",\n type: \"\",\n id: this.os.getNextOpId(1)\n }\n */\n create: function (id) {\n return {\n start: null,\n end: null,\n struct: 'List',\n id: id\n }\n },\n encode: function (op) {\n var e = {\n struct: 'List',\n id: op.id,\n type: op.type\n }\n if (op.requires != null) {\n e.requires = op.requires\n }\n if (op.info != null) {\n e.info = op.info\n }\n return e\n },\n requiredOps: function () {\n /*\n var ids = []\n if (op.start != null) {\n ids.push(op.start)\n }\n if (op.end != null){\n ids.push(op.end)\n }\n return ids\n */\n return []\n },\n execute: function * (op) {\n op.start = null\n op.end = null\n },\n ref: function * (op, pos) {\n if (op.start == null) {\n return null\n }\n var res = null\n var o = yield* this.getOperation(op.start)\n\n while (true) {\n if (!o.deleted) {\n res = o\n pos--\n }\n if (pos >= 0 && o.right != null) {\n o = yield* this.getOperation(o.right)\n } else {\n break\n }\n }\n return res\n },\n map: function * (o, f) {\n o = o.start\n var res = []\n while (o != null) { // TODO: change to != (at least some convention)\n var operation = yield* this.getOperation(o)\n if (!operation.deleted) {\n res.push(f(operation))\n }\n o = operation.right\n }\n return res\n }\n },\n Map: {\n /*\n {\n map: {},\n struct: \"Map\",\n type: \"\",\n id: this.os.getNextOpId(1)\n }\n */\n create: function (id) {\n return {\n id: id,\n map: {},\n struct: 'Map'\n }\n },\n encode: function (op) {\n var e = {\n struct: 'Map',\n type: op.type,\n id: op.id,\n map: {} // overwrite map!!\n }\n if (op.requires != null) {\n e.requires = op.requires\n }\n if (op.info != null) {\n e.info = op.info\n }\n return e\n },\n requiredOps: function () {\n return []\n },\n execute: function * () {},\n /*\n Get a property by name\n */\n get: function * (op, name) {\n var oid = op.map[name]\n if (oid != null) {\n var res = yield* this.getOperation(oid)\n if (res == null || res.deleted) {\n return void 0\n } else if (res.opContent == null) {\n return res.content[0]\n } else {\n return yield* this.getType(res.opContent)\n }\n }\n }\n }\n }\n Y.Struct = Struct\n}\n","/* @flow */\n'use strict'\n\n/*\n Partial definition of a transaction\n\n A transaction provides all the the async functionality on a database.\n\n By convention, a transaction has the following properties:\n * ss for StateSet\n * os for OperationStore\n * ds for DeleteStore\n\n A transaction must also define the following methods:\n * checkDeleteStoreForState(state)\n - When increasing the state of a user, an operation with an higher id\n may already be garbage collected, and therefore it will never be received.\n update the state to reflect this knowledge. This won't call a method to save the state!\n * getDeleteSet(id)\n - Get the delete set in a readable format:\n {\n \"userX\": [\n [5,1], // starting from position 5, one operations is deleted\n [9,4] // starting from position 9, four operations are deleted\n ],\n \"userY\": ...\n }\n * getOpsFromDeleteSet(ds) -- TODO: just call this.deleteOperation(id) here\n - get a set of deletions that need to be applied in order to get to\n achieve the state of the supplied ds\n * setOperation(op)\n - write `op` to the database.\n Note: this is allowed to return an in-memory object.\n E.g. the Memory adapter returns the object that it has in-memory.\n Changing values on this object will be stored directly in the database\n without calling this function. Therefore,\n setOperation may have no functionality in some adapters. This also has\n implications on the way we use operations that were served from the database.\n We try not to call copyObject, if not necessary.\n * addOperation(op)\n - add an operation to the database.\n This may only be called once for every op.id\n Must return a function that returns the next operation in the database (ordered by id)\n * getOperation(id)\n * removeOperation(id)\n - remove an operation from the database. This is called when an operation\n is garbage collected.\n * setState(state)\n - `state` is of the form\n {\n user: \"1\",\n clock: 4\n } <- meaning that we have four operations from user \"1\"\n (with these id's respectively: 0, 1, 2, and 3)\n * getState(user)\n * getStateVector()\n - Get the state of the OS in the form\n [{\n user: \"userX\",\n clock: 11\n },\n ..\n ]\n * getStateSet()\n - Get the state of the OS in the form\n {\n \"userX\": 11,\n \"userY\": 22\n }\n * getOperations(startSS)\n - Get the all the operations that are necessary in order to achive the\n stateSet of this user, starting from a stateSet supplied by another user\n * makeOperationReady(ss, op)\n - this is called only by `getOperations(startSS)`. It makes an operation\n applyable on a given SS.\n*/\nmodule.exports = function (Y/* :any */) {\n class TransactionInterface {\n /* ::\n store: Y.AbstractDatabase;\n ds: Store;\n os: Store;\n ss: Store;\n */\n /*\n Apply operations that this user created (no remote ones!)\n * does not check for Struct.*.requiredOps()\n * also broadcasts it through the connector\n */\n * applyCreatedOperations (ops) {\n var send = []\n for (var i = 0; i < ops.length; i++) {\n var op = ops[i]\n yield* this.store.tryExecute.call(this, op)\n if (op.id == null || typeof op.id[1] !== 'string') {\n send.push(Y.Struct[op.struct].encode(op))\n }\n }\n if (this.store.y.connector.isSynced && send.length > 0) { // TODO: && !this.store.forwardAppliedOperations (but then i don't send delete ops)\n // is connected, and this is not going to be send in addOperation\n this.store.y.connector.broadcastOps(send)\n }\n }\n\n * deleteList (start) {\n while (start != null) {\n start = yield* this.getOperation(start)\n if (!start.gc) {\n start.gc = true\n start.deleted = true\n yield* this.setOperation(start)\n var delLength = start.content != null ? start.content.length : 1\n yield* this.markDeleted(start.id, delLength)\n if (start.opContent != null) {\n yield* this.deleteOperation(start.opContent)\n }\n this.store.queueGarbageCollector(start.id)\n }\n start = start.right\n }\n }\n\n /*\n Mark an operation as deleted, and add it to the GC, if possible.\n */\n * deleteOperation (targetId, length, preventCallType) /* :Generator */ {\n if (length == null) {\n length = 1\n }\n yield* this.markDeleted(targetId, length)\n while (length > 0) {\n var callType = false\n var target = yield* this.os.findWithUpperBound([targetId[0], targetId[1] + length - 1])\n var targetLength = target != null && target.content != null ? target.content.length : 1\n if (target == null || target.id[0] !== targetId[0] || target.id[1] + targetLength <= targetId[1]) {\n // does not exist or is not in the range of the deletion\n target = null\n length = 0\n } else {\n // does exist, check if it is too long\n if (!target.deleted) {\n if (target.id[1] < targetId[1]) {\n // starts to the left of the deletion range\n target = yield* this.getInsertionCleanStart(targetId)\n targetLength = target.content.length // must have content property!\n }\n if (target.id[1] + targetLength > targetId[1] + length) {\n // ends to the right of the deletion range\n target = yield* this.getInsertionCleanEnd([targetId[0], targetId[1] + length - 1])\n targetLength = target.content.length\n }\n }\n length = target.id[1] - targetId[1]\n }\n\n if (target != null) {\n if (!target.deleted) {\n callType = true\n // set deleted & notify type\n target.deleted = true\n // delete containing lists\n if (target.start != null) {\n // TODO: don't do it like this .. -.-\n yield* this.deleteList(target.start)\n // yield* this.deleteList(target.id) -- do not gc itself because this may still get referenced\n }\n if (target.map != null) {\n for (var name in target.map) {\n yield* this.deleteList(target.map[name])\n }\n // TODO: here to.. (see above)\n // yield* this.deleteList(target.id) -- see above\n }\n if (target.opContent != null) {\n yield* this.deleteOperation(target.opContent)\n // target.opContent = null\n }\n if (target.requires != null) {\n for (var i = 0; i < target.requires.length; i++) {\n yield* this.deleteOperation(target.requires[i])\n }\n }\n }\n var left\n if (target.left != null) {\n left = yield* this.getInsertion(target.left)\n } else {\n left = null\n }\n\n // set here because it was deleted and/or gc'd\n yield* this.setOperation(target)\n\n /*\n Check if it is possible to add right to the gc.\n Because this delete can't be responsible for left being gc'd,\n we don't have to add left to the gc..\n */\n var right\n if (target.right != null) {\n right = yield* this.getOperation(target.right)\n } else {\n right = null\n }\n if (callType && !preventCallType) {\n yield* this.store.operationAdded(this, {\n struct: 'Delete',\n target: target.id,\n length: targetLength,\n targetParent: target.parent\n })\n }\n // need to gc in the end!\n yield* this.store.addToGarbageCollector.call(this, target, left)\n if (right != null) {\n yield* this.store.addToGarbageCollector.call(this, right, target)\n }\n }\n }\n }\n /*\n Mark an operation as deleted&gc'd\n */\n * markGarbageCollected (id, len) {\n // this.mem.push([\"gc\", id]);\n this.store.addToDebug('yield* this.markGarbageCollected(', id, ', ', len, ')')\n var n = yield* this.markDeleted(id, len)\n if (n.id[1] < id[1] && !n.gc) {\n // un-extend left\n var newlen = n.len - (id[1] - n.id[1])\n n.len -= newlen\n yield* this.ds.put(n)\n n = {id: id, len: newlen, gc: false}\n yield* this.ds.put(n)\n }\n // get prev&next before adding a new operation\n var prev = yield* this.ds.findPrev(id)\n var next = yield* this.ds.findNext(id)\n\n if (id[1] + len < n.id[1] + n.len && !n.gc) {\n // un-extend right\n yield* this.ds.put({id: [id[0], id[1] + len], len: n.len - len, gc: false})\n n.len = len\n }\n // set gc'd\n n.gc = true\n // can extend left?\n if (\n prev != null &&\n prev.gc &&\n Y.utils.compareIds([prev.id[0], prev.id[1] + prev.len], n.id)\n ) {\n prev.len += n.len\n yield* this.ds.delete(n.id)\n n = prev\n // ds.put n here?\n }\n // can extend right?\n if (\n next != null &&\n next.gc &&\n Y.utils.compareIds([n.id[0], n.id[1] + n.len], next.id)\n ) {\n n.len += next.len\n yield* this.ds.delete(next.id)\n }\n yield* this.ds.put(n)\n yield* this.updateState(n.id[0])\n }\n /*\n Mark an operation as deleted.\n\n returns the delete node\n */\n * markDeleted (id, length) {\n if (length == null) {\n length = 1\n }\n // this.mem.push([\"del\", id]);\n var n = yield* this.ds.findWithUpperBound(id)\n if (n != null && n.id[0] === id[0]) {\n if (n.id[1] <= id[1] && id[1] <= n.id[1] + n.len) {\n // id is in n's range\n var diff = id[1] + length - (n.id[1] + n.len) // overlapping right\n if (diff > 0) {\n // id+length overlaps n\n if (!n.gc) {\n n.len += diff\n } else {\n diff = n.id[1] + n.len - id[1] // overlapping left (id till n.end)\n if (diff < length) {\n // a partial deletion\n n = {id: [id[0], id[1] + diff], len: length - diff, gc: false}\n yield* this.ds.put(n)\n } else {\n // already gc'd\n throw new Error('Cannot happen! (it dit though.. :()')\n // return n\n }\n }\n } else {\n // no overlapping, already deleted\n return n\n }\n } else {\n // cannot extend left (there is no left!)\n n = {id: id, len: length, gc: false}\n yield* this.ds.put(n) // TODO: you double-put !!\n }\n } else {\n // cannot extend left\n n = {id: id, len: length, gc: false}\n yield* this.ds.put(n)\n }\n // can extend right?\n var next = yield* this.ds.findNext(n.id)\n if (\n next != null &&\n n.id[0] === next.id[0] &&\n n.id[1] + n.len >= next.id[1]\n ) {\n diff = n.id[1] + n.len - next.id[1] // from next.start to n.end\n while (diff >= 0) {\n // n overlaps with next\n if (next.gc) {\n // gc is stronger, so reduce length of n\n n.len -= diff\n if (diff >= next.len) {\n // delete the missing range after next\n diff = diff - next.len // missing range after next\n if (diff > 0) {\n yield* this.ds.put(n) // unneccessary? TODO!\n yield* this.markDeleted([next.id[0], next.id[1] + next.len], diff)\n }\n }\n break\n } else {\n // we can extend n with next\n if (diff > next.len) {\n // n is even longer than next\n // get next.next, and try to extend it\n var _next = yield* this.ds.findNext(next.id)\n yield* this.ds.delete(next.id)\n if (_next == null || n.id[0] !== _next.id[0]) {\n break\n } else {\n next = _next\n diff = n.id[1] + n.len - next.id[1] // from next.start to n.end\n // continue!\n }\n } else {\n // n just partially overlaps with next. extend n, delete next, and break this loop\n n.len += next.len - diff\n yield* this.ds.delete(next.id)\n break\n }\n }\n }\n }\n yield* this.ds.put(n)\n return n\n }\n /*\n Call this method when the client is connected&synced with the\n other clients (e.g. master). This will query the database for\n operations that can be gc'd and add them to the garbage collector.\n */\n * garbageCollectAfterSync () {\n if (this.store.gc1.length > 0 || this.store.gc2.length > 0) {\n console.warn('gc should be empty after sync')\n }\n if (!this.store.gc) {\n return\n }\n yield* this.os.iterate(this, null, null, function * (op) {\n if (op.gc) {\n delete op.gc\n yield* this.setOperation(op)\n }\n if (op.parent != null) {\n var parentDeleted = yield* this.isDeleted(op.parent)\n if (parentDeleted) {\n op.gc = true\n if (!op.deleted) {\n yield* this.markDeleted(op.id, op.content != null ? op.content.length : 1)\n op.deleted = true\n if (op.opContent != null) {\n yield* this.deleteOperation(op.opContent)\n }\n if (op.requires != null) {\n for (var i = 0; i < op.requires.length; i++) {\n yield* this.deleteOperation(op.requires[i])\n }\n }\n }\n yield* this.setOperation(op)\n this.store.gc1.push(op.id) // this is ok becaues its shortly before sync (otherwise use queueGarbageCollector!)\n return\n }\n }\n if (op.deleted) {\n var left = null\n if (op.left != null) {\n left = yield* this.getInsertion(op.left)\n }\n yield* this.store.addToGarbageCollector.call(this, op, left)\n }\n })\n }\n /*\n Really remove an op and all its effects.\n The complicated case here is the Insert operation:\n * reset left\n * reset right\n * reset parent.start\n * reset parent.end\n * reset origins of all right ops\n */\n * garbageCollectOperation (id) {\n this.store.addToDebug('yield* this.garbageCollectOperation(', id, ')')\n var o = yield* this.getOperation(id)\n yield* this.markGarbageCollected(id, (o != null && o.content != null) ? o.content.length : 1) // always mark gc'd\n // if op exists, then clean that mess up..\n if (o != null) {\n var deps = []\n if (o.opContent != null) {\n deps.push(o.opContent)\n }\n if (o.requires != null) {\n deps = deps.concat(o.requires)\n }\n for (var i = 0; i < deps.length; i++) {\n var dep = yield* this.getOperation(deps[i])\n if (dep != null) {\n if (!dep.deleted) {\n yield* this.deleteOperation(dep.id)\n dep = yield* this.getOperation(dep.id)\n }\n dep.gc = true\n yield* this.setOperation(dep)\n this.store.queueGarbageCollector(dep.id)\n } else {\n yield* this.markGarbageCollected(deps[i], 1)\n }\n }\n\n // remove gc'd op from the left op, if it exists\n if (o.left != null) {\n var left = yield* this.getInsertion(o.left)\n left.right = o.right\n yield* this.setOperation(left)\n }\n // remove gc'd op from the right op, if it exists\n // also reset origins of right ops\n if (o.right != null) {\n var right = yield* this.getOperation(o.right)\n right.left = o.left\n yield* this.setOperation(right)\n\n if (o.originOf != null && o.originOf.length > 0) {\n // find new origin of right ops\n // origin is the first left deleted operation\n var neworigin = o.left\n var neworigin_ = null\n while (neworigin != null) {\n neworigin_ = yield* this.getInsertion(neworigin)\n if (neworigin_.deleted) {\n break\n }\n neworigin = neworigin_.left\n }\n\n // reset origin of all right ops (except first right - duh!),\n\n /* ** The following code does not rely on the the originOf property **\n I recently added originOf to all Insert Operations (see Struct.Insert.execute),\n which saves which operations originate in a Insert operation.\n Garbage collecting without originOf is more memory efficient, but is nearly impossible for large texts, or lists!\n But I keep this code for now\n ```\n // reset origin of right\n right.origin = neworigin\n // search until you find origin pointer to the left of o\n if (right.right != null) {\n var i = yield* this.getOperation(right.right)\n var ids = [o.id, o.right]\n while (ids.some(function (id) {\n return Y.utils.compareIds(id, i.origin)\n })) {\n if (Y.utils.compareIds(i.origin, o.id)) {\n // reset origin of i\n i.origin = neworigin\n yield* this.setOperation(i)\n }\n // get next i\n if (i.right == null) {\n break\n } else {\n ids.push(i.id)\n i = yield* this.getOperation(i.right)\n }\n }\n }\n ```\n */\n // ** Now the new implementation starts **\n // reset neworigin of all originOf[*]\n for (var _i in o.originOf) {\n var originsIn = yield* this.getOperation(o.originOf[_i])\n if (originsIn != null) {\n originsIn.origin = neworigin\n yield* this.setOperation(originsIn)\n }\n }\n if (neworigin != null) {\n if (neworigin_.originOf == null) {\n neworigin_.originOf = o.originOf\n } else {\n neworigin_.originOf = o.originOf.concat(neworigin_.originOf)\n }\n yield* this.setOperation(neworigin_)\n }\n // we don't need to set right here, because\n // right should be in o.originOf => it is set it the previous for loop\n }\n }\n // o may originate in another operation.\n // Since o is deleted, we have to reset o.origin's `originOf` property\n if (o.origin != null) {\n var origin = yield* this.getInsertion(o.origin)\n origin.originOf = origin.originOf.filter(function (_id) {\n return !Y.utils.compareIds(id, _id)\n })\n yield* this.setOperation(origin)\n }\n var parent\n if (o.parent != null) {\n parent = yield* this.getOperation(o.parent)\n }\n // remove gc'd op from parent, if it exists\n if (parent != null) {\n var setParent = false // whether to save parent to the os\n if (o.parentSub != null) {\n if (Y.utils.compareIds(parent.map[o.parentSub], o.id)) {\n setParent = true\n if (o.right != null) {\n parent.map[o.parentSub] = o.right\n } else {\n delete parent.map[o.parentSub]\n }\n }\n } else {\n if (Y.utils.compareIds(parent.start, o.id)) {\n // gc'd op is the start\n setParent = true\n parent.start = o.right\n }\n if (Y.utils.matchesId(o, parent.end)) {\n // gc'd op is the end\n setParent = true\n parent.end = o.left\n }\n }\n if (setParent) {\n yield* this.setOperation(parent)\n }\n }\n // finally remove it from the os\n yield* this.removeOperation(o.id)\n }\n }\n * checkDeleteStoreForState (state) {\n var n = yield* this.ds.findWithUpperBound([state.user, state.clock])\n if (n != null && n.id[0] === state.user && n.gc) {\n state.clock = Math.max(state.clock, n.id[1] + n.len)\n }\n }\n * updateState (user) {\n var state = yield* this.getState(user)\n yield* this.checkDeleteStoreForState(state)\n var o = yield* this.getInsertion([user, state.clock])\n var oLength = (o != null && o.content != null) ? o.content.length : 1\n while (o != null && user === o.id[0] && o.id[1] <= state.clock && o.id[1] + oLength > state.clock) {\n // either its a new operation (1. case), or it is an operation that was deleted, but is not yet in the OS\n state.clock += oLength\n yield* this.checkDeleteStoreForState(state)\n o = yield* this.os.findNext(o.id)\n oLength = (o != null && o.content != null) ? o.content.length : 1\n }\n yield* this.setState(state)\n }\n /*\n apply a delete set in order to get\n the state of the supplied ds\n */\n * applyDeleteSet (ds) {\n var deletions = []\n\n for (var user in ds) {\n var dv = ds[user]\n var pos = 0\n var d = dv[pos]\n yield* this.ds.iterate(this, [user, 0], [user, Number.MAX_VALUE], function * (n) {\n // cases:\n // 1. d deletes something to the right of n\n // => go to next n (break)\n // 2. d deletes something to the left of n\n // => create deletions\n // => reset d accordingly\n // *)=> if d doesn't delete anything anymore, go to next d (continue)\n // 3. not 2) and d deletes something that also n deletes\n // => reset d so that it doesn't contain n's deletion\n // *)=> if d does not delete anything anymore, go to next d (continue)\n while (d != null) {\n var diff = 0 // describe the diff of length in 1) and 2)\n if (n.id[1] + n.len <= d[0]) {\n // 1)\n break\n } else if (d[0] < n.id[1]) {\n // 2)\n // delete maximum the len of d\n // else delete as much as possible\n diff = Math.min(n.id[1] - d[0], d[1])\n deletions.push([user, d[0], diff, d[2]])\n } else {\n // 3)\n diff = n.id[1] + n.len - d[0] // never null (see 1)\n if (d[2] && !n.gc) {\n // d marks as gc'd but n does not\n // then delete either way\n deletions.push([user, d[0], Math.min(diff, d[1]), d[2]])\n }\n }\n if (d[1] <= diff) {\n // d doesn't delete anything anymore\n d = dv[++pos]\n } else {\n d[0] = d[0] + diff // reset pos\n d[1] = d[1] - diff // reset length\n }\n }\n })\n // for the rest.. just apply it\n for (; pos < dv.length; pos++) {\n d = dv[pos]\n deletions.push([user, d[0], d[1], d[2]])\n }\n }\n for (var i = 0; i < deletions.length; i++) {\n var del = deletions[i]\n // always try to delete..\n yield* this.deleteOperation([del[0], del[1]], del[2])\n if (del[3]) {\n // gc..\n yield* this.markGarbageCollected([del[0], del[1]], del[2]) // always mark gc'd\n // remove operation..\n var counter = del[1] + del[2]\n while (counter >= del[1]) {\n var o = yield* this.os.findWithUpperBound([del[0], counter - 1])\n if (o == null) {\n break\n }\n var oLen = o.content != null ? o.content.length : 1\n if (o.id[0] !== del[0] || o.id[1] + oLen <= del[1]) {\n // not in range\n break\n }\n if (o.id[1] + oLen > del[1] + del[2]) {\n // overlaps right\n o = yield* this.getInsertionCleanEnd([del[0], del[1] + del[2] - 1])\n }\n if (o.id[1] < del[1]) {\n // overlaps left\n o = yield* this.getInsertionCleanStart([del[0], del[1]])\n }\n counter = o.id[1]\n yield* this.garbageCollectOperation(o.id)\n }\n }\n if (this.store.forwardAppliedOperations) {\n var ops = []\n ops.push({struct: 'Delete', target: [del[0], del[1]], length: del[2]})\n this.store.y.connector.broadcastOps(ops)\n }\n }\n }\n * isGarbageCollected (id) {\n var n = yield* this.ds.findWithUpperBound(id)\n return n != null && n.id[0] === id[0] && id[1] < n.id[1] + n.len && n.gc\n }\n /*\n A DeleteSet (ds) describes all the deleted ops in the OS\n */\n * getDeleteSet () {\n var ds = {}\n yield* this.ds.iterate(this, null, null, function * (n) {\n var user = n.id[0]\n var counter = n.id[1]\n var len = n.len\n var gc = n.gc\n var dv = ds[user]\n if (dv === void 0) {\n dv = []\n ds[user] = dv\n }\n dv.push([counter, len, gc])\n })\n return ds\n }\n * isDeleted (id) {\n var n = yield* this.ds.findWithUpperBound(id)\n return n != null && n.id[0] === id[0] && id[1] < n.id[1] + n.len\n }\n * setOperation (op) {\n yield* this.os.put(op)\n return op\n }\n * addOperation (op) {\n yield* this.os.put(op)\n if (this.store.y.connector.isSynced && this.store.forwardAppliedOperations && typeof op.id[1] !== 'string') {\n // is connected, and this is not going to be send in addOperation\n this.store.y.connector.broadcastOps([op])\n }\n }\n // if insertion, try to combine with left insertion (if both have content property)\n * tryCombineWithLeft (op) {\n if (\n op != null &&\n op.left != null &&\n op.content != null &&\n op.left[0] === op.id[0] &&\n Y.utils.compareIds(op.left, op.origin)\n ) {\n var left = yield* this.getInsertion(op.left)\n if (left.content != null &&\n left.id[1] + left.content.length === op.id[1] &&\n left.originOf.length === 1 &&\n !left.gc && !left.deleted &&\n !op.gc && !op.deleted\n ) {\n // combine!\n if (op.originOf != null) {\n left.originOf = op.originOf\n } else {\n delete left.originOf\n }\n left.content = left.content.concat(op.content)\n left.right = op.right\n yield* this.os.delete(op.id)\n yield* this.setOperation(left)\n }\n }\n }\n * getInsertion (id) {\n var ins = yield* this.os.findWithUpperBound(id)\n if (ins == null) {\n return null\n } else {\n var len = ins.content != null ? ins.content.length : 1 // in case of opContent\n if (id[0] === ins.id[0] && id[1] < ins.id[1] + len) {\n return ins\n } else {\n return null\n }\n }\n }\n * getInsertionCleanStartEnd (id) {\n yield* this.getInsertionCleanStart(id)\n return yield* this.getInsertionCleanEnd(id)\n }\n // Return an insertion such that id is the first element of content\n // This function manipulates an operation, if necessary\n * getInsertionCleanStart (id) {\n var ins = yield* this.getInsertion(id)\n if (ins != null) {\n if (ins.id[1] === id[1]) {\n return ins\n } else {\n var left = Y.utils.copyObject(ins)\n ins.content = left.content.splice(id[1] - ins.id[1])\n ins.id = id\n var leftLid = Y.utils.getLastId(left)\n ins.origin = leftLid\n left.originOf = [ins.id]\n left.right = ins.id\n ins.left = leftLid\n // debugger // check\n yield* this.setOperation(left)\n yield* this.setOperation(ins)\n if (left.gc) {\n this.store.queueGarbageCollector(ins.id)\n }\n return ins\n }\n } else {\n return null\n }\n }\n // Return an insertion such that id is the last element of content\n // This function manipulates an operation, if necessary\n * getInsertionCleanEnd (id) {\n var ins = yield* this.getInsertion(id)\n if (ins != null) {\n if (ins.content == null || (ins.id[1] + ins.content.length - 1 === id[1])) {\n return ins\n } else {\n var right = Y.utils.copyObject(ins)\n right.content = ins.content.splice(id[1] - ins.id[1] + 1) // cut off remainder\n right.id = [id[0], id[1] + 1]\n var insLid = Y.utils.getLastId(ins)\n right.origin = insLid\n ins.originOf = [right.id]\n ins.right = right.id\n right.left = insLid\n // debugger // check\n yield* this.setOperation(right)\n yield* this.setOperation(ins)\n if (ins.gc) {\n this.store.queueGarbageCollector(right.id)\n }\n return ins\n }\n } else {\n return null\n }\n }\n * getOperation (id/* :any */)/* :Transaction */ {\n var o = yield* this.os.find(id)\n if (id[0] !== '_' || o != null) {\n return o\n } else { // type is string\n // generate this operation?\n var comp = id[1].split('_')\n if (comp.length > 1) {\n var struct = comp[0]\n var op = Y.Struct[struct].create(id)\n op.type = comp[1]\n yield* this.setOperation(op)\n return op\n } else {\n // won't be called. but just in case..\n console.error('Unexpected case. How can this happen?')\n debugger // eslint-disable-line\n return null\n }\n }\n }\n * removeOperation (id) {\n yield* this.os.delete(id)\n }\n * setState (state) {\n var val = {\n id: [state.user],\n clock: state.clock\n }\n yield* this.ss.put(val)\n }\n * getState (user) {\n var n = yield* this.ss.find([user])\n var clock = n == null ? null : n.clock\n if (clock == null) {\n clock = 0\n }\n return {\n user: user,\n clock: clock\n }\n }\n * getStateVector () {\n var stateVector = []\n yield* this.ss.iterate(this, null, null, function * (n) {\n stateVector.push({\n user: n.id[0],\n clock: n.clock\n })\n })\n return stateVector\n }\n * getStateSet () {\n var ss = {}\n yield* this.ss.iterate(this, null, null, function * (n) {\n ss[n.id[0]] = n.clock\n })\n return ss\n }\n /*\n Here, we make all missing operations executable for the receiving user.\n\n Notes:\n startSS: denotes to the SV that the remote user sent\n currSS: denotes to the state vector that the user should have if he\n applies all already sent operations (increases is each step)\n\n We face several problems:\n * Execute op as is won't work because ops depend on each other\n -> find a way so that they do not anymore\n * When changing left, must not go more to the left than the origin\n * When changing right, you have to consider that other ops may have op\n as their origin, this means that you must not set one of these ops\n as the new right (interdependencies of ops)\n * can't just go to the right until you find the first known operation,\n With currSS\n -> interdependency of ops is a problem\n With startSS\n -> leads to inconsistencies when two users join at the same time.\n Then the position depends on the order of execution -> error!\n\n Solution:\n -> re-create originial situation\n -> set op.left = op.origin (which never changes)\n -> set op.right\n to the first operation that is known (according to startSS)\n or to the first operation that has an origin that is not to the\n right of op.\n -> Enforces unique execution order -> happy user\n\n Improvements: TODO\n * Could set left to origin, or the first known operation\n (startSS or currSS.. ?)\n -> Could be necessary when I turn GC again.\n -> Is a bad(ish) idea because it requires more computation\n\n What we do:\n * Iterate over all missing operations.\n * When there is an operation, where the right op is known, send this op all missing ops to the left to the user\n * I explained above what we have to do with each operation. Here is how we do it efficiently:\n 1. Go to the left until you find either op.origin, or a known operation (let o denote current operation in the iteration)\n 2. Found a known operation -> set op.left = o, and send it to the user. stop\n 3. Found o = op.origin -> set op.left = op.origin, and send it to the user. start again from 1. (set op = o)\n 4. Found some o -> set o.right = op, o.left = o.origin, send it to the user, continue\n */\n * getOperations (startSS) {\n // TODO: use bounds here!\n if (startSS == null) {\n startSS = {}\n }\n var send = []\n\n var endSV = yield* this.getStateVector()\n for (var endState of endSV) {\n var user = endState.user\n if (user === '_') {\n continue\n }\n var startPos = startSS[user] || 0\n if (startPos > 0) {\n // There is a change that [user, startPos] is in a composed Insertion (with a smaller counter)\n // find out if that is the case\n var firstMissing = yield* this.getInsertion([user, startPos])\n if (firstMissing != null) {\n // update startPos\n startPos = firstMissing.id[1]\n startSS[user] = startPos\n }\n }\n yield* this.os.iterate(this, [user, startPos], [user, Number.MAX_VALUE], function * (op) {\n op = Y.Struct[op.struct].encode(op)\n if (op.struct !== 'Insert') {\n send.push(op)\n } else if (op.right == null || op.right[1] < (startSS[op.right[0]] || 0)) {\n // case 1. op.right is known\n var o = op\n // Remember: ?\n // -> set op.right\n // 1. to the first operation that is known (according to startSS)\n // 2. or to the first operation that has an origin that is not to the\n // right of op.\n // For this we maintain a list of ops which origins are not found yet.\n var missing_origins = [op]\n var newright = op.right\n while (true) {\n if (o.left == null) {\n op.left = null\n send.push(op)\n if (!Y.utils.compareIds(o.id, op.id)) {\n o = Y.Struct[op.struct].encode(o)\n o.right = missing_origins[missing_origins.length - 1].id\n send.push(o)\n }\n break\n }\n o = yield* this.getInsertion(o.left)\n // we set another o, check if we can reduce $missing_origins\n while (missing_origins.length > 0 && Y.utils.matchesId(o, missing_origins[missing_origins.length - 1].origin)) {\n missing_origins.pop()\n }\n if (o.id[1] < (startSS[o.id[0]] || 0)) {\n // case 2. o is known\n op.left = Y.utils.getLastId(o)\n send.push(op)\n break\n } else if (Y.utils.matchesId(o, op.origin)) {\n // case 3. o is op.origin\n op.left = op.origin\n send.push(op)\n op = Y.Struct[op.struct].encode(o)\n op.right = newright\n if (missing_origins.length > 0) {\n console.log('This should not happen .. :( please report this')\n }\n missing_origins = [op]\n } else {\n // case 4. send o, continue to find op.origin\n var s = Y.Struct[op.struct].encode(o)\n s.right = missing_origins[missing_origins.length - 1].id\n s.left = s.origin\n send.push(s)\n missing_origins.push(o)\n }\n }\n }\n })\n }\n return send.reverse()\n }\n /*\n * Get the plain untransformed operations from the database.\n * You can apply these operations using .applyOperationsUntransformed(ops)\n *\n */\n * getOperationsUntransformed () {\n var ops = []\n yield* this.os.iterate(this, null, null, function * (op) {\n if (op.id[0] !== '_') {\n ops.push(op)\n }\n })\n return {\n untransformed: ops\n }\n }\n * applyOperationsUntransformed (m, stateSet) {\n var ops = m.untransformed\n for (var i = 0; i < ops.length; i++) {\n var op = ops[i]\n // create, and modify parent, if it is created implicitly\n if (op.parent != null && op.parent[0] === '_') {\n if (op.struct === 'Insert') {\n // update parents .map/start/end properties\n if (op.parentSub != null && op.left == null) {\n // op is child of Map\n let parent = yield* this.getOperation(op.parent)\n parent.map[op.parentSub] = op.id\n yield* this.setOperation(parent)\n } else if (op.right == null || op.left == null) {\n let parent = yield* this.getOperation(op.parent)\n if (op.right == null) {\n parent.end = Y.utils.getLastId(op)\n }\n if (op.left == null) {\n parent.start = op.id\n }\n yield* this.setOperation(parent)\n }\n }\n }\n yield* this.os.put(op)\n }\n for (var user in stateSet) {\n yield* this.ss.put({\n id: [user],\n clock: stateSet[user]\n })\n }\n }\n /* this is what we used before.. use this as a reference..\n * makeOperationReady (startSS, op) {\n op = Y.Struct[op.struct].encode(op)\n op = Y.utils.copyObject(op) -- use copyoperation instead now!\n var o = op\n var ids = [op.id]\n // search for the new op.right\n // it is either the first known op (according to startSS)\n // or the o that has no origin to the right of op\n // (this is why we use the ids array)\n while (o.right != null) {\n var right = yield* this.getOperation(o.right)\n if (o.right[1] < (startSS[o.right[0]] || 0) || !ids.some(function (id) {\n return Y.utils.compareIds(id, right.origin)\n })) {\n break\n }\n ids.push(o.right)\n o = right\n }\n op.right = o.right\n op.left = op.origin\n return op\n }\n */\n * flush () {\n yield* this.os.flush()\n yield* this.ss.flush()\n yield* this.ds.flush()\n }\n }\n Y.Transaction = TransactionInterface\n}\n","/* @flow */\n'use strict'\n\n/*\n EventHandler is an helper class for constructing custom types.\n\n Why: When constructing custom types, you sometimes want your types to work\n synchronous: E.g.\n ``` Synchronous\n mytype.setSomething(\"yay\")\n mytype.getSomething() === \"yay\"\n ```\n versus\n ``` Asynchronous\n mytype.setSomething(\"yay\")\n mytype.getSomething() === undefined\n mytype.waitForSomething().then(function(){\n mytype.getSomething() === \"yay\"\n })\n ```\n\n The structures usually work asynchronously (you have to wait for the\n database request to finish). EventHandler helps you to make your type\n synchronous.\n*/\nmodule.exports = function (Y /* : any*/) {\n Y.utils = {}\n\n Y.utils.bubbleEvent = function (type, event) {\n type.eventHandler.callEventListeners(event)\n event.path = []\n while (type != null && type._deepEventHandler != null) {\n type._deepEventHandler.callEventListeners(event)\n var parent = null\n if (type._parent != null) {\n parent = type.os.getType(type._parent)\n }\n if (parent != null && parent._getPathToChild != null) {\n event.path = [parent._getPathToChild(type._model)].concat(event.path)\n type = parent\n } else {\n type = null\n }\n }\n }\n\n class EventListenerHandler {\n constructor () {\n this.eventListeners = []\n }\n destroy () {\n this.eventListeners = null\n }\n /*\n Basic event listener boilerplate...\n */\n addEventListener (f) {\n this.eventListeners.push(f)\n }\n removeEventListener (f) {\n this.eventListeners = this.eventListeners.filter(function (g) {\n return f !== g\n })\n }\n removeAllEventListeners () {\n this.eventListeners = []\n }\n callEventListeners (event) {\n for (var i = 0; i < this.eventListeners.length; i++) {\n try {\n var _event = {}\n for (var name in event) {\n _event[name] = event[name]\n }\n this.eventListeners[i](_event)\n } catch (e) {\n console.error('Your observer threw an error. This error was caught so that Yjs still can ensure data consistency! In order to debug this error you have to check \"Pause On Caught Exceptions\"', e)\n }\n }\n }\n }\n Y.utils.EventListenerHandler = EventListenerHandler\n\n class EventHandler extends EventListenerHandler {\n /* ::\n waiting: Array;\n awaiting: number;\n onevent: Function;\n eventListeners: Array;\n */\n /*\n onevent: is called when the structure changes.\n\n Note: \"awaiting opertations\" is used to denote operations that were\n prematurely called. Events for received operations can not be executed until\n all prematurely called operations were executed (\"waiting operations\")\n */\n constructor (onevent /* : Function */) {\n super()\n this.waiting = []\n this.awaiting = 0\n this.onevent = onevent\n }\n destroy () {\n super.destroy()\n this.waiting = null\n this.onevent = null\n }\n /*\n Call this when a new operation arrives. It will be executed right away if\n there are no waiting operations, that you prematurely executed\n */\n receivedOp (op) {\n if (this.awaiting <= 0) {\n this.onevent(op)\n } else if (op.struct === 'Delete') {\n var self = this\n var checkDelete = function checkDelete (d) {\n if (d.length == null) {\n throw new Error('This shouldn\\'t happen! d.length must be defined!')\n }\n // we check if o deletes something in self.waiting\n // if so, we remove the deleted operation\n for (var w = 0; w < self.waiting.length; w++) {\n var i = self.waiting[w]\n if (i.struct === 'Insert' && i.id[0] === d.target[0]) {\n var iLength = i.hasOwnProperty('content') ? i.content.length : 1\n var dStart = d.target[1]\n var dEnd = d.target[1] + (d.length || 1)\n var iStart = i.id[1]\n var iEnd = i.id[1] + iLength\n // Check if they don't overlap\n if (iEnd <= dStart || dEnd <= iStart) {\n // no overlapping\n continue\n }\n // we check all overlapping cases. All cases:\n /*\n 1) iiiii\n ddddd\n --> modify i and d\n 2) iiiiiii\n ddddd\n --> modify i, remove d\n 3) iiiiiii\n ddd\n --> remove d, modify i, and create another i (for the right hand side)\n 4) iiiii\n ddddddd\n --> remove i, modify d\n 5) iiiiiii\n ddddddd\n --> remove both i and d (**)\n 6) iiiiiii\n ddddd\n --> modify i, remove d\n 7) iii\n ddddddd\n --> remove i, create and apply two d with checkDelete(d) (**)\n 8) iiiii\n ddddddd\n --> remove i, modify d (**)\n 9) iiiii\n ddddd\n --> modify i and d\n (**) (also check if i contains content or type)\n */\n // TODO: I left some debugger statements, because I want to debug all cases once in production. REMEMBER END TODO\n if (iStart < dStart) {\n if (dStart < iEnd) {\n if (iEnd < dEnd) {\n // Case 1\n // remove the right part of i's content\n i.content.splice(dStart - iStart)\n // remove the start of d's deletion\n d.length = dEnd - iEnd\n d.target = [d.target[0], iEnd]\n continue\n } else if (iEnd === dEnd) {\n // Case 2\n i.content.splice(dStart - iStart)\n // remove d, we do that by simply ending this function\n return\n } else { // (dEnd < iEnd)\n // Case 3\n var newI = {\n id: [i.id[0], dEnd],\n content: i.content.slice(dEnd - iStart),\n struct: 'Insert'\n }\n self.waiting.push(newI)\n i.content.splice(dStart - iStart)\n return\n }\n }\n } else if (dStart === iStart) {\n if (iEnd < dEnd) {\n // Case 4\n d.length = dEnd - iEnd\n d.target = [d.target[0], iEnd]\n i.content = []\n continue\n } else if (iEnd === dEnd) {\n // Case 5\n self.waiting.splice(w, 1)\n return\n } else { // (dEnd < iEnd)\n // Case 6\n i.content = i.content.slice(dEnd - iStart)\n i.id = [i.id[0], dEnd]\n return\n }\n } else { // (dStart < iStart)\n if (iStart < dEnd) {\n // they overlap\n /*\n 7) iii\n ddddddd\n --> remove i, create and apply two d with checkDelete(d) (**)\n 8) iiiii\n ddddddd\n --> remove i, modify d (**)\n 9) iiiii\n ddddd\n --> modify i and d\n */\n if (iEnd < dEnd) {\n // Case 7\n // debugger // TODO: You did not test this case yet!!!! (add the debugger here)\n self.waiting.splice(w, 1)\n checkDelete({\n target: [d.target[0], dStart],\n length: iStart - dStart,\n struct: 'Delete'\n })\n checkDelete({\n target: [d.target[0], iEnd],\n length: iEnd - dEnd,\n struct: 'Delete'\n })\n return\n } else if (iEnd === dEnd) {\n // Case 8\n self.waiting.splice(w, 1)\n w--\n d.length -= iLength\n continue\n } else { // dEnd < iEnd\n // Case 9\n d.length = iStart - dStart\n i.content.splice(0, dEnd - iStart)\n i.id = [i.id[0], dEnd]\n continue\n }\n }\n }\n }\n }\n // finished with remaining operations\n self.waiting.push(d)\n }\n if (op.key == null) {\n // deletes in list\n checkDelete(op)\n } else {\n // deletes in map\n this.waiting.push(op)\n }\n } else {\n this.waiting.push(op)\n }\n }\n /*\n You created some operations, and you want the `onevent` function to be\n called right away. Received operations will not be executed untill all\n prematurely called operations are executed\n */\n awaitAndPrematurelyCall (ops) {\n this.awaiting++\n ops.map(Y.utils.copyOperation).forEach(this.onevent)\n }\n * awaitOps (transaction, f, args) {\n function notSoSmartSort (array) {\n // this function sorts insertions in a executable order\n var result = []\n while (array.length > 0) {\n for (var i = 0; i < array.length; i++) {\n var independent = true\n for (var j = 0; j < array.length; j++) {\n if (Y.utils.matchesId(array[j], array[i].left)) {\n // array[i] depends on array[j]\n independent = false\n break\n }\n }\n if (independent) {\n result.push(array.splice(i, 1)[0])\n i--\n }\n }\n }\n return result\n }\n var before = this.waiting.length\n // somehow create new operations\n yield* f.apply(transaction, args)\n // remove all appended ops / awaited ops\n this.waiting.splice(before)\n if (this.awaiting > 0) this.awaiting--\n // if there are no awaited ops anymore, we can update all waiting ops, and send execute them (if there are still no awaited ops)\n if (this.awaiting === 0 && this.waiting.length > 0) {\n // update all waiting ops\n for (let i = 0; i < this.waiting.length; i++) {\n var o = this.waiting[i]\n if (o.struct === 'Insert') {\n var _o = yield* transaction.getInsertion(o.id)\n if (_o.parentSub != null && _o.left != null) {\n // if o is an insertion of a map struc (parentSub is defined), then it shouldn't be necessary to compute left\n this.waiting.splice(i, 1)\n i-- // update index\n } else if (!Y.utils.compareIds(_o.id, o.id)) {\n // o got extended\n o.left = [o.id[0], o.id[1] - 1]\n } else if (_o.left == null) {\n o.left = null\n } else {\n // find next undeleted op\n var left = yield* transaction.getInsertion(_o.left)\n while (left.deleted != null) {\n if (left.left != null) {\n left = yield* transaction.getInsertion(left.left)\n } else {\n left = null\n break\n }\n }\n o.left = left != null ? Y.utils.getLastId(left) : null\n }\n }\n }\n // the previous stuff was async, so we have to check again!\n // We also pull changes from the bindings, if there exists such a method, this could increase awaiting too\n if (this._pullChanges != null) {\n this._pullChanges()\n }\n if (this.awaiting === 0) {\n // sort by type, execute inserts first\n var ins = []\n var dels = []\n this.waiting.forEach(function (o) {\n if (o.struct === 'Delete') {\n dels.push(o)\n } else {\n ins.push(o)\n }\n })\n this.waiting = []\n // put in executable order\n ins = notSoSmartSort(ins)\n // this.onevent can trigger the creation of another operation\n // -> check if this.awaiting increased & stop computation if it does\n for (var i = 0; i < ins.length; i++) {\n if (this.awaiting === 0) {\n this.onevent(ins[i])\n } else {\n this.waiting = this.waiting.concat(ins.slice(i))\n break\n }\n }\n for (i = 0; i < dels.length; i++) {\n if (this.awaiting === 0) {\n this.onevent(dels[i])\n } else {\n this.waiting = this.waiting.concat(dels.slice(i))\n break\n }\n }\n }\n }\n }\n // TODO: Remove awaitedInserts and awaitedDeletes in favor of awaitedOps, as they are deprecated and do not always work\n // Do this in one of the coming releases that are breaking anyway\n /*\n Call this when you successfully awaited the execution of n Insert operations\n */\n awaitedInserts (n) {\n var ops = this.waiting.splice(this.waiting.length - n)\n for (var oid = 0; oid < ops.length; oid++) {\n var op = ops[oid]\n if (op.struct === 'Insert') {\n for (var i = this.waiting.length - 1; i >= 0; i--) {\n let w = this.waiting[i]\n // TODO: do I handle split operations correctly here? Super unlikely, but yeah..\n // Also: can this case happen? Can op be inserted in the middle of a larger op that is in $waiting?\n if (w.struct === 'Insert') {\n if (Y.utils.matchesId(w, op.left)) {\n // include the effect of op in w\n w.right = op.id\n // exclude the effect of w in op\n op.left = w.left\n } else if (Y.utils.compareIds(w.id, op.right)) {\n // similar..\n w.left = Y.utils.getLastId(op)\n op.right = w.right\n }\n }\n }\n } else {\n throw new Error('Expected Insert Operation!')\n }\n }\n this._tryCallEvents(n)\n }\n /*\n Call this when you successfully awaited the execution of n Delete operations\n */\n awaitedDeletes (n, newLeft) {\n var ops = this.waiting.splice(this.waiting.length - n)\n for (var j = 0; j < ops.length; j++) {\n var del = ops[j]\n if (del.struct === 'Delete') {\n if (newLeft != null) {\n for (var i = 0; i < this.waiting.length; i++) {\n let w = this.waiting[i]\n // We will just care about w.left\n if (w.struct === 'Insert' && Y.utils.compareIds(del.target, w.left)) {\n w.left = newLeft\n }\n }\n }\n } else {\n throw new Error('Expected Delete Operation!')\n }\n }\n this._tryCallEvents(n)\n }\n /* (private)\n Try to execute the events for the waiting operations\n */\n _tryCallEvents () {\n function notSoSmartSort (array) {\n var result = []\n while (array.length > 0) {\n for (var i = 0; i < array.length; i++) {\n var independent = true\n for (var j = 0; j < array.length; j++) {\n if (Y.utils.matchesId(array[j], array[i].left)) {\n // array[i] depends on array[j]\n independent = false\n break\n }\n }\n if (independent) {\n result.push(array.splice(i, 1)[0])\n i--\n }\n }\n }\n return result\n }\n if (this.awaiting > 0) this.awaiting--\n if (this.awaiting === 0 && this.waiting.length > 0) {\n var ins = []\n var dels = []\n this.waiting.forEach(function (o) {\n if (o.struct === 'Delete') {\n dels.push(o)\n } else {\n ins.push(o)\n }\n })\n ins = notSoSmartSort(ins)\n ins.forEach(this.onevent)\n dels.forEach(this.onevent)\n this.waiting = []\n }\n }\n }\n Y.utils.EventHandler = EventHandler\n\n /*\n Default class of custom types!\n */\n class CustomType {\n getPath () {\n var parent = null\n if (this._parent != null) {\n parent = this.os.getType(this._parent)\n }\n if (parent != null && parent._getPathToChild != null) {\n var firstKey = parent._getPathToChild(this._model)\n var parentKeys = parent.getPath()\n parentKeys.push(firstKey)\n return parentKeys\n } else {\n return []\n }\n }\n }\n Y.utils.CustomType = CustomType\n\n /*\n A wrapper for the definition of a custom type.\n Every custom type must have three properties:\n\n * struct\n - Structname of this type\n * initType\n - Given a model, creates a custom type\n * class\n - the constructor of the custom type (e.g. in order to inherit from a type)\n */\n class CustomTypeDefinition { // eslint-disable-line\n /* ::\n struct: any;\n initType: any;\n class: Function;\n name: String;\n */\n constructor (def) {\n if (def.struct == null ||\n def.initType == null ||\n def.class == null ||\n def.name == null ||\n def.createType == null\n ) {\n throw new Error('Custom type was not initialized correctly!')\n }\n this.struct = def.struct\n this.initType = def.initType\n this.createType = def.createType\n this.class = def.class\n this.name = def.name\n if (def.appendAdditionalInfo != null) {\n this.appendAdditionalInfo = def.appendAdditionalInfo\n }\n this.parseArguments = (def.parseArguments || function () {\n return [this]\n }).bind(this)\n this.parseArguments.typeDefinition = this\n }\n }\n Y.utils.CustomTypeDefinition = CustomTypeDefinition\n\n Y.utils.isTypeDefinition = function isTypeDefinition (v) {\n if (v != null) {\n if (v instanceof Y.utils.CustomTypeDefinition) return [v]\n else if (v.constructor === Array && v[0] instanceof Y.utils.CustomTypeDefinition) return v\n else if (v instanceof Function && v.typeDefinition instanceof Y.utils.CustomTypeDefinition) return [v.typeDefinition]\n }\n return false\n }\n\n /*\n Make a flat copy of an object\n (just copy properties)\n */\n function copyObject (o) {\n var c = {}\n for (var key in o) {\n c[key] = o[key]\n }\n return c\n }\n Y.utils.copyObject = copyObject\n\n /*\n Copy an operation, so that it can be manipulated.\n Note: You must not change subproperties (except o.content)!\n */\n function copyOperation (o) {\n o = copyObject(o)\n if (o.content != null) {\n o.content = o.content.map(function (c) { return c })\n }\n return o\n }\n\n Y.utils.copyOperation = copyOperation\n\n /*\n Defines a smaller relation on Id's\n */\n function smaller (a, b) {\n return a[0] < b[0] || (a[0] === b[0] && (a[1] < b[1] || typeof a[1] < typeof b[1]))\n }\n Y.utils.smaller = smaller\n\n function inDeletionRange (del, ins) {\n return del.target[0] === ins[0] && del.target[1] <= ins[1] && ins[1] < del.target[1] + (del.length || 1)\n }\n Y.utils.inDeletionRange = inDeletionRange\n\n function compareIds (id1, id2) {\n if (id1 == null || id2 == null) {\n return id1 === id2\n } else {\n return id1[0] === id2[0] && id1[1] === id2[1]\n }\n }\n Y.utils.compareIds = compareIds\n\n function matchesId (op, id) {\n if (id == null || op == null) {\n return id === op\n } else {\n if (id[0] === op.id[0]) {\n if (op.content == null) {\n return id[1] === op.id[1]\n } else {\n return id[1] >= op.id[1] && id[1] < op.id[1] + op.content.length\n }\n }\n }\n }\n Y.utils.matchesId = matchesId\n\n function getLastId (op) {\n if (op.content == null || op.content.length === 1) {\n return op.id\n } else {\n return [op.id[0], op.id[1] + op.content.length - 1]\n }\n }\n Y.utils.getLastId = getLastId\n\n function createEmptyOpsArray (n) {\n var a = new Array(n)\n for (var i = 0; i < a.length; i++) {\n a[i] = {\n id: [null, null]\n }\n }\n return a\n }\n\n function createSmallLookupBuffer (Store) {\n /*\n This buffer implements a very small buffer that temporarily stores operations\n after they are read / before they are written.\n The buffer basically implements FIFO. Often requested lookups will be re-queued every time they are looked up / written.\n\n It can speed up lookups on Operation Stores and State Stores. But it does not require notable use of memory or processing power.\n\n Good for os and ss, bot not for ds (because it often uses methods that require a flush)\n\n I tried to optimize this for performance, therefore no highlevel operations.\n */\n class SmallLookupBuffer extends Store {\n constructor (arg1, arg2) {\n // super(...arguments) -- do this when this is supported by stable nodejs\n super(arg1, arg2)\n this.writeBuffer = createEmptyOpsArray(5)\n this.readBuffer = createEmptyOpsArray(10)\n }\n * find (id, noSuperCall) {\n var i, r\n for (i = this.readBuffer.length - 1; i >= 0; i--) {\n r = this.readBuffer[i]\n // we don't have to use compareids, because id is always defined!\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n // found r\n // move r to the end of readBuffer\n for (; i < this.readBuffer.length - 1; i++) {\n this.readBuffer[i] = this.readBuffer[i + 1]\n }\n this.readBuffer[this.readBuffer.length - 1] = r\n return r\n }\n }\n var o\n for (i = this.writeBuffer.length - 1; i >= 0; i--) {\n r = this.writeBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n o = r\n break\n }\n }\n if (i < 0 && noSuperCall === undefined) {\n // did not reach break in last loop\n // read id and put it to the end of readBuffer\n o = yield* super.find(id)\n }\n if (o != null) {\n for (i = 0; i < this.readBuffer.length - 1; i++) {\n this.readBuffer[i] = this.readBuffer[i + 1]\n }\n this.readBuffer[this.readBuffer.length - 1] = o\n }\n return o\n }\n * put (o) {\n var id = o.id\n var i, r // helper variables\n for (i = this.writeBuffer.length - 1; i >= 0; i--) {\n r = this.writeBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n // is already in buffer\n // forget r, and move o to the end of writeBuffer\n for (; i < this.writeBuffer.length - 1; i++) {\n this.writeBuffer[i] = this.writeBuffer[i + 1]\n }\n this.writeBuffer[this.writeBuffer.length - 1] = o\n break\n }\n }\n if (i < 0) {\n // did not reach break in last loop\n // write writeBuffer[0]\n var write = this.writeBuffer[0]\n if (write.id[0] !== null) {\n yield* super.put(write)\n }\n // put o to the end of writeBuffer\n for (i = 0; i < this.writeBuffer.length - 1; i++) {\n this.writeBuffer[i] = this.writeBuffer[i + 1]\n }\n this.writeBuffer[this.writeBuffer.length - 1] = o\n }\n // check readBuffer for every occurence of o.id, overwrite if found\n // whether found or not, we'll append o to the readbuffer\n for (i = 0; i < this.readBuffer.length - 1; i++) {\n r = this.readBuffer[i + 1]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n this.readBuffer[i] = o\n } else {\n this.readBuffer[i] = r\n }\n }\n this.readBuffer[this.readBuffer.length - 1] = o\n }\n * delete (id) {\n var i, r\n for (i = 0; i < this.readBuffer.length; i++) {\n r = this.readBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n this.readBuffer[i] = {\n id: [null, null]\n }\n }\n }\n yield* this.flush()\n yield* super.delete(id)\n }\n * findWithLowerBound (id) {\n var o = yield* this.find(id, true)\n if (o != null) {\n return o\n } else {\n yield* this.flush()\n return yield* super.findWithLowerBound.apply(this, arguments)\n }\n }\n * findWithUpperBound (id) {\n var o = yield* this.find(id, true)\n if (o != null) {\n return o\n } else {\n yield* this.flush()\n return yield* super.findWithUpperBound.apply(this, arguments)\n }\n }\n * findNext () {\n yield* this.flush()\n return yield* super.findNext.apply(this, arguments)\n }\n * findPrev () {\n yield* this.flush()\n return yield* super.findPrev.apply(this, arguments)\n }\n * iterate () {\n yield* this.flush()\n yield* super.iterate.apply(this, arguments)\n }\n * flush () {\n for (var i = 0; i < this.writeBuffer.length; i++) {\n var write = this.writeBuffer[i]\n if (write.id[0] !== null) {\n yield* super.put(write)\n this.writeBuffer[i] = {\n id: [null, null]\n }\n }\n }\n }\n }\n return SmallLookupBuffer\n }\n Y.utils.createSmallLookupBuffer = createSmallLookupBuffer\n\n // Generates a unique id, for use as a user id.\n // Thx to @jed for this script https://gist.github.com/jed/982883\n function generateGuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,generateGuid)} // eslint-disable-line\n Y.utils.generateGuid = generateGuid\n}\n","/* @flow */\n'use strict'\n\nrequire('./Connector.js')(Y)\nrequire('./Database.js')(Y)\nrequire('./Transaction.js')(Y)\nrequire('./Struct.js')(Y)\nrequire('./Utils.js')(Y)\nrequire('./Connectors/Test.js')(Y)\n\nY.debug = require('debug')\n\nvar requiringModules = {}\n\nmodule.exports = Y\nY.requiringModules = requiringModules\n\nY.extend = function (name, value) {\n if (arguments.length === 2 && typeof name === 'string') {\n if (value instanceof Y.utils.CustomTypeDefinition) {\n Y[name] = value.parseArguments\n } else {\n Y[name] = value\n }\n if (requiringModules[name] != null) {\n requiringModules[name].resolve()\n delete requiringModules[name]\n }\n } else {\n for (var i = 0; i < arguments.length; i++) {\n var f = arguments[i]\n if (typeof f === 'function') {\n f(Y)\n } else {\n throw new Error('Expected function!')\n }\n }\n }\n}\n\nY.requestModules = requestModules\nfunction requestModules (modules) {\n var sourceDir\n if (Y.sourceDir === null) {\n sourceDir = null\n } else {\n sourceDir = Y.sourceDir || '/bower_components'\n }\n // determine if this module was compiled for es5 or es6 (y.js vs. y.es6)\n // if Insert.execute is a Function, then it isnt a generator..\n // then load the es5(.js) files..\n var extention = typeof regeneratorRuntime !== 'undefined' ? '.js' : '.es6'\n var promises = []\n for (var i = 0; i < modules.length; i++) {\n var module = modules[i].split('(')[0]\n var modulename = 'y-' + module.toLowerCase()\n if (Y[module] == null) {\n if (requiringModules[module] == null) {\n // module does not exist\n if (typeof window !== 'undefined' && window.Y !== 'undefined') {\n if (sourceDir != null) {\n var imported = document.createElement('script')\n imported.src = sourceDir + '/' + modulename + '/' + modulename + extention\n document.head.appendChild(imported)\n }\n let requireModule = {}\n requiringModules[module] = requireModule\n requireModule.promise = new Promise(function (resolve) {\n requireModule.resolve = resolve\n })\n promises.push(requireModule.promise)\n } else {\n console.info('YJS: Please do not depend on automatic requiring of modules anymore! Extend modules as follows `require(\\'y-modulename\\')(Y)`')\n require(modulename)(Y)\n }\n } else {\n promises.push(requiringModules[modules[i]].promise)\n }\n }\n }\n return Promise.all(promises)\n}\n\n/* ::\ntype MemoryOptions = {\n name: 'memory'\n}\ntype IndexedDBOptions = {\n name: 'indexeddb',\n namespace: string\n}\ntype DbOptions = MemoryOptions | IndexedDBOptions\n\ntype WebRTCOptions = {\n name: 'webrtc',\n room: string\n}\ntype WebsocketsClientOptions = {\n name: 'websockets-client',\n room: string\n}\ntype ConnectionOptions = WebRTCOptions | WebsocketsClientOptions\n\ntype YOptions = {\n connector: ConnectionOptions,\n db: DbOptions,\n types: Array,\n sourceDir: string,\n share: {[key: string]: TypeName}\n}\n*/\n\nfunction Y (opts/* :YOptions */) /* :Promise */ {\n if (opts.hasOwnProperty('sourceDir')) {\n Y.sourceDir = opts.sourceDir\n }\n opts.types = opts.types != null ? opts.types : []\n var modules = [opts.db.name, opts.connector.name].concat(opts.types)\n for (var name in opts.share) {\n modules.push(opts.share[name])\n }\n return new Promise(function (resolve, reject) {\n if (opts == null) reject('An options object is expected! ')\n else if (opts.connector == null) reject('You must specify a connector! (missing connector property)')\n else if (opts.connector.name == null) reject('You must specify connector name! (missing connector.name property)')\n else if (opts.db == null) reject('You must specify a database! (missing db property)')\n else if (opts.connector.name == null) reject('You must specify db name! (missing db.name property)')\n else {\n opts = Y.utils.copyObject(opts)\n opts.connector = Y.utils.copyObject(opts.connector)\n opts.db = Y.utils.copyObject(opts.db)\n opts.share = Y.utils.copyObject(opts.share)\n setTimeout(function () {\n Y.requestModules(modules).then(function () {\n var yconfig = new YConfig(opts)\n yconfig.db.whenUserIdSet(function () {\n yconfig.init(function () {\n resolve(yconfig)\n })\n })\n }).catch(reject)\n }, 0)\n }\n })\n}\n\nclass YConfig {\n /* ::\n db: Y.AbstractDatabase;\n connector: Y.AbstractConnector;\n share: {[key: string]: any};\n options: Object;\n */\n constructor (opts, callback) {\n this.options = opts\n this.db = new Y[opts.db.name](this, opts.db)\n this.connector = new Y[opts.connector.name](this, opts.connector)\n this.connected = true\n }\n init (callback) {\n var opts = this.options\n var share = {}\n this.share = share\n this.db.requestTransaction(function * requestTransaction () {\n // create shared object\n for (var propertyname in opts.share) {\n var typeConstructor = opts.share[propertyname].split('(')\n var typeName = typeConstructor.splice(0, 1)\n var type = Y[typeName]\n var typedef = type.typeDefinition\n var id = ['_', typedef.struct + '_' + typeName + '_' + propertyname + '_' + typeConstructor]\n var args = []\n if (typeConstructor.length === 1) {\n try {\n args = JSON.parse('[' + typeConstructor[0].split(')')[0] + ']')\n } catch (e) {\n throw new Error('Was not able to parse type definition! (share.' + propertyname + ')')\n }\n if (type.typeDefinition.parseArguments == null) {\n throw new Error(typeName + ' does not expect arguments!')\n } else {\n args = typedef.parseArguments(args[0])[1]\n }\n }\n share[propertyname] = yield* this.store.initType.call(this, id, args)\n }\n this.store.whenTransactionsFinished()\n .then(callback)\n })\n }\n isConnected () {\n return this.connector.isSynced\n }\n disconnect () {\n if (this.connected) {\n this.connected = false\n return this.connector.disconnect()\n } else {\n return Promise.resolve()\n }\n }\n reconnect () {\n if (!this.connected) {\n this.connected = true\n return this.connector.reconnect()\n } else {\n return Promise.resolve()\n }\n }\n destroy () {\n var self = this\n return this.close().then(function () {\n if (self.db.deleteDB != null) {\n return self.db.deleteDB()\n } else {\n return Promise.resolve()\n }\n })\n }\n close () {\n var self = this\n this.share = null\n if (this.connector.destroy != null) {\n this.connector.destroy()\n } else {\n this.connector.disconnect()\n }\n return this.db.whenTransactionsFinished(function () {\n this.db.destroyTypes()\n // make sure to wait for all transactions before destroying the db\n this.db.requestTransaction(function * () {\n yield* self.db.destroy()\n })\n return this.db.whenTransactionsFinished()\n })\n }\n}\n"]} \ No newline at end of file +{"version":3,"sources":["node_modules/browser-pack/_prelude.js","node_modules/debug/src/browser.js","node_modules/debug/src/debug.js","node_modules/ms/index.js","node_modules/process/browser.js","node_modules/regenerator/node_modules/regenerator-runtime/runtime.js","node_modules/regenerator/runtime.js","src/Connector.js","src/Connectors/Test.js","src/Database.js","src/Struct.js","src/Transaction.js","src/Utils.js","src/y.js"],"names":["f","exports","module","define","amd","g","window","global","self","this","Y","e","t","n","r","s","o","u","a","require","i","Error","code","l","call","length","1","useColors","process","type","document","documentElement","style","WebkitAppearance","console","firebug","exception","table","navigator","userAgent","toLowerCase","match","parseInt","RegExp","$1","formatArgs","args","namespace","humanize","diff","c","color","splice","index","lastC","replace","log","_typeof","Function","prototype","apply","arguments","save","namespaces","storage","removeItem","debug","load","env","DEBUG","chrome","local","localStorage","colors","formatters","j","v","JSON","stringify","err","message","enable","selectColor","hash","charCodeAt","Math","abs","createDebug","enabled","curr","Date","ms","prevTime","prev","Array","coerce","unshift","format","formatter","val","bind","init","names","skips","split","len","push","substr","disable","name","test","stack","parse","str","String","exec","parseFloat","y","d","h","m","fmtShort","round","fmtLong","plural","floor","ceil","options","isNaN","long","defaultSetTimout","defaultClearTimeout","runTimeout","fun","cachedSetTimeout","setTimeout","runClearTimeout","marker","cachedClearTimeout","clearTimeout","cleanUpNextTick","draining","currentQueue","queue","concat","queueIndex","drainQueue","timeout","run","Item","array","noop","nextTick","title","browser","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","wrap","innerFn","outerFn","tryLocsList","protoGenerator","Generator","generator","Object","create","context","Context","_invoke","makeInvokeMethod","tryCatch","fn","obj","arg","GeneratorFunction","GeneratorFunctionPrototype","defineIteratorMethods","forEach","method","AwaitArgument","AsyncIterator","invoke","resolve","reject","record","result","value","Promise","then","unwrapped","enqueue","callInvokeWithMethodAndArg","previousPromise","domain","state","GenStateSuspendedStart","GenStateExecuting","GenStateCompleted","doneResult","delegate","iterator","undefined","returnMethod","info","done","GenStateSuspendedYield","resultName","next","nextLoc","sent","_sent","dispatchException","abrupt","ContinueSentinel","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","reset","values","iterable","iteratorMethod","iteratorSymbol","hasOwn","hasOwnProperty","$Symbol","Symbol","toStringTagSymbol","toStringTag","inModule","runtime","regeneratorRuntime","Gp","constructor","displayName","isGeneratorFunction","genFun","ctor","mark","setPrototypeOf","__proto__","awrap","async","iter","toString","keys","object","key","reverse","pop","skipTempReset","charAt","slice","stop","rootEntry","rootRecord","rval","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","catch","thrown","delegateYield","warn","canRead","auth","canWrite","AbstractConnector","opts","_classCallCheck","role","logMessage","db","forwardAppliedOperations","connections","isSynced","userEventListeners","whenSyncedListeners","currentSyncTarget","syncingClients","forwardToSyncingClients","syncStep2","broadcastOpBuffer","protocolVersion","authInfo","checkAuth","generateUserId","setUserId","utils","generateGuid","_createClass","broadcast","startGarbageCollector","stopGarbageCollector","whenTransactionsFinished","findNextSyncTarget","userId","filter","user","cli","_iteratorNormalCompletion","_didIteratorError","_iteratorError","_step","_iterator","action","return","_iteratorNormalCompletion2","_didIteratorError2","_iteratorError2","_step2","_iterator2","syncUser","uid","conn","requestTransaction","_callee","stateSet","deleteSet","answer","_context","getStateSet","t0","getDeleteSet","t1","send","_callee2","_iteratorNormalCompletion3","_didIteratorError3","_iteratorError3","_iterator3","_step3","_context2","garbageCollectAfterSync","ops","broadcastOperations","map","op","Struct","struct","encode","transactionInProgress","sender","_this","_iteratorNormalCompletion4","_didIteratorError4","_iteratorError4","_step4","_iterator4","_callee3","currentStateSet","ds","_context3","applyDeleteSet","t2","getOperations","os","t3","defer","promise","_m","_callee4","_context4","osUntransformed","applyOperationsUntransformed","store","_setSyncedWith","_iteratorNormalCompletion5","_didIteratorError5","_iteratorError5","_step5","_iterator5","client","delops","broadcastOps","parseArray","node","_iteratorNormalCompletion6","_didIteratorError6","_iteratorError6","_step6","_iterator6","children","getAttribute","parseObject","json","attrName","attrs","int","msg","encodeObject","encodeArray","setAttribute","_iteratorNormalCompletion7","_didIteratorError7","_iteratorError7","_step7","_iterator7","xmlns","globalRoom","users","buffers","removeUser","userLeft","addUser","connector","uname","userJoined","ps","all","flushOne","bufs","receiver","buff","getRandom","_buff","_sender","shift","receiveMessage","flushAll","nextFlush","userIdCounter","Test","_Y$AbstractConnector","_possibleConstructorReturn","getPrototypeOf","syncingClientDuration","_inherits","_get","buffer","isDisconnected","waitForMe","AbstractDatabase","garbageCollect","gc1","gc2","oid","garbageCollectOperation","gcTimeout","gcInterval","dbOpts","userIdPromise","listenersById","listenersByIdExecuteNow","listenersByIdRequestPending","initializedTypes","waitingTransactions","transactionIsFlushed","YConcurrency_TestingMode","executeOrder","repairCheckInterval","opsReceivedTimestamp","startRepairCheck","gc","repairCheckIntervalHandler","setInterval","repair","clearInterval","id","check","command","join","ungc","getOperation","setOperation","addToGarbageCollector","left","deleted","content","getInsertionCleanStart","queueGarbageCollector","compareIds","_destroy","error","destroy","stopRepairCheck","inProgress","_context5","getState","opClock","clock","numberOfIds","required","requiredOps","requires","whenOperationsExist","ids","listener","missing","sid","exeNow","ls","_i","_listener","_o","_context6","tryExecute","getInsertion","t4","defined","overlapSize","opid","isGarbageCollected","_context7","addToDebug","Delete","execute","getLastId","origin","addOperation","operationAdded","t7","tryCombineWithLeft","transaction","opLen","parentIsDeleted","startId","_i2","opIsDeleted","delop","_context8","targetParent","_changed","updateState","parent","isDeleted","deleteList","copyOperation","t5","target","transactionsFinished","_callee5","_context9","flush","makeGen","callImmediately","_this2","transact","getNextRequest","initType","_context10","typeDefinition","typedefinition","structname","getNextOpId","_callee6","_context11","applyCreatedOperations","createType","deleteOperation","Insert","right","parentSub","opContent","getDistanceToOrigin","matchesId","tryToRemergeLater","distanceToOrigin","start","oOriginDistance","getInsertionCleanEnd","originOf","t6","t8","t10","t11","t12","t13","t15","t16","removeFromGarbageCollector","end","t22","List","ref","pos","res","operation","Map","get","getType","TransactionInterface","delLength","markDeleted","targetId","preventCallType","callType","targetLength","findWithUpperBound","markGarbageCollected","newlen","put","findPrev","findNext","delete","_next","iterate","parentDeleted","deps","dep","neworigin","neworigin_","originsIn","setParent","t9","t14","t17","_id","t19","removeOperation","checkDeleteStoreForState","max","oLength","setState","deletions","dv","del","counter","oLen","_context12","Number","MAX_VALUE","min","_context13","_context15","_context14","_context16","_context17","_context18","_context19","ins","_context20","getInsertionCleanStartEnd","_context21","leftLid","_context22","copyObject","insLid","_context23","comp","_context24","find","_context25","_context26","ss","_context27","getStateVector","stateVector","_context29","_context28","_context31","_context30","startSS","endSV","endState","startPos","firstMissing","_context33","missing_origins","newright","_context32","getOperationsUntransformed","_context35","_callee7","_context34","untransformed","_parent","_context36","_context37","Transaction","smaller","b","inDeletionRange","id1","id2","createEmptyOpsArray","createSmallLookupBuffer","Store","_Store","SmallLookupBuffer","arg1","arg2","writeBuffer","readBuffer","noSuperCall","write","_delete","findWithLowerBound","_args5","_args6","_args7","_args8","_args9","random","bubbleEvent","event","eventHandler","callEventListeners","path","_deepEventHandler","_getPathToChild","_model","EventListenerHandler","eventListeners","_event","EventHandler","_EventListenerHandler","onevent","waiting","awaiting","checkDelete","w","iLength","dStart","dEnd","iStart","iEnd","newI","awaitOps","notSoSmartSort","before","dels","independent","_pullChanges","_tryCallEvents","newLeft","CustomType","firstKey","parentKeys","getPath","CustomTypeDefinition","def","class","appendAdditionalInfo","parseArguments","isTypeDefinition","requestModules","modules","sourceDir","extention","promises","modulename","requiringModules","imported","createElement","src","head","appendChild","requireModule","types","share","yconfig","YConfig","whenUserIdSet","extend","callback","connected","propertyname","typeConstructor","typeName","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ER/wB,KAAKkS,GAAG2C,mBAARzF,mBAAAO,KAA2B,QAAAmF,KAAA,MAAA1F,oBAAAhF,KAAA,SAAA0L,GAAA,OAAA,OAAAA,EAAA1Q,KAAA0Q,EAAAxI,MAAA,IAAA,GAAA,MAAAwI,GAAAtE,cAClBzR,EAAKmS,GAAG0M,UADU,KAAA,EAAA,KAAA,GAAA,IAAA,MAAA,MAAA9I,GAAApF,SAAAoE,EAAA9U,SAGpBA,KAAKkS,GAAGsB","file":"y.js","sourcesContent":["(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= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return;\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name;\n }\n return Math.ceil(ms / n) + ' ' + name + 's';\n}\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","/**\n * Copyright (c) 2014, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * https://raw.github.com/facebook/regenerator/master/LICENSE file. An\n * additional grant of patent rights can be found in the PATENTS file in\n * the same directory.\n */\n\n!(function(global) {\n \"use strict\";\n\n var hasOwn = Object.prototype.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n var inModule = typeof module === \"object\";\n var runtime = global.regeneratorRuntime;\n if (runtime) {\n if (inModule) {\n // If regeneratorRuntime is defined globally and we're in a module,\n // make the exports object identical to regeneratorRuntime.\n module.exports = runtime;\n }\n // Don't bother evaluating the rest of this file if the runtime was\n // already defined globally.\n return;\n }\n\n // Define the runtime globally (as expected by generated code) as either\n // module.exports (if we're in a module) or a new, empty object.\n runtime = global.regeneratorRuntime = inModule ? module.exports : {};\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n runtime.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype;\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = \"GeneratorFunction\";\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n prototype[method] = function(arg) {\n return this._invoke(method, arg);\n };\n });\n }\n\n runtime.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n runtime.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n if (!(toStringTagSymbol in genFun)) {\n genFun[toStringTagSymbol] = \"GeneratorFunction\";\n }\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `value instanceof AwaitArgument` to determine if the yielded value is\n // meant to be awaited. Some may consider the name of this method too\n // cutesy, but they are curmudgeons.\n runtime.awrap = function(arg) {\n return new AwaitArgument(arg);\n };\n\n function AwaitArgument(arg) {\n this.arg = arg;\n }\n\n function AsyncIterator(generator) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value instanceof AwaitArgument) {\n return Promise.resolve(value.arg).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return Promise.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration. If the Promise is rejected, however, the\n // result for this iteration will be rejected with the same\n // reason. Note that rejections of yielded Promises are not\n // thrown back into the generator function, as is the case\n // when an awaited Promise is rejected. This difference in\n // behavior between yield and await is important, because it\n // allows the consumer to decide what to do with the yielded\n // rejection (swallow it and continue, manually .throw it back\n // into the generator, abandon iteration, whatever). With\n // await, by contrast, there is no opportunity to examine the\n // rejection reason outside the generator function, so the\n // only option is to throw it from the await expression, and\n // let the generator function handle the exception.\n result.value = unwrapped;\n resolve(result);\n }, reject);\n }\n }\n\n if (typeof process === \"object\" && process.domain) {\n invoke = process.domain.bind(invoke);\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new Promise(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n runtime.async = function(innerFn, outerFn, self, tryLocsList) {\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList)\n );\n\n return runtime.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n if (method === \"return\" ||\n (method === \"throw\" && delegate.iterator[method] === undefined)) {\n // A return or throw (when the delegate iterator has no throw\n // method) always terminates the yield* loop.\n context.delegate = null;\n\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n var returnMethod = delegate.iterator[\"return\"];\n if (returnMethod) {\n var record = tryCatch(returnMethod, delegate.iterator, arg);\n if (record.type === \"throw\") {\n // If the return method threw an exception, let that\n // exception prevail over the original return or throw.\n method = \"throw\";\n arg = record.arg;\n continue;\n }\n }\n\n if (method === \"return\") {\n // Continue with the outer return, now that the delegate\n // iterator has been terminated.\n continue;\n }\n }\n\n var record = tryCatch(\n delegate.iterator[method],\n delegate.iterator,\n arg\n );\n\n if (record.type === \"throw\") {\n context.delegate = null;\n\n // Like returning generator.throw(uncaught), but without the\n // overhead of an extra function call.\n method = \"throw\";\n arg = record.arg;\n continue;\n }\n\n // Delegate generator ran and handled its own exceptions so\n // regardless of what the method was, we continue as if it is\n // \"next\" with an undefined arg.\n method = \"next\";\n arg = undefined;\n\n var info = record.arg;\n if (info.done) {\n context[delegate.resultName] = info.value;\n context.next = delegate.nextLoc;\n } else {\n state = GenStateSuspendedYield;\n return info;\n }\n\n context.delegate = null;\n }\n\n if (method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = arg;\n\n } else if (method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw arg;\n }\n\n if (context.dispatchException(arg)) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n method = \"next\";\n arg = undefined;\n }\n\n } else if (method === \"return\") {\n context.abrupt(\"return\", arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n var info = {\n value: record.arg,\n done: context.done\n };\n\n if (record.arg === ContinueSentinel) {\n if (context.delegate && method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n arg = undefined;\n }\n } else {\n return info;\n }\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(arg) call above.\n method = \"throw\";\n arg = record.arg;\n }\n }\n };\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp[toStringTagSymbol] = \"Generator\";\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n runtime.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n runtime.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n return !!caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.next = finallyEntry.finallyLoc;\n } else {\n this.complete(record);\n }\n\n return ContinueSentinel;\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = record.arg;\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n return ContinueSentinel;\n }\n };\n})(\n // Among the various tricks for obtaining a reference to the global\n // object, this seems to be the most reliable technique that does not\n // use indirect eval (which violates Content Security Policy).\n typeof global === \"object\" ? global :\n typeof window === \"object\" ? window :\n typeof self === \"object\" ? self : this\n);\n","console.warn(\n \"The regenerator/runtime module is deprecated; \" +\n \"please import regenerator-runtime/runtime instead.\"\n);\n\nmodule.exports = require(\"regenerator-runtime/runtime\");\n","function canRead (auth) { return auth === 'read' || auth === 'write' }\nfunction canWrite (auth) { return auth === 'write' }\n\nmodule.exports = function (Y/* :any */) {\n class AbstractConnector {\n /* ::\n y: YConfig;\n role: SyncRole;\n connections: Object;\n isSynced: boolean;\n userEventListeners: Array;\n whenSyncedListeners: Array;\n currentSyncTarget: ?UserId;\n syncingClients: Array;\n forwardToSyncingClients: boolean;\n debug: boolean;\n syncStep2: Promise;\n userId: UserId;\n send: Function;\n broadcast: Function;\n broadcastOpBuffer: Array;\n protocolVersion: number;\n */\n /*\n opts contains the following information:\n role : String Role of this client (\"master\" or \"slave\")\n userId : String Uniquely defines the user.\n debug: Boolean Whether to print debug messages (optional)\n */\n constructor (y, opts) {\n this.y = y\n if (opts == null) {\n opts = {}\n }\n // Prefer to receive untransformed operations. This does only work if\n // this client receives operations from only one other client.\n // In particular, this does not work with y-webrtc.\n // It will work with y-websockets-client\n if (opts.role == null || opts.role === 'master') {\n this.role = 'master'\n } else if (opts.role === 'slave') {\n this.role = 'slave'\n } else {\n throw new Error(\"Role must be either 'master' or 'slave'!\")\n }\n this.log = Y.debug('y:connector')\n this.logMessage = Y.debug('y:connector-message')\n this.y.db.forwardAppliedOperations = opts.forwardAppliedOperations || false\n this.role = opts.role\n this.connections = {}\n this.isSynced = false\n this.userEventListeners = []\n this.whenSyncedListeners = []\n this.currentSyncTarget = null\n this.syncingClients = []\n this.forwardToSyncingClients = opts.forwardToSyncingClients !== false\n this.debug = opts.debug === true\n this.syncStep2 = Promise.resolve()\n this.broadcastOpBuffer = []\n this.protocolVersion = 11\n this.authInfo = opts.auth || null\n this.checkAuth = opts.checkAuth || function () { return Promise.resolve('write') } // default is everyone has write access\n if (opts.generateUserId === true) {\n this.setUserId(Y.utils.generateGuid())\n }\n }\n resetAuth (auth) {\n if (this.authInfo !== auth) {\n this.authInfo = auth\n this.broadcast({\n type: 'auth',\n auth: this.authInfo\n })\n }\n }\n reconnect () {\n this.log('reconnecting..')\n return this.y.db.startGarbageCollector()\n }\n disconnect () {\n this.log('discronnecting..')\n this.connections = {}\n this.isSynced = false\n this.currentSyncTarget = null\n this.syncingClients = []\n this.whenSyncedListeners = []\n this.y.db.stopGarbageCollector()\n return this.y.db.whenTransactionsFinished()\n }\n repair () {\n this.log('Repairing the state of Yjs. This can happen if messages get lost, and Yjs detects that something is wrong. If this happens often, please report an issue here: https://github.com/y-js/yjs/issues')\n for (var name in this.connections) {\n this.connections[name].isSynced = false\n }\n this.isSynced = false\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n setUserId (userId) {\n if (this.userId == null) {\n this.log('Set userId to \"%s\"', userId)\n this.userId = userId\n return this.y.db.setUserId(userId)\n } else {\n return null\n }\n }\n onUserEvent (f) {\n this.userEventListeners.push(f)\n }\n removeUserEventListener (f) {\n this.userEventListeners = this.userEventListeners.filter(g => { f !== g })\n }\n userLeft (user) {\n if (this.connections[user] != null) {\n this.log('User left: %s', user)\n delete this.connections[user]\n if (user === this.currentSyncTarget) {\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n this.syncingClients = this.syncingClients.filter(function (cli) {\n return cli !== user\n })\n for (var f of this.userEventListeners) {\n f({\n action: 'userLeft',\n user: user\n })\n }\n }\n }\n userJoined (user, role) {\n if (role == null) {\n throw new Error('You must specify the role of the joined user!')\n }\n if (this.connections[user] != null) {\n throw new Error('This user already joined!')\n }\n this.log('User joined: %s', user)\n this.connections[user] = {\n isSynced: false,\n role: role\n }\n for (var f of this.userEventListeners) {\n f({\n action: 'userJoined',\n user: user,\n role: role\n })\n }\n if (this.currentSyncTarget == null) {\n this.findNextSyncTarget()\n }\n }\n // Execute a function _when_ we are connected.\n // If not connected, wait until connected\n whenSynced (f) {\n if (this.isSynced) {\n f()\n } else {\n this.whenSyncedListeners.push(f)\n }\n }\n findNextSyncTarget () {\n if (this.currentSyncTarget != null) {\n return // \"The current sync has not finished!\"\n }\n\n var syncUser = null\n for (var uid in this.connections) {\n if (!this.connections[uid].isSynced) {\n syncUser = uid\n break\n }\n }\n var conn = this\n if (syncUser != null) {\n this.currentSyncTarget = syncUser\n this.y.db.requestTransaction(function *() {\n var stateSet = yield* this.getStateSet()\n var deleteSet = yield* this.getDeleteSet()\n var answer = {\n type: 'sync step 1',\n stateSet: stateSet,\n deleteSet: deleteSet,\n protocolVersion: conn.protocolVersion,\n auth: conn.authInfo\n }\n conn.send(syncUser, answer)\n })\n } else {\n if (!conn.isSynced) {\n this.y.db.requestTransaction(function *() {\n if (!conn.isSynced) {\n // it is crucial that isSynced is set at the time garbageCollectAfterSync is called\n conn.isSynced = true\n yield* this.garbageCollectAfterSync()\n // call whensynced listeners\n for (var f of conn.whenSyncedListeners) {\n f()\n }\n conn.whenSyncedListeners = []\n }\n })\n }\n }\n }\n send (uid, message) {\n this.log('Send \\'%s\\' to %s', message.type, uid)\n this.logMessage('Message: %j', message)\n }\n broadcast (message) {\n this.log('Broadcast \\'%s\\'', message.type)\n this.logMessage('Message: %j', message)\n }\n /*\n Buffer operations, and broadcast them when ready.\n */\n broadcastOps (ops) {\n ops = ops.map(function (op) {\n return Y.Struct[op.struct].encode(op)\n })\n var self = this\n function broadcastOperations () {\n if (self.broadcastOpBuffer.length > 0) {\n self.broadcast({\n type: 'update',\n ops: self.broadcastOpBuffer\n })\n self.broadcastOpBuffer = []\n }\n }\n if (this.broadcastOpBuffer.length === 0) {\n this.broadcastOpBuffer = ops\n if (this.y.db.transactionInProgress) {\n this.y.db.whenTransactionsFinished().then(broadcastOperations)\n } else {\n setTimeout(broadcastOperations, 0)\n }\n } else {\n this.broadcastOpBuffer = this.broadcastOpBuffer.concat(ops)\n }\n }\n /*\n You received a raw message, and you know that it is intended for Yjs. Then call this function.\n */\n receiveMessage (sender/* :UserId */, message/* :Message */) {\n if (sender === this.userId) {\n return Promise.resolve()\n }\n this.log('Receive \\'%s\\' from %s', message.type, sender)\n this.logMessage('Message: %j', message)\n if (message.protocolVersion != null && message.protocolVersion !== this.protocolVersion) {\n this.log(\n `You tried to sync with a yjs instance that has a different protocol version\n (You: ${this.protocolVersion}, Client: ${message.protocolVersion}).\n The sync was stopped. You need to upgrade your dependencies (especially Yjs & the Connector)!\n `)\n this.send(sender, {\n type: 'sync stop',\n protocolVersion: this.protocolVersion\n })\n return Promise.reject('Incompatible protocol version')\n }\n if (message.auth != null && this.connections[sender] != null) {\n // authenticate using auth in message\n var auth = this.checkAuth(message.auth, this.y, sender)\n this.connections[sender].auth = auth\n auth.then(auth => {\n for (var f of this.userEventListeners) {\n f({\n action: 'userAuthenticated',\n user: sender,\n auth: auth\n })\n }\n })\n } else if (this.connections[sender] != null && this.connections[sender].auth == null) {\n // authenticate without otherwise\n this.connections[sender].auth = this.checkAuth(null, this.y, sender)\n }\n if (this.connections[sender] != null && this.connections[sender].auth != null) {\n return this.connections[sender].auth.then((auth) => {\n if (message.type === 'sync step 1' && canRead(auth)) {\n let conn = this\n let m = message\n\n this.y.db.requestTransaction(function *() {\n var currentStateSet = yield* this.getStateSet()\n if (canWrite(auth)) {\n yield* this.applyDeleteSet(m.deleteSet)\n }\n\n var ds = yield* this.getDeleteSet()\n var answer = {\n type: 'sync step 2',\n stateSet: currentStateSet,\n deleteSet: ds,\n protocolVersion: this.protocolVersion,\n auth: this.authInfo\n }\n answer.os = yield* this.getOperations(m.stateSet)\n conn.send(sender, answer)\n if (this.forwardToSyncingClients) {\n conn.syncingClients.push(sender)\n setTimeout(function () {\n conn.syncingClients = conn.syncingClients.filter(function (cli) {\n return cli !== sender\n })\n conn.send(sender, {\n type: 'sync done'\n })\n }, 5000) // TODO: conn.syncingClientDuration)\n } else {\n conn.send(sender, {\n type: 'sync done'\n })\n }\n })\n } else if (message.type === 'sync step 2' && canWrite(auth)) {\n var db = this.y.db\n var defer = {}\n defer.promise = new Promise(function (resolve) {\n defer.resolve = resolve\n })\n this.syncStep2 = defer.promise\n let m /* :MessageSyncStep2 */ = message\n db.requestTransaction(function * () {\n yield* this.applyDeleteSet(m.deleteSet)\n if (m.osUntransformed != null) {\n yield* this.applyOperationsUntransformed(m.osUntransformed, m.stateSet)\n } else {\n this.store.apply(m.os)\n }\n /*\n * This just sends the complete hb after some time\n * Mostly for debugging..\n *\n db.requestTransaction(function * () {\n var ops = yield* this.getOperations(m.stateSet)\n if (ops.length > 0) {\n if (!broadcastHB) { // TODO: consider to broadcast here..\n conn.send(sender, {\n type: 'update',\n ops: ops\n })\n } else {\n // broadcast only once!\n conn.broadcastOps(ops)\n }\n }\n })\n */\n defer.resolve()\n })\n } else if (message.type === 'sync done') {\n var self = this\n this.syncStep2.then(function () {\n self._setSyncedWith(sender)\n })\n } else if (message.type === 'update' && canWrite(auth)) {\n if (this.forwardToSyncingClients) {\n for (var client of this.syncingClients) {\n this.send(client, message)\n }\n }\n if (this.y.db.forwardAppliedOperations) {\n var delops = message.ops.filter(function (o) {\n return o.struct === 'Delete'\n })\n if (delops.length > 0) {\n this.broadcastOps(delops)\n }\n }\n this.y.db.apply(message.ops)\n }\n })\n } else {\n return Promise.reject('Unable to deliver message')\n }\n }\n _setSyncedWith (user) {\n var conn = this.connections[user]\n if (conn != null) {\n conn.isSynced = true\n }\n if (user === this.currentSyncTarget) {\n this.currentSyncTarget = null\n this.findNextSyncTarget()\n }\n }\n /*\n Currently, the HB encodes operations as JSON. For the moment I want to keep it\n that way. Maybe we support encoding in the HB as XML in the future, but for now I don't want\n too much overhead. Y is very likely to get changed a lot in the future\n\n Because we don't want to encode JSON as string (with character escaping, wich makes it pretty much unreadable)\n we encode the JSON as XML.\n\n When the HB support encoding as XML, the format should look pretty much like this.\n\n does not support primitive values as array elements\n expects an ltx (less than xml) object\n */\n parseMessageFromXml (m/* :any */) {\n function parseArray (node) {\n for (var n of node.children) {\n if (n.getAttribute('isArray') === 'true') {\n return parseArray(n)\n } else {\n return parseObject(n)\n }\n }\n }\n function parseObject (node/* :any */) {\n var json = {}\n for (var attrName in node.attrs) {\n var value = node.attrs[attrName]\n var int = parseInt(value, 10)\n if (isNaN(int) || ('' + int) !== value) {\n json[attrName] = value\n } else {\n json[attrName] = int\n }\n }\n for (var n/* :any */ in node.children) {\n var name = n.name\n if (n.getAttribute('isArray') === 'true') {\n json[name] = parseArray(n)\n } else {\n json[name] = parseObject(n)\n }\n }\n return json\n }\n parseObject(m)\n }\n /*\n encode message in xml\n we use string because Strophe only accepts an \"xml-string\"..\n So {a:4,b:{c:5}} will look like\n \n \n \n m - ltx element\n json - Object\n */\n encodeMessageToXml (msg, obj) {\n // attributes is optional\n function encodeObject (m, json) {\n for (var name in json) {\n var value = json[name]\n if (name == null) {\n // nop\n } else if (value.constructor === Object) {\n encodeObject(m.c(name), value)\n } else if (value.constructor === Array) {\n encodeArray(m.c(name), value)\n } else {\n m.setAttribute(name, value)\n }\n }\n }\n function encodeArray (m, array) {\n m.setAttribute('isArray', 'true')\n for (var e of array) {\n if (e.constructor === Object) {\n encodeObject(m.c('array-element'), e)\n } else {\n encodeArray(m.c('array-element'), e)\n }\n }\n }\n if (obj.constructor === Object) {\n encodeObject(msg.c('y', { xmlns: 'http://y.ninja/connector-stanza' }), obj)\n } else if (obj.constructor === Array) {\n encodeArray(msg.c('y', { xmlns: 'http://y.ninja/connector-stanza' }), obj)\n } else {\n throw new Error(\"I can't encode this json!\")\n }\n }\n }\n Y.AbstractConnector = AbstractConnector\n}\n","/* global getRandom, async */\n'use strict'\n\nmodule.exports = function (Y) {\n var globalRoom = {\n users: {},\n buffers: {},\n removeUser: function (user) {\n for (var i in this.users) {\n this.users[i].userLeft(user)\n }\n delete this.users[user]\n delete this.buffers[user]\n },\n addUser: function (connector) {\n this.users[connector.userId] = connector\n this.buffers[connector.userId] = {}\n for (var uname in this.users) {\n if (uname !== connector.userId) {\n var u = this.users[uname]\n u.userJoined(connector.userId, 'master')\n connector.userJoined(u.userId, 'master')\n }\n }\n },\n whenTransactionsFinished: function () {\n var self = this\n return new Promise(function (resolve, reject) {\n // The connector first has to send the messages to the db.\n // Wait for the checkAuth-function to resolve\n // The test lib only has a simple checkAuth function: `() => Promise.resolve()`\n // Just add a function to the event-queue, in order to wait for the event.\n // TODO: this may be buggy in test applications (but it isn't be for real-life apps)\n setTimeout(function () {\n var ps = []\n for (var name in self.users) {\n ps.push(self.users[name].y.db.whenTransactionsFinished())\n }\n Promise.all(ps).then(resolve, reject)\n }, 10)\n })\n },\n flushOne: function flushOne () {\n var bufs = []\n for (var receiver in globalRoom.buffers) {\n let buff = globalRoom.buffers[receiver]\n var push = false\n for (let sender in buff) {\n if (buff[sender].length > 0) {\n push = true\n break\n }\n }\n if (push) {\n bufs.push(receiver)\n }\n }\n if (bufs.length > 0) {\n var userId = getRandom(bufs)\n let buff = globalRoom.buffers[userId]\n let sender = getRandom(Object.keys(buff))\n var m = buff[sender].shift()\n if (buff[sender].length === 0) {\n delete buff[sender]\n }\n var user = globalRoom.users[userId]\n return user.receiveMessage(m[0], m[1]).then(function () {\n return user.y.db.whenTransactionsFinished()\n }, function () {})\n } else {\n return false\n }\n },\n flushAll: function () {\n return new Promise(function (resolve) {\n // flushes may result in more created operations,\n // flush until there is nothing more to flush\n function nextFlush () {\n var c = globalRoom.flushOne()\n if (c) {\n while (c) {\n c = globalRoom.flushOne()\n }\n globalRoom.whenTransactionsFinished().then(nextFlush)\n } else {\n c = globalRoom.flushOne()\n if (c) {\n c.then(function () {\n globalRoom.whenTransactionsFinished().then(nextFlush)\n })\n } else {\n resolve()\n }\n }\n }\n globalRoom.whenTransactionsFinished().then(nextFlush)\n })\n }\n }\n Y.utils.globalRoom = globalRoom\n\n var userIdCounter = 0\n\n class Test extends Y.AbstractConnector {\n constructor (y, options) {\n if (options === undefined) {\n throw new Error('Options must not be undefined!')\n }\n options.role = 'master'\n options.forwardToSyncingClients = false\n super(y, options)\n this.setUserId((userIdCounter++) + '').then(() => {\n globalRoom.addUser(this)\n })\n this.globalRoom = globalRoom\n this.syncingClientDuration = 0\n }\n receiveMessage (sender, m) {\n return super.receiveMessage(sender, JSON.parse(JSON.stringify(m)))\n }\n send (userId, message) {\n var buffer = globalRoom.buffers[userId]\n if (buffer != null) {\n if (buffer[this.userId] == null) {\n buffer[this.userId] = []\n }\n buffer[this.userId].push(JSON.parse(JSON.stringify([this.userId, message])))\n }\n }\n broadcast (message) {\n for (var key in globalRoom.buffers) {\n var buff = globalRoom.buffers[key]\n if (buff[this.userId] == null) {\n buff[this.userId] = []\n }\n buff[this.userId].push(JSON.parse(JSON.stringify([this.userId, message])))\n }\n }\n isDisconnected () {\n return globalRoom.users[this.userId] == null\n }\n reconnect () {\n if (this.isDisconnected()) {\n globalRoom.addUser(this)\n super.reconnect()\n }\n return Y.utils.globalRoom.flushAll()\n }\n disconnect () {\n var waitForMe = Promise.resolve()\n if (!this.isDisconnected()) {\n globalRoom.removeUser(this.userId)\n waitForMe = super.disconnect()\n }\n var self = this\n return waitForMe.then(function () {\n return self.y.db.whenTransactionsFinished()\n })\n }\n flush () {\n var self = this\n return async(function * () {\n var buff = globalRoom.buffers[self.userId]\n while (Object.keys(buff).length > 0) {\n var sender = getRandom(Object.keys(buff))\n var m = buff[sender].shift()\n if (buff[sender].length === 0) {\n delete buff[sender]\n }\n yield this.receiveMessage(m[0], m[1])\n }\n yield self.whenTransactionsFinished()\n })\n }\n }\n\n Y.Test = Test\n}\n","/* @flow */\n'use strict'\n\nmodule.exports = function (Y /* :any */) {\n /*\n Partial definition of an OperationStore.\n TODO: name it Database, operation store only holds operations.\n\n A database definition must alse define the following methods:\n * logTable() (optional)\n - show relevant information information in a table\n * requestTransaction(makeGen)\n - request a transaction\n * destroy()\n - destroy the database\n */\n class AbstractDatabase {\n /* ::\n y: YConfig;\n forwardAppliedOperations: boolean;\n listenersById: Object;\n listenersByIdExecuteNow: Array;\n listenersByIdRequestPending: boolean;\n initializedTypes: Object;\n whenUserIdSetListener: ?Function;\n waitingTransactions: Array;\n transactionInProgress: boolean;\n executeOrder: Array;\n gc1: Array;\n gc2: Array;\n gcTimeout: number;\n gcInterval: any;\n garbageCollect: Function;\n executeOrder: Array; // for debugging only\n userId: UserId;\n opClock: number;\n transactionsFinished: ?{promise: Promise, resolve: any};\n transact: (x: ?Generator) => any;\n */\n constructor (y, opts) {\n this.y = y\n this.dbOpts = opts\n var os = this\n this.userId = null\n var resolve\n this.userIdPromise = new Promise(function (r) {\n resolve = r\n })\n this.userIdPromise.resolve = resolve\n // whether to broadcast all applied operations (insert & delete hook)\n this.forwardAppliedOperations = false\n // E.g. this.listenersById[id] : Array\n this.listenersById = {}\n // Execute the next time a transaction is requested\n this.listenersByIdExecuteNow = []\n // A transaction is requested\n this.listenersByIdRequestPending = false\n /* To make things more clear, the following naming conventions:\n * ls : we put this.listenersById on ls\n * l : Array\n * id : Id (can't use as property name)\n * sid : String (converted from id via JSON.stringify\n so we can use it as a property name)\n\n Always remember to first overwrite\n a property before you iterate over it!\n */\n // TODO: Use ES7 Weak Maps. This way types that are no longer user,\n // wont be kept in memory.\n this.initializedTypes = {}\n this.waitingTransactions = []\n this.transactionInProgress = false\n this.transactionIsFlushed = false\n if (typeof YConcurrency_TestingMode !== 'undefined') {\n this.executeOrder = []\n }\n this.gc1 = [] // first stage\n this.gc2 = [] // second stage -> after that, remove the op\n\n function garbageCollect () {\n return os.whenTransactionsFinished().then(function () {\n if (os.gc1.length > 0 || os.gc2.length > 0) {\n if (!os.y.connector.isSynced) {\n console.warn('gc should be empty when not synced!')\n }\n return new Promise((resolve) => {\n os.requestTransaction(function * () {\n if (os.y.connector != null && os.y.connector.isSynced) {\n for (var i = 0; i < os.gc2.length; i++) {\n var oid = os.gc2[i]\n yield* this.garbageCollectOperation(oid)\n }\n os.gc2 = os.gc1\n os.gc1 = []\n }\n // TODO: Use setInterval here instead (when garbageCollect is called several times there will be several timeouts..)\n if (os.gcTimeout > 0) {\n os.gcInterval = setTimeout(garbageCollect, os.gcTimeout)\n }\n resolve()\n })\n })\n } else {\n // TODO: see above\n if (os.gcTimeout > 0) {\n os.gcInterval = setTimeout(garbageCollect, os.gcTimeout)\n }\n return Promise.resolve()\n }\n })\n }\n this.garbageCollect = garbageCollect\n this.startGarbageCollector()\n\n this.repairCheckInterval = !opts.repairCheckInterval ? 6000 : opts.repairCheckInterval\n this.opsReceivedTimestamp = new Date()\n this.startRepairCheck()\n }\n startGarbageCollector () {\n this.gc = this.dbOpts.gc == null || this.dbOpts.gc\n if (this.gc) {\n this.gcTimeout = !this.dbOpts.gcTimeout ? 50000 : this.dbOpts.gcTimeout\n } else {\n this.gcTimeout = -1\n }\n if (this.gcTimeout > 0) {\n this.garbageCollect()\n }\n }\n startRepairCheck () {\n var os = this\n if (this.repairCheckInterval > 0) {\n this.repairCheckIntervalHandler = setInterval(function repairOnMissingOperations () {\n /*\n Case 1. No ops have been received in a while (new Date() - os.opsReceivedTimestamp > os.repairCheckInterval)\n - 1.1 os.listenersById is empty. Then the state was correct the whole time. -> Nothing to do (nor to update)\n - 1.2 os.listenersById is not empty.\n * Then the state was incorrect for at least {os.repairCheckInterval} seconds.\n * -> Remove everything in os.listenersById and sync again (connector.repair())\n Case 2. An op has been received in the last {os.repairCheckInterval } seconds.\n It is not yet necessary to check for faulty behavior. Everything can still resolve itself. Wait for more messages.\n If nothing was received for a while and os.listenersById is still not emty, we are in case 1.2\n -> Do nothing\n\n Baseline here is: we really only have to catch case 1.2..\n */\n if (\n new Date() - os.opsReceivedTimestamp > os.repairCheckInterval &&\n Object.keys(os.listenersById).length > 0 // os.listenersById is not empty\n ) {\n // haven't received operations for over {os.repairCheckInterval} seconds, resend state vector\n os.listenersById = {}\n os.opsReceivedTimestamp = new Date() // update so you don't send repair several times in a row\n os.y.connector.repair()\n }\n }, this.repairCheckInterval)\n }\n }\n stopRepairCheck () {\n clearInterval(this.repairCheckIntervalHandler)\n }\n queueGarbageCollector (id) {\n if (this.y.connector.isSynced && this.gc) {\n this.gc1.push(id)\n }\n }\n emptyGarbageCollector () {\n return new Promise(resolve => {\n var check = () => {\n if (this.gc1.length > 0 || this.gc2.length > 0) {\n this.garbageCollect().then(check)\n } else {\n resolve()\n }\n }\n setTimeout(check, 0)\n })\n }\n addToDebug () {\n if (typeof YConcurrency_TestingMode !== 'undefined') {\n var command /* :string */ = Array.prototype.map.call(arguments, function (s) {\n if (typeof s === 'string') {\n return s\n } else {\n return JSON.stringify(s)\n }\n }).join('').replace(/\"/g, \"'\").replace(/,/g, ', ').replace(/:/g, ': ')\n this.executeOrder.push(command)\n }\n }\n getDebugData () {\n console.log(this.executeOrder.join('\\n'))\n }\n stopGarbageCollector () {\n var self = this\n this.gc = false\n this.gcTimeout = -1\n return new Promise(function (resolve) {\n self.requestTransaction(function * () {\n var ungc /* :Array */ = self.gc1.concat(self.gc2)\n self.gc1 = []\n self.gc2 = []\n for (var i = 0; i < ungc.length; i++) {\n var op = yield* this.getOperation(ungc[i])\n if (op != null) {\n delete op.gc\n yield* this.setOperation(op)\n }\n }\n resolve()\n })\n })\n }\n /*\n Try to add to GC.\n\n TODO: rename this function\n\n Rulez:\n * Only gc if this user is online & gc turned on\n * The most left element in a list must not be gc'd.\n => There is at least one element in the list\n\n returns true iff op was added to GC\n */\n * addToGarbageCollector (op, left) {\n if (\n op.gc == null &&\n op.deleted === true &&\n this.store.gc &&\n this.store.y.connector.isSynced\n ) {\n var gc = false\n if (left != null && left.deleted === true) {\n gc = true\n } else if (op.content != null && op.content.length > 1) {\n op = yield* this.getInsertionCleanStart([op.id[0], op.id[1] + 1])\n gc = true\n }\n if (gc) {\n op.gc = true\n yield* this.setOperation(op)\n this.store.queueGarbageCollector(op.id)\n return true\n }\n }\n return false\n }\n removeFromGarbageCollector (op) {\n function filter (o) {\n return !Y.utils.compareIds(o, op.id)\n }\n this.gc1 = this.gc1.filter(filter)\n this.gc2 = this.gc2.filter(filter)\n delete op.gc\n }\n destroyTypes () {\n for (var key in this.initializedTypes) {\n var type = this.initializedTypes[key]\n if (type._destroy != null) {\n type._destroy()\n } else {\n console.error('The type you included does not provide destroy functionality, it will remain in memory (updating your packages will help).')\n }\n }\n }\n * destroy () {\n clearInterval(this.gcInterval)\n this.gcInterval = null\n this.stopRepairCheck()\n }\n setUserId (userId) {\n if (!this.userIdPromise.inProgress) {\n this.userIdPromise.inProgress = true\n var self = this\n self.requestTransaction(function * () {\n self.userId = userId\n var state = yield* this.getState(userId)\n self.opClock = state.clock\n self.userIdPromise.resolve(userId)\n })\n }\n return this.userIdPromise\n }\n whenUserIdSet (f) {\n this.userIdPromise.then(f)\n }\n getNextOpId (numberOfIds) {\n if (numberOfIds == null) {\n throw new Error('getNextOpId expects the number of created ids to create!')\n } else if (this.userId == null) {\n throw new Error('OperationStore not yet initialized!')\n } else {\n var id = [this.userId, this.opClock]\n this.opClock += numberOfIds\n return id\n }\n }\n /*\n Apply a list of operations.\n\n * we save a timestamp, because we received new operations that could resolve ops in this.listenersById (see this.startRepairCheck)\n * get a transaction\n * check whether all Struct.*.requiredOps are in the OS\n * check if it is an expected op (otherwise wait for it)\n * check if was deleted, apply a delete operation after op was applied\n */\n apply (ops) {\n this.opsReceivedTimestamp = new Date()\n for (var i = 0; i < ops.length; i++) {\n var o = ops[i]\n if (o.id == null || o.id[0] !== this.y.connector.userId) {\n var required = Y.Struct[o.struct].requiredOps(o)\n if (o.requires != null) {\n required = required.concat(o.requires)\n }\n this.whenOperationsExist(required, o)\n }\n }\n }\n /*\n op is executed as soon as every operation requested is available.\n Note that Transaction can (and should) buffer requests.\n */\n whenOperationsExist (ids, op) {\n if (ids.length > 0) {\n let listener = {\n op: op,\n missing: ids.length\n }\n\n for (let i = 0; i < ids.length; i++) {\n let id = ids[i]\n let sid = JSON.stringify(id)\n let l = this.listenersById[sid]\n if (l == null) {\n l = []\n this.listenersById[sid] = l\n }\n l.push(listener)\n }\n } else {\n this.listenersByIdExecuteNow.push({\n op: op\n })\n }\n\n if (this.listenersByIdRequestPending) {\n return\n }\n\n this.listenersByIdRequestPending = true\n var store = this\n\n this.requestTransaction(function * () {\n var exeNow = store.listenersByIdExecuteNow\n store.listenersByIdExecuteNow = []\n\n var ls = store.listenersById\n store.listenersById = {}\n\n store.listenersByIdRequestPending = false\n\n for (let key = 0; key < exeNow.length; key++) {\n let o = exeNow[key].op\n yield* store.tryExecute.call(this, o)\n }\n\n for (var sid in ls) {\n var l = ls[sid]\n var id = JSON.parse(sid)\n var op\n if (typeof id[1] === 'string') {\n op = yield* this.getOperation(id)\n } else {\n op = yield* this.getInsertion(id)\n }\n if (op == null) {\n store.listenersById[sid] = l\n } else {\n for (let i = 0; i < l.length; i++) {\n let listener = l[i]\n let o = listener.op\n if (--listener.missing === 0) {\n yield* store.tryExecute.call(this, o)\n }\n }\n }\n }\n })\n }\n /*\n Actually execute an operation, when all expected operations are available.\n */\n /* :: // TODO: this belongs somehow to transaction\n store: Object;\n getOperation: any;\n isGarbageCollected: any;\n addOperation: any;\n whenOperationsExist: any;\n */\n * tryExecute (op) {\n this.store.addToDebug('yield* this.store.tryExecute.call(this, ', JSON.stringify(op), ')')\n if (op.struct === 'Delete') {\n yield* Y.Struct.Delete.execute.call(this, op)\n // this is now called in Transaction.deleteOperation!\n // yield* this.store.operationAdded(this, op)\n } else {\n // check if this op was defined\n var defined = yield* this.getInsertion(op.id)\n while (defined != null && defined.content != null) {\n // check if this op has a longer content in the case it is defined\n if (defined.id[1] + defined.content.length < op.id[1] + op.content.length) {\n var overlapSize = defined.content.length - (op.id[1] - defined.id[1])\n op.content.splice(0, overlapSize)\n op.id = [op.id[0], op.id[1] + overlapSize]\n op.left = Y.utils.getLastId(defined)\n op.origin = op.left\n defined = yield* this.getOperation(op.id) // getOperation suffices here\n } else {\n break\n }\n }\n if (defined == null) {\n var opid = op.id\n var isGarbageCollected = yield* this.isGarbageCollected(opid)\n if (!isGarbageCollected) {\n // TODO: reduce number of get / put calls for op ..\n yield* Y.Struct[op.struct].execute.call(this, op)\n yield* this.addOperation(op)\n yield* this.store.operationAdded(this, op)\n // operationAdded can change op..\n op = yield* this.getOperation(opid)\n // if insertion, try to combine with left\n yield* this.tryCombineWithLeft(op)\n }\n }\n }\n }\n /*\n * Called by a transaction when an operation is added.\n * This function is especially important for y-indexeddb, where several instances may share a single database.\n * Every time an operation is created by one instance, it is send to all other instances and operationAdded is called\n *\n * If it's not a Delete operation:\n * * Checks if another operation is executable (listenersById)\n * * Update state, if possible\n *\n * Always:\n * * Call type\n */\n * operationAdded (transaction, op) {\n if (op.struct === 'Delete') {\n var type = this.initializedTypes[JSON.stringify(op.targetParent)]\n if (type != null) {\n yield* type._changed(transaction, op)\n }\n } else {\n // increase SS\n yield* transaction.updateState(op.id[0])\n var opLen = op.content != null ? op.content.length : 1\n for (let i = 0; i < opLen; i++) {\n // notify whenOperation listeners (by id)\n var sid = JSON.stringify([op.id[0], op.id[1] + i])\n var l = this.listenersById[sid]\n delete this.listenersById[sid]\n if (l != null) {\n for (var key in l) {\n var listener = l[key]\n if (--listener.missing === 0) {\n this.whenOperationsExist([], listener.op)\n }\n }\n }\n }\n var t = this.initializedTypes[JSON.stringify(op.parent)]\n\n // if parent is deleted, mark as gc'd and return\n if (op.parent != null) {\n var parentIsDeleted = yield* transaction.isDeleted(op.parent)\n if (parentIsDeleted) {\n yield* transaction.deleteList(op.id)\n return\n }\n }\n\n // notify parent, if it was instanciated as a custom type\n if (t != null) {\n let o = Y.utils.copyOperation(op)\n yield* t._changed(transaction, o)\n }\n if (!op.deleted) {\n // Delete if DS says this is actually deleted\n var len = op.content != null ? op.content.length : 1\n var startId = op.id // You must not use op.id in the following loop, because op will change when deleted\n // TODO: !! console.log('TODO: change this before commiting')\n for (let i = 0; i < len; i++) {\n var id = [startId[0], startId[1] + i]\n var opIsDeleted = yield* transaction.isDeleted(id)\n if (opIsDeleted) {\n var delop = {\n struct: 'Delete',\n target: id\n }\n yield* this.tryExecute.call(transaction, delop)\n }\n }\n }\n }\n }\n whenTransactionsFinished () {\n if (this.transactionInProgress) {\n if (this.transactionsFinished == null) {\n var resolve\n var promise = new Promise(function (r) {\n resolve = r\n })\n this.transactionsFinished = {\n resolve: resolve,\n promise: promise\n }\n }\n return this.transactionsFinished.promise\n } else {\n return Promise.resolve()\n }\n }\n // Check if there is another transaction request.\n // * the last transaction is always a flush :)\n getNextRequest () {\n if (this.waitingTransactions.length === 0) {\n if (this.transactionIsFlushed) {\n this.transactionInProgress = false\n this.transactionIsFlushed = false\n if (this.transactionsFinished != null) {\n this.transactionsFinished.resolve()\n this.transactionsFinished = null\n }\n return null\n } else {\n this.transactionIsFlushed = true\n return function * () {\n yield* this.flush()\n }\n }\n } else {\n this.transactionIsFlushed = false\n return this.waitingTransactions.shift()\n }\n }\n requestTransaction (makeGen/* :any */, callImmediately) {\n this.waitingTransactions.push(makeGen)\n if (!this.transactionInProgress) {\n this.transactionInProgress = true\n setTimeout(() => {\n this.transact(this.getNextRequest())\n }, 0)\n }\n }\n /*\n Get a created/initialized type.\n */\n getType (id) {\n return this.initializedTypes[JSON.stringify(id)]\n }\n /*\n Init type. This is called when a remote operation is retrieved, and transformed to a type\n TODO: delete type from store.initializedTypes[id] when corresponding id was deleted!\n */\n * initType (id, args) {\n var sid = JSON.stringify(id)\n var t = this.store.initializedTypes[sid]\n if (t == null) {\n var op/* :MapStruct | ListStruct */ = yield* this.getOperation(id)\n if (op != null) {\n t = yield* Y[op.type].typeDefinition.initType.call(this, this.store, op, args)\n this.store.initializedTypes[sid] = t\n }\n }\n return t\n }\n /*\n Create type. This is called when the local user creates a type (which is a synchronous action)\n */\n createType (typedefinition, id) {\n var structname = typedefinition[0].struct\n id = id || this.getNextOpId(1)\n var op = Y.Struct[structname].create(id)\n op.type = typedefinition[0].name\n\n this.requestTransaction(function * () {\n if (op.id[0] === '_') {\n yield* this.setOperation(op)\n } else {\n yield* this.applyCreatedOperations([op])\n }\n })\n var t = Y[op.type].typeDefinition.createType(this, op, typedefinition[1])\n this.initializedTypes[JSON.stringify(op.id)] = t\n return t\n }\n }\n Y.AbstractDatabase = AbstractDatabase\n}\n","/* @flow */\n'use strict'\n\n/*\n An operation also defines the structure of a type. This is why operation and\n structure are used interchangeably here.\n\n It must be of the type Object. I hope to achieve some performance\n improvements when working on databases that support the json format.\n\n An operation must have the following properties:\n\n * encode\n - Encode the structure in a readable format (preferably string- todo)\n * decode (todo)\n - decode structure to json\n * execute\n - Execute the semantics of an operation.\n * requiredOps\n - Operations that are required to execute this operation.\n*/\nmodule.exports = function (Y/* :any */) {\n var Struct = {\n /* This is the only operation that is actually not a structure, because\n it is not stored in the OS. This is why it _does not_ have an id\n\n op = {\n target: Id\n }\n */\n Delete: {\n encode: function (op) {\n return {\n target: op.target,\n length: op.length || 0,\n struct: 'Delete'\n }\n },\n requiredOps: function (op) {\n return [] // [op.target]\n },\n execute: function * (op) {\n return yield* this.deleteOperation(op.target, op.length || 1)\n }\n },\n Insert: {\n /* {\n content: [any],\n opContent: Id,\n id: Id,\n left: Id,\n origin: Id,\n right: Id,\n parent: Id,\n parentSub: string (optional), // child of Map type\n }\n */\n encode: function (op/* :Insertion */) /* :Insertion */ {\n // TODO: you could not send the \"left\" property, then you also have to\n // \"op.left = null\" in $execute or $decode\n var e/* :any */ = {\n id: op.id,\n left: op.left,\n right: op.right,\n origin: op.origin,\n parent: op.parent,\n struct: op.struct\n }\n if (op.parentSub != null) {\n e.parentSub = op.parentSub\n }\n if (op.hasOwnProperty('opContent')) {\n e.opContent = op.opContent\n } else {\n e.content = op.content.slice()\n }\n\n return e\n },\n requiredOps: function (op) {\n var ids = []\n if (op.left != null) {\n ids.push(op.left)\n }\n if (op.right != null) {\n ids.push(op.right)\n }\n if (op.origin != null && !Y.utils.compareIds(op.left, op.origin)) {\n ids.push(op.origin)\n }\n // if (op.right == null && op.left == null) {\n ids.push(op.parent)\n\n if (op.opContent != null) {\n ids.push(op.opContent)\n }\n return ids\n },\n getDistanceToOrigin: function * (op) {\n if (op.left == null) {\n return 0\n } else {\n var d = 0\n var o = yield* this.getInsertion(op.left)\n while (!Y.utils.matchesId(o, op.origin)) {\n d++\n if (o.left == null) {\n break\n } else {\n o = yield* this.getInsertion(o.left)\n }\n }\n return d\n }\n },\n /*\n # $this has to find a unique position between origin and the next known character\n # case 1: $origin equals $o.origin: the $creator parameter decides if left or right\n # let $OL= [o1,o2,o3,o4], whereby $this is to be inserted between o1 and o4\n # o2,o3 and o4 origin is 1 (the position of o2)\n # there is the case that $this.creator < o2.creator, but o3.creator < $this.creator\n # then o2 knows o3. Since on another client $OL could be [o1,o3,o4] the problem is complex\n # therefore $this would be always to the right of o3\n # case 2: $origin < $o.origin\n # if current $this insert_position > $o origin: $this ins\n # else $insert_position will not change\n # (maybe we encounter case 1 later, then this will be to the right of $o)\n # case 3: $origin > $o.origin\n # $this insert_position is to the left of $o (forever!)\n */\n execute: function * (op) {\n var i // loop counter\n\n // during this function some ops may get split into two pieces (e.g. with getInsertionCleanEnd)\n // We try to merge them later, if possible\n var tryToRemergeLater = []\n\n if (op.origin != null) { // TODO: !== instead of !=\n // we save in origin that op originates in it\n // we need that later when we eventually garbage collect origin (see transaction)\n var origin = yield* this.getInsertionCleanEnd(op.origin)\n if (origin.originOf == null) {\n origin.originOf = []\n }\n origin.originOf.push(op.id)\n yield* this.setOperation(origin)\n if (origin.right != null) {\n tryToRemergeLater.push(origin.right)\n }\n }\n var distanceToOrigin = i = yield* Struct.Insert.getDistanceToOrigin.call(this, op) // most cases: 0 (starts from 0)\n\n // now we begin to insert op in the list of insertions..\n var o\n var parent\n var start\n\n // find o. o is the first conflicting operation\n if (op.left != null) {\n o = yield* this.getInsertionCleanEnd(op.left)\n if (!Y.utils.compareIds(op.left, op.origin) && o.right != null) {\n // only if not added previously\n tryToRemergeLater.push(o.right)\n }\n o = (o.right == null) ? null : yield* this.getOperation(o.right)\n } else { // left == null\n parent = yield* this.getOperation(op.parent)\n let startId = op.parentSub ? parent.map[op.parentSub] : parent.start\n start = startId == null ? null : yield* this.getOperation(startId)\n o = start\n }\n\n // make sure to split op.right if necessary (also add to tryCombineWithLeft)\n if (op.right != null) {\n tryToRemergeLater.push(op.right)\n yield* this.getInsertionCleanStart(op.right)\n }\n\n // handle conflicts\n while (true) {\n if (o != null && !Y.utils.compareIds(o.id, op.right)) {\n var oOriginDistance = yield* Struct.Insert.getDistanceToOrigin.call(this, o)\n if (oOriginDistance === i) {\n // case 1\n if (o.id[0] < op.id[0]) {\n op.left = Y.utils.getLastId(o)\n distanceToOrigin = i + 1 // just ignore o.content.length, doesn't make a difference\n }\n } else if (oOriginDistance < i) {\n // case 2\n if (i - distanceToOrigin <= oOriginDistance) {\n op.left = Y.utils.getLastId(o)\n distanceToOrigin = i + 1 // just ignore o.content.length, doesn't make a difference\n }\n } else {\n break\n }\n i++\n if (o.right != null) {\n o = yield* this.getInsertion(o.right)\n } else {\n o = null\n }\n } else {\n break\n }\n }\n\n // reconnect..\n var left = null\n var right = null\n if (parent == null) {\n parent = yield* this.getOperation(op.parent)\n }\n\n // reconnect left and set right of op\n if (op.left != null) {\n left = yield* this.getInsertion(op.left)\n // link left\n op.right = left.right\n left.right = op.id\n\n yield* this.setOperation(left)\n } else {\n // set op.right from parent, if necessary\n op.right = op.parentSub ? parent.map[op.parentSub] || null : parent.start\n }\n // reconnect right\n if (op.right != null) {\n // TODO: wanna connect right too?\n right = yield* this.getOperation(op.right)\n right.left = Y.utils.getLastId(op)\n\n // if right exists, and it is supposed to be gc'd. Remove it from the gc\n if (right.gc != null) {\n if (right.content != null && right.content.length > 1) {\n right = yield* this.getInsertionCleanEnd(right.id)\n }\n this.store.removeFromGarbageCollector(right)\n }\n yield* this.setOperation(right)\n }\n\n // update parents .map/start/end properties\n if (op.parentSub != null) {\n if (left == null) {\n parent.map[op.parentSub] = op.id\n yield* this.setOperation(parent)\n }\n // is a child of a map struct.\n // Then also make sure that only the most left element is not deleted\n // We do not call the type in this case (this is what the third parameter is for)\n if (op.right != null) {\n yield* this.deleteOperation(op.right, 1, true)\n }\n if (op.left != null) {\n yield* this.deleteOperation(op.id, 1, true)\n }\n } else {\n if (right == null || left == null) {\n if (right == null) {\n parent.end = Y.utils.getLastId(op)\n }\n if (left == null) {\n parent.start = op.id\n }\n yield* this.setOperation(parent)\n }\n }\n\n // try to merge original op.left and op.origin\n for (i = 0; i < tryToRemergeLater.length; i++) {\n var m = yield* this.getOperation(tryToRemergeLater[i])\n yield* this.tryCombineWithLeft(m)\n }\n }\n },\n List: {\n /*\n {\n start: null,\n end: null,\n struct: \"List\",\n type: \"\",\n id: this.os.getNextOpId(1)\n }\n */\n create: function (id) {\n return {\n start: null,\n end: null,\n struct: 'List',\n id: id\n }\n },\n encode: function (op) {\n var e = {\n struct: 'List',\n id: op.id,\n type: op.type\n }\n if (op.requires != null) {\n e.requires = op.requires\n }\n if (op.info != null) {\n e.info = op.info\n }\n return e\n },\n requiredOps: function () {\n /*\n var ids = []\n if (op.start != null) {\n ids.push(op.start)\n }\n if (op.end != null){\n ids.push(op.end)\n }\n return ids\n */\n return []\n },\n execute: function * (op) {\n op.start = null\n op.end = null\n },\n ref: function * (op, pos) {\n if (op.start == null) {\n return null\n }\n var res = null\n var o = yield* this.getOperation(op.start)\n\n while (true) {\n if (!o.deleted) {\n res = o\n pos--\n }\n if (pos >= 0 && o.right != null) {\n o = yield* this.getOperation(o.right)\n } else {\n break\n }\n }\n return res\n },\n map: function * (o, f) {\n o = o.start\n var res = []\n while (o != null) { // TODO: change to != (at least some convention)\n var operation = yield* this.getOperation(o)\n if (!operation.deleted) {\n res.push(f(operation))\n }\n o = operation.right\n }\n return res\n }\n },\n Map: {\n /*\n {\n map: {},\n struct: \"Map\",\n type: \"\",\n id: this.os.getNextOpId(1)\n }\n */\n create: function (id) {\n return {\n id: id,\n map: {},\n struct: 'Map'\n }\n },\n encode: function (op) {\n var e = {\n struct: 'Map',\n type: op.type,\n id: op.id,\n map: {} // overwrite map!!\n }\n if (op.requires != null) {\n e.requires = op.requires\n }\n if (op.info != null) {\n e.info = op.info\n }\n return e\n },\n requiredOps: function () {\n return []\n },\n execute: function * () {},\n /*\n Get a property by name\n */\n get: function * (op, name) {\n var oid = op.map[name]\n if (oid != null) {\n var res = yield* this.getOperation(oid)\n if (res == null || res.deleted) {\n return void 0\n } else if (res.opContent == null) {\n return res.content[0]\n } else {\n return yield* this.getType(res.opContent)\n }\n }\n }\n }\n }\n Y.Struct = Struct\n}\n","/* @flow */\n'use strict'\n\n/*\n Partial definition of a transaction\n\n A transaction provides all the the async functionality on a database.\n\n By convention, a transaction has the following properties:\n * ss for StateSet\n * os for OperationStore\n * ds for DeleteStore\n\n A transaction must also define the following methods:\n * checkDeleteStoreForState(state)\n - When increasing the state of a user, an operation with an higher id\n may already be garbage collected, and therefore it will never be received.\n update the state to reflect this knowledge. This won't call a method to save the state!\n * getDeleteSet(id)\n - Get the delete set in a readable format:\n {\n \"userX\": [\n [5,1], // starting from position 5, one operations is deleted\n [9,4] // starting from position 9, four operations are deleted\n ],\n \"userY\": ...\n }\n * getOpsFromDeleteSet(ds) -- TODO: just call this.deleteOperation(id) here\n - get a set of deletions that need to be applied in order to get to\n achieve the state of the supplied ds\n * setOperation(op)\n - write `op` to the database.\n Note: this is allowed to return an in-memory object.\n E.g. the Memory adapter returns the object that it has in-memory.\n Changing values on this object will be stored directly in the database\n without calling this function. Therefore,\n setOperation may have no functionality in some adapters. This also has\n implications on the way we use operations that were served from the database.\n We try not to call copyObject, if not necessary.\n * addOperation(op)\n - add an operation to the database.\n This may only be called once for every op.id\n Must return a function that returns the next operation in the database (ordered by id)\n * getOperation(id)\n * removeOperation(id)\n - remove an operation from the database. This is called when an operation\n is garbage collected.\n * setState(state)\n - `state` is of the form\n {\n user: \"1\",\n clock: 4\n } <- meaning that we have four operations from user \"1\"\n (with these id's respectively: 0, 1, 2, and 3)\n * getState(user)\n * getStateVector()\n - Get the state of the OS in the form\n [{\n user: \"userX\",\n clock: 11\n },\n ..\n ]\n * getStateSet()\n - Get the state of the OS in the form\n {\n \"userX\": 11,\n \"userY\": 22\n }\n * getOperations(startSS)\n - Get the all the operations that are necessary in order to achive the\n stateSet of this user, starting from a stateSet supplied by another user\n * makeOperationReady(ss, op)\n - this is called only by `getOperations(startSS)`. It makes an operation\n applyable on a given SS.\n*/\nmodule.exports = function (Y/* :any */) {\n class TransactionInterface {\n /* ::\n store: Y.AbstractDatabase;\n ds: Store;\n os: Store;\n ss: Store;\n */\n /*\n Apply operations that this user created (no remote ones!)\n * does not check for Struct.*.requiredOps()\n * also broadcasts it through the connector\n */\n * applyCreatedOperations (ops) {\n var send = []\n for (var i = 0; i < ops.length; i++) {\n var op = ops[i]\n yield* this.store.tryExecute.call(this, op)\n if (op.id == null || typeof op.id[1] !== 'string') {\n send.push(Y.Struct[op.struct].encode(op))\n }\n }\n if (send.length > 0) { // TODO: && !this.store.forwardAppliedOperations (but then i don't send delete ops)\n // is connected, and this is not going to be send in addOperation\n this.store.y.connector.broadcastOps(send)\n }\n }\n\n * deleteList (start) {\n while (start != null) {\n start = yield* this.getOperation(start)\n if (!start.gc) {\n start.gc = true\n start.deleted = true\n yield* this.setOperation(start)\n var delLength = start.content != null ? start.content.length : 1\n yield* this.markDeleted(start.id, delLength)\n if (start.opContent != null) {\n yield* this.deleteOperation(start.opContent)\n }\n this.store.queueGarbageCollector(start.id)\n }\n start = start.right\n }\n }\n\n /*\n Mark an operation as deleted, and add it to the GC, if possible.\n */\n * deleteOperation (targetId, length, preventCallType) /* :Generator */ {\n if (length == null) {\n length = 1\n }\n yield* this.markDeleted(targetId, length)\n while (length > 0) {\n var callType = false\n var target = yield* this.os.findWithUpperBound([targetId[0], targetId[1] + length - 1])\n var targetLength = target != null && target.content != null ? target.content.length : 1\n if (target == null || target.id[0] !== targetId[0] || target.id[1] + targetLength <= targetId[1]) {\n // does not exist or is not in the range of the deletion\n target = null\n length = 0\n } else {\n // does exist, check if it is too long\n if (!target.deleted) {\n if (target.id[1] < targetId[1]) {\n // starts to the left of the deletion range\n target = yield* this.getInsertionCleanStart(targetId)\n targetLength = target.content.length // must have content property!\n }\n if (target.id[1] + targetLength > targetId[1] + length) {\n // ends to the right of the deletion range\n target = yield* this.getInsertionCleanEnd([targetId[0], targetId[1] + length - 1])\n targetLength = target.content.length\n }\n }\n length = target.id[1] - targetId[1]\n }\n\n if (target != null) {\n if (!target.deleted) {\n callType = true\n // set deleted & notify type\n target.deleted = true\n // delete containing lists\n if (target.start != null) {\n // TODO: don't do it like this .. -.-\n yield* this.deleteList(target.start)\n // yield* this.deleteList(target.id) -- do not gc itself because this may still get referenced\n }\n if (target.map != null) {\n for (var name in target.map) {\n yield* this.deleteList(target.map[name])\n }\n // TODO: here to.. (see above)\n // yield* this.deleteList(target.id) -- see above\n }\n if (target.opContent != null) {\n yield* this.deleteOperation(target.opContent)\n // target.opContent = null\n }\n if (target.requires != null) {\n for (var i = 0; i < target.requires.length; i++) {\n yield* this.deleteOperation(target.requires[i])\n }\n }\n }\n var left\n if (target.left != null) {\n left = yield* this.getInsertion(target.left)\n } else {\n left = null\n }\n\n // set here because it was deleted and/or gc'd\n yield* this.setOperation(target)\n\n /*\n Check if it is possible to add right to the gc.\n Because this delete can't be responsible for left being gc'd,\n we don't have to add left to the gc..\n */\n var right\n if (target.right != null) {\n right = yield* this.getOperation(target.right)\n } else {\n right = null\n }\n if (callType && !preventCallType) {\n yield* this.store.operationAdded(this, {\n struct: 'Delete',\n target: target.id,\n length: targetLength,\n targetParent: target.parent\n })\n }\n // need to gc in the end!\n yield* this.store.addToGarbageCollector.call(this, target, left)\n if (right != null) {\n yield* this.store.addToGarbageCollector.call(this, right, target)\n }\n }\n }\n }\n /*\n Mark an operation as deleted&gc'd\n */\n * markGarbageCollected (id, len) {\n // this.mem.push([\"gc\", id]);\n this.store.addToDebug('yield* this.markGarbageCollected(', id, ', ', len, ')')\n var n = yield* this.markDeleted(id, len)\n if (n.id[1] < id[1] && !n.gc) {\n // un-extend left\n var newlen = n.len - (id[1] - n.id[1])\n n.len -= newlen\n yield* this.ds.put(n)\n n = {id: id, len: newlen, gc: false}\n yield* this.ds.put(n)\n }\n // get prev&next before adding a new operation\n var prev = yield* this.ds.findPrev(id)\n var next = yield* this.ds.findNext(id)\n\n if (id[1] + len < n.id[1] + n.len && !n.gc) {\n // un-extend right\n yield* this.ds.put({id: [id[0], id[1] + len], len: n.len - len, gc: false})\n n.len = len\n }\n // set gc'd\n n.gc = true\n // can extend left?\n if (\n prev != null &&\n prev.gc &&\n Y.utils.compareIds([prev.id[0], prev.id[1] + prev.len], n.id)\n ) {\n prev.len += n.len\n yield* this.ds.delete(n.id)\n n = prev\n // ds.put n here?\n }\n // can extend right?\n if (\n next != null &&\n next.gc &&\n Y.utils.compareIds([n.id[0], n.id[1] + n.len], next.id)\n ) {\n n.len += next.len\n yield* this.ds.delete(next.id)\n }\n yield* this.ds.put(n)\n yield* this.updateState(n.id[0])\n }\n /*\n Mark an operation as deleted.\n\n returns the delete node\n */\n * markDeleted (id, length) {\n if (length == null) {\n length = 1\n }\n // this.mem.push([\"del\", id]);\n var n = yield* this.ds.findWithUpperBound(id)\n if (n != null && n.id[0] === id[0]) {\n if (n.id[1] <= id[1] && id[1] <= n.id[1] + n.len) {\n // id is in n's range\n var diff = id[1] + length - (n.id[1] + n.len) // overlapping right\n if (diff > 0) {\n // id+length overlaps n\n if (!n.gc) {\n n.len += diff\n } else {\n diff = n.id[1] + n.len - id[1] // overlapping left (id till n.end)\n if (diff < length) {\n // a partial deletion\n n = {id: [id[0], id[1] + diff], len: length - diff, gc: false}\n yield* this.ds.put(n)\n } else {\n // already gc'd\n throw new Error('Cannot happen! (it dit though.. :()')\n // return n\n }\n }\n } else {\n // no overlapping, already deleted\n return n\n }\n } else {\n // cannot extend left (there is no left!)\n n = {id: id, len: length, gc: false}\n yield* this.ds.put(n) // TODO: you double-put !!\n }\n } else {\n // cannot extend left\n n = {id: id, len: length, gc: false}\n yield* this.ds.put(n)\n }\n // can extend right?\n var next = yield* this.ds.findNext(n.id)\n if (\n next != null &&\n n.id[0] === next.id[0] &&\n n.id[1] + n.len >= next.id[1]\n ) {\n diff = n.id[1] + n.len - next.id[1] // from next.start to n.end\n while (diff >= 0) {\n // n overlaps with next\n if (next.gc) {\n // gc is stronger, so reduce length of n\n n.len -= diff\n if (diff >= next.len) {\n // delete the missing range after next\n diff = diff - next.len // missing range after next\n if (diff > 0) {\n yield* this.ds.put(n) // unneccessary? TODO!\n yield* this.markDeleted([next.id[0], next.id[1] + next.len], diff)\n }\n }\n break\n } else {\n // we can extend n with next\n if (diff > next.len) {\n // n is even longer than next\n // get next.next, and try to extend it\n var _next = yield* this.ds.findNext(next.id)\n yield* this.ds.delete(next.id)\n if (_next == null || n.id[0] !== _next.id[0]) {\n break\n } else {\n next = _next\n diff = n.id[1] + n.len - next.id[1] // from next.start to n.end\n // continue!\n }\n } else {\n // n just partially overlaps with next. extend n, delete next, and break this loop\n n.len += next.len - diff\n yield* this.ds.delete(next.id)\n break\n }\n }\n }\n }\n yield* this.ds.put(n)\n return n\n }\n /*\n Call this method when the client is connected&synced with the\n other clients (e.g. master). This will query the database for\n operations that can be gc'd and add them to the garbage collector.\n */\n * garbageCollectAfterSync () {\n if (this.store.gc1.length > 0 || this.store.gc2.length > 0) {\n console.warn('gc should be empty after sync')\n }\n if (!this.store.gc) {\n return\n }\n yield* this.os.iterate(this, null, null, function * (op) {\n if (op.gc) {\n delete op.gc\n yield* this.setOperation(op)\n }\n if (op.parent != null) {\n var parentDeleted = yield* this.isDeleted(op.parent)\n if (parentDeleted) {\n op.gc = true\n if (!op.deleted) {\n yield* this.markDeleted(op.id, op.content != null ? op.content.length : 1)\n op.deleted = true\n if (op.opContent != null) {\n yield* this.deleteOperation(op.opContent)\n }\n if (op.requires != null) {\n for (var i = 0; i < op.requires.length; i++) {\n yield* this.deleteOperation(op.requires[i])\n }\n }\n }\n yield* this.setOperation(op)\n this.store.gc1.push(op.id) // this is ok becaues its shortly before sync (otherwise use queueGarbageCollector!)\n return\n }\n }\n if (op.deleted) {\n var left = null\n if (op.left != null) {\n left = yield* this.getInsertion(op.left)\n }\n yield* this.store.addToGarbageCollector.call(this, op, left)\n }\n })\n }\n /*\n Really remove an op and all its effects.\n The complicated case here is the Insert operation:\n * reset left\n * reset right\n * reset parent.start\n * reset parent.end\n * reset origins of all right ops\n */\n * garbageCollectOperation (id) {\n this.store.addToDebug('yield* this.garbageCollectOperation(', id, ')')\n var o = yield* this.getOperation(id)\n yield* this.markGarbageCollected(id, (o != null && o.content != null) ? o.content.length : 1) // always mark gc'd\n // if op exists, then clean that mess up..\n if (o != null) {\n var deps = []\n if (o.opContent != null) {\n deps.push(o.opContent)\n }\n if (o.requires != null) {\n deps = deps.concat(o.requires)\n }\n for (var i = 0; i < deps.length; i++) {\n var dep = yield* this.getOperation(deps[i])\n if (dep != null) {\n if (!dep.deleted) {\n yield* this.deleteOperation(dep.id)\n dep = yield* this.getOperation(dep.id)\n }\n dep.gc = true\n yield* this.setOperation(dep)\n this.store.queueGarbageCollector(dep.id)\n } else {\n yield* this.markGarbageCollected(deps[i], 1)\n }\n }\n\n // remove gc'd op from the left op, if it exists\n if (o.left != null) {\n var left = yield* this.getInsertion(o.left)\n left.right = o.right\n yield* this.setOperation(left)\n }\n // remove gc'd op from the right op, if it exists\n // also reset origins of right ops\n if (o.right != null) {\n var right = yield* this.getOperation(o.right)\n right.left = o.left\n yield* this.setOperation(right)\n\n if (o.originOf != null && o.originOf.length > 0) {\n // find new origin of right ops\n // origin is the first left deleted operation\n var neworigin = o.left\n var neworigin_ = null\n while (neworigin != null) {\n neworigin_ = yield* this.getInsertion(neworigin)\n if (neworigin_.deleted) {\n break\n }\n neworigin = neworigin_.left\n }\n\n // reset origin of all right ops (except first right - duh!),\n\n /* ** The following code does not rely on the the originOf property **\n I recently added originOf to all Insert Operations (see Struct.Insert.execute),\n which saves which operations originate in a Insert operation.\n Garbage collecting without originOf is more memory efficient, but is nearly impossible for large texts, or lists!\n But I keep this code for now\n ```\n // reset origin of right\n right.origin = neworigin\n // search until you find origin pointer to the left of o\n if (right.right != null) {\n var i = yield* this.getOperation(right.right)\n var ids = [o.id, o.right]\n while (ids.some(function (id) {\n return Y.utils.compareIds(id, i.origin)\n })) {\n if (Y.utils.compareIds(i.origin, o.id)) {\n // reset origin of i\n i.origin = neworigin\n yield* this.setOperation(i)\n }\n // get next i\n if (i.right == null) {\n break\n } else {\n ids.push(i.id)\n i = yield* this.getOperation(i.right)\n }\n }\n }\n ```\n */\n // ** Now the new implementation starts **\n // reset neworigin of all originOf[*]\n for (var _i in o.originOf) {\n var originsIn = yield* this.getOperation(o.originOf[_i])\n if (originsIn != null) {\n originsIn.origin = neworigin\n yield* this.setOperation(originsIn)\n }\n }\n if (neworigin != null) {\n if (neworigin_.originOf == null) {\n neworigin_.originOf = o.originOf\n } else {\n neworigin_.originOf = o.originOf.concat(neworigin_.originOf)\n }\n yield* this.setOperation(neworigin_)\n }\n // we don't need to set right here, because\n // right should be in o.originOf => it is set it the previous for loop\n }\n }\n // o may originate in another operation.\n // Since o is deleted, we have to reset o.origin's `originOf` property\n if (o.origin != null) {\n var origin = yield* this.getInsertion(o.origin)\n origin.originOf = origin.originOf.filter(function (_id) {\n return !Y.utils.compareIds(id, _id)\n })\n yield* this.setOperation(origin)\n }\n var parent\n if (o.parent != null) {\n parent = yield* this.getOperation(o.parent)\n }\n // remove gc'd op from parent, if it exists\n if (parent != null) {\n var setParent = false // whether to save parent to the os\n if (o.parentSub != null) {\n if (Y.utils.compareIds(parent.map[o.parentSub], o.id)) {\n setParent = true\n if (o.right != null) {\n parent.map[o.parentSub] = o.right\n } else {\n delete parent.map[o.parentSub]\n }\n }\n } else {\n if (Y.utils.compareIds(parent.start, o.id)) {\n // gc'd op is the start\n setParent = true\n parent.start = o.right\n }\n if (Y.utils.matchesId(o, parent.end)) {\n // gc'd op is the end\n setParent = true\n parent.end = o.left\n }\n }\n if (setParent) {\n yield* this.setOperation(parent)\n }\n }\n // finally remove it from the os\n yield* this.removeOperation(o.id)\n }\n }\n * checkDeleteStoreForState (state) {\n var n = yield* this.ds.findWithUpperBound([state.user, state.clock])\n if (n != null && n.id[0] === state.user && n.gc) {\n state.clock = Math.max(state.clock, n.id[1] + n.len)\n }\n }\n * updateState (user) {\n var state = yield* this.getState(user)\n yield* this.checkDeleteStoreForState(state)\n var o = yield* this.getInsertion([user, state.clock])\n var oLength = (o != null && o.content != null) ? o.content.length : 1\n while (o != null && user === o.id[0] && o.id[1] <= state.clock && o.id[1] + oLength > state.clock) {\n // either its a new operation (1. case), or it is an operation that was deleted, but is not yet in the OS\n state.clock += oLength\n yield* this.checkDeleteStoreForState(state)\n o = yield* this.os.findNext(o.id)\n oLength = (o != null && o.content != null) ? o.content.length : 1\n }\n yield* this.setState(state)\n }\n /*\n apply a delete set in order to get\n the state of the supplied ds\n */\n * applyDeleteSet (ds) {\n var deletions = []\n\n for (var user in ds) {\n var dv = ds[user]\n var pos = 0\n var d = dv[pos]\n yield* this.ds.iterate(this, [user, 0], [user, Number.MAX_VALUE], function * (n) {\n // cases:\n // 1. d deletes something to the right of n\n // => go to next n (break)\n // 2. d deletes something to the left of n\n // => create deletions\n // => reset d accordingly\n // *)=> if d doesn't delete anything anymore, go to next d (continue)\n // 3. not 2) and d deletes something that also n deletes\n // => reset d so that it doesn't contain n's deletion\n // *)=> if d does not delete anything anymore, go to next d (continue)\n while (d != null) {\n var diff = 0 // describe the diff of length in 1) and 2)\n if (n.id[1] + n.len <= d[0]) {\n // 1)\n break\n } else if (d[0] < n.id[1]) {\n // 2)\n // delete maximum the len of d\n // else delete as much as possible\n diff = Math.min(n.id[1] - d[0], d[1])\n deletions.push([user, d[0], diff, d[2]])\n } else {\n // 3)\n diff = n.id[1] + n.len - d[0] // never null (see 1)\n if (d[2] && !n.gc) {\n // d marks as gc'd but n does not\n // then delete either way\n deletions.push([user, d[0], Math.min(diff, d[1]), d[2]])\n }\n }\n if (d[1] <= diff) {\n // d doesn't delete anything anymore\n d = dv[++pos]\n } else {\n d[0] = d[0] + diff // reset pos\n d[1] = d[1] - diff // reset length\n }\n }\n })\n // for the rest.. just apply it\n for (; pos < dv.length; pos++) {\n d = dv[pos]\n deletions.push([user, d[0], d[1], d[2]])\n }\n }\n for (var i = 0; i < deletions.length; i++) {\n var del = deletions[i]\n // always try to delete..\n yield* this.deleteOperation([del[0], del[1]], del[2])\n if (del[3]) {\n // gc..\n yield* this.markGarbageCollected([del[0], del[1]], del[2]) // always mark gc'd\n // remove operation..\n var counter = del[1] + del[2]\n while (counter >= del[1]) {\n var o = yield* this.os.findWithUpperBound([del[0], counter - 1])\n if (o == null) {\n break\n }\n var oLen = o.content != null ? o.content.length : 1\n if (o.id[0] !== del[0] || o.id[1] + oLen <= del[1]) {\n // not in range\n break\n }\n if (o.id[1] + oLen > del[1] + del[2]) {\n // overlaps right\n o = yield* this.getInsertionCleanEnd([del[0], del[1] + del[2] - 1])\n }\n if (o.id[1] < del[1]) {\n // overlaps left\n o = yield* this.getInsertionCleanStart([del[0], del[1]])\n }\n counter = o.id[1]\n yield* this.garbageCollectOperation(o.id)\n }\n }\n if (this.store.forwardAppliedOperations) {\n var ops = []\n ops.push({struct: 'Delete', target: [del[0], del[1]], length: del[2]})\n this.store.y.connector.broadcastOps(ops)\n }\n }\n }\n * isGarbageCollected (id) {\n var n = yield* this.ds.findWithUpperBound(id)\n return n != null && n.id[0] === id[0] && id[1] < n.id[1] + n.len && n.gc\n }\n /*\n A DeleteSet (ds) describes all the deleted ops in the OS\n */\n * getDeleteSet () {\n var ds = {}\n yield* this.ds.iterate(this, null, null, function * (n) {\n var user = n.id[0]\n var counter = n.id[1]\n var len = n.len\n var gc = n.gc\n var dv = ds[user]\n if (dv === void 0) {\n dv = []\n ds[user] = dv\n }\n dv.push([counter, len, gc])\n })\n return ds\n }\n * isDeleted (id) {\n var n = yield* this.ds.findWithUpperBound(id)\n return n != null && n.id[0] === id[0] && id[1] < n.id[1] + n.len\n }\n * setOperation (op) {\n yield* this.os.put(op)\n return op\n }\n * addOperation (op) {\n yield* this.os.put(op)\n if (this.store.forwardAppliedOperations && typeof op.id[1] !== 'string') {\n // is connected, and this is not going to be send in addOperation\n this.store.y.connector.broadcastOps([op])\n }\n }\n // if insertion, try to combine with left insertion (if both have content property)\n * tryCombineWithLeft (op) {\n if (\n op != null &&\n op.left != null &&\n op.content != null &&\n op.left[0] === op.id[0] &&\n Y.utils.compareIds(op.left, op.origin)\n ) {\n var left = yield* this.getInsertion(op.left)\n if (left.content != null &&\n left.id[1] + left.content.length === op.id[1] &&\n left.originOf.length === 1 &&\n !left.gc && !left.deleted &&\n !op.gc && !op.deleted\n ) {\n // combine!\n if (op.originOf != null) {\n left.originOf = op.originOf\n } else {\n delete left.originOf\n }\n left.content = left.content.concat(op.content)\n left.right = op.right\n yield* this.os.delete(op.id)\n yield* this.setOperation(left)\n }\n }\n }\n * getInsertion (id) {\n var ins = yield* this.os.findWithUpperBound(id)\n if (ins == null) {\n return null\n } else {\n var len = ins.content != null ? ins.content.length : 1 // in case of opContent\n if (id[0] === ins.id[0] && id[1] < ins.id[1] + len) {\n return ins\n } else {\n return null\n }\n }\n }\n * getInsertionCleanStartEnd (id) {\n yield* this.getInsertionCleanStart(id)\n return yield* this.getInsertionCleanEnd(id)\n }\n // Return an insertion such that id is the first element of content\n // This function manipulates an operation, if necessary\n * getInsertionCleanStart (id) {\n var ins = yield* this.getInsertion(id)\n if (ins != null) {\n if (ins.id[1] === id[1]) {\n return ins\n } else {\n var left = Y.utils.copyObject(ins)\n ins.content = left.content.splice(id[1] - ins.id[1])\n ins.id = id\n var leftLid = Y.utils.getLastId(left)\n ins.origin = leftLid\n left.originOf = [ins.id]\n left.right = ins.id\n ins.left = leftLid\n // debugger // check\n yield* this.setOperation(left)\n yield* this.setOperation(ins)\n if (left.gc) {\n this.store.queueGarbageCollector(ins.id)\n }\n return ins\n }\n } else {\n return null\n }\n }\n // Return an insertion such that id is the last element of content\n // This function manipulates an operation, if necessary\n * getInsertionCleanEnd (id) {\n var ins = yield* this.getInsertion(id)\n if (ins != null) {\n if (ins.content == null || (ins.id[1] + ins.content.length - 1 === id[1])) {\n return ins\n } else {\n var right = Y.utils.copyObject(ins)\n right.content = ins.content.splice(id[1] - ins.id[1] + 1) // cut off remainder\n right.id = [id[0], id[1] + 1]\n var insLid = Y.utils.getLastId(ins)\n right.origin = insLid\n ins.originOf = [right.id]\n ins.right = right.id\n right.left = insLid\n // debugger // check\n yield* this.setOperation(right)\n yield* this.setOperation(ins)\n if (ins.gc) {\n this.store.queueGarbageCollector(right.id)\n }\n return ins\n }\n } else {\n return null\n }\n }\n * getOperation (id/* :any */)/* :Transaction */ {\n var o = yield* this.os.find(id)\n if (id[0] !== '_' || o != null) {\n return o\n } else { // type is string\n // generate this operation?\n var comp = id[1].split('_')\n if (comp.length > 1) {\n var struct = comp[0]\n var op = Y.Struct[struct].create(id)\n op.type = comp[1]\n yield* this.setOperation(op)\n return op\n } else {\n // won't be called. but just in case..\n console.error('Unexpected case. How can this happen?')\n debugger // eslint-disable-line\n return null\n }\n }\n }\n * removeOperation (id) {\n yield* this.os.delete(id)\n }\n * setState (state) {\n var val = {\n id: [state.user],\n clock: state.clock\n }\n yield* this.ss.put(val)\n }\n * getState (user) {\n var n = yield* this.ss.find([user])\n var clock = n == null ? null : n.clock\n if (clock == null) {\n clock = 0\n }\n return {\n user: user,\n clock: clock\n }\n }\n * getStateVector () {\n var stateVector = []\n yield* this.ss.iterate(this, null, null, function * (n) {\n stateVector.push({\n user: n.id[0],\n clock: n.clock\n })\n })\n return stateVector\n }\n * getStateSet () {\n var ss = {}\n yield* this.ss.iterate(this, null, null, function * (n) {\n ss[n.id[0]] = n.clock\n })\n return ss\n }\n /*\n Here, we make all missing operations executable for the receiving user.\n\n Notes:\n startSS: denotes to the SV that the remote user sent\n currSS: denotes to the state vector that the user should have if he\n applies all already sent operations (increases is each step)\n\n We face several problems:\n * Execute op as is won't work because ops depend on each other\n -> find a way so that they do not anymore\n * When changing left, must not go more to the left than the origin\n * When changing right, you have to consider that other ops may have op\n as their origin, this means that you must not set one of these ops\n as the new right (interdependencies of ops)\n * can't just go to the right until you find the first known operation,\n With currSS\n -> interdependency of ops is a problem\n With startSS\n -> leads to inconsistencies when two users join at the same time.\n Then the position depends on the order of execution -> error!\n\n Solution:\n -> re-create originial situation\n -> set op.left = op.origin (which never changes)\n -> set op.right\n to the first operation that is known (according to startSS)\n or to the first operation that has an origin that is not to the\n right of op.\n -> Enforces unique execution order -> happy user\n\n Improvements: TODO\n * Could set left to origin, or the first known operation\n (startSS or currSS.. ?)\n -> Could be necessary when I turn GC again.\n -> Is a bad(ish) idea because it requires more computation\n\n What we do:\n * Iterate over all missing operations.\n * When there is an operation, where the right op is known, send this op all missing ops to the left to the user\n * I explained above what we have to do with each operation. Here is how we do it efficiently:\n 1. Go to the left until you find either op.origin, or a known operation (let o denote current operation in the iteration)\n 2. Found a known operation -> set op.left = o, and send it to the user. stop\n 3. Found o = op.origin -> set op.left = op.origin, and send it to the user. start again from 1. (set op = o)\n 4. Found some o -> set o.right = op, o.left = o.origin, send it to the user, continue\n */\n * getOperations (startSS) {\n // TODO: use bounds here!\n if (startSS == null) {\n startSS = {}\n }\n var send = []\n\n var endSV = yield* this.getStateVector()\n for (var endState of endSV) {\n var user = endState.user\n if (user === '_') {\n continue\n }\n var startPos = startSS[user] || 0\n if (startPos > 0) {\n // There is a change that [user, startPos] is in a composed Insertion (with a smaller counter)\n // find out if that is the case\n var firstMissing = yield* this.getInsertion([user, startPos])\n if (firstMissing != null) {\n // update startPos\n startPos = firstMissing.id[1]\n startSS[user] = startPos\n }\n }\n yield* this.os.iterate(this, [user, startPos], [user, Number.MAX_VALUE], function * (op) {\n op = Y.Struct[op.struct].encode(op)\n if (op.struct !== 'Insert') {\n send.push(op)\n } else if (op.right == null || op.right[1] < (startSS[op.right[0]] || 0)) {\n // case 1. op.right is known\n var o = op\n // Remember: ?\n // -> set op.right\n // 1. to the first operation that is known (according to startSS)\n // 2. or to the first operation that has an origin that is not to the\n // right of op.\n // For this we maintain a list of ops which origins are not found yet.\n var missing_origins = [op]\n var newright = op.right\n while (true) {\n if (o.left == null) {\n op.left = null\n send.push(op)\n if (!Y.utils.compareIds(o.id, op.id)) {\n o = Y.Struct[op.struct].encode(o)\n o.right = missing_origins[missing_origins.length - 1].id\n send.push(o)\n }\n break\n }\n o = yield* this.getInsertion(o.left)\n // we set another o, check if we can reduce $missing_origins\n while (missing_origins.length > 0 && Y.utils.matchesId(o, missing_origins[missing_origins.length - 1].origin)) {\n missing_origins.pop()\n }\n if (o.id[1] < (startSS[o.id[0]] || 0)) {\n // case 2. o is known\n op.left = Y.utils.getLastId(o)\n send.push(op)\n break\n } else if (Y.utils.matchesId(o, op.origin)) {\n // case 3. o is op.origin\n op.left = op.origin\n send.push(op)\n op = Y.Struct[op.struct].encode(o)\n op.right = newright\n if (missing_origins.length > 0) {\n console.log('This should not happen .. :( please report this')\n }\n missing_origins = [op]\n } else {\n // case 4. send o, continue to find op.origin\n var s = Y.Struct[op.struct].encode(o)\n s.right = missing_origins[missing_origins.length - 1].id\n s.left = s.origin\n send.push(s)\n missing_origins.push(o)\n }\n }\n }\n })\n }\n return send.reverse()\n }\n /*\n * Get the plain untransformed operations from the database.\n * You can apply these operations using .applyOperationsUntransformed(ops)\n *\n */\n * getOperationsUntransformed () {\n var ops = []\n yield* this.os.iterate(this, null, null, function * (op) {\n if (op.id[0] !== '_') {\n ops.push(op)\n }\n })\n return {\n untransformed: ops\n }\n }\n * applyOperationsUntransformed (m, stateSet) {\n var ops = m.untransformed\n for (var i = 0; i < ops.length; i++) {\n var op = ops[i]\n // create, and modify parent, if it is created implicitly\n if (op.parent != null && op.parent[0] === '_') {\n if (op.struct === 'Insert') {\n // update parents .map/start/end properties\n if (op.parentSub != null && op.left == null) {\n // op is child of Map\n let parent = yield* this.getOperation(op.parent)\n parent.map[op.parentSub] = op.id\n yield* this.setOperation(parent)\n } else if (op.right == null || op.left == null) {\n let parent = yield* this.getOperation(op.parent)\n if (op.right == null) {\n parent.end = Y.utils.getLastId(op)\n }\n if (op.left == null) {\n parent.start = op.id\n }\n yield* this.setOperation(parent)\n }\n }\n }\n yield* this.os.put(op)\n }\n for (var user in stateSet) {\n yield* this.ss.put({\n id: [user],\n clock: stateSet[user]\n })\n }\n }\n /* this is what we used before.. use this as a reference..\n * makeOperationReady (startSS, op) {\n op = Y.Struct[op.struct].encode(op)\n op = Y.utils.copyObject(op) -- use copyoperation instead now!\n var o = op\n var ids = [op.id]\n // search for the new op.right\n // it is either the first known op (according to startSS)\n // or the o that has no origin to the right of op\n // (this is why we use the ids array)\n while (o.right != null) {\n var right = yield* this.getOperation(o.right)\n if (o.right[1] < (startSS[o.right[0]] || 0) || !ids.some(function (id) {\n return Y.utils.compareIds(id, right.origin)\n })) {\n break\n }\n ids.push(o.right)\n o = right\n }\n op.right = o.right\n op.left = op.origin\n return op\n }\n */\n * flush () {\n yield* this.os.flush()\n yield* this.ss.flush()\n yield* this.ds.flush()\n }\n }\n Y.Transaction = TransactionInterface\n}\n","/* @flow */\n'use strict'\n\n/*\n EventHandler is an helper class for constructing custom types.\n\n Why: When constructing custom types, you sometimes want your types to work\n synchronous: E.g.\n ``` Synchronous\n mytype.setSomething(\"yay\")\n mytype.getSomething() === \"yay\"\n ```\n versus\n ``` Asynchronous\n mytype.setSomething(\"yay\")\n mytype.getSomething() === undefined\n mytype.waitForSomething().then(function(){\n mytype.getSomething() === \"yay\"\n })\n ```\n\n The structures usually work asynchronously (you have to wait for the\n database request to finish). EventHandler helps you to make your type\n synchronous.\n*/\nmodule.exports = function (Y /* : any*/) {\n Y.utils = {}\n\n Y.utils.bubbleEvent = function (type, event) {\n type.eventHandler.callEventListeners(event)\n event.path = []\n while (type != null && type._deepEventHandler != null) {\n type._deepEventHandler.callEventListeners(event)\n var parent = null\n if (type._parent != null) {\n parent = type.os.getType(type._parent)\n }\n if (parent != null && parent._getPathToChild != null) {\n event.path = [parent._getPathToChild(type._model)].concat(event.path)\n type = parent\n } else {\n type = null\n }\n }\n }\n\n class EventListenerHandler {\n constructor () {\n this.eventListeners = []\n }\n destroy () {\n this.eventListeners = null\n }\n /*\n Basic event listener boilerplate...\n */\n addEventListener (f) {\n this.eventListeners.push(f)\n }\n removeEventListener (f) {\n this.eventListeners = this.eventListeners.filter(function (g) {\n return f !== g\n })\n }\n removeAllEventListeners () {\n this.eventListeners = []\n }\n callEventListeners (event) {\n for (var i = 0; i < this.eventListeners.length; i++) {\n try {\n var _event = {}\n for (var name in event) {\n _event[name] = event[name]\n }\n this.eventListeners[i](_event)\n } catch (e) {\n console.error('Your observer threw an error. This error was caught so that Yjs still can ensure data consistency! In order to debug this error you have to check \"Pause On Caught Exceptions\"', e)\n }\n }\n }\n }\n Y.utils.EventListenerHandler = EventListenerHandler\n\n class EventHandler extends EventListenerHandler {\n /* ::\n waiting: Array;\n awaiting: number;\n onevent: Function;\n eventListeners: Array;\n */\n /*\n onevent: is called when the structure changes.\n\n Note: \"awaiting opertations\" is used to denote operations that were\n prematurely called. Events for received operations can not be executed until\n all prematurely called operations were executed (\"waiting operations\")\n */\n constructor (onevent /* : Function */) {\n super()\n this.waiting = []\n this.awaiting = 0\n this.onevent = onevent\n }\n destroy () {\n super.destroy()\n this.waiting = null\n this.onevent = null\n }\n /*\n Call this when a new operation arrives. It will be executed right away if\n there are no waiting operations, that you prematurely executed\n */\n receivedOp (op) {\n if (this.awaiting <= 0) {\n this.onevent(op)\n } else if (op.struct === 'Delete') {\n var self = this\n var checkDelete = function checkDelete (d) {\n if (d.length == null) {\n throw new Error('This shouldn\\'t happen! d.length must be defined!')\n }\n // we check if o deletes something in self.waiting\n // if so, we remove the deleted operation\n for (var w = 0; w < self.waiting.length; w++) {\n var i = self.waiting[w]\n if (i.struct === 'Insert' && i.id[0] === d.target[0]) {\n var iLength = i.hasOwnProperty('content') ? i.content.length : 1\n var dStart = d.target[1]\n var dEnd = d.target[1] + (d.length || 1)\n var iStart = i.id[1]\n var iEnd = i.id[1] + iLength\n // Check if they don't overlap\n if (iEnd <= dStart || dEnd <= iStart) {\n // no overlapping\n continue\n }\n // we check all overlapping cases. All cases:\n /*\n 1) iiiii\n ddddd\n --> modify i and d\n 2) iiiiiii\n ddddd\n --> modify i, remove d\n 3) iiiiiii\n ddd\n --> remove d, modify i, and create another i (for the right hand side)\n 4) iiiii\n ddddddd\n --> remove i, modify d\n 5) iiiiiii\n ddddddd\n --> remove both i and d (**)\n 6) iiiiiii\n ddddd\n --> modify i, remove d\n 7) iii\n ddddddd\n --> remove i, create and apply two d with checkDelete(d) (**)\n 8) iiiii\n ddddddd\n --> remove i, modify d (**)\n 9) iiiii\n ddddd\n --> modify i and d\n (**) (also check if i contains content or type)\n */\n // TODO: I left some debugger statements, because I want to debug all cases once in production. REMEMBER END TODO\n if (iStart < dStart) {\n if (dStart < iEnd) {\n if (iEnd < dEnd) {\n // Case 1\n // remove the right part of i's content\n i.content.splice(dStart - iStart)\n // remove the start of d's deletion\n d.length = dEnd - iEnd\n d.target = [d.target[0], iEnd]\n continue\n } else if (iEnd === dEnd) {\n // Case 2\n i.content.splice(dStart - iStart)\n // remove d, we do that by simply ending this function\n return\n } else { // (dEnd < iEnd)\n // Case 3\n var newI = {\n id: [i.id[0], dEnd],\n content: i.content.slice(dEnd - iStart),\n struct: 'Insert'\n }\n self.waiting.push(newI)\n i.content.splice(dStart - iStart)\n return\n }\n }\n } else if (dStart === iStart) {\n if (iEnd < dEnd) {\n // Case 4\n d.length = dEnd - iEnd\n d.target = [d.target[0], iEnd]\n i.content = []\n continue\n } else if (iEnd === dEnd) {\n // Case 5\n self.waiting.splice(w, 1)\n return\n } else { // (dEnd < iEnd)\n // Case 6\n i.content = i.content.slice(dEnd - iStart)\n i.id = [i.id[0], dEnd]\n return\n }\n } else { // (dStart < iStart)\n if (iStart < dEnd) {\n // they overlap\n /*\n 7) iii\n ddddddd\n --> remove i, create and apply two d with checkDelete(d) (**)\n 8) iiiii\n ddddddd\n --> remove i, modify d (**)\n 9) iiiii\n ddddd\n --> modify i and d\n */\n if (iEnd < dEnd) {\n // Case 7\n // debugger // TODO: You did not test this case yet!!!! (add the debugger here)\n self.waiting.splice(w, 1)\n checkDelete({\n target: [d.target[0], dStart],\n length: iStart - dStart,\n struct: 'Delete'\n })\n checkDelete({\n target: [d.target[0], iEnd],\n length: iEnd - dEnd,\n struct: 'Delete'\n })\n return\n } else if (iEnd === dEnd) {\n // Case 8\n self.waiting.splice(w, 1)\n w--\n d.length -= iLength\n continue\n } else { // dEnd < iEnd\n // Case 9\n d.length = iStart - dStart\n i.content.splice(0, dEnd - iStart)\n i.id = [i.id[0], dEnd]\n continue\n }\n }\n }\n }\n }\n // finished with remaining operations\n self.waiting.push(d)\n }\n if (op.key == null) {\n // deletes in list\n checkDelete(op)\n } else {\n // deletes in map\n this.waiting.push(op)\n }\n } else {\n this.waiting.push(op)\n }\n }\n /*\n You created some operations, and you want the `onevent` function to be\n called right away. Received operations will not be executed untill all\n prematurely called operations are executed\n */\n awaitAndPrematurelyCall (ops) {\n this.awaiting++\n ops.map(Y.utils.copyOperation).forEach(this.onevent)\n }\n * awaitOps (transaction, f, args) {\n function notSoSmartSort (array) {\n // this function sorts insertions in a executable order\n var result = []\n while (array.length > 0) {\n for (var i = 0; i < array.length; i++) {\n var independent = true\n for (var j = 0; j < array.length; j++) {\n if (Y.utils.matchesId(array[j], array[i].left)) {\n // array[i] depends on array[j]\n independent = false\n break\n }\n }\n if (independent) {\n result.push(array.splice(i, 1)[0])\n i--\n }\n }\n }\n return result\n }\n var before = this.waiting.length\n // somehow create new operations\n yield* f.apply(transaction, args)\n // remove all appended ops / awaited ops\n this.waiting.splice(before)\n if (this.awaiting > 0) this.awaiting--\n // if there are no awaited ops anymore, we can update all waiting ops, and send execute them (if there are still no awaited ops)\n if (this.awaiting === 0 && this.waiting.length > 0) {\n // update all waiting ops\n for (let i = 0; i < this.waiting.length; i++) {\n var o = this.waiting[i]\n if (o.struct === 'Insert') {\n var _o = yield* transaction.getInsertion(o.id)\n if (_o.parentSub != null && _o.left != null) {\n // if o is an insertion of a map struc (parentSub is defined), then it shouldn't be necessary to compute left\n this.waiting.splice(i, 1)\n i-- // update index\n } else if (!Y.utils.compareIds(_o.id, o.id)) {\n // o got extended\n o.left = [o.id[0], o.id[1] - 1]\n } else if (_o.left == null) {\n o.left = null\n } else {\n // find next undeleted op\n var left = yield* transaction.getInsertion(_o.left)\n while (left.deleted != null) {\n if (left.left != null) {\n left = yield* transaction.getInsertion(left.left)\n } else {\n left = null\n break\n }\n }\n o.left = left != null ? Y.utils.getLastId(left) : null\n }\n }\n }\n // the previous stuff was async, so we have to check again!\n // We also pull changes from the bindings, if there exists such a method, this could increase awaiting too\n if (this._pullChanges != null) {\n this._pullChanges()\n }\n if (this.awaiting === 0) {\n // sort by type, execute inserts first\n var ins = []\n var dels = []\n this.waiting.forEach(function (o) {\n if (o.struct === 'Delete') {\n dels.push(o)\n } else {\n ins.push(o)\n }\n })\n this.waiting = []\n // put in executable order\n ins = notSoSmartSort(ins)\n // this.onevent can trigger the creation of another operation\n // -> check if this.awaiting increased & stop computation if it does\n for (var i = 0; i < ins.length; i++) {\n if (this.awaiting === 0) {\n this.onevent(ins[i])\n } else {\n this.waiting = this.waiting.concat(ins.slice(i))\n break\n }\n }\n for (i = 0; i < dels.length; i++) {\n if (this.awaiting === 0) {\n this.onevent(dels[i])\n } else {\n this.waiting = this.waiting.concat(dels.slice(i))\n break\n }\n }\n }\n }\n }\n // TODO: Remove awaitedInserts and awaitedDeletes in favor of awaitedOps, as they are deprecated and do not always work\n // Do this in one of the coming releases that are breaking anyway\n /*\n Call this when you successfully awaited the execution of n Insert operations\n */\n awaitedInserts (n) {\n var ops = this.waiting.splice(this.waiting.length - n)\n for (var oid = 0; oid < ops.length; oid++) {\n var op = ops[oid]\n if (op.struct === 'Insert') {\n for (var i = this.waiting.length - 1; i >= 0; i--) {\n let w = this.waiting[i]\n // TODO: do I handle split operations correctly here? Super unlikely, but yeah..\n // Also: can this case happen? Can op be inserted in the middle of a larger op that is in $waiting?\n if (w.struct === 'Insert') {\n if (Y.utils.matchesId(w, op.left)) {\n // include the effect of op in w\n w.right = op.id\n // exclude the effect of w in op\n op.left = w.left\n } else if (Y.utils.compareIds(w.id, op.right)) {\n // similar..\n w.left = Y.utils.getLastId(op)\n op.right = w.right\n }\n }\n }\n } else {\n throw new Error('Expected Insert Operation!')\n }\n }\n this._tryCallEvents(n)\n }\n /*\n Call this when you successfully awaited the execution of n Delete operations\n */\n awaitedDeletes (n, newLeft) {\n var ops = this.waiting.splice(this.waiting.length - n)\n for (var j = 0; j < ops.length; j++) {\n var del = ops[j]\n if (del.struct === 'Delete') {\n if (newLeft != null) {\n for (var i = 0; i < this.waiting.length; i++) {\n let w = this.waiting[i]\n // We will just care about w.left\n if (w.struct === 'Insert' && Y.utils.compareIds(del.target, w.left)) {\n w.left = newLeft\n }\n }\n }\n } else {\n throw new Error('Expected Delete Operation!')\n }\n }\n this._tryCallEvents(n)\n }\n /* (private)\n Try to execute the events for the waiting operations\n */\n _tryCallEvents () {\n function notSoSmartSort (array) {\n var result = []\n while (array.length > 0) {\n for (var i = 0; i < array.length; i++) {\n var independent = true\n for (var j = 0; j < array.length; j++) {\n if (Y.utils.matchesId(array[j], array[i].left)) {\n // array[i] depends on array[j]\n independent = false\n break\n }\n }\n if (independent) {\n result.push(array.splice(i, 1)[0])\n i--\n }\n }\n }\n return result\n }\n if (this.awaiting > 0) this.awaiting--\n if (this.awaiting === 0 && this.waiting.length > 0) {\n var ins = []\n var dels = []\n this.waiting.forEach(function (o) {\n if (o.struct === 'Delete') {\n dels.push(o)\n } else {\n ins.push(o)\n }\n })\n ins = notSoSmartSort(ins)\n ins.forEach(this.onevent)\n dels.forEach(this.onevent)\n this.waiting = []\n }\n }\n }\n Y.utils.EventHandler = EventHandler\n\n /*\n Default class of custom types!\n */\n class CustomType {\n getPath () {\n var parent = null\n if (this._parent != null) {\n parent = this.os.getType(this._parent)\n }\n if (parent != null && parent._getPathToChild != null) {\n var firstKey = parent._getPathToChild(this._model)\n var parentKeys = parent.getPath()\n parentKeys.push(firstKey)\n return parentKeys\n } else {\n return []\n }\n }\n }\n Y.utils.CustomType = CustomType\n\n /*\n A wrapper for the definition of a custom type.\n Every custom type must have three properties:\n\n * struct\n - Structname of this type\n * initType\n - Given a model, creates a custom type\n * class\n - the constructor of the custom type (e.g. in order to inherit from a type)\n */\n class CustomTypeDefinition { // eslint-disable-line\n /* ::\n struct: any;\n initType: any;\n class: Function;\n name: String;\n */\n constructor (def) {\n if (def.struct == null ||\n def.initType == null ||\n def.class == null ||\n def.name == null ||\n def.createType == null\n ) {\n throw new Error('Custom type was not initialized correctly!')\n }\n this.struct = def.struct\n this.initType = def.initType\n this.createType = def.createType\n this.class = def.class\n this.name = def.name\n if (def.appendAdditionalInfo != null) {\n this.appendAdditionalInfo = def.appendAdditionalInfo\n }\n this.parseArguments = (def.parseArguments || function () {\n return [this]\n }).bind(this)\n this.parseArguments.typeDefinition = this\n }\n }\n Y.utils.CustomTypeDefinition = CustomTypeDefinition\n\n Y.utils.isTypeDefinition = function isTypeDefinition (v) {\n if (v != null) {\n if (v instanceof Y.utils.CustomTypeDefinition) return [v]\n else if (v.constructor === Array && v[0] instanceof Y.utils.CustomTypeDefinition) return v\n else if (v instanceof Function && v.typeDefinition instanceof Y.utils.CustomTypeDefinition) return [v.typeDefinition]\n }\n return false\n }\n\n /*\n Make a flat copy of an object\n (just copy properties)\n */\n function copyObject (o) {\n var c = {}\n for (var key in o) {\n c[key] = o[key]\n }\n return c\n }\n Y.utils.copyObject = copyObject\n\n /*\n Copy an operation, so that it can be manipulated.\n Note: You must not change subproperties (except o.content)!\n */\n function copyOperation (o) {\n o = copyObject(o)\n if (o.content != null) {\n o.content = o.content.map(function (c) { return c })\n }\n return o\n }\n\n Y.utils.copyOperation = copyOperation\n\n /*\n Defines a smaller relation on Id's\n */\n function smaller (a, b) {\n return a[0] < b[0] || (a[0] === b[0] && (a[1] < b[1] || typeof a[1] < typeof b[1]))\n }\n Y.utils.smaller = smaller\n\n function inDeletionRange (del, ins) {\n return del.target[0] === ins[0] && del.target[1] <= ins[1] && ins[1] < del.target[1] + (del.length || 1)\n }\n Y.utils.inDeletionRange = inDeletionRange\n\n function compareIds (id1, id2) {\n if (id1 == null || id2 == null) {\n return id1 === id2\n } else {\n return id1[0] === id2[0] && id1[1] === id2[1]\n }\n }\n Y.utils.compareIds = compareIds\n\n function matchesId (op, id) {\n if (id == null || op == null) {\n return id === op\n } else {\n if (id[0] === op.id[0]) {\n if (op.content == null) {\n return id[1] === op.id[1]\n } else {\n return id[1] >= op.id[1] && id[1] < op.id[1] + op.content.length\n }\n }\n }\n }\n Y.utils.matchesId = matchesId\n\n function getLastId (op) {\n if (op.content == null || op.content.length === 1) {\n return op.id\n } else {\n return [op.id[0], op.id[1] + op.content.length - 1]\n }\n }\n Y.utils.getLastId = getLastId\n\n function createEmptyOpsArray (n) {\n var a = new Array(n)\n for (var i = 0; i < a.length; i++) {\n a[i] = {\n id: [null, null]\n }\n }\n return a\n }\n\n function createSmallLookupBuffer (Store) {\n /*\n This buffer implements a very small buffer that temporarily stores operations\n after they are read / before they are written.\n The buffer basically implements FIFO. Often requested lookups will be re-queued every time they are looked up / written.\n\n It can speed up lookups on Operation Stores and State Stores. But it does not require notable use of memory or processing power.\n\n Good for os and ss, bot not for ds (because it often uses methods that require a flush)\n\n I tried to optimize this for performance, therefore no highlevel operations.\n */\n class SmallLookupBuffer extends Store {\n constructor (arg1, arg2) {\n // super(...arguments) -- do this when this is supported by stable nodejs\n super(arg1, arg2)\n this.writeBuffer = createEmptyOpsArray(5)\n this.readBuffer = createEmptyOpsArray(10)\n }\n * find (id, noSuperCall) {\n var i, r\n for (i = this.readBuffer.length - 1; i >= 0; i--) {\n r = this.readBuffer[i]\n // we don't have to use compareids, because id is always defined!\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n // found r\n // move r to the end of readBuffer\n for (; i < this.readBuffer.length - 1; i++) {\n this.readBuffer[i] = this.readBuffer[i + 1]\n }\n this.readBuffer[this.readBuffer.length - 1] = r\n return r\n }\n }\n var o\n for (i = this.writeBuffer.length - 1; i >= 0; i--) {\n r = this.writeBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n o = r\n break\n }\n }\n if (i < 0 && noSuperCall === undefined) {\n // did not reach break in last loop\n // read id and put it to the end of readBuffer\n o = yield* super.find(id)\n }\n if (o != null) {\n for (i = 0; i < this.readBuffer.length - 1; i++) {\n this.readBuffer[i] = this.readBuffer[i + 1]\n }\n this.readBuffer[this.readBuffer.length - 1] = o\n }\n return o\n }\n * put (o) {\n var id = o.id\n var i, r // helper variables\n for (i = this.writeBuffer.length - 1; i >= 0; i--) {\n r = this.writeBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n // is already in buffer\n // forget r, and move o to the end of writeBuffer\n for (; i < this.writeBuffer.length - 1; i++) {\n this.writeBuffer[i] = this.writeBuffer[i + 1]\n }\n this.writeBuffer[this.writeBuffer.length - 1] = o\n break\n }\n }\n if (i < 0) {\n // did not reach break in last loop\n // write writeBuffer[0]\n var write = this.writeBuffer[0]\n if (write.id[0] !== null) {\n yield* super.put(write)\n }\n // put o to the end of writeBuffer\n for (i = 0; i < this.writeBuffer.length - 1; i++) {\n this.writeBuffer[i] = this.writeBuffer[i + 1]\n }\n this.writeBuffer[this.writeBuffer.length - 1] = o\n }\n // check readBuffer for every occurence of o.id, overwrite if found\n // whether found or not, we'll append o to the readbuffer\n for (i = 0; i < this.readBuffer.length - 1; i++) {\n r = this.readBuffer[i + 1]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n this.readBuffer[i] = o\n } else {\n this.readBuffer[i] = r\n }\n }\n this.readBuffer[this.readBuffer.length - 1] = o\n }\n * delete (id) {\n var i, r\n for (i = 0; i < this.readBuffer.length; i++) {\n r = this.readBuffer[i]\n if (r.id[1] === id[1] && r.id[0] === id[0]) {\n this.readBuffer[i] = {\n id: [null, null]\n }\n }\n }\n yield* this.flush()\n yield* super.delete(id)\n }\n * findWithLowerBound (id) {\n var o = yield* this.find(id, true)\n if (o != null) {\n return o\n } else {\n yield* this.flush()\n return yield* super.findWithLowerBound.apply(this, arguments)\n }\n }\n * findWithUpperBound (id) {\n var o = yield* this.find(id, true)\n if (o != null) {\n return o\n } else {\n yield* this.flush()\n return yield* super.findWithUpperBound.apply(this, arguments)\n }\n }\n * findNext () {\n yield* this.flush()\n return yield* super.findNext.apply(this, arguments)\n }\n * findPrev () {\n yield* this.flush()\n return yield* super.findPrev.apply(this, arguments)\n }\n * iterate () {\n yield* this.flush()\n yield* super.iterate.apply(this, arguments)\n }\n * flush () {\n for (var i = 0; i < this.writeBuffer.length; i++) {\n var write = this.writeBuffer[i]\n if (write.id[0] !== null) {\n yield* super.put(write)\n this.writeBuffer[i] = {\n id: [null, null]\n }\n }\n }\n }\n }\n return SmallLookupBuffer\n }\n Y.utils.createSmallLookupBuffer = createSmallLookupBuffer\n\n // Generates a unique id, for use as a user id.\n // Thx to @jed for this script https://gist.github.com/jed/982883\n function generateGuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,generateGuid)} // eslint-disable-line\n Y.utils.generateGuid = generateGuid\n}\n","/* @flow */\n'use strict'\n\nrequire('./Connector.js')(Y)\nrequire('./Database.js')(Y)\nrequire('./Transaction.js')(Y)\nrequire('./Struct.js')(Y)\nrequire('./Utils.js')(Y)\nrequire('./Connectors/Test.js')(Y)\n\nY.debug = require('debug')\n\nvar requiringModules = {}\n\nmodule.exports = Y\nY.requiringModules = requiringModules\n\nY.extend = function (name, value) {\n if (arguments.length === 2 && typeof name === 'string') {\n if (value instanceof Y.utils.CustomTypeDefinition) {\n Y[name] = value.parseArguments\n } else {\n Y[name] = value\n }\n if (requiringModules[name] != null) {\n requiringModules[name].resolve()\n delete requiringModules[name]\n }\n } else {\n for (var i = 0; i < arguments.length; i++) {\n var f = arguments[i]\n if (typeof f === 'function') {\n f(Y)\n } else {\n throw new Error('Expected function!')\n }\n }\n }\n}\n\nY.requestModules = requestModules\nfunction requestModules (modules) {\n var sourceDir\n if (Y.sourceDir === null) {\n sourceDir = null\n } else {\n sourceDir = Y.sourceDir || '/bower_components'\n }\n // determine if this module was compiled for es5 or es6 (y.js vs. y.es6)\n // if Insert.execute is a Function, then it isnt a generator..\n // then load the es5(.js) files..\n var extention = typeof regeneratorRuntime !== 'undefined' ? '.js' : '.es6'\n var promises = []\n for (var i = 0; i < modules.length; i++) {\n var module = modules[i].split('(')[0]\n var modulename = 'y-' + module.toLowerCase()\n if (Y[module] == null) {\n if (requiringModules[module] == null) {\n // module does not exist\n if (typeof window !== 'undefined' && window.Y !== 'undefined') {\n if (sourceDir != null) {\n var imported = document.createElement('script')\n imported.src = sourceDir + '/' + modulename + '/' + modulename + extention\n document.head.appendChild(imported)\n }\n let requireModule = {}\n requiringModules[module] = requireModule\n requireModule.promise = new Promise(function (resolve) {\n requireModule.resolve = resolve\n })\n promises.push(requireModule.promise)\n } else {\n console.info('YJS: Please do not depend on automatic requiring of modules anymore! Extend modules as follows `require(\\'y-modulename\\')(Y)`')\n require(modulename)(Y)\n }\n } else {\n promises.push(requiringModules[modules[i]].promise)\n }\n }\n }\n return Promise.all(promises)\n}\n\n/* ::\ntype MemoryOptions = {\n name: 'memory'\n}\ntype IndexedDBOptions = {\n name: 'indexeddb',\n namespace: string\n}\ntype DbOptions = MemoryOptions | IndexedDBOptions\n\ntype WebRTCOptions = {\n name: 'webrtc',\n room: string\n}\ntype WebsocketsClientOptions = {\n name: 'websockets-client',\n room: string\n}\ntype ConnectionOptions = WebRTCOptions | WebsocketsClientOptions\n\ntype YOptions = {\n connector: ConnectionOptions,\n db: DbOptions,\n types: Array,\n sourceDir: string,\n share: {[key: string]: TypeName}\n}\n*/\n\nfunction Y (opts/* :YOptions */) /* :Promise */ {\n if (opts.hasOwnProperty('sourceDir')) {\n Y.sourceDir = opts.sourceDir\n }\n opts.types = opts.types != null ? opts.types : []\n var modules = [opts.db.name, opts.connector.name].concat(opts.types)\n for (var name in opts.share) {\n modules.push(opts.share[name])\n }\n return new Promise(function (resolve, reject) {\n if (opts == null) reject('An options object is expected! ')\n else if (opts.connector == null) reject('You must specify a connector! (missing connector property)')\n else if (opts.connector.name == null) reject('You must specify connector name! (missing connector.name property)')\n else if (opts.db == null) reject('You must specify a database! (missing db property)')\n else if (opts.connector.name == null) reject('You must specify db name! (missing db.name property)')\n else {\n opts = Y.utils.copyObject(opts)\n opts.connector = Y.utils.copyObject(opts.connector)\n opts.db = Y.utils.copyObject(opts.db)\n opts.share = Y.utils.copyObject(opts.share)\n setTimeout(function () {\n Y.requestModules(modules).then(function () {\n var yconfig = new YConfig(opts)\n yconfig.db.whenUserIdSet(function () {\n yconfig.init(function () {\n resolve(yconfig)\n })\n })\n }).catch(reject)\n }, 0)\n }\n })\n}\n\nclass YConfig {\n /* ::\n db: Y.AbstractDatabase;\n connector: Y.AbstractConnector;\n share: {[key: string]: any};\n options: Object;\n */\n constructor (opts, callback) {\n this.options = opts\n this.db = new Y[opts.db.name](this, opts.db)\n this.connector = new Y[opts.connector.name](this, opts.connector)\n this.connected = true\n }\n init (callback) {\n var opts = this.options\n var share = {}\n this.share = share\n this.db.requestTransaction(function * requestTransaction () {\n // create shared object\n for (var propertyname in opts.share) {\n var typeConstructor = opts.share[propertyname].split('(')\n var typeName = typeConstructor.splice(0, 1)\n var type = Y[typeName]\n var typedef = type.typeDefinition\n var id = ['_', typedef.struct + '_' + typeName + '_' + propertyname + '_' + typeConstructor]\n var args = []\n if (typeConstructor.length === 1) {\n try {\n args = JSON.parse('[' + typeConstructor[0].split(')')[0] + ']')\n } catch (e) {\n throw new Error('Was not able to parse type definition! (share.' + propertyname + ')')\n }\n if (type.typeDefinition.parseArguments == null) {\n throw new Error(typeName + ' does not expect arguments!')\n } else {\n args = typedef.parseArguments(args[0])[1]\n }\n }\n share[propertyname] = yield* this.store.initType.call(this, id, args)\n }\n this.store.whenTransactionsFinished()\n .then(callback)\n })\n }\n isConnected () {\n return this.connector.isSynced\n }\n disconnect () {\n if (this.connected) {\n this.connected = false\n return this.connector.disconnect()\n } else {\n return Promise.resolve()\n }\n }\n reconnect () {\n if (!this.connected) {\n this.connected = true\n return this.connector.reconnect()\n } else {\n return Promise.resolve()\n }\n }\n destroy () {\n var self = this\n return this.close().then(function () {\n if (self.db.deleteDB != null) {\n return self.db.deleteDB()\n } else {\n return Promise.resolve()\n }\n })\n }\n close () {\n var self = this\n this.share = null\n if (this.connector.destroy != null) {\n this.connector.destroy()\n } else {\n this.connector.disconnect()\n }\n return this.db.whenTransactionsFinished(function () {\n this.db.destroyTypes()\n // make sure to wait for all transactions before destroying the db\n this.db.requestTransaction(function * () {\n yield* self.db.destroy()\n })\n return this.db.whenTransactionsFinished()\n })\n }\n}\n"]} \ No newline at end of file