UpdateTranslator.js 14 KB

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