forked from Operational-Transformation/ot.js
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
69 lines (57 loc) · 1.99 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
if (typeof ot === 'undefined') {
var ot = {};
}
ot.Server = (function (global) {
'use strict';
// Constructor. Takes the current document as a string and optionally the array
// of all operations.
function Server (document, operations) {
this.document = document;
this.operations = operations || [];
this.setDocumentMaxLength(null);
}
/**
* @param {number | (() => number) | null} maxLength
*/
Server.prototype.setDocumentMaxLength = function (maxLength) {
this.documentMaxLength = maxLength;
};
// Call this method whenever you receive an operation from a client.
Server.prototype.receiveOperation = function (revision, operation) {
if (revision < 0 || this.operations.length < revision) {
throw new Error("operation revision not in history");
}
// Find all operations that the client didn't know of when it sent the
// operation ...
var concurrentOperations = this.operations.slice(revision);
// ... and transform the operation against all these operations ...
var transform = operation.constructor.transform;
for (var i = 0; i < concurrentOperations.length; i++) {
operation = transform(operation, concurrentOperations[i])[0];
}
// ... and apply that on the document.
var newDocument = operation.apply(this.document);
const maxLen =
typeof this.documentMaxLength === "function"
? this.documentMaxLength()
: this.documentMaxLength;
// ignore if exceed the max length of document
if (
typeof maxLen === "number" &&
newDocument.length > maxLen &&
newDocument.length > this.document.length
) {
return;
}
this.document = newDocument;
// Store operation in history.
this.operations.push(operation);
// It's the caller's responsibility to send the operation to all connected
// clients and an acknowledgement to the creator.
return operation;
};
return Server;
}(this));
if (typeof module === 'object') {
module.exports = ot.Server;
}