UpdateTranslator.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // @ts-check
  2. import _ from 'lodash'
  3. import Core from 'overleaf-editor-core'
  4. import * as Errors from './Errors.js'
  5. import * as OperationsCompressor from './OperationsCompressor.js'
  6. import { isInsert, isRetain, isDelete, isComment } from './Utils.js'
  7. /**
  8. * @import { AddDocUpdate, AddFileUpdate, DeleteCommentUpdate, Op, RawScanOp } from './types'
  9. * @import { RenameUpdate, TextUpdate, TrackingDirective, TrackingProps } from './types'
  10. * @import { SetCommentStateUpdate, SetFileMetadataOperation, Update, UpdateWithBlob } from './types'
  11. */
  12. /**
  13. * Convert updates into history changes
  14. *
  15. * @param {string} projectId
  16. * @param {UpdateWithBlob[]} updatesWithBlobs
  17. * @returns {Array<Core.Change | null>}
  18. */
  19. export function convertToChanges(projectId, updatesWithBlobs) {
  20. return updatesWithBlobs.map(update => _convertToChange(projectId, update))
  21. }
  22. /**
  23. * Convert an update into a history change
  24. *
  25. * @param {string} projectId
  26. * @param {UpdateWithBlob} updateWithBlob
  27. * @returns {Core.Change | null}
  28. */
  29. function _convertToChange(projectId, updateWithBlob) {
  30. let operations
  31. const { update } = updateWithBlob
  32. let projectVersion = null
  33. const v2DocVersions = {}
  34. if (_isRenameUpdate(update)) {
  35. operations = [
  36. {
  37. pathname: _convertPathname(update.pathname),
  38. newPathname: _convertPathname(update.new_pathname),
  39. },
  40. ]
  41. projectVersion = update.version
  42. } else if (isAddUpdate(update)) {
  43. const op = {
  44. pathname: _convertPathname(update.pathname),
  45. file: {
  46. hash: updateWithBlob.blobHashes.file,
  47. },
  48. }
  49. if (_isAddDocUpdate(update)) {
  50. op.file.rangesHash = updateWithBlob.blobHashes.ranges
  51. }
  52. if (_isAddFileUpdate(update)) {
  53. op.file.metadata = update.metadata
  54. }
  55. operations = [op]
  56. projectVersion = update.version
  57. } else if (isTextUpdate(update)) {
  58. const docLength = update.meta.history_doc_length ?? update.meta.doc_length
  59. let pathname = update.meta.pathname
  60. pathname = _convertPathname(pathname)
  61. const builder = new OperationsBuilder(docLength, pathname)
  62. // convert ops
  63. for (const op of update.op) {
  64. builder.addOp(op, update)
  65. }
  66. operations = builder.finish()
  67. // add doc version information if present
  68. if (update.v != null) {
  69. v2DocVersions[update.doc] = { pathname, v: update.v }
  70. }
  71. } else if (isSetCommentStateUpdate(update)) {
  72. operations = [
  73. {
  74. pathname: _convertPathname(update.pathname),
  75. commentId: update.commentId,
  76. resolved: update.resolved,
  77. },
  78. ]
  79. } else if (isSetFileMetadataOperation(update)) {
  80. operations = [
  81. {
  82. pathname: _convertPathname(update.pathname),
  83. metadata: update.metadata,
  84. },
  85. ]
  86. } else if (isDeleteCommentUpdate(update)) {
  87. operations = [
  88. {
  89. pathname: _convertPathname(update.pathname),
  90. deleteComment: update.deleteComment,
  91. },
  92. ]
  93. } else {
  94. const error = new Errors.UpdateWithUnknownFormatError(
  95. 'update with unknown format',
  96. { projectId, update }
  97. )
  98. throw error
  99. }
  100. let v2Authors
  101. if (update.meta.user_id === 'anonymous-user') {
  102. // history-v1 uses null to represent an anonymous author
  103. v2Authors = [null]
  104. } else {
  105. // user_id is missing on resync operations that update the contents of a doc
  106. v2Authors = _.compact([update.meta.user_id])
  107. }
  108. const rawChange = {
  109. operations,
  110. v2Authors,
  111. timestamp: new Date(update.meta.ts).toISOString(),
  112. projectVersion,
  113. v2DocVersions: Object.keys(v2DocVersions).length ? v2DocVersions : null,
  114. }
  115. if (update.meta.origin) {
  116. rawChange.origin = update.meta.origin
  117. } else if (update.meta.type === 'external' && update.meta.source) {
  118. rawChange.origin = { kind: update.meta.source }
  119. }
  120. const change = Core.Change.fromRaw(rawChange)
  121. if (change != null) {
  122. change.operations = OperationsCompressor.compressOperations(
  123. change.operations
  124. )
  125. }
  126. return change
  127. }
  128. /**
  129. * @param {Update} update
  130. * @returns {update is RenameUpdate}
  131. */
  132. function _isRenameUpdate(update) {
  133. return 'new_pathname' in update && update.new_pathname != null
  134. }
  135. /**
  136. * @param {Update} update
  137. * @returns {update is AddDocUpdate}
  138. */
  139. function _isAddDocUpdate(update) {
  140. return (
  141. 'doc' in update &&
  142. update.doc != null &&
  143. 'docLines' in update &&
  144. update.docLines != null
  145. )
  146. }
  147. /**
  148. * @param {Update} update
  149. * @returns {update is AddFileUpdate}
  150. */
  151. function _isAddFileUpdate(update) {
  152. return (
  153. 'file' in update &&
  154. update.file != null &&
  155. 'url' in update &&
  156. update.url != null
  157. )
  158. }
  159. /**
  160. * @param {Update} update
  161. * @returns {update is TextUpdate}
  162. */
  163. export function isTextUpdate(update) {
  164. return (
  165. 'doc' in update &&
  166. update.doc != null &&
  167. 'op' in update &&
  168. update.op != null &&
  169. 'pathname' in update.meta &&
  170. update.meta.pathname != null &&
  171. 'doc_length' in update.meta &&
  172. update.meta.doc_length != null
  173. )
  174. }
  175. export function isProjectStructureUpdate(update) {
  176. return isAddUpdate(update) || _isRenameUpdate(update)
  177. }
  178. /**
  179. * @param {Update} update
  180. * @returns {update is AddDocUpdate | AddFileUpdate}
  181. */
  182. export function isAddUpdate(update) {
  183. return _isAddDocUpdate(update) || _isAddFileUpdate(update)
  184. }
  185. /**
  186. * @param {Update} update
  187. * @returns {update is SetCommentStateUpdate}
  188. */
  189. export function isSetCommentStateUpdate(update) {
  190. return 'commentId' in update && 'resolved' in update
  191. }
  192. /**
  193. * @param {Update} update
  194. * @returns {update is DeleteCommentUpdate}
  195. */
  196. export function isDeleteCommentUpdate(update) {
  197. return 'deleteComment' in update
  198. }
  199. /**
  200. * @param {Update} update
  201. * @returns {update is SetFileMetadataOperation}
  202. */
  203. export function isSetFileMetadataOperation(update) {
  204. return 'metadata' in update
  205. }
  206. export function _convertPathname(pathname) {
  207. // Strip leading /
  208. pathname = pathname.replace(/^\//, '')
  209. // Replace \\ with _. Backslashes are no longer allowed
  210. // in projects in web, but we have some which have gone through
  211. // into history before this restriction was added. This makes
  212. // them valid for the history store.
  213. // See https://github.com/overleaf/write_latex/issues/4471
  214. pathname = pathname.replace(/\\/g, '_')
  215. // workaround for filenames containing asterisks, this will
  216. // fail if a corresponding replacement file already exists but it
  217. // would fail anyway without this attempt to fix the pathname.
  218. // See https://github.com/overleaf/internal/issues/900
  219. pathname = pathname.replace(/\*/g, '__ASTERISK__')
  220. // workaround for filenames beginning with spaces
  221. // See https://github.com/overleaf/internal/issues/1404
  222. // note: we have already stripped any leading slash above
  223. pathname = pathname.replace(/^ /, '__SPACE__') // handle top-level
  224. pathname = pathname.replace(/\/ /g, '/__SPACE__') // handle folders
  225. return pathname
  226. }
  227. class OperationsBuilder {
  228. /**
  229. * @param {number} docLength
  230. * @param {string} pathname
  231. */
  232. constructor(docLength, pathname) {
  233. /**
  234. * List of operations being built
  235. */
  236. this.operations = []
  237. /**
  238. * Currently built text operation
  239. *
  240. * @type {RawScanOp[]}
  241. */
  242. this.textOperation = []
  243. /**
  244. * Cursor inside the current text operation
  245. */
  246. this.cursor = 0
  247. this.docLength = docLength
  248. this.pathname = pathname
  249. }
  250. /**
  251. * @param {Op} op
  252. * @param {TextUpdate} update
  253. * @returns {void}
  254. */
  255. addOp(op, update) {
  256. // We sometimes receive operations that operate at positions outside the
  257. // docLength. Document updater coerces the position to the end of the
  258. // document. We do the same here.
  259. const pos = Math.min(op.hpos ?? op.p, this.docLength)
  260. if (isComment(op)) {
  261. // Close the current text operation
  262. this.pushTextOperation()
  263. // Add a comment operation
  264. const commentLength = op.hlen ?? op.c.length
  265. const commentOp = {
  266. pathname: this.pathname,
  267. commentId: op.t,
  268. ranges: commentLength > 0 ? [{ pos, length: commentLength }] : [],
  269. }
  270. if ('resolved' in op) {
  271. commentOp.resolved = op.resolved
  272. }
  273. this.operations.push(commentOp)
  274. return
  275. }
  276. if (!isInsert(op) && !isDelete(op) && !isRetain(op)) {
  277. throw new Errors.UnexpectedOpTypeError('unexpected op type', { op })
  278. }
  279. if (pos < this.cursor) {
  280. this.pushTextOperation()
  281. // At this point, this.cursor === 0 and we can continue
  282. }
  283. if (pos > this.cursor) {
  284. this.retain(pos - this.cursor)
  285. }
  286. if (isInsert(op)) {
  287. if (op.trackedDeleteRejection) {
  288. this.retain(op.i.length, {
  289. tracking: { type: 'none' },
  290. })
  291. } else {
  292. const opts = {}
  293. if (update.meta.tc != null) {
  294. opts.tracking = {
  295. type: 'insert',
  296. userId: update.meta.user_id,
  297. ts: new Date(update.meta.ts).toISOString(),
  298. }
  299. }
  300. if (op.commentIds != null) {
  301. opts.commentIds = op.commentIds
  302. }
  303. this.insert(op.i, opts)
  304. }
  305. }
  306. if (isRetain(op)) {
  307. if (op.tracking) {
  308. this.retain(op.r.length, { tracking: op.tracking })
  309. } else {
  310. this.retain(op.r.length)
  311. }
  312. }
  313. if (isDelete(op)) {
  314. const changes = op.trackedChanges ?? []
  315. // Tracked changes should already be ordered by offset, but let's make
  316. // sure they are.
  317. changes.sort((a, b) => {
  318. const posOrder = a.offset - b.offset
  319. if (posOrder !== 0) {
  320. return posOrder
  321. } else if (a.type === 'insert' && b.type === 'delete') {
  322. return 1
  323. } else if (a.type === 'delete' && b.type === 'insert') {
  324. return -1
  325. } else {
  326. return 0
  327. }
  328. })
  329. let offset = 0
  330. for (const change of changes) {
  331. if (change.offset > offset) {
  332. // Handle the portion before the tracked change
  333. if (update.meta.tc != null) {
  334. // This is a tracked delete
  335. this.retain(change.offset - offset, {
  336. tracking: {
  337. type: 'delete',
  338. userId: update.meta.user_id,
  339. ts: new Date(update.meta.ts).toISOString(),
  340. },
  341. })
  342. } else {
  343. // This is a regular delete
  344. this.delete(change.offset - offset)
  345. }
  346. offset = change.offset
  347. }
  348. // Now, handle the portion inside the tracked change
  349. if (change.type === 'delete') {
  350. // Tracked deletes are skipped over when deleting
  351. this.retain(change.length)
  352. } else if (change.type === 'insert') {
  353. // Deletes inside tracked inserts are always regular deletes
  354. this.delete(change.length)
  355. offset += change.length
  356. }
  357. }
  358. if (offset < op.d.length) {
  359. // Handle the portion after the last tracked change
  360. if (update.meta.tc != null) {
  361. // This is a tracked delete
  362. this.retain(op.d.length - offset, {
  363. tracking: {
  364. type: 'delete',
  365. userId: update.meta.user_id,
  366. ts: new Date(update.meta.ts).toISOString(),
  367. },
  368. })
  369. } else {
  370. // This is a regular delete
  371. this.delete(op.d.length - offset)
  372. }
  373. }
  374. }
  375. }
  376. /**
  377. * @param {number} length
  378. * @param {object} opts
  379. * @param {TrackingDirective} [opts.tracking]
  380. */
  381. retain(length, opts = {}) {
  382. if (opts.tracking) {
  383. this.textOperation.push({ r: length, ...opts })
  384. } else {
  385. this.textOperation.push(length)
  386. }
  387. this.cursor += length
  388. }
  389. /**
  390. * @param {string} str
  391. * @param {object} opts
  392. * @param {TrackingProps} [opts.tracking]
  393. * @param {string[]} [opts.commentIds]
  394. */
  395. insert(str, opts = {}) {
  396. if (opts.tracking || opts.commentIds) {
  397. this.textOperation.push({ i: str, ...opts })
  398. } else {
  399. this.textOperation.push(str)
  400. }
  401. this.cursor += str.length
  402. this.docLength += str.length
  403. }
  404. /**
  405. * @param {number} length
  406. * @param {object} opts
  407. */
  408. delete(length, opts = {}) {
  409. this.textOperation.push(-length)
  410. this.docLength -= length
  411. }
  412. pushTextOperation() {
  413. if (this.textOperation.length > 0)
  414. if (this.cursor < this.docLength) {
  415. this.retain(this.docLength - this.cursor)
  416. }
  417. if (this.textOperation.length > 0) {
  418. this.operations.push({
  419. pathname: this.pathname,
  420. textOperation: this.textOperation,
  421. })
  422. this.textOperation = []
  423. }
  424. this.cursor = 0
  425. }
  426. finish() {
  427. this.pushTextOperation()
  428. return this.operations
  429. }
  430. }