diff --git a/CHANGELOG.md b/CHANGELOG.md index da0bb9d..36aae68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/client.ts b/src/client.ts index 430b616..a71f0ed 100644 --- a/src/client.ts +++ b/src/client.ts @@ -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?)'; @@ -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; @@ -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 { + 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 { const comment = await this.findComment(projectId, threadId); diff --git a/src/index.ts b/src/index.ts index 172d309..6b10a19 100644 --- a/src/index.ts +++ b/src/index.ts @@ -33,6 +33,8 @@ export { DEFAULT_COMMENT_CONCURRENCY, MAX_COMMENT_CONCURRENCY, type AddCommentOptions, + type SuggestionEdit, + type SuggestionResult, type TrackedChange, type ListTrackedChangesOptions, type ProjectReview, diff --git a/test/tracked-changes.test.ts b/test/tracked-changes.test.ts index 96e4a96..34a1a8e 100644 --- a/test/tracked-changes.test.ts +++ b/test/tracked-changes.test.ts @@ -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);