ChunkTranslator.js 18 KB

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