• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

share / sharedb / 46481224691

30 Nov 2026 06:09PM UTC coverage: 98.082%. Remained the same
46481224691

Pull #790

github

web-flow
Merge a2b711b23 into 26879054c
Pull Request #790: ✨ Ship our own type declarations

1284 of 1429 branches covered (89.85%)

112 of 112 new or added lines in 19 files covered. (100.0%)

9 existing lines in 1 file now uncovered.

3785 of 3859 relevant lines covered (98.08%)

1174.7 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.25
/src/backend.ts
1
import async = require('async');
3 ✔
2
import Agent = require('./agent');
3 ✔
3
import Connection = require('./client/connection');
3 ✔
4
import emitter = require('./emitter');
3 ✔
5
import MemoryDB = require('./db/memory');
3 ✔
6
import NoOpMilestoneDB = require('./milestone-db/no-op');
3 ✔
7
import MemoryPubSub = require('./pubsub/memory');
3 ✔
8
import ot = require('./ot');
3 ✔
9
import projections = require('./projections');
3 ✔
10
import QueryEmitter = require('./query-emitter');
3 ✔
11
import ShareDBError = require('./error');
3 ✔
12
import Snapshot = require('./snapshot');
3 ✔
13
import StreamSocket = require('./stream-socket');
3 ✔
14
import SubmitRequest = require('./submit-request');
3 ✔
15
import ReadSnapshotsRequest = require('./read-snapshots-request');
3 ✔
16
import util = require('./util');
3 ✔
17
import logger = require('./logger');
3 ✔
18
import type {Duplex} from 'stream';
19
import type * as ShareDB from './sharedb';
20

21
type Rejection = string | {code?: string | number; message: string};
22

23
var ERROR_CODE = ShareDBError.CODES;
3 ✔
24

25
class Backend {
3 ✔
26
  db!: Backend.DB;
27
  pubsub!: Backend.PubSub;
28

29
  /** This contains any extra databases that can be queried */
30
  extraDbs!: {[extraDbName: string]: Backend.ExtraDB};
31

32
  milestoneDb!: Backend.MilestoneDB;
33

34
  /** Map from projected collection -> {type, fields} */
35
  readonly projections!: {readonly [name: string]: ShareDB.ReadonlyProjection};
36

37
  suppressPublish;
38
  maxSubmitRetries;
39
  presenceEnabled;
40
  doNotForwardSendPresenceErrorsToClient;
41
  doNotCommitNoOps;
42

43
  /** Map from event name to a list of middleware */
44
  middleware;
45

46
  /** The number of open agents for monitoring and testing memory leaks */
47
  agentsCount;
48

49
  remoteAgentsCount;
50
  errorHandler!: Backend.ErrorHandler;
51

52
  declare static Agent: typeof Agent;
53
  declare static Backend: typeof Backend;
54
  declare static DB: typeof import('./db');
55
  declare static Error: typeof ShareDBError;
56
  declare static logger: ShareDB.Logger;
57
  declare static MemoryDB: typeof MemoryDB;
58
  declare static MemoryMilestoneDB: typeof import('./milestone-db/memory');
59
  declare static MemoryPubSub: typeof MemoryPubSub;
60
  declare static MESSAGE_ACTIONS: ShareDB.RequestActions;
61
  declare static MilestoneDB: typeof import('./milestone-db');
62
  declare static ot: typeof ot;
63
  declare static projections: typeof projections;
64
  declare static PubSub: typeof import('./pubsub');
65
  declare static QueryEmitter: typeof QueryEmitter;
66
  declare static SubmitRequest: typeof SubmitRequest;
67
  declare static types: ShareDB.Types;
68

69
  constructor(options?: Backend.ShareDBOptions) {
70
    if (!(this instanceof Backend)) return new Backend(options);
2,835 !
71
    emitter.EventEmitter.call(this);
2,835 ✔
72

73
    if (!options) options = {};
2,835 ✔
74
    this.db = options.db || new MemoryDB();
2,835 ✔
75
    this.pubsub = options.pubsub || new MemoryPubSub();
2,835 ✔
76
    this.extraDbs = options.extraDbs || {};
2,835 ✔
77
    this.milestoneDb = options.milestoneDb || new NoOpMilestoneDB();
2,835 ✔
78

79
    this.projections = Object.create(null);
2,835 ✔
80

81
    this.suppressPublish = !!options.suppressPublish;
2,835 ✔
82
    this.maxSubmitRetries = options.maxSubmitRetries || null;
2,835 ✔
83
    this.presenceEnabled = !!options.presence;
2,835 ✔
84
    this.doNotForwardSendPresenceErrorsToClient = !!options.doNotForwardSendPresenceErrorsToClient;
2,835 ✔
85
    if (this.presenceEnabled && !this.doNotForwardSendPresenceErrorsToClient) {
2,835 ✔
86
      logger.warn(
444 ✔
87
        'Broadcasting "sendPresence" middleware errors to clients is deprecated ' +
88
        'and will be removed in a future release. Disable this behaviour with:\n\n' +
89
        'new Backend({doNotForwardSendPresenceErrorsToClient: true})\n\n'
90
      );
91
    }
92
    this.doNotCommitNoOps = !!options.doNotCommitNoOps;
2,835 ✔
93

94
    this.middleware = Object.create(null);
2,835 ✔
95

96
    this.agentsCount = 0;
2,835 ✔
97
    this.remoteAgentsCount = 0;
2,835 ✔
98

99
    this.errorHandler = typeof options.errorHandler === 'function' ?
2,835 ✔
100
      options.errorHandler :
101
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
102
      function(error, context) {
103
        logger.error(error);
3 ✔
104
      };
105
  }
106

107
  declare MIDDLEWARE_ACTIONS: {[A in keyof Backend.middleware.ActionContextMap]: A};
108

109
  static {
3 ✔
110
    Backend.prototype.MIDDLEWARE_ACTIONS = {
3 ✔
111
      // An operation was successfully written to the database.
112
      afterWrite: 'afterWrite',
113
      // An operation is about to be applied to a snapshot before being committed to the database
114
      apply: 'apply',
115
      // An operation was applied to a snapshot; The operation and new snapshot are about to be written to the database.
116
      commit: 'commit',
117
      // A new client connected to the server.
118
      connect: 'connect',
119
      // An operation was loaded from the database
120
      op: 'op',
121
      // A query is about to be sent to the database
122
      query: 'query',
123
      // Snapshot(s) were received from the database and are about to be returned to a client
124
      readSnapshots: 'readSnapshots',
125
      // Received a message from a client
126
      receive: 'receive',
127
      // About to send a non-error reply to a client message.
128
      // WARNING: This gets passed a direct reference to the reply object, so
129
      // be cautious with it. While modifications to the reply message are possible
130
      // by design, changing existing reply properties can cause weird bugs, since
131
      // the rest of ShareDB would be unaware of those changes.
132
      reply: 'reply',
133
      // The server received presence information
134
      receivePresence: 'receivePresence',
135
      // About to send presence information to a client
136
      sendPresence: 'sendPresence',
137
      // An operation lost the race to commit and is about to be retried against a newer snapshot
138
      retry: 'retry',
139
      // An operation is about to be submitted to the database
140
      submit: 'submit'
141
    };
142
  }
143

144
  declare SNAPSHOT_TYPES: {[T in Backend.middleware.SnapshotType]: T};
145

146
  static {
3 ✔
147
    Backend.prototype.SNAPSHOT_TYPES = {
3 ✔
148
      // The current snapshot is being fetched (eg through backend.fetch)
149
      current: 'current',
150
      // A specific snapshot is being fetched by version (eg through backend.fetchSnapshot)
151
      byVersion: 'byVersion',
152
      // A specific snapshot is being fetch by timestamp (eg through backend.fetchSnapshotByTimestamp)
153
      byTimestamp: 'byTimestamp'
154
    };
155
  }
156

157
  close(callback?: ShareDB.BasicCallback): void {
3 ✔
158
    var wait = 4;
2,304 ✔
159
    var backend = this;
2,304 ✔
160
    function finish(err?) {
161
      if (err) return util.callbackOrEmit(backend, err, callback);
9,258 !
162
      if (--wait) return;
9,258 ✔
163
      if (callback) callback();
2,304 ✔
164
    }
165
    this.pubsub.close(finish);
2,304 ✔
166
    this.db.close(finish);
2,304 ✔
167
    this.milestoneDb.close(finish);
2,304 ✔
168
    for (var name in this.extraDbs) {
2,304 ✔
169
      wait++;
42 ✔
170
      this.extraDbs[name].close(finish);
42 ✔
171
    }
172
    finish();
2,304 ✔
173
  }
174

175
  connect(connection?: Connection | null, req?: any, callback?: (connection: Connection) => void): Connection {
3 ✔
176
    var socket = new StreamSocket();
3,582 ✔
177
    if (connection) {
3,582 ✔
178
      connection.bindToSocket(socket);
96 ✔
179
    } else {
180
      connection = new Connection(socket);
3,486 ✔
181
    }
182
    socket._open();
3,582 ✔
183
    var agent = this.listen(socket.stream, req);
3,582 ✔
184
    // Store a reference to the agent on the connection for convenience. This is
185
    // not used internal to ShareDB, but it is handy for server-side only user
186
    // code that may cache state on the agent and read it in middleware
187
    connection.agent = agent;
3,582 ✔
188

189
    if (typeof callback === 'function') {
3,582 ✔
190
      connection.once('connected', function() {
36 ✔
191
        callback(connection);
36 ✔
192
      });
193
    }
194

195
    return connection;
3,582 ✔
196
  }
197

198
  /** A client has connected through the specified stream. Listen for messages.
199
   *
200
   * The optional second argument (req) is an initial request which is passed
201
   * through to any connect() middleware. This is useful for inspecting cookies
202
   * or an express session or whatever on the request object in your middleware.
203
   *
204
   * (The agent is available through all middleware)
205
   */
206
  listen(stream: Duplex, req?: any): Agent {
3 ✔
207
    var agent = new Agent(this, stream);
3,834 ✔
208
    this.trigger(this.MIDDLEWARE_ACTIONS.connect, agent, {stream: stream, req: req}, function(err) {
3,834 ✔
209
      if (err) return agent.close(err);
3,834 ✔
210
      agent._open();
3,828 ✔
211
    });
212
    return agent;
3,834 ✔
213
  }
214

215
  addProjection(name: string, collection: string, fields: ShareDB.ProjectionFields): void {
3 ✔
216
    if (this.projections[name]) {
150 !
UNCOV
217
      throw new Error('Projection ' + name + ' already exists');
×
218
    }
219

220
    for (var key in fields) {
150 ✔
221
      if (fields[key] !== true) {
273 !
UNCOV
222
        throw new Error(
×
223
          'Invalid field ' + key + ' - fields must be {somekey: true}. Subfields not currently supported.'
224
        );
225
      }
226
    }
227

228
    (this.projections as {[name: string]: ShareDB.ReadonlyProjection})[name] = {
150 ✔
229
      target: collection,
230
      fields: fields
231
    };
232
  }
233

234
  /**
235
   * Add middleware to an action or array of actions
236
   */
237
  use<A extends keyof Backend.middleware.ActionContextMap>(
3 ✔
238
    action: A | A[],
239
    fn: (context: Backend.middleware.ActionContextMap[A], next: (err?: any) => void) => void
240
  ): this {
241
    if (Array.isArray(action)) {
1,623 ✔
242
      for (var i = 0; i < action.length; i++) {
3 ✔
243
        this.use(action[i], fn);
6 ✔
244
      }
245
      return this;
3 ✔
246
    }
247
    var fns = this.middleware[action] || (this.middleware[action] = []);
1,620 ✔
248
    fns.push(fn);
1,620 ✔
249
    return this;
1,620 ✔
250
  }
251

252
  /**
253
   * Passes request through the middleware stack
254
   *
255
   * Middleware may modify the request object. After all middleware have been
256
   * invoked we call `callback` with `null` and the modified request. If one of
257
   * the middleware resturns an error the callback is called with that error.
258
   */
259
  trigger(action, agent, request, callback) {
3 ✔
260
    request.action = action;
53,064 ✔
261
    request.agent = agent;
53,064 ✔
262
    request.backend = this;
53,064 ✔
263

264
    var fns = this.middleware[action];
53,064 ✔
265
    if (!fns) return callback();
53,064 ✔
266

267
    // Copying the triggers we'll fire so they don't get edited while we iterate.
268
    fns = fns.slice();
2,271 ✔
269
    var next = function(err?) {
2,271 ✔
270
      if (err) return callback(err);
4,596 ✔
271
      var fn = fns.shift();
4,419 ✔
272
      if (!fn) return callback();
4,419 ✔
273
      fn(request, next);
2,358 ✔
274
    };
275
    next();
2,271 ✔
276
  }
277

278
  /**
279
   * Submit an operation on the named collection/docname. op should contain a
280
   * {op:}, {create:} or {del:} field. It should probably contain a v: field (if
281
   * it doesn't, it defaults to the current version).
282
   */
283
  submit(
3 ✔
284
    agent: Agent,
285
    index: string,
286
    id: string,
287
    op: ShareDB.CreateOp | ShareDB.DeleteOp | ShareDB.EditOp,
288
    options: ShareDB.BackendSubmitOptions | null,
289
    originalCallback: (error: Rejection | null | undefined, ops: any[], request: SubmitRequest) => void
290
  ): void {
291
    var backend = this;
3,933 ✔
292
    var request = new SubmitRequest(this, agent, index, id, op, options);
3,933 ✔
293

294
    var callback = function(error, ops?) {
3,933 ✔
295
      backend.emit('submitRequestEnd', error, request);
3,912 ✔
296
      originalCallback(error, ops, request);
3,912 ✔
297
    };
298

299
    var err = ot.checkOp(op);
3,933 ✔
300
    if (err) return callback(err);
3,933 !
301
    backend.trigger(backend.MIDDLEWARE_ACTIONS.submit, agent, request, function(err) {
3,933 ✔
302
      if (err) return callback(err);
3,933 ✔
303
      request.submit(function(err) {
3,882 ✔
304
        if (err) return callback(err);
3,864 ✔
305
        backend.trigger(backend.MIDDLEWARE_ACTIONS.afterWrite, agent, request, function(err) {
3,747 ✔
306
          if (err) return callback(err);
3,744 !
307
          backend._sanitizeOps(agent, request.projection, request.collection, id, request.ops, function(err) {
3,744 ✔
308
            if (err) return callback(err);
3,744 !
309
            backend.emit('timing', 'submit.total', Date.now() - request.start, request);
3,744 ✔
310
            callback(err, request.ops);
3,744 ✔
311
          });
312
        });
313
      });
314
    });
315
  }
316

317
  sanitizeOp(agent, index, id, op, callback) {
3 ✔
318
    var projection = this.projections[index];
258 ✔
319
    var collection = (projection) ? projection.target : index;
258 ✔
320
    this._sanitizeOp(agent, projection, collection, id, op, callback);
258 ✔
321
  }
322

323
  _sanitizeOp(agent, projection, collection, id, op, callback) {
3 ✔
324
    if (projection) {
594 ✔
325
      try {
75 ✔
326
        projections.projectOp(projection.fields, op);
75 ✔
327
      } catch (err) {
UNCOV
328
        return callback(err);
×
329
      }
330
    }
331
    this.trigger(this.MIDDLEWARE_ACTIONS.op, agent, {collection: collection, id: id, op: op}, callback);
594 ✔
332
  }
333

334
  _sanitizeOps(agent, projection, collection, id, ops, callback) {
3 ✔
335
    var backend = this;
4,353 ✔
336
    async.each(ops, function(op, eachCb) {
4,353 ✔
337
      backend._sanitizeOp(agent, projection, collection, id, op, function(err) {
336 ✔
338
        util.nextTick(eachCb, err);
336 ✔
339
      });
340
    }, callback);
341
  }
342

343
  _sanitizeOpsBulk(agent, projection, collection, opsMap, callback) {
3 ✔
344
    var backend = this;
87 ✔
345
    async.forEachOf(opsMap, function(ops, id, eachCb) {
87 ✔
346
      backend._sanitizeOps(agent, projection, collection, id, ops, eachCb);
129 ✔
347
    }, callback);
348
  }
349

350
  _sanitizeSnapshots(agent, projection, collection, snapshots, snapshotType, callback) {
3 ✔
351
    if (projection) {
2,046 ✔
352
      try {
162 ✔
353
        projections.projectSnapshots(projection.fields, snapshots);
162 ✔
354
      } catch (err) {
UNCOV
355
        return callback(err);
×
356
      }
357
    }
358

359
    var request = new ReadSnapshotsRequest(collection, snapshots, snapshotType);
2,046 ✔
360

361
    this.trigger(this.MIDDLEWARE_ACTIONS.readSnapshots, agent, request, function(err) {
2,046 ✔
362
      if (err) return callback(err);
2,040 ✔
363
      // Handle "partial rejection" - "readSnapshots" middleware functions can use
364
      // `request.rejectSnapshotRead(snapshot, error)` to reject the read of a specific snapshot.
365
      if (request.hasSnapshotRejection()) {
1,989 ✔
366
        err = request.getReadSnapshotsError();
39 ✔
367
      }
368
      if (err) {
1,989 ✔
369
        callback(err);
39 ✔
370
      } else {
371
        callback();
1,950 ✔
372
      }
373
    });
374
  }
375

376
  _getSnapshotProjection(db, projection) {
3 ✔
377
    return (db.projectsSnapshots) ? null : projection;
1,728 !
378
  }
379

380
  _getSnapshotsFromMap(ids, snapshotMap) {
3 ✔
381
    var snapshots = new Array(ids.length);
210 ✔
382
    for (var i = 0; i < ids.length; i++) {
210 ✔
383
      var id = ids[i];
450 ✔
384
      snapshots[i] = snapshotMap[id];
450 ✔
385
    }
386
    return snapshots;
210 ✔
387
  }
388

389
  _getSanitizedOps(agent, projection, collection, id, from, to, opsOptions, callback) {
3 ✔
390
    var backend = this;
480 ✔
391
    if (!opsOptions) opsOptions = {};
480 ✔
392
    if (agent) opsOptions.agentCustom = agent.custom;
480 ✔
393
    backend.db.getOps(collection, id, from, to, opsOptions, function(err, ops) {
480 ✔
394
      if (err) return callback(err);
480 !
395
      backend._sanitizeOps(agent, projection, collection, id, ops, function(err) {
480 ✔
396
        if (err) return callback(err);
480 ✔
397
        callback(null, ops);
477 ✔
398
      });
399
    });
400
  }
401

402
  _getSanitizedOpsBulk(agent, projection, collection, fromMap, toMap, opsOptions, callback) {
3 ✔
403
    var backend = this;
87 ✔
404
    if (!opsOptions) opsOptions = {};
87 ✔
405
    if (agent) opsOptions.agentCustom = agent.custom;
87 ✔
406
    backend.db.getOpsBulk(collection, fromMap, toMap, opsOptions, function(err, opsMap) {
87 ✔
407
      if (err) return callback(err);
87 !
408
      backend._sanitizeOpsBulk(agent, projection, collection, opsMap, function(err) {
87 ✔
409
        if (err) return callback(err);
87 ✔
410
        callback(null, opsMap);
84 ✔
411
      });
412
    });
413
  }
414

415
  /**
416
   * Non inclusive - gets ops from [from, to). Ie, all relevant ops. If to is
417
   * not defined (null or undefined) then it returns all ops.
418
   */
419
  getOps(
420
    agent: Agent,
421
    index: string,
422
    id: string,
423
    from: number | null,
424
    to: number | null,
425
    callback: (error: Rejection | null, ops: any[]) => any
426
  ): void;
427
  getOps(
428
    agent: Agent,
429
    index: string,
430
    id: string,
431
    from: number | null,
432
    to: number | null,
433
    options: Backend.GetOpsOptions | null,
434
    callback: (error: Rejection | null, ops: any[]) => any
435
  ): void;
436
  getOps(agent, index, id, from, to, options, callback?) {
3 ✔
437
    if (typeof options === 'function') {
204 ✔
438
      callback = options;
198 ✔
439
      options = null;
198 ✔
440
    }
441
    var start = Date.now();
204 ✔
442
    var projection = this.projections[index];
204 ✔
443
    var collection = (projection) ? projection.target : index;
204 ✔
444
    var backend = this;
204 ✔
445
    var request = {
204 ✔
446
      agent: agent,
447
      index: index,
448
      collection: collection,
449
      id: id,
450
      from: from,
451
      to: to
452
    };
453
    var opsOptions = options && options.opsOptions;
204 ✔
454
    backend._getSanitizedOps(agent, projection, collection, id, from, to, opsOptions, function(err, ops) {
204 ✔
455
      if (err) return callback(err);
204 ✔
456
      backend.emit('timing', 'getOps', Date.now() - start, request);
201 ✔
457
      callback(null, ops);
201 ✔
458
    });
459
  }
460

461
  getOpsBulk(
462
    agent: Agent,
463
    index: string,
464
    fromMap: Record<string, number | null>,
465
    toMap: Record<string, number | null> | null,
466
    callback: (error: Rejection | null, opsMap: Record<string, any[]>) => any
467
  ): void;
468
  getOpsBulk(
469
    agent: Agent,
470
    index: string,
471
    fromMap: Record<string, number | null>,
472
    toMap: Record<string, number | null> | null,
473
    options: Backend.GetOpsOptions | null,
474
    callback: (error: Rejection | null, opsMap: Record<string, any[]>) => any
475
  ): void;
476
  getOpsBulk(agent, index, fromMap, toMap, options, callback?) {
3 ✔
477
    if (typeof options === 'function') {
78 ✔
478
      callback = options;
69 ✔
479
      options = null;
69 ✔
480
    }
481
    var start = Date.now();
78 ✔
482
    var projection = this.projections[index];
78 ✔
483
    var collection = (projection) ? projection.target : index;
78 ✔
484
    var backend = this;
78 ✔
485
    var request = {
78 ✔
486
      agent: agent,
487
      index: index,
488
      collection: collection,
489
      fromMap: fromMap,
490
      toMap: toMap
491
    };
492
    var opsOptions = options && options.opsOptions;
78 ✔
493
    backend._getSanitizedOpsBulk(agent, projection, collection, fromMap, toMap, opsOptions, function(err, opsMap) {
78 ✔
494
      if (err) return callback(err);
78 ✔
495
      backend.emit('timing', 'getOpsBulk', Date.now() - start, request);
75 ✔
496
      callback(null, opsMap);
75 ✔
497
    });
498
  }
499

500
  fetch<T = unknown>(
501
    agent: Agent,
502
    index: string,
503
    id: string,
504
    callback: (error: Rejection | null, snapshot?: ShareDB.Snapshot<T>) => void
505
  ): void;
506
  fetch<T = unknown>(
507
    agent: Agent,
508
    index: string,
509
    id: string,
510
    options: ShareDB.BackendFetchOptions | null,
511
    callback: (error: Rejection | null, snapshot?: ShareDB.Snapshot<T>) => void
512
  ): void;
513
  fetch(agent, index, id, options, callback?) {
3 ✔
514
    if (typeof options === 'function') {
1,107 ✔
515
      callback = options;
1,101 ✔
516
      options = null;
1,101 ✔
517
    }
518
    var start = Date.now();
1,107 ✔
519
    var projection = this.projections[index];
1,107 ✔
520
    var collection = (projection) ? projection.target : index;
1,107 ✔
521
    var fields = projection && projection.fields;
1,107 ✔
522
    var backend = this;
1,107 ✔
523
    var request = {
1,107 ✔
524
      agent: agent,
525
      index: index,
526
      collection: collection,
527
      id: id
528
    };
529
    var snapshotOptions = (options && options.snapshotOptions) || {};
1,107 ✔
530
    snapshotOptions.agentCustom = agent.custom;
1,107 ✔
531
    backend.db.getSnapshot(collection, id, fields, snapshotOptions, function(err, snapshot) {
1,107 ✔
532
      if (err) return callback(err);
1,107 !
533
      var snapshotProjection = backend._getSnapshotProjection(backend.db, projection);
1,107 ✔
534
      var snapshots = [snapshot];
1,107 ✔
535
      backend._sanitizeSnapshots(
1,107 ✔
536
        agent,
537
        snapshotProjection,
538
        collection,
539
        snapshots,
540
        backend.SNAPSHOT_TYPES.current,
541
        function(err) {
542
          if (err) return callback(err);
1,107 ✔
543
          backend.emit('timing', 'fetch', Date.now() - start, request);
1,065 ✔
544
          callback(null, snapshot);
1,065 ✔
545
        });
546
    });
547
  }
548

549
  /**
550
   * Map of document id to Snapshot or error object.
551
   * @typedef {{ [id: string]: Snapshot | { error: Error | string } }} SnapshotMap
552
   */
553

554
  fetchBulk(agent, index, ids, callback);
555
  fetchBulk(agent, index, ids, options, callback);
556
  /**
557
   * @param {Agent} agent
558
   * @param {string} index
559
   * @param {string[]} ids
560
   * @param {*} options
561
   * @param {(err?: Error | string, snapshotMap?: SnapshotMap) => void} callback
562
   */
563
  fetchBulk(agent, index, ids, options, callback?) {
3 ✔
564
    if (typeof options === 'function') {
66 ✔
565
      callback = options;
63 ✔
566
      options = null;
63 ✔
567
    }
568
    var start = Date.now();
66 ✔
569
    var projection = this.projections[index];
66 ✔
570
    var collection = (projection) ? projection.target : index;
66 !
571
    var fields = projection && projection.fields;
66 !
572
    var backend = this;
66 ✔
573
    var request = {
66 ✔
574
      agent: agent,
575
      index: index,
576
      collection: collection,
577
      ids: ids
578
    };
579
    var snapshotOptions = (options && options.snapshotOptions) || {};
66 ✔
580
    snapshotOptions.agentCustom = agent.custom;
66 ✔
581
    backend.db.getSnapshotBulk(collection, ids, fields, snapshotOptions, function(err, snapshotMap) {
66 ✔
582
      if (err) return callback(err);
66 !
583
      var snapshotProjection = backend._getSnapshotProjection(backend.db, projection);
66 ✔
584
      var snapshots = backend._getSnapshotsFromMap(ids, snapshotMap);
66 ✔
585
      backend._sanitizeSnapshots(
66 ✔
586
        agent,
587
        snapshotProjection,
588
        collection,
589
        snapshots,
590
        backend.SNAPSHOT_TYPES.current,
591
        function(err) {
592
          if (err) {
66 ✔
593
            if (err.code === ERROR_CODE.ERR_SNAPSHOT_READS_REJECTED) {
30 ✔
594
              for (var docId in err.idToError) {
15 ✔
595
                snapshotMap[docId] = {error: err.idToError[docId]};
15 ✔
596
              }
597
              err = undefined;
15 ✔
598
            } else {
599
              snapshotMap = undefined;
15 ✔
600
            }
601
          }
602
          backend.emit('timing', 'fetchBulk', Date.now() - start, request);
66 ✔
603
          callback(err, snapshotMap);
66 ✔
604
        });
605
    });
606
  }
607

608
  /** Subscribe to the document from the specified version or null version */
609
  subscribe(agent, index, id, version, options, callback?) {
3 ✔
610
    if (typeof options === 'function') {
936 ✔
611
      callback = options;
933 ✔
612
      options = null;
933 ✔
613
    }
614
    if (options) {
936 ✔
615
      // We haven't yet implemented the ability to pass options to subscribe. This is because we need to
616
      // add the ability to SubmitRequest.commit to optionally pass the metadata to other clients on
617
      // PubSub. This behaviour is not needed right now, but we have added an options object to the
618
      // subscribe() signature so that it remains consistent with getOps() and fetch().
619
      return callback(new ShareDBError(
3 ✔
620
        ERROR_CODE.ERR_DATABASE_METHOD_NOT_IMPLEMENTED,
621
        'Passing options to subscribe has not been implemented'
622
      ));
623
    }
624
    var start = Date.now();
933 ✔
625
    var projection = this.projections[index];
933 ✔
626
    var collection = (projection) ? projection.target : index;
933 ✔
627
    var channel = this.getDocChannel(collection, id);
933 ✔
628
    var backend = this;
933 ✔
629
    var request = {
933 ✔
630
      agent: agent,
631
      index: index,
632
      collection: collection,
633
      id: id,
634
      version: version
635
    };
636
    backend.pubsub.subscribe(channel, function(err, stream) {
933 ✔
637
      if (err) return callback(err);
933 !
638
      if (version == null) {
933 ✔
639
        // Subscribing from null means that the agent doesn't have a document
640
        // and needs to fetch it as well as subscribing
641
        backend.fetch(agent, index, id, function(err, snapshot) {
657 ✔
642
          if (err) {
657 ✔
643
            stream.destroy();
21 ✔
644
            return callback(err);
21 ✔
645
          }
646
          backend.emit('timing', 'subscribe.snapshot', Date.now() - start, request);
636 ✔
647
          callback(null, stream, snapshot);
636 ✔
648
        });
649
      } else {
650
        backend._getSanitizedOps(agent, projection, collection, id, version, null, null, function(err, ops) {
276 ✔
651
          if (err) {
276 !
UNCOV
652
            stream.destroy();
×
UNCOV
653
            return callback(err);
×
654
          }
655
          backend.emit('timing', 'subscribe.ops', Date.now() - start, request);
276 ✔
656
          callback(null, stream, null, ops);
276 ✔
657
        });
658
      }
659
    });
660
  }
661

662
  /**
663
   * Map of document id to pubsub stream.
664
   * @typedef {{ [id: string]: Stream }} StreamMap
665
   */
666
  /**
667
   * Map of document id to array of ops for the doc.
668
   * @typedef {{ [id: string]: Op[] }} OpsMap
669
   */
670

671
  /**
672
   * @param {Agent} agent
673
   * @param {string} index
674
   * @param {string[]} versions
675
   * @param {(
676
   *   err?: Error | string | null,
677
   *   streams?: StreamMap,
678
   *   snapshotMap?: SnapshotMap | null
679
   *   opsMap?: OpsMap
680
   * ) => void} callback
681
   */
682
  subscribeBulk(agent, index, versions, callback) {
3 ✔
683
    var start = Date.now();
42 ✔
684
    var projection = this.projections[index];
42 ✔
685
    var collection = (projection) ? projection.target : index;
42 !
686
    var backend = this;
42 ✔
687
    var streams = Object.create(null);
42 ✔
688
    var doFetch = Array.isArray(versions);
42 ✔
689
    var ids = (doFetch) ? uniqueIds(versions) : Object.keys(versions);
42 ✔
690
    var request = {
42 ✔
691
      agent: agent,
692
      index: index,
693
      collection: collection,
694
      versions: versions
695
    };
696
    var subscribeFailed = false;
42 ✔
697
    async.each(ids, function(id, eachCb) {
42 ✔
698
      var channel = backend.getDocChannel(collection, id);
81 ✔
699
      backend.pubsub.subscribe(channel, function(err, stream) {
81 ✔
700
        if (err) return eachCb(err);
81 ✔
701
        if (subscribeFailed) return stream.destroy();
75 ✔
702
        streams[id] = stream;
72 ✔
703
        eachCb();
72 ✔
704
      });
705
    }, function(err) {
706
      if (err) {
42 ✔
707
        subscribeFailed = true;
6 ✔
708
        destroyStreams(streams);
6 ✔
709
        return callback(err);
6 ✔
710
      }
711
      if (doFetch) {
36 ✔
712
        // If an array of ids, get current snapshots
713
        backend.fetchBulk(agent, index, ids, function(err, snapshotMap) {
27 ✔
714
          if (err) {
27 ✔
715
            // Full error, destroy all streams.
716
            destroyStreams(streams);
6 ✔
717
            streams = undefined;
6 ✔
718
            snapshotMap = undefined;
6 ✔
719
          }
720
          for (var docId in snapshotMap) {
27 ✔
721
            // The doc id could map to an object `{error: Error | string}`, which indicates that
722
            // particular snapshot's read was rejected. Destroy the streams fur such docs.
723
            if (snapshotMap[docId].error) {
39 ✔
724
              streams[docId].destroy();
6 ✔
725
              delete streams[docId];
6 ✔
726
            }
727
          }
728
          backend.emit('timing', 'subscribeBulk.snapshot', Date.now() - start, request);
27 ✔
729
          callback(err, streams, snapshotMap);
27 ✔
730
        });
731
      } else {
732
        // If a versions map, get ops since requested versions
733
        backend._getSanitizedOpsBulk(agent, projection, collection, versions, null, null, function(err, opsMap) {
9 ✔
734
          if (err) {
9 !
UNCOV
735
            destroyStreams(streams);
×
UNCOV
736
            return callback(err);
×
737
          }
738
          backend.emit('timing', 'subscribeBulk.ops', Date.now() - start, request);
9 ✔
739
          callback(null, streams, null, opsMap);
9 ✔
740
        });
741
      }
742
    });
743
  }
744

745
  queryFetch(agent, index, query, options, callback) {
3 ✔
746
    var start = Date.now();
90 ✔
747
    var backend = this;
90 ✔
748
    backend._triggerQuery(agent, index, query, options, function(err, request) {
90 ✔
749
      if (err) return callback(err);
90 ✔
750
      backend._query(agent, request, function(err, snapshots, extra) {
72 ✔
751
        if (err) return callback(err);
72 ✔
752
        backend.emit('timing', 'queryFetch', Date.now() - start, request);
66 ✔
753
        callback(null, snapshots, extra);
66 ✔
754
      });
755
    });
756
  }
757

758
  /**
759
   * Options can contain:
760
   * db: The name of the DB (if the DB is specified in the otherDbs when the backend instance is created)
761
   * skipPoll: function(collection, id, op, query) {return true or false; }
762
   *  this is a synchronous function which can be used as an early filter for
763
   *  operations going through the system to reduce the load on the DB.
764
   * pollDebounce: Minimum delay between subsequent database polls. This is
765
   *  used to batch updates to reduce load on the database at the expense of
766
   *  liveness
767
   * pollInterval: Maximum delay between subsequent database polls. Set this to
768
   *  pick up changes that don't publish an op on the query's channels
769
   */
770
  querySubscribe(agent, index, query, options, callback) {
3 ✔
771
    var start = Date.now();
504 ✔
772
    var backend = this;
504 ✔
773
    backend._triggerQuery(agent, index, query, options, function(err, request) {
504 ✔
774
      if (err) return callback(err);
504 ✔
775
      if (request.db.disableSubscribe) {
483 !
UNCOV
776
        return callback(new ShareDBError(
×
777
          ERROR_CODE.ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE,
778
          'DB does not support subscribe'
779
        ));
780
      }
781

782
      var channels = request.channels;
483 ✔
783

784
      if (request.channel) {
483 ✔
785
        logger.warn(
87 ✔
786
          '[DEPRECATED] "query" middleware\'s context.channel is deprecated, use context.channels instead. ' +
787
          'Read more: https://share.github.io/sharedb/middleware/actions#query'
788
        );
789
        channels = [request.channel];
87 ✔
790
      }
791

792
      if (!channels || !channels.length) {
483 ✔
793
        return callback(new ShareDBError(ERROR_CODE.ERR_QUERY_CHANNEL_MISSING, 'Required minimum one query channel.'));
12 ✔
794
      }
795

796
      var streams: any[] = [];
471 ✔
797

798
      function destroyStreams() {
799
        streams.forEach(function(stream) {
24 ✔
800
          stream.destroy();
6 ✔
801
        });
802
      }
803

804
      function createQueryEmitter() {
805
        if (options.ids) {
459 ✔
806
          var queryEmitter = new QueryEmitter(request, streams, options.ids);
69 ✔
807
          backend.emit('timing', 'querySubscribe.reconnect', Date.now() - start, request);
69 ✔
808
          callback(null, queryEmitter);
69 ✔
809
          return;
69 ✔
810
        }
811
        // Issue query on db to get our initial results
812
        backend._query(agent, request, function(err, snapshots, extra) {
390 ✔
813
          if (err) {
390 ✔
814
            destroyStreams();
6 ✔
815
            return callback(err);
6 ✔
816
          }
817
          var ids = pluckIds(snapshots);
384 ✔
818
          var queryEmitter = new QueryEmitter(request, streams, ids, extra);
384 ✔
819
          backend.emit('timing', 'querySubscribe.initial', Date.now() - start, request);
384 ✔
820
          callback(null, queryEmitter, snapshots, extra);
384 ✔
821
        });
822
      }
823

824
      channels.forEach(function(channel) {
471 ✔
825
        backend.pubsub.subscribe(channel, function(err, stream) {
654 ✔
826
          if (err) {
654 ✔
827
            destroyStreams();
18 ✔
828
            return callback(err);
18 ✔
829
          }
830
          streams.push(stream);
636 ✔
831

832
          var subscribedToAllChannels = streams.length === channels.length;
636 ✔
833
          if (subscribedToAllChannels) {
636 ✔
834
            createQueryEmitter();
459 ✔
835
          }
836
        });
837
      });
838
    });
839
  }
840

841
  _triggerQuery(agent, index, query, options, callback) {
3 ✔
842
    var projection = this.projections[index];
594 ✔
843
    var collection = (projection) ? projection.target : index;
594 ✔
844
    var fields = projection && projection.fields;
594 ✔
845
    var request = {
594 ✔
846
      index: index,
847
      collection: collection,
848
      projection: projection,
849
      fields: fields,
850
      channels: [this.getCollectionChannel(collection)],
851
      query: query,
852
      options: options,
853
      db: null,
854
      snapshotProjection: null
855
    };
856
    var backend = this;
594 ✔
857
    backend.trigger(backend.MIDDLEWARE_ACTIONS.query, agent, request, function(err) {
594 ✔
858
      if (err) return callback(err);
594 ✔
859
      // Set the DB reference for the request after the middleware trigger so
860
      // that the db option can be changed in middleware
861
      request.db = (options.db) ? getExtraDb(backend, options.db) : backend.db;
591 ✔
862
      if (!request.db) return callback(new ShareDBError(ERROR_CODE.ERR_DATABASE_ADAPTER_NOT_FOUND, 'DB not found'));
591 ✔
863
      request.snapshotProjection = backend._getSnapshotProjection(request.db, projection);
555 ✔
864
      callback(null, request);
555 ✔
865
    });
866
  }
867

868
  _query(agent, request, callback) {
3 ✔
869
    var backend = this;
462 ✔
870
    request.db.query(
462 ✔
871
      request.collection,
872
      request.query,
873
      request.fields,
874
      request.options,
875
      function(err, snapshots, extra) {
876
        if (err) return callback(err);
462 !
877
        backend._sanitizeSnapshots(
462 ✔
878
          agent,
879
          request.snapshotProjection,
880
          request.collection,
881
          snapshots,
882
          backend.SNAPSHOT_TYPES.current,
883
          function(err) {
884
            callback(err, snapshots, extra);
462 ✔
885
          });
886
      });
887
  }
888

889
  getCollectionChannel(collection) {
3 ✔
890
    return collection;
4,431 ✔
891
  }
892

893
  getDocChannel(collection, id) {
3 ✔
894
    return collection + '.' + id;
4,851 ✔
895
  }
896

897
  getChannels(collection, id) {
3 ✔
898
    return [
3,837 ✔
899
      this.getCollectionChannel(collection),
900
      this.getDocChannel(collection, id)
901
    ];
902
  }
903

904
  fetchSnapshot(agent, index, id, version, callback) {
3 ✔
905
    var start = Date.now();
105 ✔
906
    var backend = this;
105 ✔
907
    var projection = this.projections[index];
105 ✔
908
    var collection = projection ? projection.target : index;
105 ✔
909
    var request = {
105 ✔
910
      agent: agent,
911
      index: index,
912
      collection: collection,
913
      id: id,
914
      version: version
915
    };
916

917
    this._fetchSnapshot(collection, id, version, function(error, snapshot) {
105 ✔
918
      if (error) return callback(error);
105 ✔
919
      var snapshots = [snapshot];
96 ✔
920
      var snapshotType = backend.SNAPSHOT_TYPES.byVersion;
96 ✔
921
      backend._sanitizeSnapshots(agent, projection, collection, snapshots, snapshotType, function(error) {
96 ✔
922
        if (error) return callback(error);
93 ✔
923
        backend.emit('timing', 'fetchSnapshot', Date.now() - start, request);
90 ✔
924
        callback(null, snapshot);
90 ✔
925
      });
926
    });
927
  }
928

929
  _fetchSnapshot(collection, id, version, callback) {
3 ✔
930
    var db = this.db;
105 ✔
931
    var backend = this;
105 ✔
932

933
    var shouldGetLatestSnapshot = version === null;
105 ✔
934
    if (shouldGetLatestSnapshot) {
105 ✔
935
      return backend.db.getSnapshot(collection, id, null, null, function(error, snapshot) {
45 ✔
936
        if (error) return callback(error);
45 ✔
937

938
        callback(null, snapshot);
42 ✔
939
      });
940
    }
941

942

943
    this.milestoneDb.getMilestoneSnapshot(collection, id, version, function(error, milestoneSnapshot) {
60 ✔
944
      if (error) return callback(error);
60 !
945

946
      // Bypass backend.getOps so that we don't call _sanitizeOps. We want to avoid this, because:
947
      // - we want to avoid the 'op' middleware, because we later use the 'readSnapshots' middleware in
948
      //   _sanitizeSnapshots
949
      // - we handle the projection in _sanitizeSnapshots
950
      var from = milestoneSnapshot ? milestoneSnapshot.v : 0;
60 ✔
951
      db.getOps(collection, id, from, version, null, function(error, ops) {
60 ✔
952
        if (error) return callback(error);
60 ✔
953

954
        backend._buildSnapshotFromOps(id, milestoneSnapshot, ops, function(error, snapshot) {
57 ✔
955
          if (error) return callback(error);
57 !
956

957
          if (version > snapshot.v) {
57 ✔
958
            return callback(new ShareDBError(
3 ✔
959
              ERROR_CODE.ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT,
960
              'Requested version exceeds latest snapshot version'
961
            ));
962
          }
963

964
          callback(null, snapshot);
54 ✔
965
        });
966
      });
967
    });
968
  }
969

970
  fetchSnapshotByTimestamp(agent, index, id, timestamp, callback) {
3 ✔
971
    var start = Date.now();
93 ✔
972
    var backend = this;
93 ✔
973
    var projection = this.projections[index];
93 ✔
974
    var collection = projection ? projection.target : index;
93 ✔
975
    var request = {
93 ✔
976
      agent: agent,
977
      index: index,
978
      collection: collection,
979
      id: id,
980
      timestamp: timestamp
981
    };
982

983
    this._fetchSnapshotByTimestamp(collection, id, timestamp, function(error, snapshot) {
93 ✔
984
      if (error) return callback(error);
93 ✔
985
      var snapshots = [snapshot];
90 ✔
986
      var snapshotType = backend.SNAPSHOT_TYPES.byTimestamp;
90 ✔
987
      backend._sanitizeSnapshots(agent, projection, collection, snapshots, snapshotType, function(error) {
90 ✔
988
        if (error) return callback(error);
87 ✔
989
        backend.emit('timing', 'fetchSnapshot', Date.now() - start, request);
84 ✔
990
        callback(null, snapshot);
84 ✔
991
      });
992
    });
993
  }
994

995
  _fetchSnapshotByTimestamp(collection, id, timestamp, callback) {
3 ✔
996
    var db = this.db;
93 ✔
997
    var milestoneDb = this.milestoneDb;
93 ✔
998
    var backend = this;
93 ✔
999

1000
    var milestoneSnapshot;
1001

1002
    // Always fetch the current snapshot first. We request its metadata so that we
1003
    // can read its mtime, which lets us serve the current snapshot directly when
1004
    // the requested timestamp is after it. This avoids replaying ops when they
1005
    // aren't needed, and - crucially - still works when older ops have been
1006
    // deleted/TTLed and the current version can no longer be rebuilt from ops.
1007
    db.getSnapshot(collection, id, null, {metadata: true}, function(error, currentSnapshot) {
93 ✔
1008
      if (error) return callback(error);
93 ✔
1009

1010
      var mtime = currentSnapshot.m && currentSnapshot.m.mtime;
90 ✔
1011
      var shouldGetLatestSnapshot = timestamp === null || (mtime != null && timestamp > mtime);
90 ✔
1012
      if (shouldGetLatestSnapshot) {
90 ✔
1013
        // Strip the metadata that we only fetched in order to compare the mtime,
1014
        // so that the returned snapshot is consistent with the op-replayed path.
1015
        currentSnapshot.m = null;
42 ✔
1016
        return callback(null, currentSnapshot);
42 ✔
1017
      }
1018

1019
      milestoneDb.getMilestoneSnapshotAtOrBeforeTime(collection, id, timestamp, function(error, snapshot) {
48 ✔
1020
        if (error) return callback(error);
48 !
1021
        milestoneSnapshot = snapshot;
48 ✔
1022

1023
        milestoneDb.getMilestoneSnapshotAtOrAfterTime(collection, id, timestamp, function(error, snapshot) {
48 ✔
1024
          if (error) return callback(error);
48 !
1025
          var from = milestoneSnapshot ? milestoneSnapshot.v : 0;
48 ✔
1026
          var to = snapshot ? snapshot.v : currentSnapshot.v;
48 ✔
1027
          if (from >= to) return backend._buildSnapshotFromOps(id, milestoneSnapshot, [], callback);
48 ✔
1028

1029
          var options = {metadata: true};
39 ✔
1030
          db.getOps(collection, id, from, to, options, function(error, ops) {
39 ✔
1031
            if (error) return callback(error);
39 !
1032
            filterOpsInPlaceBeforeTimestamp(ops, timestamp);
39 ✔
1033
            backend._buildSnapshotFromOps(id, milestoneSnapshot, ops, callback);
39 ✔
1034
          });
1035
        });
1036
      });
1037
    });
1038
  }
1039

1040
  _buildSnapshotFromOps(id, startingSnapshot, ops, callback) {
3 ✔
1041
    var snapshot = util.clone(startingSnapshot) || new Snapshot(id, 0, null, undefined, null);
105 ✔
1042
    var error = ot.applyOps(snapshot, ops, {_normalizeLegacyJson0Ops: true});
105 ✔
1043
    callback(error, snapshot);
105 ✔
1044
  }
1045

1046
  transformPresenceToLatestVersion(agent, presence, callback) {
3 ✔
1047
    this._transformPresenceToLatestVersion(agent, presence, null, callback);
3 ✔
1048
  }
1049

1050
  _transformPresenceToLatestVersion(agent, presence, trackedVersion, callback) {
3 ✔
1051
    if (!presence.c || !presence.d) return callback(null, presence);
738 ✔
1052
    var backend = this;
453 ✔
1053
    this._getDocVersionForPresence(agent, presence, trackedVersion, function(error, docVersion) {
453 ✔
1054
      if (error) return callback(error);
453 !
1055
      var leaving = presence.p === null;
453 ✔
1056
      if (leaving) presence.v = docVersion;
453 ✔
1057
      if (presence.v > docVersion) {
453 ✔
1058
        return callback(new ShareDBError(
15 ✔
1059
          ERROR_CODE.ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT,
1060
          'Presence version newer than current snapshot'
1061
        ));
1062
      }
1063
      if (presence.v === docVersion) return callback(null, presence);
438 ✔
1064
      backend.getOps(agent, presence.c, presence.d, presence.v, null, function(error, ops) {
36 ✔
1065
        if (error) return callback(error);
36 !
1066
        for (var i = 0; i < ops.length; i++) {
36 ✔
1067
          var op = ops[i];
36 ✔
1068
          var isOwnOp = op.src === presence.src;
36 ✔
1069
          var transformError = ot.transformPresence(presence, op, isOwnOp);
36 ✔
1070
          if (transformError) {
36 ✔
1071
            return callback(transformError);
9 ✔
1072
          }
1073
        }
1074
        callback(null, presence);
27 ✔
1075
      });
1076
    });
1077
  }
1078

1079
  _getDocVersionForPresence(agent, presence, trackedVersion, callback) {
3 ✔
1080
    var leaving = presence.p === null;
453 ✔
1081
    var presenceIsWithinTrackedVersion = trackedVersion != null && presence.v <= trackedVersion;
453 ✔
1082
    if (!leaving && presenceIsWithinTrackedVersion) return callback(null, trackedVersion);
453 ✔
1083
    var projection = this.projections[presence.c];
213 ✔
1084
    var collection = (projection) ? projection.target : presence.c;
213 !
1085
    this.db.getSnapshot(collection, presence.d, {}, {agentCustom: agent.custom}, function(error, snapshot) {
213 ✔
1086
      if (error) return callback(error);
213 !
1087
      callback(null, snapshot.v);
213 ✔
1088
    });
1089
  }
1090
}
3 ✔
1091

1092
export = Backend;
3 ✔
1093
interface Backend extends emitter.EventEmitter {
1094
  on<E extends keyof Backend.BackendEventListenerMap>(event: E, listener: Backend.BackendEventListenerMap[E]): this;
1095
  on(eventName: string | symbol, listener: (...args: any[]) => void): this;
1096
  addListener<E extends keyof Backend.BackendEventListenerMap>(
1097
    event: E,
1098
    listener: Backend.BackendEventListenerMap[E]
1099
  ): this;
1100
  addListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
1101
}
1102

1103
namespace Backend {
1104
  export type Agent<TCustom = any> = import('./agent')<TCustom>;
1105
  export type DB = import('./db');
1106
  export type MemoryDB = import('./db/memory');
1107
  export type MilestoneDB = import('./milestone-db');
1108
  export type MemoryMilestoneDB = import('./milestone-db/memory');
1109
  export type PubSub = import('./pubsub');
1110
  export type MemoryPubSub = import('./pubsub/memory');
1111
  export type Connection = ShareDB.Connection;
1112
  export type Doc<T = any> = ShareDB.Doc<T>;
1113
  export type Query<T = any> = ShareDB.Query<T>;
1114
  export type Snapshot<T = any> = ShareDB.Snapshot<T>;
1115
  export type Error = ShareDB.Error;
1116
  export type Op = ShareDB.Op;
1117
  export type CreateOp = ShareDB.CreateOp;
1118
  export type DeleteOp = ShareDB.DeleteOp;
1119
  export type EditOp = ShareDB.EditOp;
1120
  export type AddNumOp = ShareDB.AddNumOp;
1121
  export type ListMoveOp = ShareDB.ListMoveOp;
1122
  export type ListInsertOp = ShareDB.ListInsertOp;
1123
  export type ListDeleteOp = ShareDB.ListDeleteOp;
1124
  export type ListReplaceOp = ShareDB.ListReplaceOp;
1125
  export type StringInsertOp = ShareDB.StringInsertOp;
1126
  export type StringDeleteOp = ShareDB.StringDeleteOp;
1127
  export type ObjectInsertOp = ShareDB.ObjectInsertOp;
1128
  export type ObjectDeleteOp = ShareDB.ObjectDeleteOp;
1129
  export type ObjectReplaceOp = ShareDB.ObjectReplaceOp;
1130
  export type SubtypeOp = ShareDB.SubtypeOp;
1131
  export type Path = ShareDB.Path;
1132
  export type ShareDBSourceOptions = ShareDB.ShareDBSourceOptions;
1133
  export type DBQueryMethod = ShareDB.DBQueryMethod;
1134
  export type DBQueryCallback = ShareDB.DBQueryCallback;
1135
  export type MilestoneDBEventMap = ShareDB.MilestoneDBEventMap;
1136

1137
  export interface ShareDBOptions {
1138
    db?: any;
1139
    pubsub?: PubSub;
1140
    extraDbs?: {[extraDbName: string]: ExtraDB};
1141
    milestoneDb?: MilestoneDB;
1142
    suppressPublish?: boolean;
1143
    maxSubmitRetries?: number;
1144
    doNotForwardSendPresenceErrorsToClient?: boolean;
1145
    doNotCommitNoOps?: boolean;
1146
    errorHandler?: ErrorHandler;
1147
    presence?: boolean;
1148
  }
1149

1150
  export interface ExtraDB {
1151
    query: DBQueryMethod;
1152
    close(callback?: ShareDB.BasicCallback): void;
1153
  }
1154

1155
  export interface BackendEventListenerMap {
1156
    error: (err: globalThis.Error) => void;
1157
    send: (agent: Agent, response: ShareDB.ServerResponseSuccess | ShareDB.ServerResponseError) => void;
1158
    submitRequestEnd: (error: Rejection | null | undefined, request: SubmitRequest) => void;
1159
    timing: (type: string, time: number, request: any) => void;
1160
  }
1161

1162
  export type ErrorHandler = (error: Rejection, context: ErrorHandlerContext) => void;
1163
  export interface ErrorHandlerContext {
1164
    agent?: Agent;
1165
  }
1166

1167
  export interface GetOpsOptions {
1168
    opsOptions?: {
1169
      metadata?: boolean;
1170
    };
1171
  }
1172

1173
  export namespace middleware {
1174
    export interface ActionContextMap {
1175
      afterWrite: SubmitContext;
1176
      apply: ApplyContext;
1177
      commit: CommitContext;
1178
      connect: ConnectContext;
1179
      op: OpContext;
1180
      query: QueryContext;
1181
      readSnapshots: ReadSnapshotsContext;
1182
      receive: ReceiveContext;
1183
      receivePresence: PresenceContext;
1184
      reply: ReplyContext;
1185
      retry: SubmitContext;
1186
      sendPresence: PresenceContext;
1187
      submit: SubmitContext;
1188
    }
1189

1190
    export interface BaseContext {
1191
      action: keyof ActionContextMap;
1192
      agent: Agent;
1193
      backend: Backend;
1194
    }
1195

1196
    export interface SubmitContext extends BaseContext {
1197
      index: string;
1198
      projection: ShareDB.ReadonlyProjection | undefined;
1199
      collection: string;
1200
      id: string;
1201
      op: CreateOp | DeleteOp | EditOp;
1202
      options: any;
1203
      start: number;
1204
      extra: {
1205
        source?: any;
1206
      };
1207
      custom: {[key: string]: any};
1208
      saveMilestoneSnapshot: boolean | null;
1209
      suppressPublish: boolean | null;
1210
      maxRetries: number | null;
1211
      retries: number;
1212
      snapshot: Snapshot | null;
1213
      ops: any[];
1214
      channels: string[] | null;
1215
    }
1216

1217
    export interface ApplyContext extends SubmitContext {
1218
      $fixup(op: any): void;
1219
    }
1220

1221
    export type CommitContext = SubmitContext;
1222

1223
    export interface ConnectContext extends BaseContext {
1224
      stream: any;
1225
      req: any;
1226
    }
1227

1228
    export interface OpContext extends BaseContext {
1229
      collection: string;
1230
      id: string;
1231
      op: any;
1232
    }
1233

1234
    export interface PresenceContext extends BaseContext {
1235
      presence: ShareDB.PresenceMessage;
1236
      collection?: string;
1237
    }
1238

1239
    export interface QueryContext extends BaseContext {
1240
      index: string;
1241
      collection: string;
1242
      projection: ShareDB.ReadonlyProjection | undefined;
1243
      fields: Readonly<ShareDB.ProjectionFields> | undefined;
1244
      /** @deprecated Use channels instead */
1245
      channel?: string;
1246
      channels: string[];
1247
      query: any;
1248
      options?: {[key: string]: any};
1249
      db: DB | null;
1250
      snapshotProjection: ShareDB.ReadonlyProjection | null;
1251
    }
1252

1253
    export interface ReadSnapshotsContext extends BaseContext {
1254
      collection: string;
1255
      snapshots: Snapshot[];
1256
      snapshotType: SnapshotType;
1257
      rejectSnapshotRead(snapshot: Snapshot, error: globalThis.Error | string): void;
1258
      rejectSnapshotReadSilent(snapshot: Snapshot, errorMessage: string): void;
1259
    }
1260

1261
    export interface ReceiveContext extends BaseContext {
1262
      data: {[key: string]: any};
1263
    }
1264

1265
    export interface ReplyContext extends BaseContext {
1266
      request: ShareDB.ClientRequest;
1267
      reply: {[key: string]: any};
1268
    }
1269

1270
    export type SnapshotType = 'current' | 'byVersion' | 'byTimestamp';
1271
  }
1272
}
1273

1274
emitter.mixin(Backend);
3 ✔
1275

1276
function destroyStreams(streams) {
1277
  for (var id in streams) {
12 ✔
1278
    streams[id].destroy();
15 ✔
1279
  }
1280
}
1281
function uniqueIds(ids) {
1282
  var seen = Object.create(null);
33 ✔
1283
  return ids.filter(function(id) {
33 ✔
1284
    if (seen[id]) return false;
66 ✔
1285
    seen[id] = true;
63 ✔
1286
    return true;
63 ✔
1287
  });
1288
}
1289

1290
function getExtraDb(backend, name) {
1291
  if (typeof name !== 'string' || !util.hasOwn(backend.extraDbs, name)) return null;
42 ✔
1292
  return backend.extraDbs[name];
6 ✔
1293
}
1294

1295
function pluckIds(snapshots) {
1296
  var ids: string[] = [];
384 ✔
1297
  for (var i = 0; i < snapshots.length; i++) {
384 ✔
1298
    ids.push(snapshots[i].id);
324 ✔
1299
  }
1300
  return ids;
384 ✔
1301
}
1302

1303
function filterOpsInPlaceBeforeTimestamp(ops, timestamp) {
1304
  for (var i = 0; i < ops.length; i++) {
39 ✔
1305
    var op = ops[i];
93 ✔
1306
    var opTimestamp = op.m && op.m.ts;
93 ✔
1307
    if (opTimestamp > timestamp) {
93 ✔
1308
      ops.length = i;
30 ✔
1309
      return;
30 ✔
1310
    }
1311
  }
1312
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc