ChunkTranslator.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. import _ from 'lodash'
  2. import logger from '@overleaf/logger'
  3. import OError from '@overleaf/o-error'
  4. import * as HistoryStoreManager from './HistoryStoreManager.js'
  5. import * as WebApiManager from './WebApiManager.js'
  6. import * as Errors from './Errors.js'
  7. import {
  8. TextOperation,
  9. InsertOp,
  10. RemoveOp,
  11. RetainOp,
  12. Range,
  13. TrackedChangeList,
  14. } from 'overleaf-editor-core'
  15. /**
  16. * @import { RawEditOperation, TrackedChangeRawData } from 'overleaf-editor-core/lib/types'
  17. */
  18. export function convertToSummarizedUpdates(chunk, callback) {
  19. const version = chunk.chunk.startVersion
  20. const { files } = chunk.chunk.history.snapshot
  21. const builder = new UpdateSetBuilder(version, files)
  22. for (const change of chunk.chunk.history.changes) {
  23. try {
  24. builder.applyChange(change)
  25. } catch (error1) {
  26. const error = error1
  27. return callback(error)
  28. }
  29. }
  30. callback(null, builder.summarizedUpdates)
  31. }
  32. export function convertToDiffUpdates(
  33. projectId,
  34. chunk,
  35. pathname,
  36. fromVersion,
  37. toVersion,
  38. callback
  39. ) {
  40. let error
  41. let version = chunk.chunk.startVersion
  42. const { files } = chunk.chunk.history.snapshot
  43. const builder = new UpdateSetBuilder(version, files)
  44. let file = null
  45. for (const change of chunk.chunk.history.changes) {
  46. // Because we're referencing by pathname, which can change, we
  47. // want to get the last file in the range fromVersion:toVersion
  48. // that has the pathname we want. Note that this might not exist yet
  49. // at fromVersion, so we'll just settle for the last existing one we find
  50. // after that.
  51. if (fromVersion <= version && version <= toVersion) {
  52. const currentFile = builder.getFile(pathname)
  53. if (currentFile) {
  54. file = currentFile
  55. }
  56. }
  57. try {
  58. builder.applyChange(change)
  59. } catch (error1) {
  60. error = error1
  61. return callback(error)
  62. }
  63. version += 1
  64. }
  65. // Versions act as fence posts, with updates taking us from one to another,
  66. // so we also need to check after the final update, when we're at the last version.
  67. if (fromVersion <= version && version <= toVersion) {
  68. const currentFile = builder.getFile(pathname)
  69. if (currentFile) {
  70. file = currentFile
  71. }
  72. }
  73. // return an empty diff if the file was flagged as missing with an explicit null
  74. if (builder.getFile(pathname) === null) {
  75. return callback(null, { initialContent: '', updates: [] })
  76. }
  77. if (file == null) {
  78. error = new Errors.NotFoundError(
  79. `pathname '${pathname}' not found in range`
  80. )
  81. return callback(error)
  82. }
  83. WebApiManager.getHistoryId(projectId, (err, historyId) => {
  84. if (err) {
  85. return callback(err)
  86. }
  87. file.getDiffUpdates(historyId, fromVersion, toVersion, callback)
  88. })
  89. }
  90. class UpdateSetBuilder {
  91. constructor(startVersion, files) {
  92. this.version = startVersion
  93. this.summarizedUpdates = []
  94. this.files = Object.create(null)
  95. for (const pathname in files) {
  96. // initialize file from snapshot
  97. const data = files[pathname]
  98. this.files[pathname] = new File(pathname, data, startVersion)
  99. }
  100. }
  101. getFile(pathname) {
  102. return this.files[pathname]
  103. }
  104. applyChange(change) {
  105. const timestamp = new Date(change.timestamp)
  106. let authors = _.map(change.authors, id => {
  107. if (id == null) {
  108. return null
  109. }
  110. return id
  111. })
  112. authors = authors.concat(change.v2Authors || [])
  113. this.currentUpdate = {
  114. meta: {
  115. users: authors,
  116. start_ts: timestamp.getTime(),
  117. end_ts: timestamp.getTime(),
  118. },
  119. v: this.version,
  120. pathnames: new Set([]),
  121. project_ops: [],
  122. }
  123. if (change.origin) {
  124. this.currentUpdate.meta.origin = change.origin
  125. }
  126. for (const op of change.operations) {
  127. this.applyOperation(op, timestamp, authors, change.origin)
  128. }
  129. this.currentUpdate.pathnames = Array.from(this.currentUpdate.pathnames)
  130. this.summarizedUpdates.push(this.currentUpdate)
  131. this.version += 1
  132. }
  133. applyOperation(op, timestamp, authors, origin) {
  134. if (UpdateSetBuilder._isTextOperation(op)) {
  135. this.applyTextOperation(op, timestamp, authors, origin)
  136. } else if (UpdateSetBuilder._isRenameOperation(op)) {
  137. this.applyRenameOperation(op, timestamp, authors)
  138. } else if (UpdateSetBuilder._isRemoveFileOperation(op)) {
  139. this.applyRemoveFileOperation(op, timestamp, authors)
  140. } else if (UpdateSetBuilder._isAddFileOperation(op)) {
  141. this.applyAddFileOperation(op, timestamp, authors)
  142. }
  143. }
  144. applyTextOperation(operation, timestamp, authors, origin) {
  145. const { pathname } = operation
  146. if (pathname === '') {
  147. // this shouldn't happen, but we continue to allow the user to see the history
  148. logger.warn(
  149. { operation, timestamp, authors },
  150. 'pathname is empty for text operation'
  151. )
  152. return
  153. }
  154. const file = this.files[pathname]
  155. if (file == null) {
  156. // this shouldn't happen, but we continue to allow the user to see the history
  157. logger.warn(
  158. { operation, timestamp, authors },
  159. 'file is missing for text operation'
  160. )
  161. this.files[pathname] = null // marker for a missing file
  162. return
  163. }
  164. file.applyTextOperation(authors, timestamp, this.version, operation, origin)
  165. this.currentUpdate.pathnames.add(pathname)
  166. }
  167. applyRenameOperation(operation, timestamp, authors) {
  168. const { pathname, newPathname } = operation
  169. const file = this.files[pathname]
  170. if (file == null) {
  171. // this shouldn't happen, but we continue to allow the user to see the history
  172. logger.warn(
  173. { operation, timestamp, authors },
  174. 'file is missing for rename operation'
  175. )
  176. this.files[pathname] = null // marker for a missing file
  177. return
  178. }
  179. file.rename(newPathname)
  180. delete this.files[pathname]
  181. this.files[newPathname] = file
  182. this.currentUpdate.project_ops.push({
  183. rename: { pathname, newPathname },
  184. })
  185. }
  186. applyAddFileOperation(operation, timestamp, authors) {
  187. const { pathname } = operation
  188. // add file
  189. this.files[pathname] = new File(pathname, operation.file, this.version)
  190. this.currentUpdate.project_ops.push({ add: { pathname } })
  191. }
  192. applyRemoveFileOperation(operation, timestamp, authors) {
  193. const { pathname } = operation
  194. const file = this.files[pathname]
  195. if (file == null) {
  196. // this shouldn't happen, but we continue to allow the user to see the history
  197. logger.warn(
  198. { operation, timestamp, authors },
  199. 'pathname not found when removing file'
  200. )
  201. this.files[pathname] = null // marker for a missing file
  202. return
  203. }
  204. delete this.files[pathname]
  205. this.currentUpdate.project_ops.push({ remove: { pathname } })
  206. }
  207. static _isTextOperation(op) {
  208. return Object.prototype.hasOwnProperty.call(op, 'textOperation')
  209. }
  210. static _isRenameOperation(op) {
  211. return (
  212. Object.prototype.hasOwnProperty.call(op, 'newPathname') &&
  213. op.newPathname !== ''
  214. )
  215. }
  216. static _isRemoveFileOperation(op) {
  217. return (
  218. Object.prototype.hasOwnProperty.call(op, 'newPathname') &&
  219. op.newPathname === ''
  220. )
  221. }
  222. static _isAddFileOperation(op) {
  223. return Object.prototype.hasOwnProperty.call(op, 'file')
  224. }
  225. }
  226. /**
  227. * @param {string} content
  228. * @param {TrackedChangeList} trackedChanges
  229. * @returns {string}
  230. */
  231. function removeTrackedDeletesFromString(content, trackedChanges) {
  232. let result = ''
  233. let cursor = 0
  234. const trackedDeletes = trackedChanges
  235. .asSorted()
  236. .filter(tc => tc.tracking.type === 'delete')
  237. for (const trackedChange of trackedDeletes) {
  238. if (cursor < trackedChange.range.start) {
  239. result += content.slice(cursor, trackedChange.range.start)
  240. }
  241. // skip the tracked change itself
  242. cursor = trackedChange.range.end
  243. }
  244. result += content.slice(cursor)
  245. return result
  246. }
  247. class File {
  248. constructor(pathname, snapshot, initialVersion) {
  249. this.pathname = pathname
  250. this.snapshot = snapshot
  251. this.initialVersion = initialVersion
  252. this.operations = []
  253. }
  254. applyTextOperation(authors, timestamp, version, operation, origin) {
  255. this.operations.push({ authors, timestamp, version, operation, origin })
  256. }
  257. rename(pathname) {
  258. this.pathname = pathname
  259. }
  260. getDiffUpdates(historyId, fromVersion, toVersion, callback) {
  261. if (this.snapshot.stringLength == null) {
  262. // Binary file
  263. return callback(null, { binary: true })
  264. }
  265. this._loadContentAndRanges(historyId, (error, content, ranges) => {
  266. if (error != null) {
  267. return callback(OError.tag(error))
  268. }
  269. const trackedChanges = TrackedChangeList.fromRaw(
  270. ranges?.trackedChanges || []
  271. )
  272. /** @type {string | undefined} */
  273. let initialContent
  274. const updates = []
  275. for (const operationInfo of this.operations) {
  276. if (!('textOperation' in operationInfo.operation)) {
  277. // We only care about text operations
  278. continue
  279. }
  280. const { authors, timestamp, version, operation } = operationInfo
  281. // Set the initialContent to the latest version we have before the diff
  282. // begins. 'version' here refers to the document version as we are
  283. // applying the updates. So we store the content *before* applying the
  284. // updates.
  285. if (version >= fromVersion && initialContent === undefined) {
  286. initialContent = removeTrackedDeletesFromString(
  287. content,
  288. trackedChanges
  289. )
  290. }
  291. let ops
  292. ;({ content, ops } = this._convertTextOperation(
  293. content,
  294. operation,
  295. trackedChanges
  296. ))
  297. // We only need to return the updates between fromVersion and toVersion
  298. if (fromVersion <= version && version < toVersion) {
  299. const update = {
  300. meta: {
  301. users: authors,
  302. start_ts: timestamp.getTime(),
  303. end_ts: timestamp.getTime(),
  304. },
  305. v: version,
  306. op: ops,
  307. }
  308. if (operationInfo.origin) {
  309. update.meta.origin = operationInfo.origin
  310. }
  311. updates.push(update)
  312. }
  313. }
  314. if (initialContent === undefined) {
  315. initialContent = removeTrackedDeletesFromString(content, trackedChanges)
  316. }
  317. callback(null, { initialContent, updates })
  318. })
  319. }
  320. /**
  321. *
  322. * @param {string} initialContent
  323. * @param {RawEditOperation} operation
  324. * @param {TrackedChangeList} trackedChanges
  325. */
  326. _convertTextOperation(initialContent, operation, trackedChanges) {
  327. const textOp = TextOperation.fromJSON(operation)
  328. const textUpdateBuilder = new TextUpdateBuilder(
  329. initialContent,
  330. trackedChanges
  331. )
  332. for (const op of textOp.ops) {
  333. textUpdateBuilder.applyOp(op)
  334. }
  335. textUpdateBuilder.finish()
  336. return {
  337. content: textUpdateBuilder.result,
  338. ops: textUpdateBuilder.changes,
  339. }
  340. }
  341. _loadContentAndRanges(historyId, callback) {
  342. HistoryStoreManager.getProjectBlob(
  343. historyId,
  344. this.snapshot.hash,
  345. (err, content) => {
  346. if (err) {
  347. return callback(err)
  348. }
  349. if (this.snapshot.rangesHash) {
  350. HistoryStoreManager.getProjectBlob(
  351. historyId,
  352. this.snapshot.rangesHash,
  353. (err, ranges) => {
  354. if (err) {
  355. return callback(err)
  356. }
  357. return callback(null, content, JSON.parse(ranges))
  358. }
  359. )
  360. } else {
  361. return callback(null, content, undefined)
  362. }
  363. }
  364. )
  365. }
  366. }
  367. class TextUpdateBuilder {
  368. /**
  369. *
  370. * @param {string} source
  371. * @param {TrackedChangeList} ranges
  372. */
  373. constructor(source, ranges) {
  374. this.trackedChanges = ranges
  375. this.source = source
  376. this.sourceCursor = 0
  377. this.result = ''
  378. /** @type {({i: string, p: number} | {d: string, p: number})[]} */
  379. this.changes = []
  380. }
  381. applyOp(op) {
  382. if (op instanceof RetainOp) {
  383. const length = this.result.length
  384. this.applyRetain(op)
  385. this.trackedChanges.applyRetain(length, op.length, {
  386. tracking: op.tracking,
  387. })
  388. }
  389. if (op instanceof InsertOp) {
  390. const length = this.result.length
  391. this.applyInsert(op)
  392. this.trackedChanges.applyInsert(length, op.insertion, {
  393. tracking: op.tracking,
  394. })
  395. }
  396. if (op instanceof RemoveOp) {
  397. const length = this.result.length
  398. this.applyDelete(op)
  399. this.trackedChanges.applyDelete(length, op.length)
  400. }
  401. }
  402. /**
  403. *
  404. * @param {RetainOp} retain
  405. */
  406. applyRetain(retain) {
  407. const resultRetentionRange = new Range(this.result.length, retain.length)
  408. const sourceRetentionRange = new Range(this.sourceCursor, retain.length)
  409. let scanCursor = this.result.length
  410. if (retain.tracking) {
  411. // We are modifying existing tracked deletes. We need to treat removal
  412. // (type insert/none) of a tracked delete as an insertion. Similarly, any
  413. // range we introduce as a tracked deletion must be reported as a deletion.
  414. const trackedDeletes = this.trackedChanges
  415. .asSorted()
  416. .filter(
  417. tc =>
  418. tc.tracking.type === 'delete' &&
  419. tc.range.overlaps(resultRetentionRange)
  420. )
  421. const sourceOffset = this.sourceCursor - this.result.length
  422. for (const trackedDelete of trackedDeletes) {
  423. const resultTrackedDelete = trackedDelete.range
  424. const sourceTrackedDelete = trackedDelete.range.moveBy(sourceOffset)
  425. if (scanCursor < resultTrackedDelete.start) {
  426. if (retain.tracking.type === 'delete') {
  427. this.changes.push({
  428. d: this.source.slice(
  429. this.sourceCursor,
  430. sourceTrackedDelete.start
  431. ),
  432. p: this.result.length,
  433. })
  434. }
  435. this.result += this.source.slice(
  436. this.sourceCursor,
  437. sourceTrackedDelete.start
  438. )
  439. scanCursor = resultTrackedDelete.start
  440. this.sourceCursor = sourceTrackedDelete.start
  441. }
  442. const endOfInsertionResult = Math.min(
  443. resultTrackedDelete.end,
  444. resultRetentionRange.end
  445. )
  446. const endOfInsertionSource = Math.min(
  447. sourceTrackedDelete.end,
  448. sourceRetentionRange.end
  449. )
  450. const text = this.source.slice(this.sourceCursor, endOfInsertionSource)
  451. if (
  452. retain.tracking.type === 'none' ||
  453. retain.tracking.type === 'insert'
  454. ) {
  455. this.changes.push({
  456. i: text,
  457. p: this.result.length,
  458. })
  459. }
  460. this.result += text
  461. // skip the tracked delete itself
  462. scanCursor = endOfInsertionResult
  463. this.sourceCursor = endOfInsertionSource
  464. if (scanCursor >= resultRetentionRange.end) {
  465. break
  466. }
  467. }
  468. }
  469. if (scanCursor < resultRetentionRange.end) {
  470. // The last region is not a tracked delete. But we should still handle
  471. // a new tracked delete as a deletion.
  472. const text = this.source.slice(
  473. this.sourceCursor,
  474. sourceRetentionRange.end
  475. )
  476. if (retain.tracking?.type === 'delete') {
  477. this.changes.push({
  478. d: text,
  479. p: this.result.length,
  480. })
  481. }
  482. this.result += text
  483. }
  484. this.sourceCursor = sourceRetentionRange.end
  485. }
  486. /**
  487. *
  488. * @param {InsertOp} insert
  489. */
  490. applyInsert(insert) {
  491. if (insert.tracking?.type !== 'delete') {
  492. // Skip tracked deletions
  493. this.changes.push({
  494. i: insert.insertion,
  495. p: this.result.length,
  496. })
  497. }
  498. this.result += insert.insertion
  499. // The source cursor doesn't advance
  500. }
  501. /**
  502. *
  503. * @param {RemoveOp} deletion
  504. */
  505. applyDelete(deletion) {
  506. const sourceDeletionRange = new Range(this.sourceCursor, deletion.length)
  507. const resultDeletionRange = new Range(this.result.length, deletion.length)
  508. const trackedDeletes = this.trackedChanges
  509. .asSorted()
  510. .filter(
  511. tc =>
  512. tc.tracking.type === 'delete' &&
  513. tc.range.overlaps(resultDeletionRange)
  514. )
  515. .sort((a, b) => a.range.start - b.range.start)
  516. let scanCursor = this.result.length
  517. const sourceOffset = this.sourceCursor - this.result.length
  518. for (const trackedDelete of trackedDeletes) {
  519. const resultTrackDeleteRange = trackedDelete.range
  520. const sourceTrackDeleteRange = trackedDelete.range.moveBy(sourceOffset)
  521. if (scanCursor < resultTrackDeleteRange.start) {
  522. this.changes.push({
  523. d: this.source.slice(this.sourceCursor, sourceTrackDeleteRange.start),
  524. p: this.result.length,
  525. })
  526. }
  527. // skip the tracked delete itself
  528. scanCursor = Math.min(resultTrackDeleteRange.end, resultDeletionRange.end)
  529. this.sourceCursor = Math.min(
  530. sourceTrackDeleteRange.end,
  531. sourceDeletionRange.end
  532. )
  533. if (scanCursor >= resultDeletionRange.end) {
  534. break
  535. }
  536. }
  537. if (scanCursor < resultDeletionRange.end) {
  538. this.changes.push({
  539. d: this.source.slice(this.sourceCursor, sourceDeletionRange.end),
  540. p: this.result.length,
  541. })
  542. }
  543. this.sourceCursor = sourceDeletionRange.end
  544. }
  545. finish() {
  546. if (this.sourceCursor < this.source.length) {
  547. this.result += this.source.slice(this.sourceCursor)
  548. }
  549. for (const op of this.changes) {
  550. if ('p' in op && typeof op.p === 'number') {
  551. // Maybe we have to move the position of the deletion to account for
  552. // tracked changes that we're hiding in the UI.
  553. op.p -= this.trackedChanges
  554. .asSorted()
  555. .filter(tc => tc.tracking.type === 'delete' && tc.range.start < op.p)
  556. .map(tc => {
  557. if (tc.range.end < op.p) {
  558. return tc.range.length
  559. }
  560. return op.p - tc.range.start
  561. })
  562. .reduce((a, b) => a + b, 0)
  563. }
  564. }
  565. }
  566. }