@createiq/htmldiff 1.0.5 → 1.1.0

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/dist/HtmlDiff.mjs CHANGED
@@ -202,6 +202,1007 @@ var Operation = class {
202
202
  }
203
203
  };
204
204
  //#endregion
205
+ //#region src/TableDiff.ts
206
+ const PLACEHOLDER_PREFIX_BASE = "<!--HTMLDIFF_TABLE_";
207
+ const PLACEHOLDER_SUFFIX = "-->";
208
+ /**
209
+ * Hard cap on table dimensions handled by the structural-aware path.
210
+ * The row-LCS is O(rows²), the per-row cell-LCS is O(cells²), and each
211
+ * comparison string-equals row content (potentially many KB). Without a
212
+ * cap, a several-thousand-row table can pin a CPU for seconds. Tables
213
+ * larger than this fall through to the word-level diff, which scales
214
+ * linearly. Tuned to comfortably cover real-world ISDA schedules
215
+ * (which routinely have 1000+ rows).
216
+ */
217
+ const MAX_TABLE_ROWS = 1500;
218
+ const MAX_TABLE_CELLS_PER_ROW = 200;
219
+ const MAX_COLUMN_DELTA = 6;
220
+ const MAX_COLUMN_SEARCH_WIDTH = 40;
221
+ function makePlaceholderPrefix(oldHtml, newHtml) {
222
+ for (let attempt = 0; attempt < 8; attempt++) {
223
+ const prefix = `${PLACEHOLDER_PREFIX_BASE}${Math.floor(Math.random() * 4294967295).toString(16).padStart(8, "0")}_`;
224
+ if (!oldHtml.includes(prefix) && !newHtml.includes(prefix)) return prefix;
225
+ }
226
+ return `${PLACEHOLDER_PREFIX_BASE}fallback_${Date.now()}_`;
227
+ }
228
+ /**
229
+ * Diffs every paired-by-position table in the inputs and replaces each
230
+ * source table with a placeholder, returning the modified inputs plus the
231
+ * placeholder→diff mapping. Returns null when there are no tables to
232
+ * preprocess or the table counts don't line up.
233
+ */
234
+ function preprocessTables(oldHtml, newHtml, diffCell) {
235
+ const oldTables = findTopLevelTables(oldHtml);
236
+ const newTables = findTopLevelTables(newHtml);
237
+ if (oldTables.length === 0 && newTables.length === 0) return null;
238
+ if (oldTables.length !== newTables.length) return null;
239
+ for (let i = 0; i < oldTables.length; i++) if (exceedsSizeLimit(oldTables[i]) || exceedsSizeLimit(newTables[i])) return null;
240
+ const pairs = [];
241
+ for (let i = 0; i < oldTables.length; i++) pairs.push({
242
+ oldTable: oldTables[i],
243
+ newTable: newTables[i],
244
+ diffed: diffTable(oldHtml, newHtml, oldTables[i], newTables[i], diffCell)
245
+ });
246
+ let modifiedOld = oldHtml;
247
+ let modifiedNew = newHtml;
248
+ const placeholderPrefix = makePlaceholderPrefix(oldHtml, newHtml);
249
+ const placeholderToDiff = /* @__PURE__ */ new Map();
250
+ for (let i = pairs.length - 1; i >= 0; i--) {
251
+ const placeholder = `${placeholderPrefix}${i}${PLACEHOLDER_SUFFIX}`;
252
+ placeholderToDiff.set(placeholder, pairs[i].diffed);
253
+ modifiedOld = spliceString(modifiedOld, pairs[i].oldTable.tableStart, pairs[i].oldTable.tableEnd, placeholder);
254
+ modifiedNew = spliceString(modifiedNew, pairs[i].newTable.tableStart, pairs[i].newTable.tableEnd, placeholder);
255
+ }
256
+ return {
257
+ modifiedOld,
258
+ modifiedNew,
259
+ placeholderToDiff
260
+ };
261
+ }
262
+ function restoreTablePlaceholders(diffOutput, placeholderToDiff) {
263
+ let result = diffOutput;
264
+ for (const [placeholder, html] of placeholderToDiff) result = result.split(placeholder).join(html);
265
+ return result;
266
+ }
267
+ function spliceString(s, start, end, replacement) {
268
+ return s.slice(0, start) + replacement + s.slice(end);
269
+ }
270
+ function exceedsSizeLimit(table) {
271
+ if (table.rows.length > MAX_TABLE_ROWS) return true;
272
+ for (const row of table.rows) if (row.cells.length > MAX_TABLE_CELLS_PER_ROW) return true;
273
+ return false;
274
+ }
275
+ function diffTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
276
+ if (sameDimensions(oldTable, newTable)) return diffPositionalTable(oldHtml, newHtml, oldTable, newTable, diffCell);
277
+ if (oldTable.rows.length === newTable.rows.length) return diffSameRowCountTable(oldHtml, newHtml, oldTable, newTable, diffCell);
278
+ return diffStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, diffCell);
279
+ }
280
+ function diffSameRowCountTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
281
+ const out = [];
282
+ let cursor = newTable.tableStart;
283
+ let r = 0;
284
+ while (r < newTable.rows.length) {
285
+ const merge = detectVerticalMerge(oldHtml, newHtml, oldTable, newTable, r);
286
+ if (merge) {
287
+ out.push(newHtml.slice(cursor, newTable.rows[r].rowStart));
288
+ out.push(merge.diff);
289
+ cursor = newTable.rows[r + merge.span - 1].rowEnd;
290
+ r += merge.span;
291
+ continue;
292
+ }
293
+ const split = detectVerticalSplit(oldHtml, newHtml, oldTable, newTable, r);
294
+ if (split) {
295
+ out.push(newHtml.slice(cursor, newTable.rows[r].rowStart));
296
+ out.push(split.diff);
297
+ cursor = newTable.rows[r + split.span - 1].rowEnd;
298
+ r += split.span;
299
+ continue;
300
+ }
301
+ const newRow = newTable.rows[r];
302
+ out.push(newHtml.slice(cursor, newRow.rowStart));
303
+ out.push(diffPreservedRow(oldHtml, newHtml, oldTable.rows[r], newRow, diffCell));
304
+ cursor = newRow.rowEnd;
305
+ r++;
306
+ }
307
+ out.push(newHtml.slice(cursor, newTable.tableEnd));
308
+ return out.join("");
309
+ }
310
+ /**
311
+ * Detects a vertical merge starting at row `r`: new row R has a single
312
+ * cell with rowspan=K (and any colspan ≥ 1), with rows R+1..R+K-1 empty
313
+ * in new. Old rows R..R+K-1 must have a logical column width equal to
314
+ * the new cell's colspan and contain no rowspan'd cells of their own.
315
+ * This handles both single-column merges (old rows are 1-cell, new cell
316
+ * rowspan=K) and rectangular merges (e.g. 2×2 merge into a single
317
+ * colspan=2 rowspan=2 cell). Output: emit the merged cell with
318
+ * `class='mod rowspan'` and the empty trailing rows unchanged.
319
+ */
320
+ function detectVerticalMerge(oldHtml, newHtml, oldTable, newTable, r) {
321
+ const newRow = newTable.rows[r];
322
+ if (newRow.cells.length !== 1) return null;
323
+ const cell = newRow.cells[0];
324
+ const span = getRowspan(newHtml, cell);
325
+ if (span <= 1) return null;
326
+ if (r + span > newTable.rows.length) return null;
327
+ const colspan = getColspan(newHtml, cell);
328
+ for (let k = 1; k < span; k++) if (newTable.rows[r + k].cells.length !== 0) return null;
329
+ for (let k = 0; k < span; k++) {
330
+ const oldRow = oldTable.rows[r + k];
331
+ if (!oldRow) return null;
332
+ if (sumColspans(oldHtml, oldRow.cells) !== colspan) return null;
333
+ for (const c of oldRow.cells) if (getRowspan(oldHtml, c) !== 1) return null;
334
+ }
335
+ const out = [];
336
+ out.push(rowHeaderSlice(newHtml, newRow));
337
+ out.push(emitSpanChangedCell(newHtml, cell, "rowspan"));
338
+ out.push("</tr>");
339
+ for (let k = 1; k < span; k++) out.push(emitEmptyRow(newHtml, newTable.rows[r + k]));
340
+ return {
341
+ diff: out.join(""),
342
+ span
343
+ };
344
+ }
345
+ /**
346
+ * Detects a vertical split starting at row `r`: old row R has a single
347
+ * cell with rowspan=K, old rows R+1..R+K-1 are empty. New rows R..R+K-1
348
+ * each have a single cell. Output: emit each new row with the new cell
349
+ * tagged `class='mod rowspan'`.
350
+ */
351
+ function detectVerticalSplit(oldHtml, newHtml, oldTable, newTable, r) {
352
+ const oldRow = oldTable.rows[r];
353
+ if (oldRow.cells.length !== 1) return null;
354
+ const oldCell = oldRow.cells[0];
355
+ const span = getRowspan(oldHtml, oldCell);
356
+ if (span <= 1) return null;
357
+ if (r + span > oldTable.rows.length) return null;
358
+ const colspan = getColspan(oldHtml, oldCell);
359
+ for (let k = 1; k < span; k++) if (oldTable.rows[r + k].cells.length !== 0) return null;
360
+ for (let k = 0; k < span; k++) {
361
+ const newRow = newTable.rows[r + k];
362
+ if (!newRow) return null;
363
+ if (sumColspans(newHtml, newRow.cells) !== colspan) return null;
364
+ for (const c of newRow.cells) if (getRowspan(newHtml, c) !== 1) return null;
365
+ }
366
+ const out = [];
367
+ for (let k = 0; k < span; k++) {
368
+ const newRow = newTable.rows[r + k];
369
+ out.push(rowHeaderSlice(newHtml, newRow));
370
+ for (const c of newRow.cells) out.push(emitSpanChangedCell(newHtml, c, "rowspan"));
371
+ out.push("</tr>");
372
+ }
373
+ return {
374
+ diff: out.join(""),
375
+ span
376
+ };
377
+ }
378
+ function emitEmptyRow(html, row) {
379
+ return html.slice(row.rowStart, row.rowEnd);
380
+ }
381
+ function sameDimensions(a, b) {
382
+ if (a.rows.length !== b.rows.length) return false;
383
+ for (let i = 0; i < a.rows.length; i++) if (a.rows[i].cells.length !== b.rows[i].cells.length) return false;
384
+ return true;
385
+ }
386
+ /**
387
+ * Same-dimension path: walk the new table verbatim and substitute each
388
+ * cell content range with the cell-level diff. The surrounding
389
+ * `<thead>`/`<tbody>`/whitespace passes through untouched.
390
+ */
391
+ function diffPositionalTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
392
+ const out = [];
393
+ let cursor = newTable.tableStart;
394
+ for (let r = 0; r < newTable.rows.length; r++) {
395
+ const oldRow = oldTable.rows[r];
396
+ const newRow = newTable.rows[r];
397
+ for (let c = 0; c < newRow.cells.length; c++) {
398
+ const oldCell = oldRow.cells[c];
399
+ const newCell = newRow.cells[c];
400
+ out.push(newHtml.slice(cursor, newCell.contentStart));
401
+ out.push(diffCell(oldHtml.slice(oldCell.contentStart, oldCell.contentEnd), newHtml.slice(newCell.contentStart, newCell.contentEnd)));
402
+ cursor = newCell.contentEnd;
403
+ }
404
+ }
405
+ out.push(newHtml.slice(cursor, newTable.tableEnd));
406
+ return out.join("");
407
+ }
408
+ /**
409
+ * Mismatched-dimensions path: row-level LCS to identify added/deleted rows,
410
+ * then per preserved row a cell-level LCS to identify added/deleted cells.
411
+ * Reconstructs the table from scratch — there's no "single new structure"
412
+ * to walk verbatim, since we're stitching together kept rows from both
413
+ * sides.
414
+ */
415
+ function diffStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
416
+ const alignment = orderAlignmentForEmission(pairSimilarUnmatchedRows(lcsAlign(oldTable.rows.map((row) => rowKey(oldHtml, row)), newTable.rows.map((row) => rowKey(newHtml, row))), oldTable, newTable, oldHtml, newHtml));
417
+ if (newTable.rows.length === 0) return rebuildStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, alignment);
418
+ const out = [];
419
+ out.push(newHtml.slice(newTable.tableStart, newTable.rows[0].rowStart));
420
+ let cursor = newTable.rows[0].rowStart;
421
+ for (const align of alignment) if (align.newIdx !== null) {
422
+ const newRow = newTable.rows[align.newIdx];
423
+ out.push(newHtml.slice(cursor, newRow.rowStart));
424
+ if (align.oldIdx !== null) out.push(diffPreservedRow(oldHtml, newHtml, oldTable.rows[align.oldIdx], newRow, diffCell));
425
+ else out.push(emitFullRow(newHtml, newRow, "ins"));
426
+ cursor = newRow.rowEnd;
427
+ } else if (align.oldIdx !== null) out.push(emitFullRow(oldHtml, oldTable.rows[align.oldIdx], "del"));
428
+ out.push(newHtml.slice(cursor, newTable.tableEnd));
429
+ return out.join("");
430
+ }
431
+ /**
432
+ * Reorders the alignment so emission produces rows in the visually-
433
+ * correct order. Each entry is assigned a fractional "position" in
434
+ * new's flow:
435
+ *
436
+ * • Preserved/paired (oldIdx, newIdx): position = newIdx.
437
+ * • Pure insert (null, newIdx): position = newIdx.
438
+ * • Pure delete (oldIdx, null): position = newIdx-of-preserved-just-
439
+ * before-this-oldIdx + 0.5. Dels at the same gap sort by oldIdx so
440
+ * they appear in old's row order. The +0.5 places dels BEFORE any
441
+ * insert at the same gap (insert at newIdx N1+1 has position N1+1
442
+ * which is > N1+0.5), giving the natural "delete first, insert
443
+ * second" reading order at a replaced position.
444
+ *
445
+ * This handles the full range:
446
+ * • Run of unpaired dels at the start (no preserved predecessor):
447
+ * position -0.5, sorted by oldIdx.
448
+ * • Dels in the middle: positioned right after their preceding
449
+ * preserved row.
450
+ * • Dels at the end (no preserved successor): positioned after the
451
+ * last preserved row.
452
+ *
453
+ * Without this reordering, a run of unpaired deletes at low alignment
454
+ * indices got emitted at cursor = first-new-row position — putting
455
+ * all deletes before any preserved row in the output, regardless of
456
+ * where they came from in old.
457
+ */
458
+ function orderAlignmentForEmission(alignment) {
459
+ const preserved = [];
460
+ for (const a of alignment) if (a.oldIdx !== null && a.newIdx !== null) preserved.push({
461
+ oldIdx: a.oldIdx,
462
+ newIdx: a.newIdx
463
+ });
464
+ preserved.sort((a, b) => a.oldIdx - b.oldIdx);
465
+ function newIdxOfPreservedBefore(oldIdx) {
466
+ let result = -1;
467
+ for (const p of preserved) {
468
+ if (p.oldIdx >= oldIdx) break;
469
+ result = p.newIdx;
470
+ }
471
+ return result;
472
+ }
473
+ const decorated = alignment.map((a, i) => {
474
+ let primary;
475
+ let secondary;
476
+ if (a.newIdx !== null) {
477
+ primary = a.newIdx;
478
+ secondary = a.oldIdx === null ? 1 : 0;
479
+ } else {
480
+ primary = newIdxOfPreservedBefore(a.oldIdx) + .5;
481
+ secondary = a.oldIdx;
482
+ }
483
+ return {
484
+ entry: a,
485
+ primary,
486
+ secondary,
487
+ originalIdx: i
488
+ };
489
+ });
490
+ decorated.sort((a, b) => {
491
+ if (a.primary !== b.primary) return a.primary - b.primary;
492
+ if (a.secondary !== b.secondary) return a.secondary - b.secondary;
493
+ return a.originalIdx - b.originalIdx;
494
+ });
495
+ return decorated.map((d) => d.entry);
496
+ }
497
+ function rebuildStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, alignment) {
498
+ const out = [];
499
+ out.push(headerSlice(newHtml, newTable, oldHtml, oldTable));
500
+ for (const align of alignment) if (align.oldIdx !== null) out.push(emitFullRow(oldHtml, oldTable.rows[align.oldIdx], "del"));
501
+ else if (align.newIdx !== null) out.push(emitFullRow(newHtml, newTable.rows[align.newIdx], "ins"));
502
+ out.push("</table>");
503
+ return out.join("");
504
+ }
505
+ function headerSlice(newHtml, newTable, oldHtml, oldTable) {
506
+ const newFirstRow = newTable.rows[0]?.rowStart ?? newTable.tableEnd - 8;
507
+ if (newFirstRow > newTable.tableStart) return newHtml.slice(newTable.tableStart, newFirstRow);
508
+ const oldFirstRow = oldTable.rows[0]?.rowStart ?? oldTable.tableEnd - 8;
509
+ return oldHtml.slice(oldTable.tableStart, oldFirstRow);
510
+ }
511
+ function rowKey(html, row) {
512
+ return html.slice(row.rowStart, row.rowEnd).replace(/\s+/g, " ").trim();
513
+ }
514
+ function diffPreservedRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
515
+ if (oldRow.cells.length === newRow.cells.length) return diffPositionalRow(oldHtml, newHtml, oldRow, newRow, diffCell);
516
+ const colspanAligned = diffColspanChangedRow(oldHtml, newHtml, oldRow, newRow, diffCell);
517
+ if (colspanAligned !== null) return colspanAligned;
518
+ const delta = newRow.cells.length - oldRow.cells.length;
519
+ const absDelta = Math.abs(delta);
520
+ if (absDelta > 0 && absDelta <= MAX_COLUMN_DELTA && Math.max(oldRow.cells.length, newRow.cells.length) <= MAX_COLUMN_SEARCH_WIDTH) {
521
+ if (delta > 0) return diffMultiColumnAddRow(oldHtml, newHtml, oldRow, newRow, delta, diffCell);
522
+ return diffMultiColumnDeleteRow(oldHtml, newHtml, oldRow, newRow, -delta, diffCell);
523
+ }
524
+ return diffStructurallyAlignedRow(oldHtml, newHtml, oldRow, newRow, diffCell);
525
+ }
526
+ /**
527
+ * For a row where new has K more cells than old, find the K column
528
+ * positions in new where cells were inserted by scanning all C(newCount,
529
+ * K) combinations and picking the one that maximises positional content
530
+ * similarity with the remaining cells. The inserted cells are emitted
531
+ * with diff markers; the rest are aligned positionally with content
532
+ * diff for matched pairs.
533
+ */
534
+ function diffMultiColumnAddRow(oldHtml, newHtml, oldRow, newRow, k, diffCell) {
535
+ const insertedPositions = findBestColumnInsertPositions(oldRow, newRow, k, oldHtml, newHtml);
536
+ const inserted = new Set(insertedPositions);
537
+ const out = [rowHeaderSlice(newHtml, newRow)];
538
+ let oldIdx = 0;
539
+ for (let c = 0; c < newRow.cells.length; c++) if (inserted.has(c)) out.push(emitFullCell(newHtml, newRow.cells[c], "ins"));
540
+ else {
541
+ out.push(emitDiffedCell(oldHtml, newHtml, oldRow.cells[oldIdx], newRow.cells[c], diffCell));
542
+ oldIdx++;
543
+ }
544
+ out.push("</tr>");
545
+ return out.join("");
546
+ }
547
+ function diffMultiColumnDeleteRow(oldHtml, newHtml, oldRow, newRow, k, diffCell) {
548
+ const deletedPositions = findBestColumnDeletePositions(oldRow, newRow, k, oldHtml, newHtml);
549
+ const deleted = new Set(deletedPositions);
550
+ const out = [rowHeaderSlice(newHtml, newRow)];
551
+ let newIdx = 0;
552
+ for (let oldIdx = 0; oldIdx < oldRow.cells.length; oldIdx++) {
553
+ if (deleted.has(oldIdx)) {
554
+ out.push(emitFullCell(oldHtml, oldRow.cells[oldIdx], "del"));
555
+ continue;
556
+ }
557
+ out.push(emitDiffedCell(oldHtml, newHtml, oldRow.cells[oldIdx], newRow.cells[newIdx], diffCell));
558
+ newIdx++;
559
+ }
560
+ out.push("</tr>");
561
+ return out.join("");
562
+ }
563
+ function findBestColumnInsertPositions(oldRow, newRow, k, oldHtml, newHtml) {
564
+ const oldTexts = oldRow.cells.map((c) => cellText(oldHtml, c));
565
+ const newTexts = newRow.cells.map((c) => cellText(newHtml, c));
566
+ let bestPositions = [];
567
+ let bestScore = -1;
568
+ for (const combo of combinationsOfRange(newRow.cells.length, k)) {
569
+ const inserted = new Set(combo);
570
+ let score = 0;
571
+ let oldIdx = 0;
572
+ for (let newIdx = 0; newIdx < newRow.cells.length; newIdx++) {
573
+ if (inserted.has(newIdx)) continue;
574
+ score += textSimilarity(oldTexts[oldIdx], newTexts[newIdx]);
575
+ oldIdx++;
576
+ }
577
+ if (score > bestScore) {
578
+ bestScore = score;
579
+ bestPositions = combo;
580
+ }
581
+ }
582
+ return bestPositions;
583
+ }
584
+ function findBestColumnDeletePositions(oldRow, newRow, k, oldHtml, newHtml) {
585
+ const oldTexts = oldRow.cells.map((c) => cellText(oldHtml, c));
586
+ const newTexts = newRow.cells.map((c) => cellText(newHtml, c));
587
+ let bestPositions = [];
588
+ let bestScore = -1;
589
+ for (const combo of combinationsOfRange(oldRow.cells.length, k)) {
590
+ const deleted = new Set(combo);
591
+ let score = 0;
592
+ let newIdx = 0;
593
+ for (let oldIdx = 0; oldIdx < oldRow.cells.length; oldIdx++) {
594
+ if (deleted.has(oldIdx)) continue;
595
+ score += textSimilarity(oldTexts[oldIdx], newTexts[newIdx]);
596
+ newIdx++;
597
+ }
598
+ if (score > bestScore) {
599
+ bestScore = score;
600
+ bestPositions = combo;
601
+ }
602
+ }
603
+ return bestPositions;
604
+ }
605
+ /**
606
+ * Yields all sorted-ascending combinations of `k` distinct integers
607
+ * from [0, n). Iterative implementation avoids recursion overhead and
608
+ * keeps memory at O(k).
609
+ */
610
+ function* combinationsOfRange(n, k) {
611
+ if (k === 0 || k > n) return;
612
+ const indices = Array.from({ length: k }, (_, i) => i);
613
+ while (true) {
614
+ yield indices.slice();
615
+ let i = k - 1;
616
+ while (i >= 0 && indices[i] === n - k + i) i--;
617
+ if (i < 0) return;
618
+ indices[i]++;
619
+ for (let j = i + 1; j < k; j++) indices[j] = indices[j - 1] + 1;
620
+ }
621
+ }
622
+ /**
623
+ * Try to align cells by logical column position (sum of colspans). When
624
+ * one side has a colspan'd cell that absorbs multiple cells on the other
625
+ * side, emit the new structure with `class='mod colspan'` on the
626
+ * merged/split cells. Returns null if the rows don't align cleanly —
627
+ * caller falls back to a generic cell-LCS.
628
+ */
629
+ function diffColspanChangedRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
630
+ if (sumColspans(oldHtml, oldRow.cells) !== sumColspans(newHtml, newRow.cells)) return null;
631
+ const out = [];
632
+ out.push(rowHeaderSlice(newHtml, newRow));
633
+ let oi = 0;
634
+ let ni = 0;
635
+ while (oi < oldRow.cells.length && ni < newRow.cells.length) {
636
+ const oCell = oldRow.cells[oi];
637
+ const nCell = newRow.cells[ni];
638
+ const oSpan = getColspan(oldHtml, oCell);
639
+ const nSpan = getColspan(newHtml, nCell);
640
+ if (oSpan === nSpan) {
641
+ out.push(emitDiffedCell(oldHtml, newHtml, oCell, nCell, diffCell));
642
+ oi++;
643
+ ni++;
644
+ } else if (nSpan > oSpan) {
645
+ let totalOldSpan = 0;
646
+ let oj = oi;
647
+ while (oj < oldRow.cells.length && totalOldSpan < nSpan) {
648
+ totalOldSpan += getColspan(oldHtml, oldRow.cells[oj]);
649
+ oj++;
650
+ }
651
+ if (totalOldSpan !== nSpan) return null;
652
+ out.push(emitSpanChangedCell(newHtml, nCell, "colspan"));
653
+ oi = oj;
654
+ ni++;
655
+ } else {
656
+ let totalNewSpan = 0;
657
+ let nj = ni;
658
+ while (nj < newRow.cells.length && totalNewSpan < oSpan) {
659
+ totalNewSpan += getColspan(newHtml, newRow.cells[nj]);
660
+ nj++;
661
+ }
662
+ if (totalNewSpan !== oSpan) return null;
663
+ for (let k = ni; k < nj; k++) out.push(emitSpanChangedCell(newHtml, newRow.cells[k], "colspan"));
664
+ oi++;
665
+ ni = nj;
666
+ }
667
+ }
668
+ if (oi !== oldRow.cells.length || ni !== newRow.cells.length) return null;
669
+ out.push("</tr>");
670
+ return out.join("");
671
+ }
672
+ function sumColspans(html, cells) {
673
+ let total = 0;
674
+ for (const cell of cells) total += getColspan(html, cell);
675
+ return total;
676
+ }
677
+ function getColspan(html, cell) {
678
+ return parseSpanAttribute(html.slice(cell.cellStart, cell.contentStart), "colspan");
679
+ }
680
+ function getRowspan(html, cell) {
681
+ return parseSpanAttribute(html.slice(cell.cellStart, cell.contentStart), "rowspan");
682
+ }
683
+ function parseSpanAttribute(openingTag, name) {
684
+ const m = (name === "colspan" ? /\bcolspan\s*=\s*["']?(\d+)["']?/i : /\browspan\s*=\s*["']?(\d+)["']?/i).exec(openingTag);
685
+ if (!m) return 1;
686
+ const value = Number.parseInt(m[1], 10);
687
+ return Number.isFinite(value) && value > 0 ? value : 1;
688
+ }
689
+ /**
690
+ * Emits a cell that's the merged/split product of a structural change,
691
+ * tagged with `class='mod colspan'` or `class='mod rowspan'`. Content is
692
+ * carried through unmodified — Word doesn't track these changes, and
693
+ * inserting del/ins around content that didn't really change would be
694
+ * misleading.
695
+ */
696
+ function emitSpanChangedCell(html, cell, kind) {
697
+ const tdOpening = parseOpeningTagAt(html, cell.cellStart);
698
+ if (!tdOpening) return html.slice(cell.cellStart, cell.cellEnd);
699
+ return injectClass(html.slice(cell.cellStart, tdOpening.end), `mod ${kind}`) + html.slice(cell.contentStart, cell.cellEnd);
700
+ }
701
+ function diffPositionalRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
702
+ const out = [];
703
+ const trHeader = rowHeaderSlice(newHtml, newRow);
704
+ out.push(trHeader);
705
+ let cursor = newRow.cells[0]?.cellStart ?? newRow.rowEnd;
706
+ for (let c = 0; c < newRow.cells.length; c++) {
707
+ const oldCell = oldRow.cells[c];
708
+ const newCell = newRow.cells[c];
709
+ out.push(newHtml.slice(cursor, newCell.contentStart));
710
+ out.push(diffCell(oldHtml.slice(oldCell.contentStart, oldCell.contentEnd), newHtml.slice(newCell.contentStart, newCell.contentEnd)));
711
+ cursor = newCell.contentEnd;
712
+ }
713
+ out.push(newHtml.slice(cursor, newRow.rowEnd));
714
+ return out.join("");
715
+ }
716
+ function diffStructurallyAlignedRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
717
+ const alignment = pairSimilarUnmatchedCells(lcsAlign(oldRow.cells.map((cell) => cellKey(oldHtml, cell)), newRow.cells.map((cell) => cellKey(newHtml, cell))), oldRow, newRow, oldHtml, newHtml);
718
+ const out = [];
719
+ out.push(rowHeaderSlice(newHtml, newRow));
720
+ for (const align of alignment) if (align.oldIdx !== null && align.newIdx !== null) {
721
+ const oldCell = oldRow.cells[align.oldIdx];
722
+ const newCell = newRow.cells[align.newIdx];
723
+ out.push(emitDiffedCell(oldHtml, newHtml, oldCell, newCell, diffCell));
724
+ } else if (align.newIdx !== null) out.push(emitFullCell(newHtml, newRow.cells[align.newIdx], "ins"));
725
+ else if (align.oldIdx !== null) out.push(emitFullCell(oldHtml, oldRow.cells[align.oldIdx], "del"));
726
+ out.push("</tr>");
727
+ return out.join("");
728
+ }
729
+ function cellKey(html, cell) {
730
+ return html.slice(cell.contentStart, cell.contentEnd).replace(/\s+/g, " ").trim();
731
+ }
732
+ /**
733
+ * Emits a row with all cells either inserted (kind='ins') or deleted
734
+ * (kind='del'). Adds `class='diffins'`/`'diffdel'` to the `<tr>` and to
735
+ * each `<td>`, with an `<ins>`/`<del>` wrapper around any cell content
736
+ * (empty cells get the class but no wrapper).
737
+ */
738
+ function emitFullRow(html, row, kind) {
739
+ const cls = kind === "ins" ? "diffins" : "diffdel";
740
+ const trOpening = parseOpeningTagAt(html, row.rowStart);
741
+ if (!trOpening) return html.slice(row.rowStart, row.rowEnd);
742
+ const out = [injectClass(html.slice(row.rowStart, trOpening.end), cls)];
743
+ let cursor = trOpening.end;
744
+ for (const cell of row.cells) {
745
+ out.push(html.slice(cursor, cell.cellStart));
746
+ out.push(emitFullCell(html, cell, kind));
747
+ cursor = cell.cellEnd;
748
+ }
749
+ out.push(html.slice(cursor, row.rowEnd));
750
+ return out.join("");
751
+ }
752
+ /**
753
+ * Emits a fully-inserted or fully-deleted cell. Inner text runs are wrapped
754
+ * with `<ins>`/`<del>` while formatting tags pass through unchanged, so
755
+ * `<strong>B</strong>` renders as `<strong><ins>B</ins></strong>` —
756
+ * matching htmldiff's general convention without the doubled-`<ins>` that
757
+ * the full recursive diff would produce for newly-inserted formatting.
758
+ * Empty cells get the class on the `<td>` but no inner wrapping.
759
+ */
760
+ function emitFullCell(html, cell, kind) {
761
+ const cls = kind === "ins" ? "diffins" : "diffdel";
762
+ const tdOpening = parseOpeningTagAt(html, cell.cellStart);
763
+ if (!tdOpening) return html.slice(cell.cellStart, cell.cellEnd);
764
+ const tdOpenTag = injectClass(html.slice(cell.cellStart, tdOpening.end), cls);
765
+ const content = html.slice(cell.contentStart, cell.contentEnd);
766
+ const wrapped = content.trim().length === 0 ? content : wrapInlineTextRuns(content, kind);
767
+ const closing = html.slice(cell.contentEnd, cell.cellEnd);
768
+ return tdOpenTag + wrapped + closing;
769
+ }
770
+ /**
771
+ * Wraps every non-whitespace text run in the given content with an
772
+ * `<ins>`/`<del>` tag, leaving HTML tags untouched. This produces output
773
+ * like `<strong><ins>X</ins></strong>` for fully-inserted formatted
774
+ * content — the same shape the rest of htmldiff emits for content
775
+ * insertions inside existing formatting.
776
+ */
777
+ function wrapInlineTextRuns(content, kind) {
778
+ const tag = kind === "ins" ? "ins" : "del";
779
+ const cls = kind === "ins" ? "diffins" : "diffdel";
780
+ const out = [];
781
+ let i = 0;
782
+ while (i < content.length) {
783
+ if (content[i] === "<") {
784
+ const tagEnd = parseOpeningTagAt(content, i);
785
+ if (!tagEnd) {
786
+ out.push(content.slice(i));
787
+ break;
788
+ }
789
+ out.push(content.slice(i, tagEnd.end));
790
+ i = tagEnd.end;
791
+ continue;
792
+ }
793
+ let j = i;
794
+ while (j < content.length && content[j] !== "<") j++;
795
+ const text = content.slice(i, j);
796
+ if (text.trim().length > 0) out.push(wrapText(text, tag, cls));
797
+ else out.push(text);
798
+ i = j;
799
+ }
800
+ return out.join("");
801
+ }
802
+ function emitDiffedCell(oldHtml, newHtml, oldCell, newCell, diffCell) {
803
+ const tdOpening = parseOpeningTagAt(newHtml, newCell.cellStart);
804
+ if (!tdOpening) return newHtml.slice(newCell.cellStart, newCell.cellEnd);
805
+ const tdOpenTag = newHtml.slice(newCell.cellStart, tdOpening.end);
806
+ const content = diffCell(oldHtml.slice(oldCell.contentStart, oldCell.contentEnd), newHtml.slice(newCell.contentStart, newCell.contentEnd));
807
+ const closing = newHtml.slice(newCell.contentEnd, newCell.cellEnd);
808
+ return tdOpenTag + content + closing;
809
+ }
810
+ function rowHeaderSlice(html, row) {
811
+ const opening = parseOpeningTagAt(html, row.rowStart);
812
+ if (!opening) return "";
813
+ if (row.cells.length === 0) return html.slice(row.rowStart, opening.end);
814
+ return html.slice(row.rowStart, row.cells[0].cellStart);
815
+ }
816
+ /** Character-level similarity threshold above which we treat two rows as "the same row, edited". */
817
+ const ROW_FUZZY_THRESHOLD = .5;
818
+ /**
819
+ * Threshold for "this cell is a content-edit of that cell." Tuned the same
820
+ * as ROW_FUZZY_THRESHOLD; cells in legal docs that share most of their
821
+ * content typically ARE the same logical cell with a body edit, so 0.5
822
+ * works for both granularities in practice.
823
+ */
824
+ const CELL_FUZZY_THRESHOLD = .5;
825
+ /**
826
+ * After exact LCS, scan the alignment for runs of "old deleted, then new
827
+ * inserted" (or vice versa) and pair entries whose content is similar
828
+ * enough to be treated as an edit rather than a delete+insert. This keeps
829
+ * row-level edits (a typo fix, a single word change) from being shown as
830
+ * an entire row vanishing and a new one appearing — matching what users
831
+ * expect from a typical track-changes view.
832
+ */
833
+ function pairSimilarUnmatchedRows(alignment, oldTable, newTable, oldHtml, newHtml) {
834
+ const oldTexts = oldTable.rows.map((r) => rowText(oldHtml, r));
835
+ const newTexts = newTable.rows.map((r) => rowText(newHtml, r));
836
+ return pairSimilarUnmatched(alignment, ROW_FUZZY_THRESHOLD, (oldIdx, newIdx) => textSimilarity(oldTexts[oldIdx], newTexts[newIdx]));
837
+ }
838
+ function pairSimilarUnmatchedCells(alignment, oldRow, newRow, oldHtml, newHtml) {
839
+ const oldTexts = oldRow.cells.map((c) => cellText(oldHtml, c));
840
+ const newTexts = newRow.cells.map((c) => cellText(newHtml, c));
841
+ return pairSimilarUnmatched(alignment, CELL_FUZZY_THRESHOLD, (oldIdx, newIdx) => textSimilarity(oldTexts[oldIdx], newTexts[newIdx]));
842
+ }
843
+ /**
844
+ * Identify pairings inside each unmatched-only run, then build the output
845
+ * alignment by walking the original and substituting paired entries at
846
+ * the *ins position* (not the del position). This keeps the result
847
+ * monotonic in newIdx — critical because the cursor-based emission
848
+ * downstream walks new's html in order. Emitting at the del position
849
+ * would be fine when del<ins in the alignment array (the typical case),
850
+ * but can violate monotonicity when there are mixed unpaired entries in
851
+ * between (column-add + row-add together, content-edit + column-add,
852
+ * etc.).
853
+ *
854
+ * Generic over what's being paired — works for both rows (by full row
855
+ * content similarity) and cells (by per-cell content similarity).
856
+ */
857
+ function pairSimilarUnmatched(alignment, threshold, similarity) {
858
+ const pairs = /* @__PURE__ */ new Map();
859
+ let i = 0;
860
+ while (i < alignment.length) {
861
+ if (alignment[i].oldIdx !== null && alignment[i].newIdx !== null) {
862
+ i++;
863
+ continue;
864
+ }
865
+ const runStart = i;
866
+ while (i < alignment.length && alignment[i].oldIdx === null !== (alignment[i].newIdx === null)) i++;
867
+ const runEnd = i;
868
+ const delIndices = [];
869
+ const insIndices = [];
870
+ for (let k = runStart; k < runEnd; k++) if (alignment[k].oldIdx !== null) delIndices.push(k);
871
+ else insIndices.push(k);
872
+ const usedIns = /* @__PURE__ */ new Set();
873
+ for (const di of delIndices) {
874
+ let bestIi = -1;
875
+ let bestSim = threshold;
876
+ for (const ii of insIndices) {
877
+ if (usedIns.has(ii)) continue;
878
+ const sim = similarity(alignment[di].oldIdx, alignment[ii].newIdx);
879
+ if (sim > bestSim) {
880
+ bestSim = sim;
881
+ bestIi = ii;
882
+ }
883
+ }
884
+ if (bestIi >= 0) {
885
+ pairs.set(di, bestIi);
886
+ usedIns.add(bestIi);
887
+ }
888
+ }
889
+ }
890
+ const insToDel = /* @__PURE__ */ new Map();
891
+ for (const [delAi, insAi] of pairs) insToDel.set(insAi, delAi);
892
+ const pairedDels = new Set(pairs.keys());
893
+ const result = [];
894
+ for (let k = 0; k < alignment.length; k++) {
895
+ if (pairedDels.has(k)) continue;
896
+ if (insToDel.has(k)) {
897
+ const delAi = insToDel.get(k);
898
+ result.push({
899
+ oldIdx: alignment[delAi].oldIdx,
900
+ newIdx: alignment[k].newIdx
901
+ });
902
+ } else result.push(alignment[k]);
903
+ }
904
+ return result;
905
+ }
906
+ /**
907
+ * Combined similarity metric used for both row-level and cell-level
908
+ * fuzzy pairing. Returns the MAX of two complementary metrics:
909
+ *
910
+ * 1. **Character prefix+suffix similarity** — fraction of the longer
911
+ * string covered by shared prefix + shared suffix. Catches small
912
+ * edits in the middle of a string (one word changed in a row).
913
+ * Misses cases where the bulk of common content is in the middle
914
+ * and the ends differ.
915
+ *
916
+ * 2. **Token Jaccard similarity** — intersection-over-union of the
917
+ * whitespace-split tokens. Catches "most of the content is the
918
+ * same but bookended by different bits" — e.g. a row whose only
919
+ * edit is a column added at the start and another at the end,
920
+ * where the ~50 chars in the middle that DO match would be
921
+ * invisible to prefix+suffix.
922
+ *
923
+ * Either metric exceeding the threshold means pair. Neither alone is
924
+ * sufficient for the full range of legal-doc edits we see in
925
+ * production tables.
926
+ */
927
+ function textSimilarity(a, b) {
928
+ if (a === b) return 1;
929
+ if (a.length === 0 || b.length === 0) return 0;
930
+ return Math.max(charPrefixSuffixSimilarity(a, b), tokenJaccardSimilarity(a, b));
931
+ }
932
+ function charPrefixSuffixSimilarity(a, b) {
933
+ let prefix = 0;
934
+ const minLen = Math.min(a.length, b.length);
935
+ while (prefix < minLen && a[prefix] === b[prefix]) prefix++;
936
+ let suffix = 0;
937
+ while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix++;
938
+ return (prefix + suffix) / Math.max(a.length, b.length);
939
+ }
940
+ function tokenJaccardSimilarity(a, b) {
941
+ const tokensA = new Set(a.split(/\s+/).filter(Boolean));
942
+ const tokensB = new Set(b.split(/\s+/).filter(Boolean));
943
+ if (tokensA.size === 0 && tokensB.size === 0) return 1;
944
+ let intersection = 0;
945
+ for (const t of tokensA) if (tokensB.has(t)) intersection++;
946
+ const union = tokensA.size + tokensB.size - intersection;
947
+ return union === 0 ? 0 : intersection / union;
948
+ }
949
+ function rowText(html, row) {
950
+ const parts = [];
951
+ for (const cell of row.cells) parts.push(html.slice(cell.contentStart, cell.contentEnd).replace(/<[^>]+>/g, " "));
952
+ return parts.join(" ").replace(/\s+/g, " ").trim().toLowerCase();
953
+ }
954
+ function cellText(html, cell) {
955
+ return html.slice(cell.contentStart, cell.contentEnd).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().toLowerCase();
956
+ }
957
+ /**
958
+ * Standard LCS alignment: walks both sequences and emits a list of pairs
959
+ * where `(oldIdx, newIdx)` are both set for matching positions, and one
960
+ * side is null for an unmatched entry on the other side. Equality uses
961
+ * strict ===.
962
+ */
963
+ function lcsAlign(oldKeys, newKeys) {
964
+ const m = oldKeys.length;
965
+ const n = newKeys.length;
966
+ const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
967
+ for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) if (oldKeys[i - 1] === newKeys[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
968
+ else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
969
+ const result = [];
970
+ let i = m;
971
+ let j = n;
972
+ while (i > 0 || j > 0) if (i > 0 && j > 0 && oldKeys[i - 1] === newKeys[j - 1]) {
973
+ result.push({
974
+ oldIdx: i - 1,
975
+ newIdx: j - 1
976
+ });
977
+ i--;
978
+ j--;
979
+ } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
980
+ result.push({
981
+ oldIdx: null,
982
+ newIdx: j - 1
983
+ });
984
+ j--;
985
+ } else {
986
+ result.push({
987
+ oldIdx: i - 1,
988
+ newIdx: null
989
+ });
990
+ i--;
991
+ }
992
+ result.reverse();
993
+ return result;
994
+ }
995
+ /**
996
+ * Returns the opening tag with the given class injected. Locates the real
997
+ * `class` attribute via attribute-aware walking (NOT a flat regex — that
998
+ * would mis-match inside a foreign attribute value like
999
+ * `title="see class='x'"`). When the class already partially overlaps with
1000
+ * `cls` — e.g. existing `class="mod"` and we're injecting `mod colspan` —
1001
+ * only the missing tokens get appended, so we never end up with
1002
+ * `class="mod mod colspan"`.
1003
+ */
1004
+ function injectClass(openingTag, cls) {
1005
+ const clsTokens = cls.split(/\s+/).filter(Boolean);
1006
+ if (clsTokens.length === 0) return openingTag;
1007
+ const classAttr = findClassAttribute(openingTag);
1008
+ if (classAttr) {
1009
+ const existingTokens = classAttr.value.split(/\s+/).filter(Boolean);
1010
+ const missing = clsTokens.filter((t) => !existingTokens.includes(t));
1011
+ if (missing.length === 0) return openingTag;
1012
+ const updatedValue = existingTokens.length === 0 ? missing.join(" ") : `${existingTokens.join(" ")} ${missing.join(" ")}`;
1013
+ return openingTag.slice(0, classAttr.valueStart) + updatedValue + openingTag.slice(classAttr.valueEnd);
1014
+ }
1015
+ const insertAt = openingTag.endsWith("/>") ? openingTag.length - 2 : openingTag.length - 1;
1016
+ return `${openingTag.slice(0, insertAt).replace(/\s*$/, "")} class='${cls}'${openingTag.slice(insertAt)}`;
1017
+ }
1018
+ /**
1019
+ * Walks the opening tag's attributes (respecting quoted values) to find
1020
+ * the actual `class` attribute. Returns the value range (start/end of the
1021
+ * value content, *excluding* the surrounding quotes) and the value, or
1022
+ * null if no `class` attribute is present.
1023
+ */
1024
+ function findClassAttribute(openingTag) {
1025
+ let i = 1;
1026
+ while (i < openingTag.length && /[A-Za-z0-9_:-]/.test(openingTag[i])) i++;
1027
+ while (i < openingTag.length) {
1028
+ while (i < openingTag.length && /\s/.test(openingTag[i])) i++;
1029
+ if (i >= openingTag.length) break;
1030
+ if (openingTag[i] === ">" || openingTag[i] === "/") break;
1031
+ const nameStart = i;
1032
+ while (i < openingTag.length && !/[\s=>/]/.test(openingTag[i])) i++;
1033
+ const name = openingTag.slice(nameStart, i);
1034
+ while (i < openingTag.length && /\s/.test(openingTag[i])) i++;
1035
+ if (openingTag[i] !== "=") continue;
1036
+ i++;
1037
+ while (i < openingTag.length && /\s/.test(openingTag[i])) i++;
1038
+ let valueStart;
1039
+ let valueEnd;
1040
+ if (openingTag[i] === "\"" || openingTag[i] === "'") {
1041
+ const quote = openingTag[i];
1042
+ i++;
1043
+ valueStart = i;
1044
+ while (i < openingTag.length && openingTag[i] !== quote) i++;
1045
+ valueEnd = i;
1046
+ if (i < openingTag.length) i++;
1047
+ } else {
1048
+ valueStart = i;
1049
+ while (i < openingTag.length && !/[\s>/]/.test(openingTag[i])) i++;
1050
+ valueEnd = i;
1051
+ }
1052
+ if (name.toLowerCase() === "class") return {
1053
+ valueStart,
1054
+ valueEnd,
1055
+ value: openingTag.slice(valueStart, valueEnd)
1056
+ };
1057
+ }
1058
+ return null;
1059
+ }
1060
+ /**
1061
+ * Walks html and returns ranges for every top-level `<table>...</table>`
1062
+ * block. Nested tables aren't extracted as separate top-level entries —
1063
+ * they're captured inside the parent's content range and handled when the
1064
+ * cell-level diff recurses through them.
1065
+ */
1066
+ function findTopLevelTables(html) {
1067
+ const tables = [];
1068
+ let i = 0;
1069
+ while (i < html.length) if (matchesTagAt(html, i, "table")) {
1070
+ const opening = parseOpeningTagAt(html, i);
1071
+ if (!opening) {
1072
+ i++;
1073
+ continue;
1074
+ }
1075
+ const tableContentStart = opening.end;
1076
+ const tableEnd = findMatchingClosingTag(html, tableContentStart, "table");
1077
+ if (tableEnd === -1) {
1078
+ i = opening.end;
1079
+ continue;
1080
+ }
1081
+ const rows = findTopLevelRows(html, tableContentStart, tableEnd - 8);
1082
+ tables.push({
1083
+ tableStart: i,
1084
+ tableEnd,
1085
+ rows
1086
+ });
1087
+ i = tableEnd;
1088
+ } else i++;
1089
+ return tables;
1090
+ }
1091
+ function findTopLevelRows(html, start, end) {
1092
+ const rows = [];
1093
+ let i = start;
1094
+ while (i < end) if (matchesTagAt(html, i, "tr")) {
1095
+ const opening = parseOpeningTagAt(html, i);
1096
+ if (!opening) {
1097
+ i++;
1098
+ continue;
1099
+ }
1100
+ const rowContentStart = opening.end;
1101
+ const rowEnd = findMatchingClosingTag(html, rowContentStart, "tr", end);
1102
+ if (rowEnd === -1) {
1103
+ i = opening.end;
1104
+ continue;
1105
+ }
1106
+ const cells = findTopLevelCells(html, rowContentStart, rowEnd - 5);
1107
+ rows.push({
1108
+ rowStart: i,
1109
+ rowEnd,
1110
+ cells
1111
+ });
1112
+ i = rowEnd;
1113
+ } else if (matchesClosingTagAt(html, i, "table")) break;
1114
+ else i++;
1115
+ return rows;
1116
+ }
1117
+ function findTopLevelCells(html, start, end) {
1118
+ const cells = [];
1119
+ let i = start;
1120
+ while (i < end) if (matchesTagAt(html, i, "td") || matchesTagAt(html, i, "th")) {
1121
+ const tagName = matchesTagAt(html, i, "td") ? "td" : "th";
1122
+ const opening = parseOpeningTagAt(html, i);
1123
+ if (!opening) {
1124
+ i++;
1125
+ continue;
1126
+ }
1127
+ const contentStart = opening.end;
1128
+ const cellEnd = findMatchingClosingTag(html, contentStart, tagName, end);
1129
+ if (cellEnd === -1) {
1130
+ i = opening.end;
1131
+ continue;
1132
+ }
1133
+ const contentEnd = cellEnd - `</${tagName}>`.length;
1134
+ cells.push({
1135
+ cellStart: i,
1136
+ cellEnd,
1137
+ contentStart,
1138
+ contentEnd
1139
+ });
1140
+ i = cellEnd;
1141
+ } else if (matchesClosingTagAt(html, i, "tr")) break;
1142
+ else i++;
1143
+ return cells;
1144
+ }
1145
+ function matchesTagAt(html, i, tagName) {
1146
+ if (html[i] !== "<") return false;
1147
+ if (html.slice(i + 1, i + 1 + tagName.length).toLowerCase() !== tagName) return false;
1148
+ const after = html[i + 1 + tagName.length];
1149
+ return after === ">" || after === " " || after === " " || after === "\n" || after === "\r" || after === "/";
1150
+ }
1151
+ function matchesClosingTagAt(html, i, tagName) {
1152
+ if (html[i] !== "<" || html[i + 1] !== "/") return false;
1153
+ if (html.slice(i + 2, i + 2 + tagName.length).toLowerCase() !== tagName) return false;
1154
+ const after = html[i + 2 + tagName.length];
1155
+ return after === ">" || after === " " || after === " " || after === "\n" || after === "\r";
1156
+ }
1157
+ function parseOpeningTagAt(html, i) {
1158
+ if (html.startsWith("<!--", i)) {
1159
+ const close = html.indexOf("-->", i + 4);
1160
+ return close === -1 ? null : { end: close + 3 };
1161
+ }
1162
+ if (html.startsWith("<![CDATA[", i)) {
1163
+ const close = html.indexOf("]]>", i + 9);
1164
+ return close === -1 ? null : { end: close + 3 };
1165
+ }
1166
+ if (html.startsWith("<?", i)) {
1167
+ const close = html.indexOf("?>", i + 2);
1168
+ return close === -1 ? null : { end: close + 2 };
1169
+ }
1170
+ let j = i + 1;
1171
+ let quote = null;
1172
+ while (j < html.length) {
1173
+ const ch = html[j];
1174
+ if (quote) {
1175
+ if (ch === quote) quote = null;
1176
+ } else if (ch === "\"" || ch === "'") quote = ch;
1177
+ else if (ch === ">") return { end: j + 1 };
1178
+ j++;
1179
+ }
1180
+ return null;
1181
+ }
1182
+ /**
1183
+ * Returns the index just past the matching `</tagName>`, accounting for
1184
+ * nested tags of the same name. Returns -1 if no match before `limit`.
1185
+ */
1186
+ function findMatchingClosingTag(html, from, tagName, limit = html.length) {
1187
+ let depth = 1;
1188
+ let i = from;
1189
+ while (i < limit) if (matchesTagAt(html, i, tagName)) {
1190
+ const opening = parseOpeningTagAt(html, i);
1191
+ if (!opening) {
1192
+ i++;
1193
+ continue;
1194
+ }
1195
+ if (!html.slice(i, opening.end).endsWith("/>")) depth++;
1196
+ i = opening.end;
1197
+ } else if (matchesClosingTagAt(html, i, tagName)) {
1198
+ depth--;
1199
+ const closingEnd = parseOpeningTagAt(html, i)?.end ?? i + `</${tagName}>`.length;
1200
+ if (depth === 0) return closingEnd;
1201
+ i = closingEnd;
1202
+ } else i++;
1203
+ return -1;
1204
+ }
1205
+ //#endregion
205
1206
  //#region src/WordSplitter.ts
206
1207
  var WordSplitter = class WordSplitter {
207
1208
  text;
@@ -447,9 +1448,20 @@ var HtmlDiff = class HtmlDiff {
447
1448
  "s",
448
1449
  "span"
449
1450
  ]);
1451
+ /**
1452
+ * Hard cap on nested `HtmlDiff.execute` calls (table preprocessing
1453
+ * recurses through `diffCell` for cell content). Each level allocates
1454
+ * fresh DP matrices and word arrays; without a guard a maliciously
1455
+ * nested table-in-cell-in-table-in-cell input could blow stack and
1456
+ * memory. Set high enough to comfortably handle real legal documents
1457
+ * (tables nested 2-3 deep at most), low enough to short-circuit
1458
+ * pathological input.
1459
+ */
1460
+ static MaxTablePreprocessDepth = 8;
450
1461
  content = [];
451
1462
  newText;
452
1463
  oldText;
1464
+ tablePreprocessDepth;
453
1465
  specialTagDiffStack = [];
454
1466
  newWords = [];
455
1467
  oldWords = [];
@@ -512,13 +1524,17 @@ var HtmlDiff = class HtmlDiff {
512
1524
  * Initializes a new instance of the class.
513
1525
  * @param oldText The old text.
514
1526
  * @param newText The new text.
1527
+ * @param tablePreprocessDepth Internal: nested-call depth for table
1528
+ * preprocessing. Callers should leave at default (0); the recursive
1529
+ * `diffCell` callback in TableDiff bumps it.
515
1530
  */
516
- constructor(oldText, newText) {
1531
+ constructor(oldText, newText, tablePreprocessDepth = 0) {
517
1532
  this.oldText = oldText;
518
1533
  this.newText = newText;
1534
+ this.tablePreprocessDepth = tablePreprocessDepth;
519
1535
  }
520
- static execute(oldText, newText) {
521
- return new HtmlDiff(oldText, newText).build();
1536
+ static execute(oldText, newText, tablePreprocessDepth = 0) {
1537
+ return new HtmlDiff(oldText, newText, tablePreprocessDepth).build();
522
1538
  }
523
1539
  /**
524
1540
  * Builds the HTML diff output
@@ -526,6 +1542,22 @@ var HtmlDiff = class HtmlDiff {
526
1542
  */
527
1543
  build() {
528
1544
  if (this.oldText === this.newText) return this.newText;
1545
+ const blockExpressions = this.blockExpressions;
1546
+ const repeatingWordsAccuracy = this.repeatingWordsAccuracy;
1547
+ const orphanMatchThreshold = this.orphanMatchThreshold;
1548
+ const ignoreWhitespaceDifferences = this.ignoreWhitespaceDifferences;
1549
+ const tablePreprocess = this.tablePreprocessDepth >= HtmlDiff.MaxTablePreprocessDepth ? null : preprocessTables(this.oldText, this.newText, (oldCell, newCell) => {
1550
+ const inner = new HtmlDiff(oldCell, newCell, this.tablePreprocessDepth + 1);
1551
+ for (const expr of blockExpressions) inner.addBlockExpression(expr);
1552
+ inner.repeatingWordsAccuracy = repeatingWordsAccuracy;
1553
+ inner.orphanMatchThreshold = orphanMatchThreshold;
1554
+ inner.ignoreWhitespaceDifferences = ignoreWhitespaceDifferences;
1555
+ return inner.build();
1556
+ });
1557
+ if (tablePreprocess) {
1558
+ this.oldText = tablePreprocess.modifiedOld;
1559
+ this.newText = tablePreprocess.modifiedNew;
1560
+ }
529
1561
  this.splitInputsToWords();
530
1562
  this.buildContentProjections();
531
1563
  const wordsForDiffOld = this.oldContentWords ?? this.oldWords;
@@ -533,7 +1565,8 @@ var HtmlDiff = class HtmlDiff {
533
1565
  this.matchGranularity = Math.min(HtmlDiff.MatchGranularityMaximum, Math.min(wordsForDiffOld.length, wordsForDiffNew.length));
534
1566
  const operations = this.operations();
535
1567
  for (const op of operations) this.performOperation(op);
536
- return this.content.join("");
1568
+ const result = this.content.join("");
1569
+ return tablePreprocess ? restoreTablePlaceholders(result, tablePreprocess.placeholderToDiff) : result;
537
1570
  }
538
1571
  /**
539
1572
  * Uses {@link expression} to group text together so that any change detected within the group is treated as a single block
@@ -760,7 +1793,7 @@ var HtmlDiff = class HtmlDiff {
760
1793
  if (words.slice(0, indexLastTagInFirstTagBlock + 1).some((w) => !HtmlDiff.SpecialCaseClosingTagsSet.has(w.toLowerCase()))) tagIndexToCompare = 0;
761
1794
  }
762
1795
  const openingAndClosingTagsMatch = !!openingTag && Utils_default.getTagName(openingTag) === Utils_default.getTagName(words[tagIndexToCompare]);
763
- if (!!openingTag && openingAndClosingTagsMatch) {
1796
+ if (openingTag && openingAndClosingTagsMatch) {
764
1797
  specialCaseTagInjection = "</ins>";
765
1798
  specialCaseTagInjectionIsBefore = true;
766
1799
  } else if (openingTag) this.specialTagDiffStack.push(openingTag);