UpdateTranslator.js 13 KB

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