Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

All notable changes to this project will be documented in this file.

## [Unreleased]

### Added
- **Turn pushed edits into tracked changes** - `suggestChanges(projectId, path, edits)` makes edits that reached Overleaf as plain text, through git, `olcli push` or a sync, show up as tracked changes, as if they had been typed in Reviewing mode. Each edit is given as the old and new text with some text around it; olcli finds the new text, undoes the edit without tracking and redoes it with tracking (`meta.tc` on the update, as the editor sends it). The text ends up as it was, so a git clone that pushed the edit has nothing new to pull. An edit whose new text is not on Overleaf yet is reported as `not-pushed` and left alone. sharejs-text-ot docs only; history-ot docs are refused

## [0.17.0] - 2026-11-15

### Added
Expand Down
83 changes: 83 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,20 @@ export function retryDelayMs(retryAfter: string | string[] | undefined, attempt:
return 1000 * 2 ** attempt * (0.75 + random() * 0.5);
}

/** Offset of the occurrence of `needle` nearest to `hint`, or -1. */
function nearestIndex(text: string, needle: string, hint: number): number {
let best = -1;
for (let i = text.indexOf(needle); i !== -1; i = text.indexOf(needle, i + 1)) {
if (best === -1 || Math.abs(i - hint) < Math.abs(best - hint)) best = i;
}
return best;
}

/** The editor names tracked changes by an 18-hex-digit seed plus a counter, and sends the seed as `meta.tc`. */
function trackChangesSeed(): string {
return Array.from({ length: 18 }, () => Math.floor(Math.random() * 16).toString(16)).join('');
}

const DEFAULT_BASE_URL = 'https://www.overleaf.com';
const RESOURCE_PATH_FAILURE_HINT = ' (Perhaps the resource file you specified does not exist in the project?)';

Expand Down Expand Up @@ -260,6 +274,24 @@ export interface AcceptancePlan {

export { RejectConflictError };

/**
* An edit that was made outside Overleaf and pushed as plain text (through
* git, `olcli push` or a sync): `deleted` was replaced by `inserted` between
* `before` and `after`. `suggestChanges` turns it into a tracked change.
*/
export interface SuggestionEdit {
before: string;
after: string;
deleted: string;
inserted: string;
/** About where the edit is in the doc; the match nearest to it wins. */
hint: number;
}

/** done: now a tracked change. not-pushed: Overleaf still has the old text. not-found: neither text is there. */
export type SuggestionResult = 'done' | 'not-pushed' | 'not-found';


export interface AddCommentOptions {
filePath: string;
content: string;
Expand Down Expand Up @@ -2803,6 +2835,57 @@ export class OverleafClient {
return plan;
}

/**
* Turn edits that already reached Overleaf as plain text into tracked
* changes, as if they had been typed in Reviewing mode: each edit is undone
* without tracking and then redone with tracking (the update's `meta.tc`).
* The text ends up as it was, so a git clone that pushed the edit has
* nothing new to pull. An edit whose new text is not in the doc is left
* alone and reported. One socket, one join; sharejs-text-ot docs only.
*/
async suggestChanges(projectId: string, filePath: string, edits: SuggestionEdit[]): Promise<SuggestionResult[]> {
const docs = this.collectProjectDocs(await this.getProjectInfo(projectId));
const wanted = filePath.replace(/^\/+/, '');
const doc = docs.find(item => item.path.replace(/^\/+/, '') === wanted);
if (!doc) {
throw new Error(`Doc not found: ${filePath}`);
}

const session = await this.openProjectSocket(projectId);
try {
const joinedDoc = await this.joinDocument(session, doc.id);
if (joinedDoc.type !== 'sharejs-text-ot') {
throw new Error(`${doc.path}: turning edits into tracked changes is not supported for history-ot docs yet`);
}
const content = joinedDoc.content;
let version = joinedDoc.version;
const send = async (op: ShareJsTextOp[], tc?: string) => {
await this.socketRpc(session, 'applyOtUpdate', [doc.id, { doc: doc.id, op, v: version, ...(tc ? { meta: { tc } } : {}) }]);
version++;
};

const results: SuggestionResult[] = [];
for (const edit of edits) {
const from = edit.hint - edit.before.length;
const at = edit.inserted === edit.deleted ? -1 : nearestIndex(content, edit.before + edit.inserted + edit.after, from);
if (at === -1) {
results.push(nearestIndex(content, edit.before + edit.deleted + edit.after, from) === -1 ? 'not-found' : 'not-pushed');
continue;
}
const p = at + edit.before.length;
// Each edit leaves the text as it found it, so the offsets of the next edits stay valid.
const undo: ShareJsTextOp[] = [...(edit.inserted ? [{ p, d: edit.inserted }] : []), ...(edit.deleted ? [{ p, i: edit.deleted }] : [])];
const redo: ShareJsTextOp[] = [...(edit.deleted ? [{ p, d: edit.deleted }] : []), ...(edit.inserted ? [{ p, i: edit.inserted }] : [])];
await send(undo);
await send(redo, trackChangesSeed());
results.push('done');
}
return results;
} finally {
await this.closeProjectSocket(session);
}
}

async resolveComment(projectId: string, threadId: string): Promise<ProjectComment> {
const comment = await this.findComment(projectId, threadId);

Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export {
DEFAULT_COMMENT_CONCURRENCY,
MAX_COMMENT_CONCURRENCY,
type AddCommentOptions,
type SuggestionEdit,
type SuggestionResult,
type TrackedChange,
type ListTrackedChangesOptions,
type ProjectReview,
Expand Down
35 changes: 35 additions & 0 deletions test/tracked-changes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,41 @@ test('not found error explains premium only when the project has no tracked chan
await assert.rejects(some.client.acceptTrackedChanges('p', ['x']), (err: Error) => /not found: x$/.test(err.message));
});

test('suggestChanges undoes a pushed edit untracked, redoes it tracked, and leaves unpushed edits alone', async () => {
const client: any = new OverleafClient({ cookies: {}, csrf: 'c' });
client.getProjectInfo = async () => ({ rootFolder: [{ docs: [{ _id: 'd1', name: 'main.tex' }], folders: [] }] });
client.openProjectSocket = async () => ({});
client.closeProjectSocket = async () => {};
client.joinDocument = async () => ({ docId: 'd1', content: 'The new cat sat. The new dog.', lines: [], version: 7, type: 'sharejs-text-ot', ranges: {} });
const sent: any[] = [];
client.socketRpc = async (_s: object, name: string, args: any[]) => { sent.push([name, args[1]]); return []; };

const res = await client.suggestChanges('p', '/main.tex', [
{ before: 'The ', deleted: 'old', inserted: 'new', after: ' dog', hint: 21 },
{ before: 'cat ', deleted: 'sat', inserted: 'ran', after: '.', hint: 12 },
{ before: 'zzz', deleted: 'a', inserted: 'b', after: 'zzz', hint: 0 }
]);

assert.deepEqual(res, ['done', 'not-pushed', 'not-found']);
assert.equal(sent.length, 2);
assert.deepEqual(sent[0][1].op, [{ p: 21, d: 'new' }, { p: 21, i: 'old' }], 'the nearest "The new" is the second one');
assert.equal(sent[0][1].meta, undefined);
assert.deepEqual(sent[1][1].op, [{ p: 21, d: 'old' }, { p: 21, i: 'new' }]);
assert.match(sent[1][1].meta.tc, /^[0-9a-f]{18}$/);
assert.deepEqual([sent[0][1].v, sent[1][1].v], [7, 8]);
});

test('suggestChanges refuses history-ot docs', async () => {
const client: any = new OverleafClient({ cookies: {}, csrf: 'c' });
client.getProjectInfo = async () => ({ rootFolder: [{ docs: [{ _id: 'd1', name: 'main.tex' }], folders: [] }] });
client.openProjectSocket = async () => ({});
let closed = false;
client.closeProjectSocket = async () => { closed = true; };
client.joinDocument = async () => ({ docId: 'd1', content: 'x', lines: ['x'], version: 1, type: 'history-ot', ranges: {} });
await assert.rejects(client.suggestChanges('p', 'main.tex', []), /history-ot/);
assert.equal(closed, true);
});

test('the package entry exports the tracked-change API', async () => {
const entry = await import('../src/index.js');
assert.equal(entry.RejectConflictError, RejectConflictError);
Expand Down
Loading