UpdateTranslator.js 12 KB

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