UpdateTranslator.js 13 KB

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