@createiq/htmldiff 1.0.5-beta.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/TableDiff.ts DELETED
@@ -1,1504 +0,0 @@
1
- /**
2
- * Table-aware preprocessing for HtmlDiff.
3
- *
4
- * The word-level diff alone matches longest-common-subsequences across cell
5
- * boundaries and produces structurally wrong output for table edits — it
6
- * shuffles content between cells, introduces phantom `<td>`s, and provides
7
- * no signal that an entire row or column was added/deleted. We pre-process
8
- * the inputs to give Word-style results:
9
- *
10
- * • When dimensions match (same row count, same cell count per row), we
11
- * diff cell content positionally so cross-cell shifts produce one
12
- * independent del/ins per cell.
13
- * • When dimensions don't match (added/deleted row, added/deleted column),
14
- * we run a row-level LCS to identify structurally added/deleted rows,
15
- * then within preserved rows a cell-level LCS to identify added/deleted
16
- * columns. Structurally added rows/cells get `class='diffins'` on the
17
- * `<tr>`/`<td>`; deleted ones get `class='diffdel'`. Preserved cells
18
- * fall back to a content diff via the recursive HtmlDiff callback.
19
- *
20
- * Tables are spliced out into placeholders before the main diff runs and
21
- * spliced back in after, so the surrounding (non-table) content is diffed
22
- * by the normal word-level pipeline.
23
- */
24
-
25
- interface CellRange {
26
- /** Start index of the cell's opening tag in the original html. */
27
- cellStart: number
28
- /** Index just past the cell's closing tag. */
29
- cellEnd: number
30
- /** Cell content range — the slice we feed into the cell-level diff. */
31
- contentStart: number
32
- contentEnd: number
33
- }
34
-
35
- interface RowRange {
36
- rowStart: number
37
- rowEnd: number
38
- cells: CellRange[]
39
- }
40
-
41
- interface TableRange {
42
- tableStart: number
43
- tableEnd: number
44
- rows: RowRange[]
45
- }
46
-
47
- export interface PreprocessResult {
48
- modifiedOld: string
49
- modifiedNew: string
50
- /** Maps placeholder marker → already-diffed table HTML to splice back in. */
51
- placeholderToDiff: Map<string, string>
52
- }
53
-
54
- // HTML comments survive WordSplitter as a single atomic token and are
55
- // treated as equal on both sides, so they pass through the diff
56
- // untouched and are easy to substitute back later. The nonce is generated
57
- // per call so a previously-diffed document being re-diffed (or any input
58
- // that legitimately contains an `<!--HTMLDIFF_TABLE_*-->` comment) can't
59
- // collide with the placeholder we substitute. We additionally regenerate
60
- // the nonce if it appears in either input.
61
- const PLACEHOLDER_PREFIX_BASE = '<!--HTMLDIFF_TABLE_'
62
- const PLACEHOLDER_SUFFIX = '-->'
63
-
64
- /**
65
- * Hard cap on table dimensions handled by the structural-aware path.
66
- * The row-LCS is O(rows²), the per-row cell-LCS is O(cells²), and each
67
- * comparison string-equals row content (potentially many KB). Without a
68
- * cap, a several-thousand-row table can pin a CPU for seconds. Tables
69
- * larger than this fall through to the word-level diff, which scales
70
- * linearly. Tuned to comfortably cover real-world ISDA schedules
71
- * (which routinely have 1000+ rows).
72
- */
73
- const MAX_TABLE_ROWS = 1500
74
- const MAX_TABLE_CELLS_PER_ROW = 200
75
-
76
- function makePlaceholderPrefix(oldHtml: string, newHtml: string): string {
77
- // 4 random bytes → 8 hex chars → 16^8 ≈ 4.3 billion combinations. We
78
- // also retry if the generated nonce happens to occur in either input.
79
- // Using `Math.random` here is fine: we're not defending against a
80
- // malicious adversary, just avoiding accidental collisions.
81
- for (let attempt = 0; attempt < 8; attempt++) {
82
- const nonce = Math.floor(Math.random() * 0xffffffff)
83
- .toString(16)
84
- .padStart(8, '0')
85
- const prefix = `${PLACEHOLDER_PREFIX_BASE}${nonce}_`
86
- if (!oldHtml.includes(prefix) && !newHtml.includes(prefix)) {
87
- return prefix
88
- }
89
- }
90
- // Astronomically unlikely. Falling back to a counter ensures progress
91
- // rather than an infinite loop, and any remaining collision will simply
92
- // surface as a malformed diff that the caller can detect.
93
- return `${PLACEHOLDER_PREFIX_BASE}fallback_${Date.now()}_`
94
- }
95
-
96
- type DiffCellFn = (oldCellContent: string, newCellContent: string) => string
97
-
98
- /**
99
- * Diffs every paired-by-position table in the inputs and replaces each
100
- * source table with a placeholder, returning the modified inputs plus the
101
- * placeholder→diff mapping. Returns null when there are no tables to
102
- * preprocess or the table counts don't line up.
103
- */
104
- export function preprocessTables(oldHtml: string, newHtml: string, diffCell: DiffCellFn): PreprocessResult | null {
105
- const oldTables = findTopLevelTables(oldHtml)
106
- const newTables = findTopLevelTables(newHtml)
107
-
108
- if (oldTables.length === 0 && newTables.length === 0) return null
109
- if (oldTables.length !== newTables.length) return null
110
-
111
- // Bail out on pathologically large tables — see MAX_TABLE_ROWS comment.
112
- for (let i = 0; i < oldTables.length; i++) {
113
- if (exceedsSizeLimit(oldTables[i]) || exceedsSizeLimit(newTables[i])) return null
114
- }
115
-
116
- const pairs: Array<{ oldTable: TableRange; newTable: TableRange; diffed: string }> = []
117
- for (let i = 0; i < oldTables.length; i++) {
118
- pairs.push({
119
- oldTable: oldTables[i],
120
- newTable: newTables[i],
121
- diffed: diffTable(oldHtml, newHtml, oldTables[i], newTables[i], diffCell),
122
- })
123
- }
124
-
125
- // Splice from end → start so earlier offsets stay valid.
126
- let modifiedOld = oldHtml
127
- let modifiedNew = newHtml
128
- const placeholderPrefix = makePlaceholderPrefix(oldHtml, newHtml)
129
- const placeholderToDiff = new Map<string, string>()
130
- for (let i = pairs.length - 1; i >= 0; i--) {
131
- const placeholder = `${placeholderPrefix}${i}${PLACEHOLDER_SUFFIX}`
132
- placeholderToDiff.set(placeholder, pairs[i].diffed)
133
- modifiedOld = spliceString(modifiedOld, pairs[i].oldTable.tableStart, pairs[i].oldTable.tableEnd, placeholder)
134
- modifiedNew = spliceString(modifiedNew, pairs[i].newTable.tableStart, pairs[i].newTable.tableEnd, placeholder)
135
- }
136
-
137
- return { modifiedOld, modifiedNew, placeholderToDiff }
138
- }
139
-
140
- export function restoreTablePlaceholders(diffOutput: string, placeholderToDiff: Map<string, string>): string {
141
- let result = diffOutput
142
- for (const [placeholder, html] of placeholderToDiff) {
143
- result = result.split(placeholder).join(html)
144
- }
145
- return result
146
- }
147
-
148
- function spliceString(s: string, start: number, end: number, replacement: string): string {
149
- return s.slice(0, start) + replacement + s.slice(end)
150
- }
151
-
152
- function exceedsSizeLimit(table: TableRange): boolean {
153
- if (table.rows.length > MAX_TABLE_ROWS) return true
154
- for (const row of table.rows) {
155
- if (row.cells.length > MAX_TABLE_CELLS_PER_ROW) return true
156
- }
157
- return false
158
- }
159
-
160
- function diffTable(
161
- oldHtml: string,
162
- newHtml: string,
163
- oldTable: TableRange,
164
- newTable: TableRange,
165
- diffCell: DiffCellFn
166
- ): string {
167
- if (sameDimensions(oldTable, newTable)) {
168
- return diffPositionalTable(oldHtml, newHtml, oldTable, newTable, diffCell)
169
- }
170
- if (oldTable.rows.length === newTable.rows.length) {
171
- // Same row count, different cell counts: column add/delete only.
172
- // Aligning rows positionally avoids the LCS row-key mismatch that
173
- // happens when rows have different cell counts.
174
- return diffSameRowCountTable(oldHtml, newHtml, oldTable, newTable, diffCell)
175
- }
176
- return diffStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, diffCell)
177
- }
178
-
179
- function diffSameRowCountTable(
180
- oldHtml: string,
181
- newHtml: string,
182
- oldTable: TableRange,
183
- newTable: TableRange,
184
- diffCell: DiffCellFn
185
- ): string {
186
- // Walk the new table verbatim (preserving `<thead>`/`<tbody>` wrappers,
187
- // whitespace, etc.) and substitute each row's content with the diffed
188
- // form. The cursor-based emission keeps everything between rows intact.
189
- const out: string[] = []
190
- let cursor = newTable.tableStart
191
- let r = 0
192
- while (r < newTable.rows.length) {
193
- const merge = detectVerticalMerge(oldHtml, newHtml, oldTable, newTable, r)
194
- if (merge) {
195
- out.push(newHtml.slice(cursor, newTable.rows[r].rowStart))
196
- out.push(merge.diff)
197
- cursor = newTable.rows[r + merge.span - 1].rowEnd
198
- r += merge.span
199
- continue
200
- }
201
- const split = detectVerticalSplit(oldHtml, newHtml, oldTable, newTable, r)
202
- if (split) {
203
- out.push(newHtml.slice(cursor, newTable.rows[r].rowStart))
204
- out.push(split.diff)
205
- cursor = newTable.rows[r + split.span - 1].rowEnd
206
- r += split.span
207
- continue
208
- }
209
- const newRow = newTable.rows[r]
210
- out.push(newHtml.slice(cursor, newRow.rowStart))
211
- out.push(diffPreservedRow(oldHtml, newHtml, oldTable.rows[r], newRow, diffCell))
212
- cursor = newRow.rowEnd
213
- r++
214
- }
215
- out.push(newHtml.slice(cursor, newTable.tableEnd))
216
- return out.join('')
217
- }
218
-
219
- /**
220
- * Detects a vertical merge starting at row `r`: new row R has a single
221
- * cell with rowspan=K (and any colspan ≥ 1), with rows R+1..R+K-1 empty
222
- * in new. Old rows R..R+K-1 must have a logical column width equal to
223
- * the new cell's colspan and contain no rowspan'd cells of their own.
224
- * This handles both single-column merges (old rows are 1-cell, new cell
225
- * rowspan=K) and rectangular merges (e.g. 2×2 merge into a single
226
- * colspan=2 rowspan=2 cell). Output: emit the merged cell with
227
- * `class='mod rowspan'` and the empty trailing rows unchanged.
228
- */
229
- function detectVerticalMerge(
230
- oldHtml: string,
231
- newHtml: string,
232
- oldTable: TableRange,
233
- newTable: TableRange,
234
- r: number
235
- ): { diff: string; span: number } | null {
236
- const newRow = newTable.rows[r]
237
- if (newRow.cells.length !== 1) return null
238
- const cell = newRow.cells[0]
239
- const span = getRowspan(newHtml, cell)
240
- if (span <= 1) return null
241
- if (r + span > newTable.rows.length) return null
242
-
243
- const colspan = getColspan(newHtml, cell)
244
-
245
- for (let k = 1; k < span; k++) {
246
- if (newTable.rows[r + k].cells.length !== 0) return null
247
- }
248
- for (let k = 0; k < span; k++) {
249
- const oldRow = oldTable.rows[r + k]
250
- if (!oldRow) return null
251
- // The absorbed region's logical width must match the merged cell's
252
- // colspan; otherwise this isn't a clean rectangular merge and we let
253
- // the caller fall through.
254
- if (sumColspans(oldHtml, oldRow.cells) !== colspan) return null
255
- for (const c of oldRow.cells) {
256
- if (getRowspan(oldHtml, c) !== 1) return null
257
- }
258
- }
259
-
260
- const out: string[] = []
261
- out.push(rowHeaderSlice(newHtml, newRow))
262
- out.push(emitSpanChangedCell(newHtml, cell, 'rowspan'))
263
- out.push('</tr>')
264
- for (let k = 1; k < span; k++) {
265
- out.push(emitEmptyRow(newHtml, newTable.rows[r + k]))
266
- }
267
- return { diff: out.join(''), span }
268
- }
269
-
270
- /**
271
- * Detects a vertical split starting at row `r`: old row R has a single
272
- * cell with rowspan=K, old rows R+1..R+K-1 are empty. New rows R..R+K-1
273
- * each have a single cell. Output: emit each new row with the new cell
274
- * tagged `class='mod rowspan'`.
275
- */
276
- function detectVerticalSplit(
277
- oldHtml: string,
278
- newHtml: string,
279
- oldTable: TableRange,
280
- newTable: TableRange,
281
- r: number
282
- ): { diff: string; span: number } | null {
283
- const oldRow = oldTable.rows[r]
284
- if (oldRow.cells.length !== 1) return null
285
- const oldCell = oldRow.cells[0]
286
- const span = getRowspan(oldHtml, oldCell)
287
- if (span <= 1) return null
288
- if (r + span > oldTable.rows.length) return null
289
-
290
- const colspan = getColspan(oldHtml, oldCell)
291
-
292
- for (let k = 1; k < span; k++) {
293
- if (oldTable.rows[r + k].cells.length !== 0) return null
294
- }
295
- for (let k = 0; k < span; k++) {
296
- const newRow = newTable.rows[r + k]
297
- if (!newRow) return null
298
- // New rows must collectively cover the same logical width as the old
299
- // merged cell's colspan, with no rowspan'd cells of their own.
300
- if (sumColspans(newHtml, newRow.cells) !== colspan) return null
301
- for (const c of newRow.cells) {
302
- if (getRowspan(newHtml, c) !== 1) return null
303
- }
304
- }
305
-
306
- const out: string[] = []
307
- for (let k = 0; k < span; k++) {
308
- const newRow = newTable.rows[r + k]
309
- out.push(rowHeaderSlice(newHtml, newRow))
310
- for (const c of newRow.cells) {
311
- out.push(emitSpanChangedCell(newHtml, c, 'rowspan'))
312
- }
313
- out.push('</tr>')
314
- }
315
- return { diff: out.join(''), span }
316
- }
317
-
318
- function emitEmptyRow(html: string, row: RowRange): string {
319
- // Re-emit the source row's `<tr ...></tr>` verbatim.
320
- return html.slice(row.rowStart, row.rowEnd)
321
- }
322
-
323
- function sameDimensions(a: TableRange, b: TableRange): boolean {
324
- if (a.rows.length !== b.rows.length) return false
325
- for (let i = 0; i < a.rows.length; i++) {
326
- if (a.rows[i].cells.length !== b.rows[i].cells.length) return false
327
- }
328
- return true
329
- }
330
-
331
- /**
332
- * Same-dimension path: walk the new table verbatim and substitute each
333
- * cell content range with the cell-level diff. The surrounding
334
- * `<thead>`/`<tbody>`/whitespace passes through untouched.
335
- */
336
- function diffPositionalTable(
337
- oldHtml: string,
338
- newHtml: string,
339
- oldTable: TableRange,
340
- newTable: TableRange,
341
- diffCell: DiffCellFn
342
- ): string {
343
- const out: string[] = []
344
- let cursor = newTable.tableStart
345
- for (let r = 0; r < newTable.rows.length; r++) {
346
- const oldRow = oldTable.rows[r]
347
- const newRow = newTable.rows[r]
348
- for (let c = 0; c < newRow.cells.length; c++) {
349
- const oldCell = oldRow.cells[c]
350
- const newCell = newRow.cells[c]
351
- out.push(newHtml.slice(cursor, newCell.contentStart))
352
- out.push(
353
- diffCell(
354
- oldHtml.slice(oldCell.contentStart, oldCell.contentEnd),
355
- newHtml.slice(newCell.contentStart, newCell.contentEnd)
356
- )
357
- )
358
- cursor = newCell.contentEnd
359
- }
360
- }
361
- out.push(newHtml.slice(cursor, newTable.tableEnd))
362
- return out.join('')
363
- }
364
-
365
- /**
366
- * Mismatched-dimensions path: row-level LCS to identify added/deleted rows,
367
- * then per preserved row a cell-level LCS to identify added/deleted cells.
368
- * Reconstructs the table from scratch — there's no "single new structure"
369
- * to walk verbatim, since we're stitching together kept rows from both
370
- * sides.
371
- */
372
- function diffStructurallyAlignedTable(
373
- oldHtml: string,
374
- newHtml: string,
375
- oldTable: TableRange,
376
- newTable: TableRange,
377
- diffCell: DiffCellFn
378
- ): string {
379
- const oldKeys = oldTable.rows.map(row => rowKey(oldHtml, row))
380
- const newKeys = newTable.rows.map(row => rowKey(newHtml, row))
381
- const exactAlignment = lcsAlign(oldKeys, newKeys)
382
- const paired = pairSimilarUnmatchedRows(exactAlignment, oldTable, newTable, oldHtml, newHtml)
383
- // Reorder so unpaired deleted rows appear at their *natural old-side
384
- // position* — immediately after the preserved/paired row that came
385
- // before them in old. Without this, runs of unpaired dels at low
386
- // alignment indices end up emitted before any preserved row (the
387
- // "deleted rows out of order" bug).
388
- const alignment = orderAlignmentForEmission(paired)
389
-
390
- // Walk new's tableStart→tableEnd, substituting rows with their diffed
391
- // form so `<thead>`/`<tbody>` wrappers and inter-row whitespace are
392
- // preserved verbatim. Deleted rows (no position in new) are injected
393
- // inline at the cursor's current position, which now corresponds to
394
- // their natural old-side slot thanks to the reordering above. If new
395
- // has no rows at all, fall back to a from-scratch reconstruction so
396
- // we still emit deleted rows.
397
- if (newTable.rows.length === 0) {
398
- return rebuildStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, alignment, diffCell)
399
- }
400
-
401
- const out: string[] = []
402
- out.push(newHtml.slice(newTable.tableStart, newTable.rows[0].rowStart))
403
- let cursor = newTable.rows[0].rowStart
404
- for (const align of alignment) {
405
- if (align.newIdx !== null) {
406
- const newRow = newTable.rows[align.newIdx]
407
- out.push(newHtml.slice(cursor, newRow.rowStart))
408
- if (align.oldIdx !== null) {
409
- out.push(diffPreservedRow(oldHtml, newHtml, oldTable.rows[align.oldIdx], newRow, diffCell))
410
- } else {
411
- out.push(emitFullRow(newHtml, newRow, 'ins', diffCell))
412
- }
413
- cursor = newRow.rowEnd
414
- } else if (align.oldIdx !== null) {
415
- out.push(emitFullRow(oldHtml, oldTable.rows[align.oldIdx], 'del', diffCell))
416
- }
417
- }
418
- out.push(newHtml.slice(cursor, newTable.tableEnd))
419
- return out.join('')
420
- }
421
-
422
- /**
423
- * Reorders the alignment so emission produces rows in the visually-
424
- * correct order. Each entry is assigned a fractional "position" in
425
- * new's flow:
426
- *
427
- * • Preserved/paired (oldIdx, newIdx): position = newIdx.
428
- * • Pure insert (null, newIdx): position = newIdx.
429
- * • Pure delete (oldIdx, null): position = newIdx-of-preserved-just-
430
- * before-this-oldIdx + 0.5. Dels at the same gap sort by oldIdx so
431
- * they appear in old's row order. The +0.5 places dels BEFORE any
432
- * insert at the same gap (insert at newIdx N1+1 has position N1+1
433
- * which is > N1+0.5), giving the natural "delete first, insert
434
- * second" reading order at a replaced position.
435
- *
436
- * This handles the full range:
437
- * • Run of unpaired dels at the start (no preserved predecessor):
438
- * position -0.5, sorted by oldIdx.
439
- * • Dels in the middle: positioned right after their preceding
440
- * preserved row.
441
- * • Dels at the end (no preserved successor): positioned after the
442
- * last preserved row.
443
- *
444
- * Without this reordering, a run of unpaired deletes at low alignment
445
- * indices got emitted at cursor = first-new-row position — putting
446
- * all deletes before any preserved row in the output, regardless of
447
- * where they came from in old.
448
- */
449
- function orderAlignmentForEmission(alignment: Alignment[]): Alignment[] {
450
- const preserved: Array<{ oldIdx: number; newIdx: number }> = []
451
- for (const a of alignment) {
452
- if (a.oldIdx !== null && a.newIdx !== null) {
453
- preserved.push({ oldIdx: a.oldIdx, newIdx: a.newIdx })
454
- }
455
- }
456
- preserved.sort((a, b) => a.oldIdx - b.oldIdx)
457
-
458
- // For a deleted row with oldIdx K, return the newIdx of the preserved
459
- // entry with the largest oldIdx less than K, or -1 if none.
460
- function newIdxOfPreservedBefore(oldIdx: number): number {
461
- let result = -1
462
- for (const p of preserved) {
463
- if (p.oldIdx >= oldIdx) break
464
- result = p.newIdx
465
- }
466
- return result
467
- }
468
-
469
- // Decorate each alignment with a fractional position. We use
470
- // (primary, secondary) tuples so dels at the same gap sort by oldIdx
471
- // (in old's row order) and inserts at the same newIdx stay stable.
472
- const decorated = alignment.map((a, i) => {
473
- let primary: number
474
- let secondary: number
475
- if (a.newIdx !== null) {
476
- primary = a.newIdx
477
- secondary = a.oldIdx === null ? 1 : 0 // preserved before pure-insert at same newIdx (rare)
478
- } else {
479
- // Pure delete
480
- primary = newIdxOfPreservedBefore(a.oldIdx as number) + 0.5
481
- secondary = a.oldIdx as number
482
- }
483
- return { entry: a, primary, secondary, originalIdx: i }
484
- })
485
-
486
- decorated.sort((a, b) => {
487
- if (a.primary !== b.primary) return a.primary - b.primary
488
- if (a.secondary !== b.secondary) return a.secondary - b.secondary
489
- return a.originalIdx - b.originalIdx // stable
490
- })
491
-
492
- return decorated.map(d => d.entry)
493
- }
494
-
495
- function rebuildStructurallyAlignedTable(
496
- oldHtml: string,
497
- newHtml: string,
498
- oldTable: TableRange,
499
- newTable: TableRange,
500
- alignment: Alignment[],
501
- diffCell: DiffCellFn
502
- ): string {
503
- // Used when new has no rows but old does — we lose the per-row
504
- // wrappers from new (there are none), so reconstruct from old's frame.
505
- const out: string[] = []
506
- out.push(headerSlice(newHtml, newTable, oldHtml, oldTable))
507
- for (const align of alignment) {
508
- if (align.oldIdx !== null) {
509
- out.push(emitFullRow(oldHtml, oldTable.rows[align.oldIdx], 'del', diffCell))
510
- } else if (align.newIdx !== null) {
511
- out.push(emitFullRow(newHtml, newTable.rows[align.newIdx], 'ins', diffCell))
512
- }
513
- }
514
- out.push('</table>')
515
- return out.join('')
516
- }
517
-
518
- function headerSlice(newHtml: string, newTable: TableRange, oldHtml: string, oldTable: TableRange): string {
519
- // Slice from <table> to the start of the first <tr>. Prefer new since
520
- // attribute changes on <table> itself should follow new.
521
- const newFirstRow = newTable.rows[0]?.rowStart ?? newTable.tableEnd - '</table>'.length
522
- if (newFirstRow > newTable.tableStart) {
523
- return newHtml.slice(newTable.tableStart, newFirstRow)
524
- }
525
- const oldFirstRow = oldTable.rows[0]?.rowStart ?? oldTable.tableEnd - '</table>'.length
526
- return oldHtml.slice(oldTable.tableStart, oldFirstRow)
527
- }
528
-
529
- function rowKey(html: string, row: RowRange): string {
530
- // Include cell tag text in the key so column-add doesn't accidentally
531
- // match a row to one with different cell counts. Whitespace-normalize to
532
- // tolerate formatting differences.
533
- return html.slice(row.rowStart, row.rowEnd).replace(/\s+/g, ' ').trim()
534
- }
535
-
536
- function diffPreservedRow(
537
- oldHtml: string,
538
- newHtml: string,
539
- oldRow: RowRange,
540
- newRow: RowRange,
541
- diffCell: DiffCellFn
542
- ): string {
543
- if (oldRow.cells.length === newRow.cells.length) {
544
- return diffPositionalRow(oldHtml, newHtml, oldRow, newRow, diffCell)
545
- }
546
- // Cell counts differ. Try to interpret it as a horizontal merge/split via
547
- // colspan first — preserving the new structure with `class='mod colspan'`
548
- // on each affected cell.
549
- const colspanAligned = diffColspanChangedRow(oldHtml, newHtml, oldRow, newRow, diffCell)
550
- if (colspanAligned !== null) return colspanAligned
551
- // For a single-column add/delete (cell count differs by exactly 1),
552
- // detect the position via positional similarity scan and align the
553
- // remaining cells positionally. This handles the case where a column
554
- // was added AND a different cell got an unrelated content edit — the
555
- // edited cell still aligns by position rather than getting orphaned by
556
- // the cell-LCS exact-match.
557
- const delta = newRow.cells.length - oldRow.cells.length
558
- // For column add/delete (cell counts differ), find the best insertion
559
- // or deletion positions via positional similarity scan and align the
560
- // remaining cells positionally. This handles content-edit alongside
561
- // column-add by keeping the edited cell in its column position rather
562
- // than orphaning it via the cell-LCS exact match.
563
- // Guardrail: combinatorial search is C(newCount, k); we cap to avoid
564
- // explosion on very wide tables. The cap is generous for real legal
565
- // schedules; anything above falls through to cell-LCS.
566
- const absDelta = Math.abs(delta)
567
- if (
568
- absDelta > 0 &&
569
- absDelta <= MAX_COLUMN_DELTA &&
570
- Math.max(oldRow.cells.length, newRow.cells.length) <= MAX_COLUMN_SEARCH_WIDTH
571
- ) {
572
- if (delta > 0) return diffMultiColumnAddRow(oldHtml, newHtml, oldRow, newRow, delta, diffCell)
573
- return diffMultiColumnDeleteRow(oldHtml, newHtml, oldRow, newRow, -delta, diffCell)
574
- }
575
- return diffStructurallyAlignedRow(oldHtml, newHtml, oldRow, newRow, diffCell)
576
- }
577
-
578
- const MAX_COLUMN_DELTA = 6
579
- const MAX_COLUMN_SEARCH_WIDTH = 40
580
-
581
- /**
582
- * For a row where new has K more cells than old, find the K column
583
- * positions in new where cells were inserted by scanning all C(newCount,
584
- * K) combinations and picking the one that maximises positional content
585
- * similarity with the remaining cells. The inserted cells are emitted
586
- * with diff markers; the rest are aligned positionally with content
587
- * diff for matched pairs.
588
- */
589
- function diffMultiColumnAddRow(
590
- oldHtml: string,
591
- newHtml: string,
592
- oldRow: RowRange,
593
- newRow: RowRange,
594
- k: number,
595
- diffCell: DiffCellFn
596
- ): string {
597
- const insertedPositions = findBestColumnInsertPositions(oldRow, newRow, k, oldHtml, newHtml)
598
- const inserted = new Set(insertedPositions)
599
- const out: string[] = [rowHeaderSlice(newHtml, newRow)]
600
- let oldIdx = 0
601
- for (let c = 0; c < newRow.cells.length; c++) {
602
- if (inserted.has(c)) {
603
- out.push(emitFullCell(newHtml, newRow.cells[c], 'ins', diffCell))
604
- } else {
605
- out.push(emitDiffedCell(oldHtml, newHtml, oldRow.cells[oldIdx], newRow.cells[c], diffCell))
606
- oldIdx++
607
- }
608
- }
609
- out.push('</tr>')
610
- return out.join('')
611
- }
612
-
613
- function diffMultiColumnDeleteRow(
614
- oldHtml: string,
615
- newHtml: string,
616
- oldRow: RowRange,
617
- newRow: RowRange,
618
- k: number,
619
- diffCell: DiffCellFn
620
- ): string {
621
- const deletedPositions = findBestColumnDeletePositions(oldRow, newRow, k, oldHtml, newHtml)
622
- const deleted = new Set(deletedPositions)
623
- const out: string[] = [rowHeaderSlice(newHtml, newRow)]
624
- let newIdx = 0
625
- for (let oldIdx = 0; oldIdx < oldRow.cells.length; oldIdx++) {
626
- if (deleted.has(oldIdx)) {
627
- out.push(emitFullCell(oldHtml, oldRow.cells[oldIdx], 'del', diffCell))
628
- continue
629
- }
630
- out.push(emitDiffedCell(oldHtml, newHtml, oldRow.cells[oldIdx], newRow.cells[newIdx], diffCell))
631
- newIdx++
632
- }
633
- out.push('</tr>')
634
- return out.join('')
635
- }
636
-
637
- function findBestColumnInsertPositions(
638
- oldRow: RowRange,
639
- newRow: RowRange,
640
- k: number,
641
- oldHtml: string,
642
- newHtml: string
643
- ): number[] {
644
- let bestPositions: number[] = []
645
- let bestScore = -1
646
- for (const combo of combinationsOfRange(newRow.cells.length, k)) {
647
- const inserted = new Set(combo)
648
- let score = 0
649
- let oldIdx = 0
650
- for (let newIdx = 0; newIdx < newRow.cells.length; newIdx++) {
651
- if (inserted.has(newIdx)) continue
652
- score += cellSimilarity(oldRow.cells[oldIdx], newRow.cells[newIdx], oldHtml, newHtml)
653
- oldIdx++
654
- }
655
- if (score > bestScore) {
656
- bestScore = score
657
- bestPositions = combo
658
- }
659
- }
660
- return bestPositions
661
- }
662
-
663
- function findBestColumnDeletePositions(
664
- oldRow: RowRange,
665
- newRow: RowRange,
666
- k: number,
667
- oldHtml: string,
668
- newHtml: string
669
- ): number[] {
670
- let bestPositions: number[] = []
671
- let bestScore = -1
672
- for (const combo of combinationsOfRange(oldRow.cells.length, k)) {
673
- const deleted = new Set(combo)
674
- let score = 0
675
- let newIdx = 0
676
- for (let oldIdx = 0; oldIdx < oldRow.cells.length; oldIdx++) {
677
- if (deleted.has(oldIdx)) continue
678
- score += cellSimilarity(oldRow.cells[oldIdx], newRow.cells[newIdx], oldHtml, newHtml)
679
- newIdx++
680
- }
681
- if (score > bestScore) {
682
- bestScore = score
683
- bestPositions = combo
684
- }
685
- }
686
- return bestPositions
687
- }
688
-
689
- /**
690
- * Yields all sorted-ascending combinations of `k` distinct integers
691
- * from [0, n). Iterative implementation avoids recursion overhead and
692
- * keeps memory at O(k).
693
- */
694
- function* combinationsOfRange(n: number, k: number): IterableIterator<number[]> {
695
- if (k === 0 || k > n) return
696
- const indices = Array.from({ length: k }, (_, i) => i)
697
- while (true) {
698
- yield indices.slice()
699
- let i = k - 1
700
- while (i >= 0 && indices[i] === n - k + i) i--
701
- if (i < 0) return
702
- indices[i]++
703
- for (let j = i + 1; j < k; j++) indices[j] = indices[j - 1] + 1
704
- }
705
- }
706
-
707
- /**
708
- * Try to align cells by logical column position (sum of colspans). When
709
- * one side has a colspan'd cell that absorbs multiple cells on the other
710
- * side, emit the new structure with `class='mod colspan'` on the
711
- * merged/split cells. Returns null if the rows don't align cleanly —
712
- * caller falls back to a generic cell-LCS.
713
- */
714
- function diffColspanChangedRow(
715
- oldHtml: string,
716
- newHtml: string,
717
- oldRow: RowRange,
718
- newRow: RowRange,
719
- diffCell: DiffCellFn
720
- ): string | null {
721
- const oldWidth = sumColspans(oldHtml, oldRow.cells)
722
- const newWidth = sumColspans(newHtml, newRow.cells)
723
- if (oldWidth !== newWidth) return null
724
-
725
- const out: string[] = []
726
- out.push(rowHeaderSlice(newHtml, newRow))
727
-
728
- let oi = 0
729
- let ni = 0
730
- while (oi < oldRow.cells.length && ni < newRow.cells.length) {
731
- const oCell = oldRow.cells[oi]
732
- const nCell = newRow.cells[ni]
733
- const oSpan = getColspan(oldHtml, oCell)
734
- const nSpan = getColspan(newHtml, nCell)
735
-
736
- if (oSpan === nSpan) {
737
- out.push(emitDiffedCell(oldHtml, newHtml, oCell, nCell, diffCell))
738
- oi++
739
- ni++
740
- } else if (nSpan > oSpan) {
741
- // New cell absorbs multiple old cells — horizontal merge.
742
- let totalOldSpan = 0
743
- let oj = oi
744
- while (oj < oldRow.cells.length && totalOldSpan < nSpan) {
745
- totalOldSpan += getColspan(oldHtml, oldRow.cells[oj])
746
- oj++
747
- }
748
- if (totalOldSpan !== nSpan) return null
749
- out.push(emitSpanChangedCell(newHtml, nCell, 'colspan'))
750
- oi = oj
751
- ni++
752
- } else {
753
- // One old cell becomes multiple new cells — horizontal split.
754
- let totalNewSpan = 0
755
- let nj = ni
756
- while (nj < newRow.cells.length && totalNewSpan < oSpan) {
757
- totalNewSpan += getColspan(newHtml, newRow.cells[nj])
758
- nj++
759
- }
760
- if (totalNewSpan !== oSpan) return null
761
- for (let k = ni; k < nj; k++) {
762
- out.push(emitSpanChangedCell(newHtml, newRow.cells[k], 'colspan'))
763
- }
764
- oi++
765
- ni = nj
766
- }
767
- }
768
-
769
- // If we couldn't consume both sides cleanly, bail out.
770
- if (oi !== oldRow.cells.length || ni !== newRow.cells.length) return null
771
-
772
- out.push('</tr>')
773
- return out.join('')
774
- }
775
-
776
- function sumColspans(html: string, cells: CellRange[]): number {
777
- let total = 0
778
- for (const cell of cells) total += getColspan(html, cell)
779
- return total
780
- }
781
-
782
- function getColspan(html: string, cell: CellRange): number {
783
- return parseSpanAttribute(html.slice(cell.cellStart, cell.contentStart), 'colspan')
784
- }
785
-
786
- function getRowspan(html: string, cell: CellRange): number {
787
- return parseSpanAttribute(html.slice(cell.cellStart, cell.contentStart), 'rowspan')
788
- }
789
-
790
- function parseSpanAttribute(openingTag: string, name: 'colspan' | 'rowspan'): number {
791
- const re = name === 'colspan' ? /\bcolspan\s*=\s*["']?(\d+)["']?/i : /\browspan\s*=\s*["']?(\d+)["']?/i
792
- const m = re.exec(openingTag)
793
- if (!m) return 1
794
- const value = Number.parseInt(m[1], 10)
795
- return Number.isFinite(value) && value > 0 ? value : 1
796
- }
797
-
798
- /**
799
- * Emits a cell that's the merged/split product of a structural change,
800
- * tagged with `class='mod colspan'` or `class='mod rowspan'`. Content is
801
- * carried through unmodified — Word doesn't track these changes, and
802
- * inserting del/ins around content that didn't really change would be
803
- * misleading.
804
- */
805
- function emitSpanChangedCell(html: string, cell: CellRange, kind: 'colspan' | 'rowspan'): string {
806
- const tdOpening = parseOpeningTagAt(html, cell.cellStart)
807
- if (!tdOpening) return html.slice(cell.cellStart, cell.cellEnd)
808
- const tdOpenTag = injectClass(html.slice(cell.cellStart, tdOpening.end), `mod ${kind}`)
809
- return tdOpenTag + html.slice(cell.contentStart, cell.cellEnd)
810
- }
811
-
812
- function diffPositionalRow(
813
- oldHtml: string,
814
- newHtml: string,
815
- oldRow: RowRange,
816
- newRow: RowRange,
817
- diffCell: DiffCellFn
818
- ): string {
819
- const out: string[] = []
820
- // Use new's <tr> opening tag (preserves attributes from new).
821
- const trHeader = rowHeaderSlice(newHtml, newRow)
822
- out.push(trHeader)
823
-
824
- let cursor = newRow.cells[0]?.cellStart ?? newRow.rowEnd
825
- for (let c = 0; c < newRow.cells.length; c++) {
826
- const oldCell = oldRow.cells[c]
827
- const newCell = newRow.cells[c]
828
- out.push(newHtml.slice(cursor, newCell.contentStart))
829
- out.push(
830
- diffCell(
831
- oldHtml.slice(oldCell.contentStart, oldCell.contentEnd),
832
- newHtml.slice(newCell.contentStart, newCell.contentEnd)
833
- )
834
- )
835
- cursor = newCell.contentEnd
836
- }
837
- out.push(newHtml.slice(cursor, newRow.rowEnd))
838
- return out.join('')
839
- }
840
-
841
- function diffStructurallyAlignedRow(
842
- oldHtml: string,
843
- newHtml: string,
844
- oldRow: RowRange,
845
- newRow: RowRange,
846
- diffCell: DiffCellFn
847
- ): string {
848
- const oldKeys = oldRow.cells.map(cell => cellKey(oldHtml, cell))
849
- const newKeys = newRow.cells.map(cell => cellKey(newHtml, cell))
850
- const exactAlignment = lcsAlign(oldKeys, newKeys)
851
- // After exact LCS, fuzzy-pair adjacent unmatched old/new cells whose
852
- // content is similar enough — so a content-edit cell alongside a
853
- // column-add in the same row produces a content diff for the edited
854
- // cell rather than a phantom delete + insert + extra cell.
855
- const alignment = pairSimilarUnmatchedCells(exactAlignment, oldRow, newRow, oldHtml, newHtml)
856
-
857
- const out: string[] = []
858
- // Use new's <tr> if it exists; otherwise old's.
859
- out.push(rowHeaderSlice(newHtml, newRow))
860
-
861
- for (const align of alignment) {
862
- if (align.oldIdx !== null && align.newIdx !== null) {
863
- const oldCell = oldRow.cells[align.oldIdx]
864
- const newCell = newRow.cells[align.newIdx]
865
- out.push(emitDiffedCell(oldHtml, newHtml, oldCell, newCell, diffCell))
866
- } else if (align.newIdx !== null) {
867
- out.push(emitFullCell(newHtml, newRow.cells[align.newIdx], 'ins', diffCell))
868
- } else if (align.oldIdx !== null) {
869
- out.push(emitFullCell(oldHtml, oldRow.cells[align.oldIdx], 'del', diffCell))
870
- }
871
- }
872
-
873
- out.push('</tr>')
874
- return out.join('')
875
- }
876
-
877
- function cellKey(html: string, cell: CellRange): string {
878
- // Use cell content (not tag attributes) for matching, since column-add
879
- // typically changes content but not tag attributes — and matching purely
880
- // on attributes would mis-pair cells with the same content but different
881
- // styling.
882
- return html.slice(cell.contentStart, cell.contentEnd).replace(/\s+/g, ' ').trim()
883
- }
884
-
885
- /**
886
- * Emits a row with all cells either inserted (kind='ins') or deleted
887
- * (kind='del'). Adds `class='diffins'`/`'diffdel'` to the `<tr>` and to
888
- * each `<td>`, with an `<ins>`/`<del>` wrapper around any cell content
889
- * (empty cells get the class but no wrapper).
890
- */
891
- function emitFullRow(html: string, row: RowRange, kind: 'ins' | 'del', diffCell: DiffCellFn): string {
892
- const cls = kind === 'ins' ? 'diffins' : 'diffdel'
893
- const trOpening = parseOpeningTagAt(html, row.rowStart)
894
- if (!trOpening) return html.slice(row.rowStart, row.rowEnd)
895
- const trOpenTag = injectClass(html.slice(row.rowStart, trOpening.end), cls)
896
-
897
- const out: string[] = [trOpenTag]
898
- let cursor = trOpening.end
899
- for (const cell of row.cells) {
900
- out.push(html.slice(cursor, cell.cellStart))
901
- out.push(emitFullCell(html, cell, kind, diffCell))
902
- cursor = cell.cellEnd
903
- }
904
- out.push(html.slice(cursor, row.rowEnd))
905
- return out.join('')
906
- }
907
-
908
- /**
909
- * Emits a fully-inserted or fully-deleted cell. Inner text runs are wrapped
910
- * with `<ins>`/`<del>` while formatting tags pass through unchanged, so
911
- * `<strong>B</strong>` renders as `<strong><ins>B</ins></strong>` —
912
- * matching htmldiff's general convention without the doubled-`<ins>` that
913
- * the full recursive diff would produce for newly-inserted formatting.
914
- * Empty cells get the class on the `<td>` but no inner wrapping.
915
- */
916
- function emitFullCell(html: string, cell: CellRange, kind: 'ins' | 'del', _diffCell: DiffCellFn): string {
917
- const cls = kind === 'ins' ? 'diffins' : 'diffdel'
918
- const tdOpening = parseOpeningTagAt(html, cell.cellStart)
919
- if (!tdOpening) return html.slice(cell.cellStart, cell.cellEnd)
920
- const tdOpenTag = injectClass(html.slice(cell.cellStart, tdOpening.end), cls)
921
-
922
- const content = html.slice(cell.contentStart, cell.contentEnd)
923
- const wrapped = content.trim().length === 0 ? content : wrapInlineTextRuns(content, kind)
924
- const closing = html.slice(cell.contentEnd, cell.cellEnd)
925
- return tdOpenTag + wrapped + closing
926
- }
927
-
928
- /**
929
- * Wraps every non-whitespace text run in the given content with an
930
- * `<ins>`/`<del>` tag, leaving HTML tags untouched. This produces output
931
- * like `<strong><ins>X</ins></strong>` for fully-inserted formatted
932
- * content — the same shape the rest of htmldiff emits for content
933
- * insertions inside existing formatting.
934
- */
935
- function wrapInlineTextRuns(content: string, kind: 'ins' | 'del'): string {
936
- const tag = kind === 'ins' ? 'ins' : 'del'
937
- const cls = kind === 'ins' ? 'diffins' : 'diffdel'
938
-
939
- const out: string[] = []
940
- let i = 0
941
- while (i < content.length) {
942
- if (content[i] === '<') {
943
- const tagEnd = parseOpeningTagAt(content, i)
944
- if (!tagEnd) {
945
- // Malformed — pass the rest through verbatim.
946
- out.push(content.slice(i))
947
- break
948
- }
949
- out.push(content.slice(i, tagEnd.end))
950
- i = tagEnd.end
951
- continue
952
- }
953
- let j = i
954
- while (j < content.length && content[j] !== '<') j++
955
- const text = content.slice(i, j)
956
- if (text.trim().length > 0) {
957
- out.push(`<${tag} class='${cls}'>${text}</${tag}>`)
958
- } else {
959
- out.push(text)
960
- }
961
- i = j
962
- }
963
- return out.join('')
964
- }
965
-
966
- function emitDiffedCell(
967
- oldHtml: string,
968
- newHtml: string,
969
- oldCell: CellRange,
970
- newCell: CellRange,
971
- diffCell: DiffCellFn
972
- ): string {
973
- const tdOpening = parseOpeningTagAt(newHtml, newCell.cellStart)
974
- if (!tdOpening) return newHtml.slice(newCell.cellStart, newCell.cellEnd)
975
- const tdOpenTag = newHtml.slice(newCell.cellStart, tdOpening.end)
976
- const content = diffCell(
977
- oldHtml.slice(oldCell.contentStart, oldCell.contentEnd),
978
- newHtml.slice(newCell.contentStart, newCell.contentEnd)
979
- )
980
- const closing = newHtml.slice(newCell.contentEnd, newCell.cellEnd)
981
- return tdOpenTag + content + closing
982
- }
983
-
984
- function rowHeaderSlice(html: string, row: RowRange): string {
985
- // Slice from <tr> to just before the first <td> opening tag. Preserves
986
- // the <tr ...> attributes plus any inter-tag whitespace. For a row with
987
- // no cells, we only want the `<tr ...>` opening — the caller appends the
988
- // closing `</tr>` explicitly, so taking the whole `<tr></tr>` here would
989
- // double the close.
990
- const opening = parseOpeningTagAt(html, row.rowStart)
991
- if (!opening) return ''
992
- if (row.cells.length === 0) return html.slice(row.rowStart, opening.end)
993
- return html.slice(row.rowStart, row.cells[0].cellStart)
994
- }
995
-
996
- interface Alignment {
997
- oldIdx: number | null
998
- newIdx: number | null
999
- }
1000
-
1001
- /** Character-level similarity threshold above which we treat two rows as "the same row, edited". */
1002
- const ROW_FUZZY_THRESHOLD = 0.5
1003
-
1004
- /**
1005
- * Threshold for "this cell is a content-edit of that cell." Tuned the same
1006
- * as ROW_FUZZY_THRESHOLD; cells in legal docs that share most of their
1007
- * content typically ARE the same logical cell with a body edit, so 0.5
1008
- * works for both granularities in practice.
1009
- */
1010
- const CELL_FUZZY_THRESHOLD = 0.5
1011
-
1012
- /**
1013
- * After exact LCS, scan the alignment for runs of "old deleted, then new
1014
- * inserted" (or vice versa) and pair entries whose content is similar
1015
- * enough to be treated as an edit rather than a delete+insert. This keeps
1016
- * row-level edits (a typo fix, a single word change) from being shown as
1017
- * an entire row vanishing and a new one appearing — matching what users
1018
- * expect from a typical track-changes view.
1019
- */
1020
- function pairSimilarUnmatchedRows(
1021
- alignment: Alignment[],
1022
- oldTable: TableRange,
1023
- newTable: TableRange,
1024
- oldHtml: string,
1025
- newHtml: string
1026
- ): Alignment[] {
1027
- return pairSimilarUnmatched(alignment, ROW_FUZZY_THRESHOLD, (oldIdx, newIdx) =>
1028
- rowSimilarity(oldTable.rows[oldIdx], newTable.rows[newIdx], oldHtml, newHtml)
1029
- )
1030
- }
1031
-
1032
- function pairSimilarUnmatchedCells(
1033
- alignment: Alignment[],
1034
- oldRow: RowRange,
1035
- newRow: RowRange,
1036
- oldHtml: string,
1037
- newHtml: string
1038
- ): Alignment[] {
1039
- return pairSimilarUnmatched(alignment, CELL_FUZZY_THRESHOLD, (oldIdx, newIdx) =>
1040
- cellSimilarity(oldRow.cells[oldIdx], newRow.cells[newIdx], oldHtml, newHtml)
1041
- )
1042
- }
1043
-
1044
- /**
1045
- * Identify pairings inside each unmatched-only run, then build the output
1046
- * alignment by walking the original and substituting paired entries at
1047
- * the *ins position* (not the del position). This keeps the result
1048
- * monotonic in newIdx — critical because the cursor-based emission
1049
- * downstream walks new's html in order. Emitting at the del position
1050
- * would be fine when del<ins in the alignment array (the typical case),
1051
- * but can violate monotonicity when there are mixed unpaired entries in
1052
- * between (column-add + row-add together, content-edit + column-add,
1053
- * etc.).
1054
- *
1055
- * Generic over what's being paired — works for both rows (by full row
1056
- * content similarity) and cells (by per-cell content similarity).
1057
- */
1058
- function pairSimilarUnmatched(
1059
- alignment: Alignment[],
1060
- threshold: number,
1061
- similarity: (oldIdx: number, newIdx: number) => number
1062
- ): Alignment[] {
1063
- const pairs = new Map<number, number>() // del-alignment-idx → ins-alignment-idx
1064
- let i = 0
1065
- while (i < alignment.length) {
1066
- if (alignment[i].oldIdx !== null && alignment[i].newIdx !== null) {
1067
- i++
1068
- continue
1069
- }
1070
- const runStart = i
1071
- while (i < alignment.length && (alignment[i].oldIdx === null) !== (alignment[i].newIdx === null)) i++
1072
- const runEnd = i
1073
-
1074
- const delIndices: number[] = []
1075
- const insIndices: number[] = []
1076
- for (let k = runStart; k < runEnd; k++) {
1077
- if (alignment[k].oldIdx !== null) delIndices.push(k)
1078
- else insIndices.push(k)
1079
- }
1080
-
1081
- const usedIns = new Set<number>()
1082
- for (const di of delIndices) {
1083
- let bestIi = -1
1084
- let bestSim = threshold
1085
- for (const ii of insIndices) {
1086
- if (usedIns.has(ii)) continue
1087
- const sim = similarity(alignment[di].oldIdx as number, alignment[ii].newIdx as number)
1088
- if (sim > bestSim) {
1089
- bestSim = sim
1090
- bestIi = ii
1091
- }
1092
- }
1093
- if (bestIi >= 0) {
1094
- pairs.set(di, bestIi)
1095
- usedIns.add(bestIi)
1096
- }
1097
- }
1098
- }
1099
-
1100
- const insToDel = new Map<number, number>() // ins-alignment-idx → del-alignment-idx
1101
- for (const [delAi, insAi] of pairs) insToDel.set(insAi, delAi)
1102
- const pairedDels = new Set<number>(pairs.keys())
1103
-
1104
- const result: Alignment[] = []
1105
- for (let k = 0; k < alignment.length; k++) {
1106
- if (pairedDels.has(k)) continue // paired del — emitted when we reach its ins
1107
- if (insToDel.has(k)) {
1108
- const delAi = insToDel.get(k) as number
1109
- result.push({ oldIdx: alignment[delAi].oldIdx, newIdx: alignment[k].newIdx })
1110
- } else {
1111
- result.push(alignment[k])
1112
- }
1113
- }
1114
- return result
1115
- }
1116
-
1117
- /**
1118
- * Combined similarity metric used for both row-level and cell-level
1119
- * fuzzy pairing. Returns the MAX of two complementary metrics:
1120
- *
1121
- * 1. **Character prefix+suffix similarity** — fraction of the longer
1122
- * string covered by shared prefix + shared suffix. Catches small
1123
- * edits in the middle of a string (one word changed in a row).
1124
- * Misses cases where the bulk of common content is in the middle
1125
- * and the ends differ.
1126
- *
1127
- * 2. **Token Jaccard similarity** — intersection-over-union of the
1128
- * whitespace-split tokens. Catches "most of the content is the
1129
- * same but bookended by different bits" — e.g. a row whose only
1130
- * edit is a column added at the start and another at the end,
1131
- * where the ~50 chars in the middle that DO match would be
1132
- * invisible to prefix+suffix.
1133
- *
1134
- * Either metric exceeding the threshold means pair. Neither alone is
1135
- * sufficient for the full range of legal-doc edits we see in
1136
- * production tables.
1137
- */
1138
- function rowSimilarity(oldRow: RowRange, newRow: RowRange, oldHtml: string, newHtml: string): number {
1139
- return textSimilarity(rowText(oldHtml, oldRow), rowText(newHtml, newRow))
1140
- }
1141
-
1142
- function cellSimilarity(oldCell: CellRange, newCell: CellRange, oldHtml: string, newHtml: string): number {
1143
- return textSimilarity(cellText(oldHtml, oldCell), cellText(newHtml, newCell))
1144
- }
1145
-
1146
- function textSimilarity(a: string, b: string): number {
1147
- if (a === b) return 1
1148
- if (a.length === 0 || b.length === 0) return 0
1149
- return Math.max(charPrefixSuffixSimilarity(a, b), tokenJaccardSimilarity(a, b))
1150
- }
1151
-
1152
- function charPrefixSuffixSimilarity(a: string, b: string): number {
1153
- let prefix = 0
1154
- const minLen = Math.min(a.length, b.length)
1155
- while (prefix < minLen && a[prefix] === b[prefix]) prefix++
1156
-
1157
- let suffix = 0
1158
- while (
1159
- suffix < a.length - prefix &&
1160
- suffix < b.length - prefix &&
1161
- a[a.length - 1 - suffix] === b[b.length - 1 - suffix]
1162
- ) {
1163
- suffix++
1164
- }
1165
-
1166
- return (prefix + suffix) / Math.max(a.length, b.length)
1167
- }
1168
-
1169
- function tokenJaccardSimilarity(a: string, b: string): number {
1170
- const tokensA = new Set(a.split(/\s+/).filter(Boolean))
1171
- const tokensB = new Set(b.split(/\s+/).filter(Boolean))
1172
- if (tokensA.size === 0 && tokensB.size === 0) return 1
1173
- let intersection = 0
1174
- for (const t of tokensA) {
1175
- if (tokensB.has(t)) intersection++
1176
- }
1177
- const union = tokensA.size + tokensB.size - intersection
1178
- return union === 0 ? 0 : intersection / union
1179
- }
1180
-
1181
- function rowText(html: string, row: RowRange): string {
1182
- const parts: string[] = []
1183
- for (const cell of row.cells) {
1184
- parts.push(html.slice(cell.contentStart, cell.contentEnd).replace(/<[^>]+>/g, ' '))
1185
- }
1186
- return parts.join(' ').replace(/\s+/g, ' ').trim().toLowerCase()
1187
- }
1188
-
1189
- function cellText(html: string, cell: CellRange): string {
1190
- return html
1191
- .slice(cell.contentStart, cell.contentEnd)
1192
- .replace(/<[^>]+>/g, ' ')
1193
- .replace(/\s+/g, ' ')
1194
- .trim()
1195
- .toLowerCase()
1196
- }
1197
-
1198
- /**
1199
- * Standard LCS alignment: walks both sequences and emits a list of pairs
1200
- * where `(oldIdx, newIdx)` are both set for matching positions, and one
1201
- * side is null for an unmatched entry on the other side. Equality uses
1202
- * strict ===.
1203
- */
1204
- function lcsAlign(oldKeys: string[], newKeys: string[]): Alignment[] {
1205
- const m = oldKeys.length
1206
- const n = newKeys.length
1207
- const dp: number[][] = Array.from({ length: m + 1 }, () => new Array<number>(n + 1).fill(0))
1208
- for (let i = 1; i <= m; i++) {
1209
- for (let j = 1; j <= n; j++) {
1210
- if (oldKeys[i - 1] === newKeys[j - 1]) {
1211
- dp[i][j] = dp[i - 1][j - 1] + 1
1212
- } else {
1213
- dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])
1214
- }
1215
- }
1216
- }
1217
-
1218
- const result: Alignment[] = []
1219
- let i = m
1220
- let j = n
1221
- while (i > 0 || j > 0) {
1222
- if (i > 0 && j > 0 && oldKeys[i - 1] === newKeys[j - 1]) {
1223
- result.unshift({ oldIdx: i - 1, newIdx: j - 1 })
1224
- i--
1225
- j--
1226
- } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
1227
- result.unshift({ oldIdx: null, newIdx: j - 1 })
1228
- j--
1229
- } else {
1230
- result.unshift({ oldIdx: i - 1, newIdx: null })
1231
- i--
1232
- }
1233
- }
1234
- return result
1235
- }
1236
-
1237
- /**
1238
- * Returns the opening tag string with the given class injected. Existing
1239
- * `class` attributes are preserved and the new class appended.
1240
- */
1241
- /**
1242
- * Returns the opening tag with the given class injected. Locates the real
1243
- * `class` attribute via attribute-aware walking (NOT a flat regex — that
1244
- * would mis-match inside a foreign attribute value like
1245
- * `title="see class='x'"`). When the class already partially overlaps with
1246
- * `cls` — e.g. existing `class="mod"` and we're injecting `mod colspan` —
1247
- * only the missing tokens get appended, so we never end up with
1248
- * `class="mod mod colspan"`.
1249
- */
1250
- function injectClass(openingTag: string, cls: string): string {
1251
- const clsTokens = cls.split(/\s+/).filter(Boolean)
1252
- if (clsTokens.length === 0) return openingTag
1253
-
1254
- const classAttr = findClassAttribute(openingTag)
1255
- if (classAttr) {
1256
- const existingTokens = classAttr.value.split(/\s+/).filter(Boolean)
1257
- const missing = clsTokens.filter(t => !existingTokens.includes(t))
1258
- if (missing.length === 0) return openingTag
1259
- const updatedValue =
1260
- existingTokens.length === 0 ? missing.join(' ') : `${existingTokens.join(' ')} ${missing.join(' ')}`
1261
- return openingTag.slice(0, classAttr.valueStart) + updatedValue + openingTag.slice(classAttr.valueEnd)
1262
- }
1263
-
1264
- const isSelfClosing = openingTag.endsWith('/>')
1265
- const insertAt = isSelfClosing ? openingTag.length - 2 : openingTag.length - 1
1266
- return `${openingTag.slice(0, insertAt).replace(/\s*$/, '')} class='${cls}'${openingTag.slice(insertAt)}`
1267
- }
1268
-
1269
- /**
1270
- * Walks the opening tag's attributes (respecting quoted values) to find
1271
- * the actual `class` attribute. Returns the value range (start/end of the
1272
- * value content, *excluding* the surrounding quotes) and the value, or
1273
- * null if no `class` attribute is present.
1274
- */
1275
- function findClassAttribute(openingTag: string): { valueStart: number; valueEnd: number; value: string } | null {
1276
- // Skip past the tag name. Tag starts with `<`; first run of [A-Za-z0-9-]
1277
- // is the tag name. Anything after is attribute territory.
1278
- let i = 1
1279
- while (i < openingTag.length && /[A-Za-z0-9_:-]/.test(openingTag[i])) i++
1280
-
1281
- while (i < openingTag.length) {
1282
- // Skip whitespace
1283
- while (i < openingTag.length && /\s/.test(openingTag[i])) i++
1284
- if (i >= openingTag.length) break
1285
- if (openingTag[i] === '>' || openingTag[i] === '/') break
1286
-
1287
- // Read attribute name
1288
- const nameStart = i
1289
- while (i < openingTag.length && !/[\s=>/]/.test(openingTag[i])) i++
1290
- const name = openingTag.slice(nameStart, i)
1291
-
1292
- // Optional whitespace + '=' + optional whitespace + value
1293
- while (i < openingTag.length && /\s/.test(openingTag[i])) i++
1294
- if (openingTag[i] !== '=') {
1295
- // Bare attribute (no value) — not class
1296
- continue
1297
- }
1298
- i++ // past '='
1299
- while (i < openingTag.length && /\s/.test(openingTag[i])) i++
1300
-
1301
- // Value: quoted or unquoted
1302
- let valueStart: number
1303
- let valueEnd: number
1304
- if (openingTag[i] === '"' || openingTag[i] === "'") {
1305
- const quote = openingTag[i]
1306
- i++
1307
- valueStart = i
1308
- while (i < openingTag.length && openingTag[i] !== quote) i++
1309
- valueEnd = i
1310
- if (i < openingTag.length) i++ // past closing quote
1311
- } else {
1312
- valueStart = i
1313
- while (i < openingTag.length && !/[\s>/]/.test(openingTag[i])) i++
1314
- valueEnd = i
1315
- }
1316
-
1317
- if (name.toLowerCase() === 'class') {
1318
- return { valueStart, valueEnd, value: openingTag.slice(valueStart, valueEnd) }
1319
- }
1320
- }
1321
-
1322
- return null
1323
- }
1324
-
1325
- /**
1326
- * Walks html and returns ranges for every top-level `<table>...</table>`
1327
- * block. Nested tables aren't extracted as separate top-level entries —
1328
- * they're captured inside the parent's content range and handled when the
1329
- * cell-level diff recurses through them.
1330
- */
1331
- function findTopLevelTables(html: string): TableRange[] {
1332
- const tables: TableRange[] = []
1333
- let i = 0
1334
- while (i < html.length) {
1335
- if (matchesTagAt(html, i, 'table')) {
1336
- const opening = parseOpeningTagAt(html, i)
1337
- if (!opening) {
1338
- i++
1339
- continue
1340
- }
1341
- const tableContentStart = opening.end
1342
- const tableEnd = findMatchingClosingTag(html, tableContentStart, 'table')
1343
- if (tableEnd === -1) {
1344
- i = opening.end
1345
- continue
1346
- }
1347
- const closingTagStart = tableEnd - '</table>'.length
1348
- const rows = findTopLevelRows(html, tableContentStart, closingTagStart)
1349
- tables.push({ tableStart: i, tableEnd, rows })
1350
- i = tableEnd
1351
- } else {
1352
- i++
1353
- }
1354
- }
1355
- return tables
1356
- }
1357
-
1358
- function findTopLevelRows(html: string, start: number, end: number): RowRange[] {
1359
- const rows: RowRange[] = []
1360
- let i = start
1361
- while (i < end) {
1362
- if (matchesTagAt(html, i, 'tr')) {
1363
- const opening = parseOpeningTagAt(html, i)
1364
- if (!opening) {
1365
- i++
1366
- continue
1367
- }
1368
- const rowContentStart = opening.end
1369
- const rowEnd = findMatchingClosingTag(html, rowContentStart, 'tr', end)
1370
- if (rowEnd === -1) {
1371
- i = opening.end
1372
- continue
1373
- }
1374
- const closingTagStart = rowEnd - '</tr>'.length
1375
- const cells = findTopLevelCells(html, rowContentStart, closingTagStart)
1376
- rows.push({ rowStart: i, rowEnd, cells })
1377
- i = rowEnd
1378
- } else if (matchesClosingTagAt(html, i, 'table')) {
1379
- // Defensive: bail out if we encounter a closing </table> while
1380
- // scanning rows (we should have stopped at `end` already).
1381
- break
1382
- } else {
1383
- i++
1384
- }
1385
- }
1386
- return rows
1387
- }
1388
-
1389
- function findTopLevelCells(html: string, start: number, end: number): CellRange[] {
1390
- const cells: CellRange[] = []
1391
- let i = start
1392
- while (i < end) {
1393
- if (matchesTagAt(html, i, 'td') || matchesTagAt(html, i, 'th')) {
1394
- const tagName = matchesTagAt(html, i, 'td') ? 'td' : 'th'
1395
- const opening = parseOpeningTagAt(html, i)
1396
- if (!opening) {
1397
- i++
1398
- continue
1399
- }
1400
- const contentStart = opening.end
1401
- const cellEnd = findMatchingClosingTag(html, contentStart, tagName, end)
1402
- if (cellEnd === -1) {
1403
- i = opening.end
1404
- continue
1405
- }
1406
- const contentEnd = cellEnd - `</${tagName}>`.length
1407
- cells.push({ cellStart: i, cellEnd, contentStart, contentEnd })
1408
- i = cellEnd
1409
- } else if (matchesClosingTagAt(html, i, 'tr')) {
1410
- break
1411
- } else {
1412
- i++
1413
- }
1414
- }
1415
- return cells
1416
- }
1417
-
1418
- function matchesTagAt(html: string, i: number, tagName: string): boolean {
1419
- if (html[i] !== '<') return false
1420
- const candidate = html.slice(i + 1, i + 1 + tagName.length).toLowerCase()
1421
- if (candidate !== tagName) return false
1422
- const after = html[i + 1 + tagName.length]
1423
- return after === '>' || after === ' ' || after === '\t' || after === '\n' || after === '\r' || after === '/'
1424
- }
1425
-
1426
- function matchesClosingTagAt(html: string, i: number, tagName: string): boolean {
1427
- if (html[i] !== '<' || html[i + 1] !== '/') return false
1428
- const candidate = html.slice(i + 2, i + 2 + tagName.length).toLowerCase()
1429
- if (candidate !== tagName) return false
1430
- const after = html[i + 2 + tagName.length]
1431
- return after === '>' || after === ' ' || after === '\t' || after === '\n' || after === '\r'
1432
- }
1433
-
1434
- interface OpeningTag {
1435
- /** Index just past the closing `>` of the opening tag. */
1436
- end: number
1437
- }
1438
-
1439
- function parseOpeningTagAt(html: string, i: number): OpeningTag | null {
1440
- // HTML comments, CDATA, processing instructions, and DOCTYPE need their
1441
- // own terminators — a plain `>`-walker would cut a comment like
1442
- // `<!-- a > b -->` at the first inner `>`, treating the rest as text
1443
- // and corrupting downstream offsets. Word-exported HTML routinely
1444
- // emits comments inside tables (conditional comments, OLE markers) so
1445
- // these have to be handled, not just be theoretical.
1446
- if (html.startsWith('<!--', i)) {
1447
- const close = html.indexOf('-->', i + 4)
1448
- return close === -1 ? null : { end: close + 3 }
1449
- }
1450
- if (html.startsWith('<![CDATA[', i)) {
1451
- const close = html.indexOf(']]>', i + 9)
1452
- return close === -1 ? null : { end: close + 3 }
1453
- }
1454
- if (html.startsWith('<?', i)) {
1455
- const close = html.indexOf('?>', i + 2)
1456
- return close === -1 ? null : { end: close + 2 }
1457
- }
1458
- // Walk to the next unquoted '>'. Handles attributes whose values contain
1459
- // a literal '>' inside quotes, which a plain indexOf would mishandle.
1460
- let j = i + 1
1461
- let quote: string | null = null
1462
- while (j < html.length) {
1463
- const ch = html[j]
1464
- if (quote) {
1465
- if (ch === quote) quote = null
1466
- } else if (ch === '"' || ch === "'") {
1467
- quote = ch
1468
- } else if (ch === '>') {
1469
- return { end: j + 1 }
1470
- }
1471
- j++
1472
- }
1473
- return null
1474
- }
1475
-
1476
- /**
1477
- * Returns the index just past the matching `</tagName>`, accounting for
1478
- * nested tags of the same name. Returns -1 if no match before `limit`.
1479
- */
1480
- function findMatchingClosingTag(html: string, from: number, tagName: string, limit: number = html.length): number {
1481
- let depth = 1
1482
- let i = from
1483
- while (i < limit) {
1484
- if (matchesTagAt(html, i, tagName)) {
1485
- const opening = parseOpeningTagAt(html, i)
1486
- if (!opening) {
1487
- i++
1488
- continue
1489
- }
1490
- const tagText = html.slice(i, opening.end)
1491
- if (!tagText.endsWith('/>')) depth++
1492
- i = opening.end
1493
- } else if (matchesClosingTagAt(html, i, tagName)) {
1494
- depth--
1495
- const closing = parseOpeningTagAt(html, i)
1496
- const closingEnd = closing?.end ?? i + `</${tagName}>`.length
1497
- if (depth === 0) return closingEnd
1498
- i = closingEnd
1499
- } else {
1500
- i++
1501
- }
1502
- }
1503
- return -1
1504
- }