-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.ts
More file actions
146 lines (120 loc) · 4.27 KB
/
Copy pathindex.ts
File metadata and controls
146 lines (120 loc) · 4.27 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import {
receiveCommitTransaction,
Commit,
CommitJSON,
getVersion,
sendableCommit,
NodeJSON,
} from "@stepwisehq/prosemirror-collab-commit/collab-commit";
import { EditorState } from "prosemirror-state";
export { receiveCommitTransaction, getVersion, Commit, type CommitJSON, type NodeJSON };
export { collab, collabKey } from "./plugin";
export interface CommitsListener {
listen: (
version: number,
options?: { signal?: AbortSignal },
) => AsyncIterableIterator<CommitJSON[]>;
}
export interface CollabClientConfig {
sendCommit: (commit: Commit) => Promise<void>;
listener: CommitsListener;
receiveCommits: (commits: Commit[]) => void;
}
export class CollabClient {
private sending: null | string = null;
private version: number | undefined = undefined;
private seen = new Set<string>();
private controller = new AbortController();
private sendCommit: CollabClientConfig["sendCommit"];
private listener: CollabClientConfig["listener"];
private receiveCommits: CollabClientConfig["receiveCommits"];
constructor(config: CollabClientConfig) {
this.sendCommit = config.sendCommit;
this.receiveCommits = config.receiveCommits;
this.listener = config.listener;
}
async send(editorState: EditorState) {
const commit = sendableCommit(editorState);
if (!commit) return;
// Avoid unnecessary network traffic by skipping commits
// that we're already sending
if (commit.ref === this.sending) return;
this.sending = commit.ref;
try {
await this.sendCommit(commit);
} catch {
// If the send fails, then unset the
// sending ref so that it's possible
// to attempt to send this commit again
// later.
this.sending = null;
}
}
update(config: Partial<Omit<CollabClientConfig, "listener">>) {
if (config.sendCommit) this.sendCommit = config.sendCommit;
if (config.receiveCommits) this.receiveCommits = config.receiveCommits;
}
async listen(editorState: EditorState, signal?: AbortSignal) {
this.version = getVersion(editorState);
if (this.version === undefined) {
throw new Error("EditorState is missing the collab plugin, unable to listen for changes");
}
const getCommitsSignal = AbortSignal.any([...(signal ? [signal] : []), this.controller.signal]);
for await (const commitJSONs of this.listener.listen(this.version, {
signal: getCommitsSignal,
})) {
if (getCommitsSignal.aborted) break;
const commits = commitJSONs.map((json) => Commit.FromJSON(editorState.schema, json));
// Ensure that we don't process the same commit multiple times
const newCommits = commits.filter((commit) => !this.seen.has(commit.ref));
const lastCommit = newCommits[newCommits.length - 1];
if (!lastCommit) continue;
this.version = lastCommit.version;
newCommits.forEach((commit) => this.seen.add(commit.ref));
this.receiveCommits(newCommits);
}
}
}
export interface LongPollListenerOptions {
timeout?: number;
headers?: HeadersInit;
fetch?: typeof globalThis.fetch;
}
export class LongPollListener {
private headers: HeadersInit;
private fetch: typeof globalThis.fetch;
constructor(
private url: URL,
options: LongPollListenerOptions = {},
) {
this.headers = options.headers ?? {};
this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
}
update(headers: HeadersInit) {
this.headers = headers;
}
async *listen(version: number, options: { signal?: AbortSignal } = {}) {
while (!options?.signal || !options.signal.aborted) {
const url = new URL(this.url);
url.searchParams.append("version", version.toString());
try {
const response = await this.fetch(url, {
headers: this.headers,
...(options?.signal && { signal: options.signal }),
});
if (!response.ok) {
throw new Error(`Failed to get commits. ${response.status}: ${response.statusText}`);
}
const commitJSONs = (await response.json()) as CommitJSON[];
yield commitJSONs;
} catch (e) {
console.error(e);
if (options.signal?.aborted) return;
// TODO: Implement a backoff strategy
await new Promise<void>((resolve) => {
setTimeout(() => resolve(), 3_000);
});
}
}
}
}