@aloth/olcli 0.16.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -19,14 +19,30 @@ import { readFileSync } from 'node:fs';
19
19
  import { dirname, join } from 'node:path';
20
20
  import { fileURLToPath } from 'node:url';
21
21
  import { routeRequest } from './proxy.js';
22
- import { RejectConflictError, buildUserDirectory, planRejection, renderRejectionDiff, describeAuthor, parseHistoryOtChanges, parseShareJsChanges } from './tracked-changes.js';
22
+ import { RejectConflictError, buildUserDirectory, planRejection, renderRejectionDiff, describeAuthor, parseHistoryOtChanges, parseShareJsChanges, matchSuggestionEdit, trackedParts, generateIdSeed } from './tracked-changes.js';
23
23
  import { planEntityMove } from './move-plan.js';
24
24
  import { matchProject } from './project-match.js';
25
- import { HttpStatusError, ProjectOwnerOnlyError, SessionExpiredError, httpError, isAuthStatus } from './errors.js';
25
+ import { CaptchaRequiredError, HttpStatusError, ProjectOwnerOnlyError, SessionExpiredError, httpError, isAuthStatus } from './errors.js';
26
26
  // Read version from package.json
27
27
  const __dirname = dirname(fileURLToPath(import.meta.url));
28
28
  const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));
29
29
  const USER_AGENT = `olcli/${pkg.version}`;
30
+ /** How often a request answered with HTTP 429 is retried before the 429 is returned to the caller. */
31
+ const MAX_429_RETRIES = 5;
32
+ /** Longest wait olcli accepts from a Retry-After header, so a server cannot stall a command for an hour. */
33
+ export const MAX_RETRY_AFTER_MS = 60_000;
34
+ /**
35
+ * How long to wait before retry number `attempt + 1` of a request answered with 429. A Retry-After value in
36
+ * seconds wins when present, capped at 60 s; a missing, non-numeric or negative value falls back to exponential
37
+ * backoff (1, 2, 4, 8, 16 s with +/-25% jitter).
38
+ */
39
+ export function retryDelayMs(retryAfter, attempt, random = Math.random) {
40
+ const raw = Array.isArray(retryAfter) ? retryAfter[0] : retryAfter;
41
+ const seconds = raw === undefined || raw.trim() === '' ? NaN : Number(raw);
42
+ if (Number.isFinite(seconds) && seconds >= 0)
43
+ return Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);
44
+ return 1000 * 2 ** attempt * (0.75 + random() * 0.5);
45
+ }
30
46
  const DEFAULT_BASE_URL = 'https://www.overleaf.com';
31
47
  const RESOURCE_PATH_FAILURE_HINT = ' (Perhaps the resource file you specified does not exist in the project?)';
32
48
  /**
@@ -58,6 +74,60 @@ export function resolveCommentConcurrency(value, env = process.env) {
58
74
  return parsed;
59
75
  }
60
76
  export { RejectConflictError };
77
+ /** Thrown when the account may review but not edit: turning an edit into a suggestion first writes untracked. */
78
+ /**
79
+ * The `errorReason` Overleaf answers a login post with when its reCAPTCHA
80
+ * check fails (HTTP 400, JSON). Sent before the credentials are checked, so
81
+ * it also means nothing is known about the password.
82
+ */
83
+ export const CAPTCHA_ERROR_REASON = 'cannot_verify_user_not_robot';
84
+ function parseJsonObject(text) {
85
+ try {
86
+ const parsed = JSON.parse(text);
87
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined;
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ }
93
+ /** True when a login response body says the reCAPTCHA check failed. */
94
+ export function isCaptchaRejection(body) {
95
+ return parseJsonObject(body)?.errorReason === CAPTCHA_ERROR_REASON;
96
+ }
97
+ /**
98
+ * True when a login response body is JSON that gives a reason of its own
99
+ * (`errorReason` or `message`), such as a wrong password. Such an answer is
100
+ * not second-guessed with the login page markers.
101
+ */
102
+ function hasLoginMessage(body) {
103
+ const parsed = parseJsonObject(body);
104
+ return Boolean(parsed && (parsed.errorReason || parsed.message));
105
+ }
106
+ /**
107
+ * True when an Overleaf login page has reCAPTCHA switched on for login:
108
+ * `recaptchaDisabled.login === false` in the `ol-ExposedSettings` meta data,
109
+ * or, on releases without that setting, the reCAPTCHA script or widget on the
110
+ * page. Self-hosted instances without reCAPTCHA have neither.
111
+ */
112
+ export function loginPageRequiresCaptcha(html) {
113
+ const $ = cheerio.load(html);
114
+ const settingsText = $('meta[name="ol-ExposedSettings"]').attr('content');
115
+ if (settingsText) {
116
+ const settings = parseJsonObject(settingsText);
117
+ const disabled = settings?.recaptchaDisabled;
118
+ if (disabled && typeof disabled === 'object' && typeof disabled.login === 'boolean') {
119
+ return !disabled.login && Boolean(settings?.recaptchaSiteKey || settings?.recaptchaSiteKeyV3 || settings?.recaptchaEnterpriseSiteKey);
120
+ }
121
+ }
122
+ const scriptSources = $('script[src]').toArray().map(el => $(el).attr('src') ?? '');
123
+ return scriptSources.some(src => /\/recaptcha\/(api|enterprise)\.js/.test(src)) || $('.g-recaptcha').length > 0;
124
+ }
125
+ export class SuggestionPermissionError extends Error {
126
+ constructor(path, detail) {
127
+ super(`${path}: this account needs edit access to the project to turn edits into suggestions; review-only access cannot do it, because the edit is first undone without tracking. Nothing was changed${detail ? ` (${detail})` : ''}`);
128
+ this.name = 'SuggestionPermissionError';
129
+ }
130
+ }
61
131
  export class OverleafClient {
62
132
  cookies;
63
133
  csrf;
@@ -236,12 +306,19 @@ export class OverleafClient {
236
306
  });
237
307
  bootstrapClient.applySetCookieHeaders(loginResponse.headers['set-cookie']);
238
308
  if (![302, 303].includes(loginResponse.status)) {
239
- const loginFailure = typeof loginResponse.body === 'string'
240
- ? OverleafClient.isLoginPage(cheerio.load(loginResponse.body))
241
- : false;
309
+ const responseText = typeof loginResponse.body === 'string' ? loginResponse.body : '';
310
+ if (isCaptchaRejection(responseText)) {
311
+ throw new CaptchaRequiredError(new URL(baseUrl).host, loginResponse.status);
312
+ }
313
+ const loginFailure = responseText ? OverleafClient.isLoginPage(cheerio.load(responseText)) : false;
242
314
  if (loginFailure) {
243
315
  throw new Error('Password login failed. Email or password may be incorrect.');
244
316
  }
317
+ // An answer that does not say why: if the login page asked for a
318
+ // captcha, that is the most likely reason.
319
+ if (!hasLoginMessage(responseText) && loginPageRequiresCaptcha(loginHtml)) {
320
+ throw new CaptchaRequiredError(new URL(baseUrl).host, loginResponse.status);
321
+ }
245
322
  throw new HttpStatusError('Password login failed', loginResponse.status);
246
323
  }
247
324
  const projectUrl = new URL(loginResponse.headers.location || '/project', baseUrl).toString();
@@ -496,7 +573,17 @@ export class OverleafClient {
496
573
  req.end();
497
574
  });
498
575
  };
499
- return doRequest(url, maxRedirects);
576
+ // Overleaf answers bursts with 429 before doing anything, so a retry is safe for every method. It sends no
577
+ // Retry-After in practice and its limit lasts about 25 s, so wait 1, 2, 4, 8 and 16 s (about 30 s in all), with
578
+ // +/-25% jitter so parallel callers do not retry in step. A Retry-After header wins when present, capped at 60 s.
579
+ for (let attempt = 0;; attempt++) {
580
+ const res = await doRequest(url, maxRedirects);
581
+ if (res.status !== 429 || options.retryOn429 === false || attempt >= MAX_429_RETRIES)
582
+ return res;
583
+ const waitMs = retryDelayMs(res.headers['retry-after'], attempt);
584
+ this.logVerbose(`${method} ${url} -> 429, retrying in ${Math.round(waitMs)}ms (${attempt + 1}/${MAX_429_RETRIES})`);
585
+ await new Promise(resolve => setTimeout(resolve, waitMs));
586
+ }
500
587
  }
501
588
  /**
502
589
  * Get all projects (not archived, not trashed)
@@ -990,12 +1077,14 @@ export class OverleafClient {
990
1077
  }
991
1078
  return docs;
992
1079
  }
993
- async openProjectSocket(projectId) {
1080
+ /** `retryOn429: false` for sockets the caller can do without: a rate-limited one then fails at once. */
1081
+ async openProjectSocket(projectId, { retryOn429 = true } = {}) {
994
1082
  const handshakeUrl = `${this.baseUrl}/socket.io/1/?projectId=${encodeURIComponent(projectId)}&t=${Date.now()}`;
995
1083
  const handshakeResponse = await this.httpRequest(handshakeUrl, {
996
1084
  headers: { 'Cookie': this.getCookieHeader(), 'User-Agent': USER_AGENT },
997
1085
  expect: 'text',
998
- timeoutMs: 5000
1086
+ timeoutMs: 5000,
1087
+ retryOn429
999
1088
  });
1000
1089
  if (!handshakeResponse.ok) {
1001
1090
  throw httpError('Failed to open project socket', handshakeResponse.status);
@@ -1016,7 +1105,13 @@ export class OverleafClient {
1016
1105
  if (!packet.startsWith('5:::'))
1017
1106
  return false;
1018
1107
  try {
1019
- return JSON.parse(packet.slice(4))?.name === 'joinProjectResponse';
1108
+ const payload = JSON.parse(packet.slice(4));
1109
+ if (payload?.name !== 'joinProjectResponse')
1110
+ return false;
1111
+ const level = payload?.args?.[0]?.permissionsLevel;
1112
+ if (typeof level === 'string')
1113
+ session.permissionsLevel = level;
1114
+ return true;
1020
1115
  }
1021
1116
  catch {
1022
1117
  return false;
@@ -1950,7 +2045,7 @@ export class OverleafClient {
1950
2045
  const extra = Array.from({ length: Math.min(concurrency, docs.length) - 1 }, async () => {
1951
2046
  let session;
1952
2047
  try {
1953
- session = await this.openProjectSocket(projectId);
2048
+ session = await this.openProjectSocket(projectId, { retryOn429: false });
1954
2049
  }
1955
2050
  catch (error) {
1956
2051
  if (error.status === 429)
@@ -1982,7 +2077,7 @@ export class OverleafClient {
1982
2077
  const joinedDocs = await this.joinDocuments(projectId, docs, resolveCommentConcurrency(options.concurrency));
1983
2078
  return {
1984
2079
  comments: this.commentsFromDocs(docs, joinedDocs, threads, options.status || 'all', contextLines),
1985
- changes: await this.changesFromDocs(projectId, projectInfo, docs, joinedDocs, contextLines)
2080
+ changes: await this.changesFromDocs(projectId, projectInfo, docs, joinedDocs, contextLines, options.surroundingChars)
1986
2081
  };
1987
2082
  }
1988
2083
  commentsFromDocs(docs, joinedDocs, threads, status, contextLines) {
@@ -2081,9 +2176,9 @@ export class OverleafClient {
2081
2176
  const projectInfo = await this.getProjectInfo(projectId);
2082
2177
  const docs = this.collectProjectDocs(projectInfo);
2083
2178
  const joinedDocs = await this.joinDocuments(projectId, docs, resolveCommentConcurrency(options.concurrency));
2084
- return this.changesFromDocs(projectId, projectInfo, docs, joinedDocs, options.contextLines || 0);
2179
+ return this.changesFromDocs(projectId, projectInfo, docs, joinedDocs, options.contextLines || 0, options.surroundingChars);
2085
2180
  }
2086
- async changesFromDocs(projectId, projectInfo, docs, joinedDocs, contextLines) {
2181
+ async changesFromDocs(projectId, projectInfo, docs, joinedDocs, contextLines, surroundingChars = 0) {
2087
2182
  const perDoc = joinedDocs.map(doc => this.docTrackedChanges(doc));
2088
2183
  const anyChanges = perDoc.some(doc => doc.changes.length > 0);
2089
2184
  const users = buildUserDirectory(projectInfo, anyChanges ? await this.getChangesUsers(projectId) : []);
@@ -2092,6 +2187,7 @@ export class OverleafClient {
2092
2187
  const { changes, visibleContent } = perDoc[index];
2093
2188
  for (const change of changes) {
2094
2189
  const location = this.positionToLineColumn(visibleContent, change.position);
2190
+ const end = change.kind === 'insert' ? change.position + change.text.length : change.position;
2095
2191
  result.push({
2096
2192
  id: change.id,
2097
2193
  docId: doc.id,
@@ -2103,7 +2199,11 @@ export class OverleafClient {
2103
2199
  text: change.text,
2104
2200
  author: describeAuthor(change.userId, users),
2105
2201
  ...(change.timestamp ? { timestamp: change.timestamp } : {}),
2106
- ...(contextLines > 0 ? { context: this.buildCommentContext(visibleContent, location.line, contextLines) } : {})
2202
+ ...(contextLines > 0 ? { context: this.buildCommentContext(visibleContent, location.line, contextLines) } : {}),
2203
+ ...(surroundingChars > 0 ? {
2204
+ before: visibleContent.slice(Math.max(0, change.position - surroundingChars), change.position),
2205
+ after: visibleContent.slice(end, end + surroundingChars)
2206
+ } : {})
2107
2207
  });
2108
2208
  }
2109
2209
  }
@@ -2135,16 +2235,7 @@ export class OverleafClient {
2135
2235
  for (const change of selected)
2136
2236
  byDoc.set(change.docId, [...(byDoc.get(change.docId) ?? []), change]);
2137
2237
  for (const [docId, changes] of byDoc) {
2138
- const response = await this.httpRequest(`${this.baseUrl}/project/${projectId}/doc/${docId}/changes/accept`, {
2139
- method: 'POST',
2140
- headers: this.getHeaders(true),
2141
- body: JSON.stringify({ change_ids: changes.map(change => change.id) }),
2142
- expect: 'text'
2143
- });
2144
- if (!response.ok) {
2145
- throw httpError(`Failed to accept tracked changes in ${changes[0].path}`, response.status);
2146
- }
2147
- this.applySetCookieHeaders(response.headers['set-cookie']);
2238
+ await this.acceptTrackedChangesInDoc(projectId, docId, changes.map(change => change.id), changes[0].path);
2148
2239
  }
2149
2240
  const after = await this.listTrackedChanges(projectId);
2150
2241
  const remaining = selected.filter(change => after.some(other => other.docId === change.docId && other.id === change.id));
@@ -2153,6 +2244,24 @@ export class OverleafClient {
2153
2244
  }
2154
2245
  return selected;
2155
2246
  }
2247
+ /**
2248
+ * Accept tracked changes of one doc with a single request, the editor's
2249
+ * route, without listing the project before or after. For callers that
2250
+ * already hold the changes and their doc id and re-read the project anyway;
2251
+ * `acceptTrackedChanges` resolves ids and checks the result for you.
2252
+ */
2253
+ async acceptTrackedChangesInDoc(projectId, docId, ids, label = docId) {
2254
+ const response = await this.httpRequest(`${this.baseUrl}/project/${projectId}/doc/${docId}/changes/accept`, {
2255
+ method: 'POST',
2256
+ headers: this.getHeaders(true),
2257
+ body: JSON.stringify({ change_ids: ids }),
2258
+ expect: 'text'
2259
+ });
2260
+ if (!response.ok) {
2261
+ throw httpError(`Failed to accept tracked changes in ${label}`, response.status);
2262
+ }
2263
+ this.applySetCookieHeaders(response.headers['set-cookie']);
2264
+ }
2156
2265
  selectTrackedChanges(all, ids) {
2157
2266
  const wanted = [...new Set(ids)];
2158
2267
  if (wanted.length === 0)
@@ -2280,6 +2389,179 @@ export class OverleafClient {
2280
2389
  }
2281
2390
  return plan;
2282
2391
  }
2392
+ /**
2393
+ * Work out what `suggestChanges` would do with `edits`, without writing:
2394
+ * per edit the outcome and, for an edit that would become a suggestion or
2395
+ * is already tracked, its line and column. Refuses history-ot docs, like
2396
+ * `suggestChanges`.
2397
+ */
2398
+ async planSuggestions(projectId, filePath, edits) {
2399
+ const docs = this.collectProjectDocs(await this.getProjectInfo(projectId));
2400
+ const wanted = filePath.replace(/^\/+/, '');
2401
+ const doc = docs.find(item => item.path.replace(/^\/+/, '') === wanted);
2402
+ if (!doc) {
2403
+ throw new Error(`Doc not found: ${filePath}`);
2404
+ }
2405
+ const session = await this.openProjectSocket(projectId);
2406
+ try {
2407
+ const joinedDoc = await this.joinDocument(session, doc.id);
2408
+ if (joinedDoc.type !== 'sharejs-text-ot') {
2409
+ throw new Error(`${doc.path}: turning edits into tracked changes is not supported for history-ot docs yet`);
2410
+ }
2411
+ const changes = parseShareJsChanges(joinedDoc.ranges);
2412
+ const planned = edits.map(edit => {
2413
+ const match = matchSuggestionEdit(joinedDoc.content, changes, edit);
2414
+ const location = match.position === undefined ? undefined : this.positionToLineColumn(joinedDoc.content, match.position);
2415
+ if (match.outcome === 'suggest') {
2416
+ // A repeated edit later in the list must see this one as tracked.
2417
+ if (edit.deleted)
2418
+ changes.push({ id: '', kind: 'delete', position: match.position + edit.inserted.length, text: edit.deleted, userId: null });
2419
+ if (edit.inserted)
2420
+ changes.push({ id: '', kind: 'insert', position: match.position, text: edit.inserted, userId: null });
2421
+ }
2422
+ return { edit, outcome: match.outcome, ...(location ?? {}) };
2423
+ });
2424
+ return { docId: doc.id, path: doc.path, version: joinedDoc.version, permissionsLevel: session.permissionsLevel, edits: planned };
2425
+ }
2426
+ finally {
2427
+ await this.closeProjectSocket(session);
2428
+ }
2429
+ }
2430
+ /**
2431
+ * Delays before each read-back of a doc after `suggestChanges` wrote to it.
2432
+ * The real-time service acknowledges an update when it is queued, so the
2433
+ * new ranges can take a moment to show up.
2434
+ */
2435
+ suggestionVerifyDelaysMs = [0, 300, 700, 1500];
2436
+ /**
2437
+ * Experimental. Turn edits that already reached Overleaf as plain text
2438
+ * (through git, `olcli push` or a sync) into tracked changes, as if they
2439
+ * had been typed in Reviewing mode: each edit is undone without tracking
2440
+ * and then redone with tracking (the update's `meta.tc`). The text ends up
2441
+ * as it was, so a git clone that pushed the edit has nothing new to pull.
2442
+ *
2443
+ * Limits: sharejs-text-ot docs only; history-ot docs are refused. Between
2444
+ * the undo and the redo, collaborators who have the doc open see the old
2445
+ * text for a short moment (about 0.2 s on overleaf.com). The account needs
2446
+ * edit access: the undo is an untracked edit, which review-only access
2447
+ * cannot send.
2448
+ *
2449
+ * One result per edit, in order (see `SuggestionResult`). Edits that are
2450
+ * invalid, unchanged, not pushed, not found or already tracked are left
2451
+ * alone. After writing, the doc is read again and an edit without a
2452
+ * tracked change is reported as `not-tracked` instead of `done`. With
2453
+ * `expectedVersion` (from `planSuggestions`), a doc that changed since is
2454
+ * refused with `RejectConflictError` and nothing is written.
2455
+ */
2456
+ async suggestChanges(projectId, filePath, edits, options = {}) {
2457
+ const docs = this.collectProjectDocs(await this.getProjectInfo(projectId));
2458
+ const wanted = filePath.replace(/^\/+/, '');
2459
+ const doc = docs.find(item => item.path.replace(/^\/+/, '') === wanted);
2460
+ if (!doc) {
2461
+ throw new Error(`Doc not found: ${filePath}`);
2462
+ }
2463
+ const results = [];
2464
+ const written = [];
2465
+ const session = await this.openProjectSocket(projectId);
2466
+ try {
2467
+ const joinedDoc = await this.joinDocument(session, doc.id);
2468
+ if (joinedDoc.type !== 'sharejs-text-ot') {
2469
+ throw new Error(`${doc.path}: turning edits into tracked changes is not supported for history-ot docs yet`);
2470
+ }
2471
+ if (options.expectedVersion !== undefined && joinedDoc.version !== options.expectedVersion) {
2472
+ throw new RejectConflictError(`${doc.path} changed since the preview (version ${options.expectedVersion} -> ${joinedDoc.version}); nothing was written, run it again`);
2473
+ }
2474
+ const content = joinedDoc.content;
2475
+ const changes = parseShareJsChanges(joinedDoc.ranges);
2476
+ const level = session.permissionsLevel;
2477
+ const canEdit = level === undefined || level === 'owner' || level === 'readAndWrite';
2478
+ let version = joinedDoc.version;
2479
+ const send = async (op, tc) => {
2480
+ await this.socketRpc(session, 'applyOtUpdate', [doc.id, { doc: doc.id, op, v: version, ...(tc ? { meta: { tc } } : {}) }]);
2481
+ version++;
2482
+ };
2483
+ for (const edit of edits) {
2484
+ const match = matchSuggestionEdit(content, changes, edit);
2485
+ if (match.outcome !== 'suggest') {
2486
+ results.push(match.outcome === 'invalid' || match.outcome === 'unchanged' || match.outcome === 'not-pushed'
2487
+ || match.outcome === 'not-found' || match.outcome === 'already-tracked' ? match.outcome : 'not-found');
2488
+ continue;
2489
+ }
2490
+ // Refuse before the first write: a review-only account can send the tracked redo but not the untracked undo.
2491
+ if (!canEdit)
2492
+ throw new SuggestionPermissionError(doc.path, `access level ${level}`);
2493
+ const p = match.position;
2494
+ // Each edit leaves the text as it found it, so the offsets of the next edits stay valid.
2495
+ const undo = [...(edit.inserted ? [{ p, d: edit.inserted }] : []), ...(edit.deleted ? [{ p, i: edit.deleted }] : [])];
2496
+ const redo = [...(edit.deleted ? [{ p, d: edit.deleted }] : []), ...(edit.inserted ? [{ p, i: edit.inserted }] : [])];
2497
+ try {
2498
+ await send(undo);
2499
+ }
2500
+ catch (error) {
2501
+ const message = error instanceof Error ? error.message : String(error);
2502
+ if (/not authorized/.test(message)) {
2503
+ throw new SuggestionPermissionError(doc.path, message);
2504
+ }
2505
+ if (/did not return an acknowledgement/.test(message)) {
2506
+ // What a review-only account gets live: the server refuses the untracked undo and drops the socket.
2507
+ throw new SuggestionPermissionError(doc.path, `${message}; if the account does have edit access, check ${doc.path} on Overleaf, since the undo may have arrived without the redo`);
2508
+ }
2509
+ throw error;
2510
+ }
2511
+ const seed = generateIdSeed();
2512
+ await send(redo, seed);
2513
+ written.push({ index: results.length, seed, position: p, edit });
2514
+ results.push('done');
2515
+ // A repeated edit in the same call must see this one as tracked.
2516
+ if (edit.deleted)
2517
+ changes.push({ id: `${seed}-d`, kind: 'delete', position: p + edit.inserted.length, text: edit.deleted, userId: null });
2518
+ if (edit.inserted)
2519
+ changes.push({ id: `${seed}-i`, kind: 'insert', position: p, text: edit.inserted, userId: null });
2520
+ }
2521
+ }
2522
+ finally {
2523
+ await this.closeProjectSocket(session);
2524
+ }
2525
+ if (written.length > 0) {
2526
+ const unverified = await this.unverifiedSuggestions(projectId, doc.id, written);
2527
+ for (const index of unverified)
2528
+ results[index] = 'not-tracked';
2529
+ }
2530
+ return results;
2531
+ }
2532
+ /**
2533
+ * Read a doc again until every written suggestion shows up as a tracked
2534
+ * change, or the read-back delays run out. Returns the result indexes that
2535
+ * never showed up. A change counts when its id starts with the seed sent
2536
+ * with the redo, or, since the ranges tracker merges an insert into an
2537
+ * adjacent one by the same user, when a tracked change covers the edit.
2538
+ */
2539
+ async unverifiedSuggestions(projectId, docId, written) {
2540
+ let missing = written;
2541
+ for (const delay of this.suggestionVerifyDelaysMs) {
2542
+ if (delay > 0)
2543
+ await new Promise(resolve => setTimeout(resolve, delay));
2544
+ const session = await this.openProjectSocket(projectId);
2545
+ let changes;
2546
+ try {
2547
+ changes = parseShareJsChanges((await this.joinDocument(session, docId)).ranges);
2548
+ }
2549
+ finally {
2550
+ await this.closeProjectSocket(session);
2551
+ }
2552
+ missing = missing.filter(item => {
2553
+ const { deleted, inserted } = item.edit;
2554
+ const bySeed = (kind) => changes.some(change => change.kind === kind && change.id.startsWith(item.seed));
2555
+ const parts = trackedParts(changes, item.position, deleted, inserted);
2556
+ const insertOk = inserted === '' || bySeed('insert') || parts.insert;
2557
+ const deleteOk = deleted === '' || bySeed('delete') || parts.delete;
2558
+ return !(insertOk && deleteOk);
2559
+ });
2560
+ if (missing.length === 0)
2561
+ break;
2562
+ }
2563
+ return missing.map(item => item.index);
2564
+ }
2283
2565
  async resolveComment(projectId, threadId) {
2284
2566
  const comment = await this.findComment(projectId, threadId);
2285
2567
  const response = await this.httpRequest(`${this.baseUrl}/project/${projectId}/doc/${comment.docId}/thread/${threadId}/resolve`, {