From 7a69e7533db2fc827cb6a744153f252fa1bad5ae Mon Sep 17 00:00:00 2001 From: Steve Oney Date: Mon, 13 Aug 2018 13:53:25 -0400 Subject: [PATCH] adding sharedb types --- types/sharedb/index.d.ts | 150 +++++++++++++++++++++++++++ types/sharedb/sharedb-tests.ts | 47 +++++++++ types/sharedb/tsconfig.json | 26 +++++ types/sharedb/tslint.json | 79 ++++++++++++++ types/sharedb/websocketJSONStream.ts | 26 +++++ 5 files changed, 328 insertions(+) create mode 100644 types/sharedb/index.d.ts create mode 100644 types/sharedb/sharedb-tests.ts create mode 100644 types/sharedb/tsconfig.json create mode 100644 types/sharedb/tslint.json create mode 100644 types/sharedb/websocketJSONStream.ts diff --git a/types/sharedb/index.d.ts b/types/sharedb/index.d.ts new file mode 100644 index 0000000000..1317174866 --- /dev/null +++ b/types/sharedb/index.d.ts @@ -0,0 +1,150 @@ +// Type definitions for sharedb v1.0.0-beta.10 +// Project: https://github.com/share/sharedb +// Definitions by: Steve Oney +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace ShareDB { + type DocumentID = string; + type Path = ReadonlyArray + type Snapshot = number; + + interface AddNumOp { p:Path, na:number } + + interface ListInsertOp { p:Path, li:any } + interface ListDeleteOp { p:Path, ld:any } + interface ListReplaceOp { p:Path, li:any, ld:any } + interface ListMoveOp { p:Path, lm:any } + + interface ObjectInsertOp { p:Path, oi:any } + interface ObjectDeleteOp { p:Path, od:any } + interface ObjectReplaceOp { p:Path, oi:any, od:any } + + interface StringInsertOp { p:Path, si:string } + interface StringDeleteOp { p:Path, sd:string } + + interface SubtypeOp { p:Path, t:string, o:any } + + type Op = AddNumOp | ListInsertOp | ListDeleteOp | ListReplaceOp | ListMoveOp | ObjectInsertOp | ObjectDeleteOp | ObjectReplaceOp | StringInsertOp | StringDeleteOp | SubtypeOp; + + interface RawOp { + src:string, + seq:number, + v:number, + op:Array, + m:any, + c:string, + d:string + } + type OTType = 'ot-text' | 'ot-json0' | 'ot-text-tp2' | 'rich-text'; + type Action = 'connect'|'op'|'doc'|'query'|'submit'|'apply'|'commit'|'after submit'|'receive'; + interface Error { + code:number, + message:string + } + interface ShareDBSourceOptions { source?:boolean } + interface ShareDBCreateOptions extends ShareDBSourceOptions{} + interface ShareDBDelOptions extends ShareDBSourceOptions{} + interface ShareDBSubmitOpOptions extends ShareDBSourceOptions{} + + type Callback = (err:ShareDB.Error)=>any; + + export class Doc { + type:string; + id:DocumentID; + data:any; + fetch:(callback:(err:ShareDB.Error)=>void) => void; + subscribe:(callback:(err:ShareDB.Error)=>void) => void + on:(event:'load'|'create'|'before op'|'op'|'del'|'error', callback:(...args:Array)=>any)=>void; + ingestSnapshot:(snapshot:Snapshot, callback: Callback)=>void; + destroy:()=>void; + create(data:any, callback?:Callback): void; + create(data:any, type?:OTType, callback?:Callback):void; + create(data:any, type?:OTType, options?:ShareDBCreateOptions, callback?:Callback):void; + submitOp:(data:ReadonlyArray, options?:ShareDBSubmitOpOptions, callback?:Callback)=>void; + del:(options:ShareDBDelOptions, callback:(err:ShareDB.Error)=>void)=>void + removeListener:(eventName:string, listener:Function)=>void + } + + class Query { + ready:boolean; + results:Array; + extra:any; + on:(event:'ready'|'error'|'changed'|'insert'|'move'|'remove'|'extra', callback:(...args:Array)=>any)=>any; + destroy:()=>void; + } +} + +declare module 'sharedb/lib/client' { + export type Doc = ShareDB.Doc; + export type Op = ShareDB.Op; + export type Action = ShareDB.Action; + export class Connection { + constructor(ws:WebSocket); + public get(collectionName:string, documentID:ShareDB.DocumentID):ShareDB.Doc + public createFetchQuery(collectionName:string, query:string, options:{results?:Array}, callback:(err:ShareDB.Error, results:any)=>any):ShareDB.Query + public createSubscribeQuery(collectionName:string, query:string, options:{results?:Array}, callback:(err:ShareDB.Error, results:any)=>any):ShareDB.Query + } +} + +declare module 'sharedb' { + class ShareDBServer { + constructor(options?:{db?:ShareDBServer.DB, pubsub?:ShareDBServer.PubSub, disableDocAction?: boolean, disableSpaceDelimitedActions?: boolean}); + public connect:()=>ShareDBServer.Connection; + public addProjection(name:string, collection:string, fields:{}):any; + public listen(stream:any):void; + public close(callback?:(err:ShareDBServer.Error)=>any):void; + public use(action:ShareDB.Action, fn:ShareDBServer.UseCallback); + public types:{ + register:Function + }; + } + namespace ShareDBServer { + type UseCallback = ((request:{action:ShareDB.Action,agent:any,req:any,collection:string,id:string,query:any,op:ShareDB.RawOp}, callback:Function)=>void); + interface Error { + code:number, + message:string + } + + interface DB { } + + class MemoryDB implements DB { } + export interface IPubSubOptions { + prefix?: string; + } + export interface IStream { + id: string; + } + export abstract class PubSub { + private static shallowCopy(obj: any); + protected prefix?: string; + protected nextStreamId: number; + protected streamsCount: number; + protected streams: { + [channel: string]: IStream; + }; + protected subscribed: { + [channel: string]: boolean; + }; + protected constructor(options?: IPubSubOptions); + close(callback?: (err:Error|null) => void): void; + publish(channels: string[], data: {[k: string]: any}, callback: (err: Error | null) => void): void; + subscribe(channel: string, callback: (err: Error | null, stream?: IStream) => void): void; + protected abstract _subscribe(channel: string, callback: (err: Error | null) => void): void; + protected abstract _unsubscribe(channel: string, callback: (err: Error | null) => void): void; + protected abstract _publish(channels: string[], data: Object, callback: (err: Error | null) => void): void; + protected _emit(channel: string, data: {[k: string]: any}): void; + private _createStream(channel); + private _removeStream(channel, stream); + } + type Doc = ShareDB.Doc; + type Op = ShareDB.Op; + type Action = ShareDB.Action; + class Connection { + constructor(ws:WebSocket); + public get(collectionName:string, documentID:ShareDB.DocumentID):ShareDB.Doc + public createFetchQuery(collectionName:string, query:string, options:{results?:Array}, callback:(err:ShareDB.Error, results:any)=>any):ShareDB.Query + public createSubscribeQuery(collectionName:string, query:string, options:{results?:Array}, callback:(err:ShareDB.Error, results:any)=>any):ShareDB.Query + } + } + export = ShareDBServer; +} \ No newline at end of file diff --git a/types/sharedb/sharedb-tests.ts b/types/sharedb/sharedb-tests.ts new file mode 100644 index 0000000000..b156b60965 --- /dev/null +++ b/types/sharedb/sharedb-tests.ts @@ -0,0 +1,47 @@ +/// +import * as ShareDB from 'sharedb'; +import * as http from 'http'; +import * as WebSocket from 'ws'; +import { WebSocketJSONStream } from './websocketJSONStream'; + +const backend = new ShareDB(); +const connection = backend.connect(); +const doc = connection.get('examples', 'counter'); + +doc.fetch((err) => { + if(err) { throw err; } + if(doc.type === null) { + doc.create({numClicks:0}, startServer); + } else { + startServer(); + } +}); + +function startServer() { + var server = http.createServer(); + + // Connect any incoming WebSocket connection to ShareDB + var wss = new WebSocket.Server({server: server}); + wss.on('connection', function(ws, req) { + var stream = new WebSocketJSONStream(ws); + backend.listen(stream); + }); + + server.listen(8080); + // console.log('Listening on http://localhost:8080'); + startClient(() => { + server.close(); + wss.close(); + }); +} + +function startClient(callback) { + var sharedb = require('sharedb/lib/client'); + var socket = new WebSocket('ws://localhost:8080'); + var connection = new sharedb.Connection(socket); + var doc = connection.get('examples', 'counter'); + doc.subscribe(() => { + doc.submitOp([{p: ['numClicks'], na: 1}]); + callback(); + }); +} \ No newline at end of file diff --git a/types/sharedb/tsconfig.json b/types/sharedb/tsconfig.json new file mode 100644 index 0000000000..fcbe6c741a --- /dev/null +++ b/types/sharedb/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": false, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sharedb-tests.ts" + ] +} \ No newline at end of file diff --git a/types/sharedb/tslint.json b/types/sharedb/tslint.json new file mode 100644 index 0000000000..b7cf998e42 --- /dev/null +++ b/types/sharedb/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} \ No newline at end of file diff --git a/types/sharedb/websocketJSONStream.ts b/types/sharedb/websocketJSONStream.ts new file mode 100644 index 0000000000..f21d2fa94e --- /dev/null +++ b/types/sharedb/websocketJSONStream.ts @@ -0,0 +1,26 @@ +import {Duplex} from 'stream'; +import * as WebSocket from 'ws'; + +//Adapted from https://github.com/avital/websocket-json-stream +export class WebSocketJSONStream extends Duplex { + constructor(private readonly ws:WebSocket) { + super({objectMode: true}); + this.ws.on('message', (msg: string) => { + this.push(JSON.parse(msg)) + }); + this.ws.on('close', () => { + this.push(null); // end readable stream + this.end(); // end writable stream + + this.emit('close'); + this.emit('end'); + }); + this.on('error', function() { ws.close(); }); + this.on('end', function() { ws.close(); }); + }; + public _read():void {}; + public _write(msg:any, encoding:string, next:Function):void { + this.ws.send(JSON.stringify(msg)); + next(); + }; +}; \ No newline at end of file