@xyne/xyne-cli-linux-x64 0.2.6 → 0.3.1

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.
Files changed (150) hide show
  1. package/node_modules/@opentui/core/node_modules/diff/CONTRIBUTING.md +28 -0
  2. package/node_modules/@opentui/core/node_modules/diff/LICENSE +29 -0
  3. package/node_modules/@opentui/core/node_modules/diff/README.md +378 -0
  4. package/node_modules/@opentui/core/node_modules/diff/dist/diff.js +1674 -0
  5. package/node_modules/@opentui/core/node_modules/diff/dist/diff.min.js +1 -0
  6. package/node_modules/@opentui/core/node_modules/diff/eslint.config.mjs +182 -0
  7. package/node_modules/@opentui/core/node_modules/diff/libcjs/convert/dmp.d.ts +8 -0
  8. package/node_modules/@opentui/core/node_modules/diff/libcjs/convert/dmp.d.ts.map +1 -0
  9. package/node_modules/@opentui/core/node_modules/diff/libcjs/convert/dmp.js +24 -0
  10. package/node_modules/@opentui/core/node_modules/diff/libcjs/convert/xml.d.ts +6 -0
  11. package/node_modules/@opentui/core/node_modules/diff/libcjs/convert/xml.d.ts.map +1 -0
  12. package/node_modules/@opentui/core/node_modules/diff/libcjs/convert/xml.js +34 -0
  13. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/array.d.ts +19 -0
  14. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/array.d.ts.map +1 -0
  15. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/array.js +40 -0
  16. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/base.d.ts +20 -0
  17. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/base.d.ts.map +1 -0
  18. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/base.js +265 -0
  19. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/character.d.ts +19 -0
  20. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/character.d.ts.map +1 -0
  21. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/character.js +31 -0
  22. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/css.d.ts +18 -0
  23. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/css.d.ts.map +1 -0
  24. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/css.js +34 -0
  25. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/json.d.ts +24 -0
  26. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/json.d.ts.map +1 -0
  27. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/json.js +105 -0
  28. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/line.d.ts +24 -0
  29. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/line.d.ts.map +1 -0
  30. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/line.js +89 -0
  31. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/sentence.d.ts +21 -0
  32. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/sentence.d.ts.map +1 -0
  33. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/sentence.js +67 -0
  34. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/word.d.ts +35 -0
  35. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/word.d.ts.map +1 -0
  36. package/node_modules/@opentui/core/node_modules/diff/libcjs/diff/word.js +307 -0
  37. package/node_modules/@opentui/core/node_modules/diff/libcjs/index.d.ts +20 -0
  38. package/node_modules/@opentui/core/node_modules/diff/libcjs/index.d.ts.map +1 -0
  39. package/node_modules/@opentui/core/node_modules/diff/libcjs/index.js +61 -0
  40. package/node_modules/@opentui/core/node_modules/diff/libcjs/package.json +1 -0
  41. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/apply.d.ts +62 -0
  42. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/apply.d.ts.map +1 -0
  43. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/apply.js +267 -0
  44. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/create.d.ts +100 -0
  45. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/create.d.ts.map +1 -0
  46. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/create.js +223 -0
  47. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/line-endings.d.ts +17 -0
  48. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/line-endings.d.ts.map +1 -0
  49. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/line-endings.js +61 -0
  50. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/parse.d.ts +8 -0
  51. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/parse.d.ts.map +1 -0
  52. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/parse.js +133 -0
  53. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/reverse.d.ts +9 -0
  54. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/reverse.d.ts.map +1 -0
  55. package/node_modules/@opentui/core/node_modules/diff/libcjs/patch/reverse.js +37 -0
  56. package/node_modules/@opentui/core/node_modules/diff/libcjs/types.d.ts +213 -0
  57. package/node_modules/@opentui/core/node_modules/diff/libcjs/types.d.ts.map +1 -0
  58. package/node_modules/@opentui/core/node_modules/diff/libcjs/types.js +2 -0
  59. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/array.d.ts +3 -0
  60. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/array.d.ts.map +1 -0
  61. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/array.js +21 -0
  62. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/distance-iterator.d.ts +2 -0
  63. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/distance-iterator.d.ts.map +1 -0
  64. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/distance-iterator.js +40 -0
  65. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/params.d.ts +4 -0
  66. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/params.d.ts.map +1 -0
  67. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/params.js +17 -0
  68. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/string.d.ts +18 -0
  69. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/string.d.ts.map +1 -0
  70. package/node_modules/@opentui/core/node_modules/diff/libcjs/util/string.js +141 -0
  71. package/node_modules/@opentui/core/node_modules/diff/libesm/convert/dmp.d.ts +8 -0
  72. package/node_modules/@opentui/core/node_modules/diff/libesm/convert/dmp.d.ts.map +1 -0
  73. package/node_modules/@opentui/core/node_modules/diff/libesm/convert/dmp.js +21 -0
  74. package/node_modules/@opentui/core/node_modules/diff/libesm/convert/xml.d.ts +6 -0
  75. package/node_modules/@opentui/core/node_modules/diff/libesm/convert/xml.d.ts.map +1 -0
  76. package/node_modules/@opentui/core/node_modules/diff/libesm/convert/xml.js +31 -0
  77. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/array.d.ts +19 -0
  78. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/array.d.ts.map +1 -0
  79. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/array.js +16 -0
  80. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/base.d.ts +20 -0
  81. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/base.d.ts.map +1 -0
  82. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/base.js +253 -0
  83. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/character.d.ts +19 -0
  84. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/character.d.ts.map +1 -0
  85. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/character.js +7 -0
  86. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/css.d.ts +18 -0
  87. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/css.d.ts.map +1 -0
  88. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/css.js +10 -0
  89. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/json.d.ts +24 -0
  90. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/json.d.ts.map +1 -0
  91. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/json.js +78 -0
  92. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/line.d.ts +24 -0
  93. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/line.d.ts.map +1 -0
  94. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/line.js +65 -0
  95. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/sentence.d.ts +21 -0
  96. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/sentence.d.ts.map +1 -0
  97. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/sentence.js +43 -0
  98. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/word.d.ts +35 -0
  99. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/word.d.ts.map +1 -0
  100. package/node_modules/@opentui/core/node_modules/diff/libesm/diff/word.js +276 -0
  101. package/node_modules/@opentui/core/node_modules/diff/libesm/index.d.ts +20 -0
  102. package/node_modules/@opentui/core/node_modules/diff/libesm/index.d.ts.map +1 -0
  103. package/node_modules/@opentui/core/node_modules/diff/libesm/index.js +30 -0
  104. package/node_modules/@opentui/core/node_modules/diff/libesm/package.json +1 -0
  105. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/apply.d.ts +62 -0
  106. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/apply.d.ts.map +1 -0
  107. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/apply.js +257 -0
  108. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/create.d.ts +100 -0
  109. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/create.d.ts.map +1 -0
  110. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/create.js +201 -0
  111. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/line-endings.d.ts +17 -0
  112. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/line-endings.d.ts.map +1 -0
  113. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/line-endings.js +44 -0
  114. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/parse.d.ts +8 -0
  115. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/parse.d.ts.map +1 -0
  116. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/parse.js +130 -0
  117. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/reverse.d.ts +9 -0
  118. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/reverse.d.ts.map +1 -0
  119. package/node_modules/@opentui/core/node_modules/diff/libesm/patch/reverse.js +23 -0
  120. package/node_modules/@opentui/core/node_modules/diff/libesm/types.d.ts +213 -0
  121. package/node_modules/@opentui/core/node_modules/diff/libesm/types.d.ts.map +1 -0
  122. package/node_modules/@opentui/core/node_modules/diff/libesm/types.js +1 -0
  123. package/node_modules/@opentui/core/node_modules/diff/libesm/util/array.d.ts +3 -0
  124. package/node_modules/@opentui/core/node_modules/diff/libesm/util/array.d.ts.map +1 -0
  125. package/node_modules/@opentui/core/node_modules/diff/libesm/util/array.js +17 -0
  126. package/node_modules/@opentui/core/node_modules/diff/libesm/util/distance-iterator.d.ts +2 -0
  127. package/node_modules/@opentui/core/node_modules/diff/libesm/util/distance-iterator.d.ts.map +1 -0
  128. package/node_modules/@opentui/core/node_modules/diff/libesm/util/distance-iterator.js +37 -0
  129. package/node_modules/@opentui/core/node_modules/diff/libesm/util/params.d.ts +4 -0
  130. package/node_modules/@opentui/core/node_modules/diff/libesm/util/params.d.ts.map +1 -0
  131. package/node_modules/@opentui/core/node_modules/diff/libesm/util/params.js +14 -0
  132. package/node_modules/@opentui/core/node_modules/diff/libesm/util/string.d.ts +18 -0
  133. package/node_modules/@opentui/core/node_modules/diff/libesm/util/string.d.ts.map +1 -0
  134. package/node_modules/@opentui/core/node_modules/diff/libesm/util/string.js +128 -0
  135. package/node_modules/@opentui/core/node_modules/diff/package.json +131 -0
  136. package/node_modules/@opentui/core/node_modules/diff/release-notes.md +397 -0
  137. package/node_modules/@opentui/core/node_modules/marked/LICENSE.md +44 -0
  138. package/node_modules/@opentui/core/node_modules/marked/README.md +107 -0
  139. package/node_modules/@opentui/core/node_modules/marked/bin/main.js +283 -0
  140. package/node_modules/@opentui/core/node_modules/marked/bin/marked.js +16 -0
  141. package/node_modules/@opentui/core/node_modules/marked/lib/marked.d.ts +756 -0
  142. package/node_modules/@opentui/core/node_modules/marked/lib/marked.esm.js +72 -0
  143. package/node_modules/@opentui/core/node_modules/marked/lib/marked.esm.js.map +7 -0
  144. package/node_modules/@opentui/core/node_modules/marked/lib/marked.umd.js +74 -0
  145. package/node_modules/@opentui/core/node_modules/marked/lib/marked.umd.js.map +7 -0
  146. package/node_modules/@opentui/core/node_modules/marked/man/marked.1 +113 -0
  147. package/node_modules/@opentui/core/node_modules/marked/man/marked.1.md +93 -0
  148. package/node_modules/@opentui/core/node_modules/marked/package.json +103 -0
  149. package/package.json +1 -1
  150. package/xyne-linux-x64 +0 -0
@@ -0,0 +1,1674 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Diff = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ class Diff {
8
+ diff(oldStr, newStr,
9
+ // Type below is not accurate/complete - see above for full possibilities - but it compiles
10
+ options = {}) {
11
+ let callback;
12
+ if (typeof options === 'function') {
13
+ callback = options;
14
+ options = {};
15
+ }
16
+ else if ('callback' in options) {
17
+ callback = options.callback;
18
+ }
19
+ // Allow subclasses to massage the input prior to running
20
+ const oldString = this.castInput(oldStr, options);
21
+ const newString = this.castInput(newStr, options);
22
+ const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
23
+ const newTokens = this.removeEmpty(this.tokenize(newString, options));
24
+ return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
25
+ }
26
+ diffWithOptionsObj(oldTokens, newTokens, options, callback) {
27
+ var _a;
28
+ const done = (value) => {
29
+ value = this.postProcess(value, options);
30
+ if (callback) {
31
+ setTimeout(function () { callback(value); }, 0);
32
+ return undefined;
33
+ }
34
+ else {
35
+ return value;
36
+ }
37
+ };
38
+ const newLen = newTokens.length, oldLen = oldTokens.length;
39
+ let editLength = 1;
40
+ let maxEditLength = newLen + oldLen;
41
+ if (options.maxEditLength != null) {
42
+ maxEditLength = Math.min(maxEditLength, options.maxEditLength);
43
+ }
44
+ const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;
45
+ const abortAfterTimestamp = Date.now() + maxExecutionTime;
46
+ const bestPath = [{ oldPos: -1, lastComponent: undefined }];
47
+ // Seed editLength = 0, i.e. the content starts with the same values
48
+ let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
49
+ if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
50
+ // Identity per the equality and tokenizer
51
+ return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
52
+ }
53
+ // Once we hit the right edge of the edit graph on some diagonal k, we can
54
+ // definitely reach the end of the edit graph in no more than k edits, so
55
+ // there's no point in considering any moves to diagonal k+1 any more (from
56
+ // which we're guaranteed to need at least k+1 more edits).
57
+ // Similarly, once we've reached the bottom of the edit graph, there's no
58
+ // point considering moves to lower diagonals.
59
+ // We record this fact by setting minDiagonalToConsider and
60
+ // maxDiagonalToConsider to some finite value once we've hit the edge of
61
+ // the edit graph.
62
+ // This optimization is not faithful to the original algorithm presented in
63
+ // Myers's paper, which instead pointlessly extends D-paths off the end of
64
+ // the edit graph - see page 7 of Myers's paper which notes this point
65
+ // explicitly and illustrates it with a diagram. This has major performance
66
+ // implications for some common scenarios. For instance, to compute a diff
67
+ // where the new text simply appends d characters on the end of the
68
+ // original text of length n, the true Myers algorithm will take O(n+d^2)
69
+ // time while this optimization needs only O(n+d) time.
70
+ let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
71
+ // Main worker method. checks all permutations of a given edit length for acceptance.
72
+ const execEditLength = () => {
73
+ for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
74
+ let basePath;
75
+ const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
76
+ if (removePath) {
77
+ // No one else is going to attempt to use this value, clear it
78
+ // @ts-expect-error - perf optimisation. This type-violating value will never be read.
79
+ bestPath[diagonalPath - 1] = undefined;
80
+ }
81
+ let canAdd = false;
82
+ if (addPath) {
83
+ // what newPos will be after we do an insertion:
84
+ const addPathNewPos = addPath.oldPos - diagonalPath;
85
+ canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
86
+ }
87
+ const canRemove = removePath && removePath.oldPos + 1 < oldLen;
88
+ if (!canAdd && !canRemove) {
89
+ // If this path is a terminal then prune
90
+ // @ts-expect-error - perf optimisation. This type-violating value will never be read.
91
+ bestPath[diagonalPath] = undefined;
92
+ continue;
93
+ }
94
+ // Select the diagonal that we want to branch from. We select the prior
95
+ // path whose position in the old string is the farthest from the origin
96
+ // and does not pass the bounds of the diff graph
97
+ if (!canRemove || (canAdd && removePath.oldPos < addPath.oldPos)) {
98
+ basePath = this.addToPath(addPath, true, false, 0, options);
99
+ }
100
+ else {
101
+ basePath = this.addToPath(removePath, false, true, 1, options);
102
+ }
103
+ newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
104
+ if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
105
+ // If we have hit the end of both strings, then we are done
106
+ return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
107
+ }
108
+ else {
109
+ bestPath[diagonalPath] = basePath;
110
+ if (basePath.oldPos + 1 >= oldLen) {
111
+ maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
112
+ }
113
+ if (newPos + 1 >= newLen) {
114
+ minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
115
+ }
116
+ }
117
+ }
118
+ editLength++;
119
+ };
120
+ // Performs the length of edit iteration. Is a bit fugly as this has to support the
121
+ // sync and async mode which is never fun. Loops over execEditLength until a value
122
+ // is produced, or until the edit length exceeds options.maxEditLength (if given),
123
+ // in which case it will return undefined.
124
+ if (callback) {
125
+ (function exec() {
126
+ setTimeout(function () {
127
+ if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
128
+ return callback(undefined);
129
+ }
130
+ if (!execEditLength()) {
131
+ exec();
132
+ }
133
+ }, 0);
134
+ }());
135
+ }
136
+ else {
137
+ while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
138
+ const ret = execEditLength();
139
+ if (ret) {
140
+ return ret;
141
+ }
142
+ }
143
+ }
144
+ }
145
+ addToPath(path, added, removed, oldPosInc, options) {
146
+ const last = path.lastComponent;
147
+ if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
148
+ return {
149
+ oldPos: path.oldPos + oldPosInc,
150
+ lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent }
151
+ };
152
+ }
153
+ else {
154
+ return {
155
+ oldPos: path.oldPos + oldPosInc,
156
+ lastComponent: { count: 1, added: added, removed: removed, previousComponent: last }
157
+ };
158
+ }
159
+ }
160
+ extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
161
+ const newLen = newTokens.length, oldLen = oldTokens.length;
162
+ let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
163
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
164
+ newPos++;
165
+ oldPos++;
166
+ commonCount++;
167
+ if (options.oneChangePerToken) {
168
+ basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
169
+ }
170
+ }
171
+ if (commonCount && !options.oneChangePerToken) {
172
+ basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
173
+ }
174
+ basePath.oldPos = oldPos;
175
+ return newPos;
176
+ }
177
+ equals(left, right, options) {
178
+ if (options.comparator) {
179
+ return options.comparator(left, right);
180
+ }
181
+ else {
182
+ return left === right
183
+ || (!!options.ignoreCase && left.toLowerCase() === right.toLowerCase());
184
+ }
185
+ }
186
+ removeEmpty(array) {
187
+ const ret = [];
188
+ for (let i = 0; i < array.length; i++) {
189
+ if (array[i]) {
190
+ ret.push(array[i]);
191
+ }
192
+ }
193
+ return ret;
194
+ }
195
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
196
+ castInput(value, options) {
197
+ return value;
198
+ }
199
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
200
+ tokenize(value, options) {
201
+ return Array.from(value);
202
+ }
203
+ join(chars) {
204
+ // Assumes ValueT is string, which is the case for most subclasses.
205
+ // When it's false, e.g. in diffArrays, this method needs to be overridden (e.g. with a no-op)
206
+ // Yes, the casts are verbose and ugly, because this pattern - of having the base class SORT OF
207
+ // assume tokens and values are strings, but not completely - is weird and janky.
208
+ return chars.join('');
209
+ }
210
+ postProcess(changeObjects,
211
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
212
+ options) {
213
+ return changeObjects;
214
+ }
215
+ get useLongestToken() {
216
+ return false;
217
+ }
218
+ buildValues(lastComponent, newTokens, oldTokens) {
219
+ // First we convert our linked list of components in reverse order to an
220
+ // array in the right order:
221
+ const components = [];
222
+ let nextComponent;
223
+ while (lastComponent) {
224
+ components.push(lastComponent);
225
+ nextComponent = lastComponent.previousComponent;
226
+ delete lastComponent.previousComponent;
227
+ lastComponent = nextComponent;
228
+ }
229
+ components.reverse();
230
+ const componentLen = components.length;
231
+ let componentPos = 0, newPos = 0, oldPos = 0;
232
+ for (; componentPos < componentLen; componentPos++) {
233
+ const component = components[componentPos];
234
+ if (!component.removed) {
235
+ if (!component.added && this.useLongestToken) {
236
+ let value = newTokens.slice(newPos, newPos + component.count);
237
+ value = value.map(function (value, i) {
238
+ const oldValue = oldTokens[oldPos + i];
239
+ return oldValue.length > value.length ? oldValue : value;
240
+ });
241
+ component.value = this.join(value);
242
+ }
243
+ else {
244
+ component.value = this.join(newTokens.slice(newPos, newPos + component.count));
245
+ }
246
+ newPos += component.count;
247
+ // Common case
248
+ if (!component.added) {
249
+ oldPos += component.count;
250
+ }
251
+ }
252
+ else {
253
+ component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
254
+ oldPos += component.count;
255
+ }
256
+ }
257
+ return components;
258
+ }
259
+ }
260
+
261
+ class CharacterDiff extends Diff {
262
+ }
263
+ const characterDiff = new CharacterDiff();
264
+ function diffChars(oldStr, newStr, options) {
265
+ return characterDiff.diff(oldStr, newStr, options);
266
+ }
267
+
268
+ function longestCommonPrefix(str1, str2) {
269
+ let i;
270
+ for (i = 0; i < str1.length && i < str2.length; i++) {
271
+ if (str1[i] != str2[i]) {
272
+ return str1.slice(0, i);
273
+ }
274
+ }
275
+ return str1.slice(0, i);
276
+ }
277
+ function longestCommonSuffix(str1, str2) {
278
+ let i;
279
+ // Unlike longestCommonPrefix, we need a special case to handle all scenarios
280
+ // where we return the empty string since str1.slice(-0) will return the
281
+ // entire string.
282
+ if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {
283
+ return '';
284
+ }
285
+ for (i = 0; i < str1.length && i < str2.length; i++) {
286
+ if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) {
287
+ return str1.slice(-i);
288
+ }
289
+ }
290
+ return str1.slice(-i);
291
+ }
292
+ function replacePrefix(string, oldPrefix, newPrefix) {
293
+ if (string.slice(0, oldPrefix.length) != oldPrefix) {
294
+ throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`);
295
+ }
296
+ return newPrefix + string.slice(oldPrefix.length);
297
+ }
298
+ function replaceSuffix(string, oldSuffix, newSuffix) {
299
+ if (!oldSuffix) {
300
+ return string + newSuffix;
301
+ }
302
+ if (string.slice(-oldSuffix.length) != oldSuffix) {
303
+ throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`);
304
+ }
305
+ return string.slice(0, -oldSuffix.length) + newSuffix;
306
+ }
307
+ function removePrefix(string, oldPrefix) {
308
+ return replacePrefix(string, oldPrefix, '');
309
+ }
310
+ function removeSuffix(string, oldSuffix) {
311
+ return replaceSuffix(string, oldSuffix, '');
312
+ }
313
+ function maximumOverlap(string1, string2) {
314
+ return string2.slice(0, overlapCount(string1, string2));
315
+ }
316
+ // Nicked from https://stackoverflow.com/a/60422853/1709587
317
+ function overlapCount(a, b) {
318
+ // Deal with cases where the strings differ in length
319
+ let startA = 0;
320
+ if (a.length > b.length) {
321
+ startA = a.length - b.length;
322
+ }
323
+ let endB = b.length;
324
+ if (a.length < b.length) {
325
+ endB = a.length;
326
+ }
327
+ // Create a back-reference for each index
328
+ // that should be followed in case of a mismatch.
329
+ // We only need B to make these references:
330
+ const map = Array(endB);
331
+ let k = 0; // Index that lags behind j
332
+ map[0] = 0;
333
+ for (let j = 1; j < endB; j++) {
334
+ if (b[j] == b[k]) {
335
+ map[j] = map[k]; // skip over the same character (optional optimisation)
336
+ }
337
+ else {
338
+ map[j] = k;
339
+ }
340
+ while (k > 0 && b[j] != b[k]) {
341
+ k = map[k];
342
+ }
343
+ if (b[j] == b[k]) {
344
+ k++;
345
+ }
346
+ }
347
+ // Phase 2: use these references while iterating over A
348
+ k = 0;
349
+ for (let i = startA; i < a.length; i++) {
350
+ while (k > 0 && a[i] != b[k]) {
351
+ k = map[k];
352
+ }
353
+ if (a[i] == b[k]) {
354
+ k++;
355
+ }
356
+ }
357
+ return k;
358
+ }
359
+ /**
360
+ * Returns true if the string consistently uses Windows line endings.
361
+ */
362
+ function hasOnlyWinLineEndings(string) {
363
+ return string.includes('\r\n') && !string.startsWith('\n') && !string.match(/[^\r]\n/);
364
+ }
365
+ /**
366
+ * Returns true if the string consistently uses Unix line endings.
367
+ */
368
+ function hasOnlyUnixLineEndings(string) {
369
+ return !string.includes('\r\n') && string.includes('\n');
370
+ }
371
+ function trailingWs(string) {
372
+ // Yes, this looks overcomplicated and dumb - why not replace the whole function with
373
+ // return string match(/\s*$/)[0]
374
+ // you ask? Because:
375
+ // 1. the trap described at https://markamery.com/blog/quadratic-time-regexes/ would mean doing
376
+ // this would cause this function to take O(n²) time in the worst case (specifically when
377
+ // there is a massive run of NON-TRAILING whitespace in `string`), and
378
+ // 2. the fix proposed in the same blog post, of using a negative lookbehind, is incompatible
379
+ // with old Safari versions that we'd like to not break if possible (see
380
+ // https://github.com/kpdecker/jsdiff/pull/550)
381
+ // It feels absurd to do this with an explicit loop instead of a regex, but I really can't see a
382
+ // better way that doesn't result in broken behaviour.
383
+ let i;
384
+ for (i = string.length - 1; i >= 0; i--) {
385
+ if (!string[i].match(/\s/)) {
386
+ break;
387
+ }
388
+ }
389
+ return string.substring(i + 1);
390
+ }
391
+ function leadingWs(string) {
392
+ // Thankfully the annoying considerations described in trailingWs don't apply here:
393
+ const match = string.match(/^\s*/);
394
+ return match ? match[0] : '';
395
+ }
396
+
397
+ // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode
398
+ //
399
+ // Ranges and exceptions:
400
+ // Latin-1 Supplement, 0080–00FF
401
+ // - U+00D7 × Multiplication sign
402
+ // - U+00F7 ÷ Division sign
403
+ // Latin Extended-A, 0100–017F
404
+ // Latin Extended-B, 0180–024F
405
+ // IPA Extensions, 0250–02AF
406
+ // Spacing Modifier Letters, 02B0–02FF
407
+ // - U+02C7 ˇ &#711; Caron
408
+ // - U+02D8 ˘ &#728; Breve
409
+ // - U+02D9 ˙ &#729; Dot Above
410
+ // - U+02DA ˚ &#730; Ring Above
411
+ // - U+02DB ˛ &#731; Ogonek
412
+ // - U+02DC ˜ &#732; Small Tilde
413
+ // - U+02DD ˝ &#733; Double Acute Accent
414
+ // Latin Extended Additional, 1E00–1EFF
415
+ const extendedWordChars = 'a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}';
416
+ // Each token is one of the following:
417
+ // - A punctuation mark plus the surrounding whitespace
418
+ // - A word plus the surrounding whitespace
419
+ // - Pure whitespace (but only in the special case where this the entire text
420
+ // is just whitespace)
421
+ //
422
+ // We have to include surrounding whitespace in the tokens because the two
423
+ // alternative approaches produce horribly broken results:
424
+ // * If we just discard the whitespace, we can't fully reproduce the original
425
+ // text from the sequence of tokens and any attempt to render the diff will
426
+ // get the whitespace wrong.
427
+ // * If we have separate tokens for whitespace, then in a typical text every
428
+ // second token will be a single space character. But this often results in
429
+ // the optimal diff between two texts being a perverse one that preserves
430
+ // the spaces between words but deletes and reinserts actual common words.
431
+ // See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640
432
+ // for an example.
433
+ //
434
+ // Keeping the surrounding whitespace of course has implications for .equals
435
+ // and .join, not just .tokenize.
436
+ // This regex does NOT fully implement the tokenization rules described above.
437
+ // Instead, it gives runs of whitespace their own "token". The tokenize method
438
+ // then handles stitching whitespace tokens onto adjacent word or punctuation
439
+ // tokens.
440
+ const tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\s+|[^${extendedWordChars}]`, 'ug');
441
+ class WordDiff extends Diff {
442
+ equals(left, right, options) {
443
+ if (options.ignoreCase) {
444
+ left = left.toLowerCase();
445
+ right = right.toLowerCase();
446
+ }
447
+ return left.trim() === right.trim();
448
+ }
449
+ tokenize(value, options = {}) {
450
+ let parts;
451
+ if (options.intlSegmenter) {
452
+ const segmenter = options.intlSegmenter;
453
+ if (segmenter.resolvedOptions().granularity != 'word') {
454
+ throw new Error('The segmenter passed must have a granularity of "word"');
455
+ }
456
+ parts = Array.from(segmenter.segment(value), segment => segment.segment);
457
+ }
458
+ else {
459
+ parts = value.match(tokenizeIncludingWhitespace) || [];
460
+ }
461
+ const tokens = [];
462
+ let prevPart = null;
463
+ parts.forEach(part => {
464
+ if ((/\s/).test(part)) {
465
+ if (prevPart == null) {
466
+ tokens.push(part);
467
+ }
468
+ else {
469
+ tokens.push(tokens.pop() + part);
470
+ }
471
+ }
472
+ else if (prevPart != null && (/\s/).test(prevPart)) {
473
+ if (tokens[tokens.length - 1] == prevPart) {
474
+ tokens.push(tokens.pop() + part);
475
+ }
476
+ else {
477
+ tokens.push(prevPart + part);
478
+ }
479
+ }
480
+ else {
481
+ tokens.push(part);
482
+ }
483
+ prevPart = part;
484
+ });
485
+ return tokens;
486
+ }
487
+ join(tokens) {
488
+ // Tokens being joined here will always have appeared consecutively in the
489
+ // same text, so we can simply strip off the leading whitespace from all the
490
+ // tokens except the first (and except any whitespace-only tokens - but such
491
+ // a token will always be the first and only token anyway) and then join them
492
+ // and the whitespace around words and punctuation will end up correct.
493
+ return tokens.map((token, i) => {
494
+ if (i == 0) {
495
+ return token;
496
+ }
497
+ else {
498
+ return token.replace((/^\s+/), '');
499
+ }
500
+ }).join('');
501
+ }
502
+ postProcess(changes, options) {
503
+ if (!changes || options.oneChangePerToken) {
504
+ return changes;
505
+ }
506
+ let lastKeep = null;
507
+ // Change objects representing any insertion or deletion since the last
508
+ // "keep" change object. There can be at most one of each.
509
+ let insertion = null;
510
+ let deletion = null;
511
+ changes.forEach(change => {
512
+ if (change.added) {
513
+ insertion = change;
514
+ }
515
+ else if (change.removed) {
516
+ deletion = change;
517
+ }
518
+ else {
519
+ if (insertion || deletion) { // May be false at start of text
520
+ dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change);
521
+ }
522
+ lastKeep = change;
523
+ insertion = null;
524
+ deletion = null;
525
+ }
526
+ });
527
+ if (insertion || deletion) {
528
+ dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null);
529
+ }
530
+ return changes;
531
+ }
532
+ }
533
+ const wordDiff = new WordDiff();
534
+ function diffWords(oldStr, newStr, options) {
535
+ // This option has never been documented and never will be (it's clearer to
536
+ // just call `diffWordsWithSpace` directly if you need that behavior), but
537
+ // has existed in jsdiff for a long time, so we retain support for it here
538
+ // for the sake of backwards compatibility.
539
+ if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) {
540
+ return diffWordsWithSpace(oldStr, newStr, options);
541
+ }
542
+ return wordDiff.diff(oldStr, newStr, options);
543
+ }
544
+ function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) {
545
+ // Before returning, we tidy up the leading and trailing whitespace of the
546
+ // change objects to eliminate cases where trailing whitespace in one object
547
+ // is repeated as leading whitespace in the next.
548
+ // Below are examples of the outcomes we want here to explain the code.
549
+ // I=insert, K=keep, D=delete
550
+ // 1. diffing 'foo bar baz' vs 'foo baz'
551
+ // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'
552
+ // After cleanup, we want: K:'foo ' D:'bar ' K:'baz'
553
+ //
554
+ // 2. Diffing 'foo bar baz' vs 'foo qux baz'
555
+ // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz'
556
+ // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz'
557
+ //
558
+ // 3. Diffing 'foo\nbar baz' vs 'foo baz'
559
+ // Prior to cleanup, we have K:'foo ' D:'\nbar ' K:' baz'
560
+ // After cleanup, we want K'foo' D:'\nbar' K:' baz'
561
+ //
562
+ // 4. Diffing 'foo baz' vs 'foo\nbar baz'
563
+ // Prior to cleanup, we have K:'foo\n' I:'\nbar ' K:' baz'
564
+ // After cleanup, we ideally want K'foo' I:'\nbar' K:' baz'
565
+ // but don't actually manage this currently (the pre-cleanup change
566
+ // objects don't contain enough information to make it possible).
567
+ //
568
+ // 5. Diffing 'foo bar baz' vs 'foo baz'
569
+ // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'
570
+ // After cleanup, we want K:'foo ' D:' bar ' K:'baz'
571
+ //
572
+ // Our handling is unavoidably imperfect in the case where there's a single
573
+ // indel between keeps and the whitespace has changed. For instance, consider
574
+ // diffing 'foo\tbar\nbaz' vs 'foo baz'. Unless we create an extra change
575
+ // object to represent the insertion of the space character (which isn't even
576
+ // a token), we have no way to avoid losing information about the texts'
577
+ // original whitespace in the result we return. Still, we do our best to
578
+ // output something that will look sensible if we e.g. print it with
579
+ // insertions in green and deletions in red.
580
+ // Between two "keep" change objects (or before the first or after the last
581
+ // change object), we can have either:
582
+ // * A "delete" followed by an "insert"
583
+ // * Just an "insert"
584
+ // * Just a "delete"
585
+ // We handle the three cases separately.
586
+ if (deletion && insertion) {
587
+ const oldWsPrefix = leadingWs(deletion.value);
588
+ const oldWsSuffix = trailingWs(deletion.value);
589
+ const newWsPrefix = leadingWs(insertion.value);
590
+ const newWsSuffix = trailingWs(insertion.value);
591
+ if (startKeep) {
592
+ const commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);
593
+ startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);
594
+ deletion.value = removePrefix(deletion.value, commonWsPrefix);
595
+ insertion.value = removePrefix(insertion.value, commonWsPrefix);
596
+ }
597
+ if (endKeep) {
598
+ const commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);
599
+ endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);
600
+ deletion.value = removeSuffix(deletion.value, commonWsSuffix);
601
+ insertion.value = removeSuffix(insertion.value, commonWsSuffix);
602
+ }
603
+ }
604
+ else if (insertion) {
605
+ // The whitespaces all reflect what was in the new text rather than
606
+ // the old, so we essentially have no information about whitespace
607
+ // insertion or deletion. We just want to dedupe the whitespace.
608
+ // We do that by having each change object keep its trailing
609
+ // whitespace and deleting duplicate leading whitespace where
610
+ // present.
611
+ if (startKeep) {
612
+ const ws = leadingWs(insertion.value);
613
+ insertion.value = insertion.value.substring(ws.length);
614
+ }
615
+ if (endKeep) {
616
+ const ws = leadingWs(endKeep.value);
617
+ endKeep.value = endKeep.value.substring(ws.length);
618
+ }
619
+ // otherwise we've got a deletion and no insertion
620
+ }
621
+ else if (startKeep && endKeep) {
622
+ const newWsFull = leadingWs(endKeep.value), delWsStart = leadingWs(deletion.value), delWsEnd = trailingWs(deletion.value);
623
+ // Any whitespace that comes straight after startKeep in both the old and
624
+ // new texts, assign to startKeep and remove from the deletion.
625
+ const newWsStart = longestCommonPrefix(newWsFull, delWsStart);
626
+ deletion.value = removePrefix(deletion.value, newWsStart);
627
+ // Any whitespace that comes straight before endKeep in both the old and
628
+ // new texts, and hasn't already been assigned to startKeep, assign to
629
+ // endKeep and remove from the deletion.
630
+ const newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd);
631
+ deletion.value = removeSuffix(deletion.value, newWsEnd);
632
+ endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);
633
+ // If there's any whitespace from the new text that HASN'T already been
634
+ // assigned, assign it to the start:
635
+ startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length));
636
+ }
637
+ else if (endKeep) {
638
+ // We are at the start of the text. Preserve all the whitespace on
639
+ // endKeep, and just remove whitespace from the end of deletion to the
640
+ // extent that it overlaps with the start of endKeep.
641
+ const endKeepWsPrefix = leadingWs(endKeep.value);
642
+ const deletionWsSuffix = trailingWs(deletion.value);
643
+ const overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
644
+ deletion.value = removeSuffix(deletion.value, overlap);
645
+ }
646
+ else if (startKeep) {
647
+ // We are at the END of the text. Preserve all the whitespace on
648
+ // startKeep, and just remove whitespace from the start of deletion to
649
+ // the extent that it overlaps with the end of startKeep.
650
+ const startKeepWsSuffix = trailingWs(startKeep.value);
651
+ const deletionWsPrefix = leadingWs(deletion.value);
652
+ const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);
653
+ deletion.value = removePrefix(deletion.value, overlap);
654
+ }
655
+ }
656
+ class WordsWithSpaceDiff extends Diff {
657
+ tokenize(value) {
658
+ // Slightly different to the tokenizeIncludingWhitespace regex used above in
659
+ // that this one treats each individual newline as a distinct tokens, rather
660
+ // than merging them into other surrounding whitespace. This was requested
661
+ // in https://github.com/kpdecker/jsdiff/issues/180 &
662
+ // https://github.com/kpdecker/jsdiff/issues/211
663
+ const regex = new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`, 'ug');
664
+ return value.match(regex) || [];
665
+ }
666
+ }
667
+ const wordsWithSpaceDiff = new WordsWithSpaceDiff();
668
+ function diffWordsWithSpace(oldStr, newStr, options) {
669
+ return wordsWithSpaceDiff.diff(oldStr, newStr, options);
670
+ }
671
+
672
+ function generateOptions(options, defaults) {
673
+ if (typeof options === 'function') {
674
+ defaults.callback = options;
675
+ }
676
+ else if (options) {
677
+ for (const name in options) {
678
+ /* istanbul ignore else */
679
+ if (Object.prototype.hasOwnProperty.call(options, name)) {
680
+ defaults[name] = options[name];
681
+ }
682
+ }
683
+ }
684
+ return defaults;
685
+ }
686
+
687
+ class LineDiff extends Diff {
688
+ constructor() {
689
+ super(...arguments);
690
+ this.tokenize = tokenize;
691
+ }
692
+ equals(left, right, options) {
693
+ // If we're ignoring whitespace, we need to normalise lines by stripping
694
+ // whitespace before checking equality. (This has an annoying interaction
695
+ // with newlineIsToken that requires special handling: if newlines get their
696
+ // own token, then we DON'T want to trim the *newline* tokens down to empty
697
+ // strings, since this would cause us to treat whitespace-only line content
698
+ // as equal to a separator between lines, which would be weird and
699
+ // inconsistent with the documented behavior of the options.)
700
+ if (options.ignoreWhitespace) {
701
+ if (!options.newlineIsToken || !left.includes('\n')) {
702
+ left = left.trim();
703
+ }
704
+ if (!options.newlineIsToken || !right.includes('\n')) {
705
+ right = right.trim();
706
+ }
707
+ }
708
+ else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
709
+ if (left.endsWith('\n')) {
710
+ left = left.slice(0, -1);
711
+ }
712
+ if (right.endsWith('\n')) {
713
+ right = right.slice(0, -1);
714
+ }
715
+ }
716
+ return super.equals(left, right, options);
717
+ }
718
+ }
719
+ const lineDiff = new LineDiff();
720
+ function diffLines(oldStr, newStr, options) {
721
+ return lineDiff.diff(oldStr, newStr, options);
722
+ }
723
+ function diffTrimmedLines(oldStr, newStr, options) {
724
+ options = generateOptions(options, { ignoreWhitespace: true });
725
+ return lineDiff.diff(oldStr, newStr, options);
726
+ }
727
+ // Exported standalone so it can be used from jsonDiff too.
728
+ function tokenize(value, options) {
729
+ if (options.stripTrailingCr) {
730
+ // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior
731
+ value = value.replace(/\r\n/g, '\n');
732
+ }
733
+ const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
734
+ // Ignore the final empty token that occurs if the string ends with a new line
735
+ if (!linesAndNewlines[linesAndNewlines.length - 1]) {
736
+ linesAndNewlines.pop();
737
+ }
738
+ // Merge the content and line separators into single tokens
739
+ for (let i = 0; i < linesAndNewlines.length; i++) {
740
+ const line = linesAndNewlines[i];
741
+ if (i % 2 && !options.newlineIsToken) {
742
+ retLines[retLines.length - 1] += line;
743
+ }
744
+ else {
745
+ retLines.push(line);
746
+ }
747
+ }
748
+ return retLines;
749
+ }
750
+
751
+ function isSentenceEndPunct(char) {
752
+ return char == '.' || char == '!' || char == '?';
753
+ }
754
+ class SentenceDiff extends Diff {
755
+ tokenize(value) {
756
+ var _a;
757
+ // If in future we drop support for environments that don't support lookbehinds, we can replace
758
+ // this entire function with:
759
+ // return value.split(/(?<=[.!?])(\s+|$)/);
760
+ // but until then, for similar reasons to the trailingWs function in string.ts, we are forced
761
+ // to do this verbosely "by hand" instead of using a regex.
762
+ const result = [];
763
+ let tokenStartI = 0;
764
+ for (let i = 0; i < value.length; i++) {
765
+ if (i == value.length - 1) {
766
+ result.push(value.slice(tokenStartI));
767
+ break;
768
+ }
769
+ if (isSentenceEndPunct(value[i]) && value[i + 1].match(/\s/)) {
770
+ // We've hit a sentence break - i.e. a punctuation mark followed by whitespace.
771
+ // We now want to push TWO tokens to the result:
772
+ // 1. the sentence
773
+ result.push(value.slice(tokenStartI, i + 1));
774
+ // 2. the whitespace
775
+ i = tokenStartI = i + 1;
776
+ while ((_a = value[i + 1]) === null || _a === void 0 ? void 0 : _a.match(/\s/)) {
777
+ i++;
778
+ }
779
+ result.push(value.slice(tokenStartI, i + 1));
780
+ // Then the next token (a sentence) starts on the character after the whitespace.
781
+ // (It's okay if this is off the end of the string - then the outer loop will terminate
782
+ // here anyway.)
783
+ tokenStartI = i + 1;
784
+ }
785
+ }
786
+ return result;
787
+ }
788
+ }
789
+ const sentenceDiff = new SentenceDiff();
790
+ function diffSentences(oldStr, newStr, options) {
791
+ return sentenceDiff.diff(oldStr, newStr, options);
792
+ }
793
+
794
+ class CssDiff extends Diff {
795
+ tokenize(value) {
796
+ return value.split(/([{}:;,]|\s+)/);
797
+ }
798
+ }
799
+ const cssDiff = new CssDiff();
800
+ function diffCss(oldStr, newStr, options) {
801
+ return cssDiff.diff(oldStr, newStr, options);
802
+ }
803
+
804
+ class JsonDiff extends Diff {
805
+ constructor() {
806
+ super(...arguments);
807
+ this.tokenize = tokenize;
808
+ }
809
+ get useLongestToken() {
810
+ // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
811
+ // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
812
+ return true;
813
+ }
814
+ castInput(value, options) {
815
+ const { undefinedReplacement, stringifyReplacer = (k, v) => typeof v === 'undefined' ? undefinedReplacement : v } = options;
816
+ return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), null, ' ');
817
+ }
818
+ equals(left, right, options) {
819
+ return super.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'), options);
820
+ }
821
+ }
822
+ const jsonDiff = new JsonDiff();
823
+ function diffJson(oldStr, newStr, options) {
824
+ return jsonDiff.diff(oldStr, newStr, options);
825
+ }
826
+ // This function handles the presence of circular references by bailing out when encountering an
827
+ // object that is already on the "stack" of items being processed. Accepts an optional replacer
828
+ function canonicalize(obj, stack, replacementStack, replacer, key) {
829
+ stack = stack || [];
830
+ replacementStack = replacementStack || [];
831
+ if (replacer) {
832
+ obj = replacer(key === undefined ? '' : key, obj);
833
+ }
834
+ let i;
835
+ for (i = 0; i < stack.length; i += 1) {
836
+ if (stack[i] === obj) {
837
+ return replacementStack[i];
838
+ }
839
+ }
840
+ let canonicalizedObj;
841
+ if ('[object Array]' === Object.prototype.toString.call(obj)) {
842
+ stack.push(obj);
843
+ canonicalizedObj = new Array(obj.length);
844
+ replacementStack.push(canonicalizedObj);
845
+ for (i = 0; i < obj.length; i += 1) {
846
+ canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, String(i));
847
+ }
848
+ stack.pop();
849
+ replacementStack.pop();
850
+ return canonicalizedObj;
851
+ }
852
+ if (obj && obj.toJSON) {
853
+ obj = obj.toJSON();
854
+ }
855
+ if (typeof obj === 'object' && obj !== null) {
856
+ stack.push(obj);
857
+ canonicalizedObj = {};
858
+ replacementStack.push(canonicalizedObj);
859
+ const sortedKeys = [];
860
+ let key;
861
+ for (key in obj) {
862
+ /* istanbul ignore else */
863
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
864
+ sortedKeys.push(key);
865
+ }
866
+ }
867
+ sortedKeys.sort();
868
+ for (i = 0; i < sortedKeys.length; i += 1) {
869
+ key = sortedKeys[i];
870
+ canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack, replacer, key);
871
+ }
872
+ stack.pop();
873
+ replacementStack.pop();
874
+ }
875
+ else {
876
+ canonicalizedObj = obj;
877
+ }
878
+ return canonicalizedObj;
879
+ }
880
+
881
+ class ArrayDiff extends Diff {
882
+ tokenize(value) {
883
+ return value.slice();
884
+ }
885
+ join(value) {
886
+ return value;
887
+ }
888
+ removeEmpty(value) {
889
+ return value;
890
+ }
891
+ }
892
+ const arrayDiff = new ArrayDiff();
893
+ function diffArrays(oldArr, newArr, options) {
894
+ return arrayDiff.diff(oldArr, newArr, options);
895
+ }
896
+
897
+ function unixToWin(patch) {
898
+ if (Array.isArray(patch)) {
899
+ // It would be cleaner if instead of the line below we could just write
900
+ // return patch.map(unixToWin)
901
+ // but mysteriously TypeScript (v5.7.3 at the time of writing) does not like this and it will
902
+ // refuse to compile, thinking that unixToWin could then return StructuredPatch[][] and the
903
+ // result would be incompatible with the overload signatures.
904
+ // See bug report at https://github.com/microsoft/TypeScript/issues/61398.
905
+ return patch.map(p => unixToWin(p));
906
+ }
907
+ return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => {
908
+ var _a;
909
+ return (line.startsWith('\\') || line.endsWith('\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\')))
910
+ ? line
911
+ : line + '\r';
912
+ }) }))) });
913
+ }
914
+ function winToUnix(patch) {
915
+ if (Array.isArray(patch)) {
916
+ // (See comment above equivalent line in unixToWin)
917
+ return patch.map(p => winToUnix(p));
918
+ }
919
+ return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map(line => line.endsWith('\r') ? line.substring(0, line.length - 1) : line) }))) });
920
+ }
921
+ /**
922
+ * Returns true if the patch consistently uses Unix line endings (or only involves one line and has
923
+ * no line endings).
924
+ */
925
+ function isUnix(patch) {
926
+ if (!Array.isArray(patch)) {
927
+ patch = [patch];
928
+ }
929
+ return !patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => !line.startsWith('\\') && line.endsWith('\r'))));
930
+ }
931
+ /**
932
+ * Returns true if the patch uses Windows line endings and only Windows line endings.
933
+ */
934
+ function isWin(patch) {
935
+ if (!Array.isArray(patch)) {
936
+ patch = [patch];
937
+ }
938
+ return patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => line.endsWith('\r'))))
939
+ && patch.every(index => index.hunks.every(hunk => hunk.lines.every((line, i) => { var _a; return line.startsWith('\\') || line.endsWith('\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\')); })));
940
+ }
941
+
942
+ /**
943
+ * Parses a patch into structured data, in the same structure returned by `structuredPatch`.
944
+ *
945
+ * @return a JSON object representation of the a patch, suitable for use with the `applyPatch` method.
946
+ */
947
+ function parsePatch(uniDiff) {
948
+ const diffstr = uniDiff.split(/\n/), list = [];
949
+ let i = 0;
950
+ function parseIndex() {
951
+ const index = {};
952
+ list.push(index);
953
+ // Parse diff metadata
954
+ while (i < diffstr.length) {
955
+ const line = diffstr[i];
956
+ // File header found, end parsing diff metadata
957
+ if ((/^(---|\+\+\+|@@)\s/).test(line)) {
958
+ break;
959
+ }
960
+ // Diff index
961
+ const header = (/^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/).exec(line);
962
+ if (header) {
963
+ index.index = header[1];
964
+ }
965
+ i++;
966
+ }
967
+ // Parse file headers if they are defined. Unified diff requires them, but
968
+ // there's no technical issues to have an isolated hunk without file header
969
+ parseFileHeader(index);
970
+ parseFileHeader(index);
971
+ // Parse hunks
972
+ index.hunks = [];
973
+ while (i < diffstr.length) {
974
+ const line = diffstr[i];
975
+ if ((/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/).test(line)) {
976
+ break;
977
+ }
978
+ else if ((/^@@/).test(line)) {
979
+ index.hunks.push(parseHunk());
980
+ }
981
+ else if (line) {
982
+ throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(line));
983
+ }
984
+ else {
985
+ i++;
986
+ }
987
+ }
988
+ }
989
+ // Parses the --- and +++ headers, if none are found, no lines
990
+ // are consumed.
991
+ function parseFileHeader(index) {
992
+ const fileHeader = (/^(---|\+\+\+)\s+(.*)\r?$/).exec(diffstr[i]);
993
+ if (fileHeader) {
994
+ const data = fileHeader[2].split('\t', 2), header = (data[1] || '').trim();
995
+ let fileName = data[0].replace(/\\\\/g, '\\');
996
+ if ((/^".*"$/).test(fileName)) {
997
+ fileName = fileName.substr(1, fileName.length - 2);
998
+ }
999
+ if (fileHeader[1] === '---') {
1000
+ index.oldFileName = fileName;
1001
+ index.oldHeader = header;
1002
+ }
1003
+ else {
1004
+ index.newFileName = fileName;
1005
+ index.newHeader = header;
1006
+ }
1007
+ i++;
1008
+ }
1009
+ }
1010
+ // Parses a hunk
1011
+ // This assumes that we are at the start of a hunk.
1012
+ function parseHunk() {
1013
+ var _a;
1014
+ const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
1015
+ const hunk = {
1016
+ oldStart: +chunkHeader[1],
1017
+ oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],
1018
+ newStart: +chunkHeader[3],
1019
+ newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],
1020
+ lines: []
1021
+ };
1022
+ // Unified Diff Format quirk: If the chunk size is 0,
1023
+ // the first number is one lower than one would expect.
1024
+ // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
1025
+ if (hunk.oldLines === 0) {
1026
+ hunk.oldStart += 1;
1027
+ }
1028
+ if (hunk.newLines === 0) {
1029
+ hunk.newStart += 1;
1030
+ }
1031
+ let addCount = 0, removeCount = 0;
1032
+ for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a = diffstr[i]) === null || _a === void 0 ? void 0 : _a.startsWith('\\'))); i++) {
1033
+ const operation = (diffstr[i].length == 0 && i != (diffstr.length - 1)) ? ' ' : diffstr[i][0];
1034
+ if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
1035
+ hunk.lines.push(diffstr[i]);
1036
+ if (operation === '+') {
1037
+ addCount++;
1038
+ }
1039
+ else if (operation === '-') {
1040
+ removeCount++;
1041
+ }
1042
+ else if (operation === ' ') {
1043
+ addCount++;
1044
+ removeCount++;
1045
+ }
1046
+ }
1047
+ else {
1048
+ throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`);
1049
+ }
1050
+ }
1051
+ // Handle the empty block count case
1052
+ if (!addCount && hunk.newLines === 1) {
1053
+ hunk.newLines = 0;
1054
+ }
1055
+ if (!removeCount && hunk.oldLines === 1) {
1056
+ hunk.oldLines = 0;
1057
+ }
1058
+ // Perform sanity checking
1059
+ if (addCount !== hunk.newLines) {
1060
+ throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
1061
+ }
1062
+ if (removeCount !== hunk.oldLines) {
1063
+ throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
1064
+ }
1065
+ return hunk;
1066
+ }
1067
+ while (i < diffstr.length) {
1068
+ parseIndex();
1069
+ }
1070
+ return list;
1071
+ }
1072
+
1073
+ // Iterator that traverses in the range of [min, max], stepping
1074
+ // by distance from a given start position. I.e. for [0, 4], with
1075
+ // start of 2, this will iterate 2, 3, 1, 4, 0.
1076
+ function distanceIterator (start, minLine, maxLine) {
1077
+ let wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1;
1078
+ return function iterator() {
1079
+ if (wantForward && !forwardExhausted) {
1080
+ if (backwardExhausted) {
1081
+ localOffset++;
1082
+ }
1083
+ else {
1084
+ wantForward = false;
1085
+ }
1086
+ // Check if trying to fit beyond text length, and if not, check it fits
1087
+ // after offset location (or desired location on first iteration)
1088
+ if (start + localOffset <= maxLine) {
1089
+ return start + localOffset;
1090
+ }
1091
+ forwardExhausted = true;
1092
+ }
1093
+ if (!backwardExhausted) {
1094
+ if (!forwardExhausted) {
1095
+ wantForward = true;
1096
+ }
1097
+ // Check if trying to fit before text beginning, and if not, check it fits
1098
+ // before offset location
1099
+ if (minLine <= start - localOffset) {
1100
+ return start - localOffset++;
1101
+ }
1102
+ backwardExhausted = true;
1103
+ return iterator();
1104
+ }
1105
+ // We tried to fit hunk before text beginning and beyond text length, then
1106
+ // hunk can't fit on the text. Return undefined
1107
+ return undefined;
1108
+ };
1109
+ }
1110
+
1111
+ /**
1112
+ * attempts to apply a unified diff patch.
1113
+ *
1114
+ * Hunks are applied first to last.
1115
+ * `applyPatch` first tries to apply the first hunk at the line number specified in the hunk header, and with all context lines matching exactly.
1116
+ * If that fails, it tries scanning backwards and forwards, one line at a time, to find a place to apply the hunk where the context lines match exactly.
1117
+ * If that still fails, and `fuzzFactor` is greater than zero, it increments the maximum number of mismatches (missing, extra, or changed context lines) that there can be between the hunk context and a region where we are trying to apply the patch such that the hunk will still be considered to match.
1118
+ * Regardless of `fuzzFactor`, lines to be deleted in the hunk *must* be present for a hunk to match, and the context lines *immediately* before and after an insertion must match exactly.
1119
+ *
1120
+ * Once a hunk is successfully fitted, the process begins again with the next hunk.
1121
+ * Regardless of `fuzzFactor`, later hunks must be applied later in the file than earlier hunks.
1122
+ *
1123
+ * If a hunk cannot be successfully fitted *anywhere* with fewer than `fuzzFactor` mismatches, `applyPatch` fails and returns `false`.
1124
+ *
1125
+ * If a hunk is successfully fitted but not at the line number specified by the hunk header, all subsequent hunks have their target line number adjusted accordingly.
1126
+ * (e.g. if the first hunk is applied 10 lines below where the hunk header said it should fit, `applyPatch` will *start* looking for somewhere to apply the second hunk 10 lines below where its hunk header says it goes.)
1127
+ *
1128
+ * If the patch was applied successfully, returns a string containing the patched text.
1129
+ * If the patch could not be applied (because some hunks in the patch couldn't be fitted to the text in `source`), `applyPatch` returns false.
1130
+ *
1131
+ * @param patch a string diff or the output from the `parsePatch` or `structuredPatch` methods.
1132
+ */
1133
+ function applyPatch(source, patch, options = {}) {
1134
+ let patches;
1135
+ if (typeof patch === 'string') {
1136
+ patches = parsePatch(patch);
1137
+ }
1138
+ else if (Array.isArray(patch)) {
1139
+ patches = patch;
1140
+ }
1141
+ else {
1142
+ patches = [patch];
1143
+ }
1144
+ if (patches.length > 1) {
1145
+ throw new Error('applyPatch only works with a single input.');
1146
+ }
1147
+ return applyStructuredPatch(source, patches[0], options);
1148
+ }
1149
+ function applyStructuredPatch(source, patch, options = {}) {
1150
+ if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) {
1151
+ if (hasOnlyWinLineEndings(source) && isUnix(patch)) {
1152
+ patch = unixToWin(patch);
1153
+ }
1154
+ else if (hasOnlyUnixLineEndings(source) && isWin(patch)) {
1155
+ patch = winToUnix(patch);
1156
+ }
1157
+ }
1158
+ // Apply the diff to the input
1159
+ const lines = source.split('\n'), hunks = patch.hunks, compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent), fuzzFactor = options.fuzzFactor || 0;
1160
+ let minLine = 0;
1161
+ if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) {
1162
+ throw new Error('fuzzFactor must be a non-negative integer');
1163
+ }
1164
+ // Special case for empty patch.
1165
+ if (!hunks.length) {
1166
+ return source;
1167
+ }
1168
+ // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change
1169
+ // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a
1170
+ // newline that already exists - then we either return false and fail to apply the patch (if
1171
+ // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0).
1172
+ // If we do need to remove/add a newline at EOF, this will always be in the final hunk:
1173
+ let prevLine = '', removeEOFNL = false, addEOFNL = false;
1174
+ for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) {
1175
+ const line = hunks[hunks.length - 1].lines[i];
1176
+ if (line[0] == '\\') {
1177
+ if (prevLine[0] == '+') {
1178
+ removeEOFNL = true;
1179
+ }
1180
+ else if (prevLine[0] == '-') {
1181
+ addEOFNL = true;
1182
+ }
1183
+ }
1184
+ prevLine = line;
1185
+ }
1186
+ if (removeEOFNL) {
1187
+ if (addEOFNL) {
1188
+ // This means the final line gets changed but doesn't have a trailing newline in either the
1189
+ // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if
1190
+ // fuzzFactor is 0, we simply validate that the source file has no trailing newline.
1191
+ if (!fuzzFactor && lines[lines.length - 1] == '') {
1192
+ return false;
1193
+ }
1194
+ }
1195
+ else if (lines[lines.length - 1] == '') {
1196
+ lines.pop();
1197
+ }
1198
+ else if (!fuzzFactor) {
1199
+ return false;
1200
+ }
1201
+ }
1202
+ else if (addEOFNL) {
1203
+ if (lines[lines.length - 1] != '') {
1204
+ lines.push('');
1205
+ }
1206
+ else if (!fuzzFactor) {
1207
+ return false;
1208
+ }
1209
+ }
1210
+ /**
1211
+ * Checks if the hunk can be made to fit at the provided location with at most `maxErrors`
1212
+ * insertions, substitutions, or deletions, while ensuring also that:
1213
+ * - lines deleted in the hunk match exactly, and
1214
+ * - wherever an insertion operation or block of insertion operations appears in the hunk, the
1215
+ * immediately preceding and following lines of context match exactly
1216
+ *
1217
+ * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0].
1218
+ *
1219
+ * If the hunk can be applied, returns an object with properties `oldLineLastI` and
1220
+ * `replacementLines`. Otherwise, returns null.
1221
+ */
1222
+ function applyHunk(hunkLines, toPos, maxErrors, hunkLinesI = 0, lastContextLineMatched = true, patchedLines = [], patchedLinesLength = 0) {
1223
+ let nConsecutiveOldContextLines = 0;
1224
+ let nextContextLineMustMatch = false;
1225
+ for (; hunkLinesI < hunkLines.length; hunkLinesI++) {
1226
+ const hunkLine = hunkLines[hunkLinesI], operation = (hunkLine.length > 0 ? hunkLine[0] : ' '), content = (hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine);
1227
+ if (operation === '-') {
1228
+ if (compareLine(toPos + 1, lines[toPos], operation, content)) {
1229
+ toPos++;
1230
+ nConsecutiveOldContextLines = 0;
1231
+ }
1232
+ else {
1233
+ if (!maxErrors || lines[toPos] == null) {
1234
+ return null;
1235
+ }
1236
+ patchedLines[patchedLinesLength] = lines[toPos];
1237
+ return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1);
1238
+ }
1239
+ }
1240
+ if (operation === '+') {
1241
+ if (!lastContextLineMatched) {
1242
+ return null;
1243
+ }
1244
+ patchedLines[patchedLinesLength] = content;
1245
+ patchedLinesLength++;
1246
+ nConsecutiveOldContextLines = 0;
1247
+ nextContextLineMustMatch = true;
1248
+ }
1249
+ if (operation === ' ') {
1250
+ nConsecutiveOldContextLines++;
1251
+ patchedLines[patchedLinesLength] = lines[toPos];
1252
+ if (compareLine(toPos + 1, lines[toPos], operation, content)) {
1253
+ patchedLinesLength++;
1254
+ lastContextLineMatched = true;
1255
+ nextContextLineMustMatch = false;
1256
+ toPos++;
1257
+ }
1258
+ else {
1259
+ if (nextContextLineMustMatch || !maxErrors) {
1260
+ return null;
1261
+ }
1262
+ // Consider 3 possibilities in sequence:
1263
+ // 1. lines contains a *substitution* not included in the patch context, or
1264
+ // 2. lines contains an *insertion* not included in the patch context, or
1265
+ // 3. lines contains a *deletion* not included in the patch context
1266
+ // The first two options are of course only possible if the line from lines is non-null -
1267
+ // i.e. only option 3 is possible if we've overrun the end of the old file.
1268
+ return (lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength));
1269
+ }
1270
+ }
1271
+ }
1272
+ // Before returning, trim any unmodified context lines off the end of patchedLines and reduce
1273
+ // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region
1274
+ // that starts in this hunk's trailing context.
1275
+ patchedLinesLength -= nConsecutiveOldContextLines;
1276
+ toPos -= nConsecutiveOldContextLines;
1277
+ patchedLines.length = patchedLinesLength;
1278
+ return {
1279
+ patchedLines,
1280
+ oldLineLastI: toPos - 1
1281
+ };
1282
+ }
1283
+ const resultLines = [];
1284
+ // Search best fit offsets for each hunk based on the previous ones
1285
+ let prevHunkOffset = 0;
1286
+ for (let i = 0; i < hunks.length; i++) {
1287
+ const hunk = hunks[i];
1288
+ let hunkResult;
1289
+ const maxLine = lines.length - hunk.oldLines + fuzzFactor;
1290
+ let toPos;
1291
+ for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) {
1292
+ toPos = hunk.oldStart + prevHunkOffset - 1;
1293
+ const iterator = distanceIterator(toPos, minLine, maxLine);
1294
+ for (; toPos !== undefined; toPos = iterator()) {
1295
+ hunkResult = applyHunk(hunk.lines, toPos, maxErrors);
1296
+ if (hunkResult) {
1297
+ break;
1298
+ }
1299
+ }
1300
+ if (hunkResult) {
1301
+ break;
1302
+ }
1303
+ }
1304
+ if (!hunkResult) {
1305
+ return false;
1306
+ }
1307
+ // Copy everything from the end of where we applied the last hunk to the start of this hunk
1308
+ for (let i = minLine; i < toPos; i++) {
1309
+ resultLines.push(lines[i]);
1310
+ }
1311
+ // Add the lines produced by applying the hunk:
1312
+ for (let i = 0; i < hunkResult.patchedLines.length; i++) {
1313
+ const line = hunkResult.patchedLines[i];
1314
+ resultLines.push(line);
1315
+ }
1316
+ // Set lower text limit to end of the current hunk, so next ones don't try
1317
+ // to fit over already patched text
1318
+ minLine = hunkResult.oldLineLastI + 1;
1319
+ // Note the offset between where the patch said the hunk should've applied and where we
1320
+ // applied it, so we can adjust future hunks accordingly:
1321
+ prevHunkOffset = toPos + 1 - hunk.oldStart;
1322
+ }
1323
+ // Copy over the rest of the lines from the old text
1324
+ for (let i = minLine; i < lines.length; i++) {
1325
+ resultLines.push(lines[i]);
1326
+ }
1327
+ return resultLines.join('\n');
1328
+ }
1329
+ /**
1330
+ * applies one or more patches.
1331
+ *
1332
+ * `patch` may be either an array of structured patch objects, or a string representing a patch in unified diff format (which may patch one or more files).
1333
+ *
1334
+ * This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is:
1335
+ *
1336
+ * - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution.
1337
+ * - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution.
1338
+ *
1339
+ * Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made.
1340
+ */
1341
+ function applyPatches(uniDiff, options) {
1342
+ const spDiff = typeof uniDiff === 'string' ? parsePatch(uniDiff) : uniDiff;
1343
+ let currentIndex = 0;
1344
+ function processIndex() {
1345
+ const index = spDiff[currentIndex++];
1346
+ if (!index) {
1347
+ return options.complete();
1348
+ }
1349
+ options.loadFile(index, function (err, data) {
1350
+ if (err) {
1351
+ return options.complete(err);
1352
+ }
1353
+ const updatedContent = applyPatch(data, index, options);
1354
+ options.patched(index, updatedContent, function (err) {
1355
+ if (err) {
1356
+ return options.complete(err);
1357
+ }
1358
+ processIndex();
1359
+ });
1360
+ });
1361
+ }
1362
+ processIndex();
1363
+ }
1364
+
1365
+ function reversePatch(structuredPatch) {
1366
+ if (Array.isArray(structuredPatch)) {
1367
+ // (See comment in unixToWin for why we need the pointless-looking anonymous function here)
1368
+ return structuredPatch.map(patch => reversePatch(patch)).reverse();
1369
+ }
1370
+ return Object.assign(Object.assign({}, structuredPatch), { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(hunk => {
1371
+ return {
1372
+ oldLines: hunk.newLines,
1373
+ oldStart: hunk.newStart,
1374
+ newLines: hunk.oldLines,
1375
+ newStart: hunk.oldStart,
1376
+ lines: hunk.lines.map(l => {
1377
+ if (l.startsWith('-')) {
1378
+ return `+${l.slice(1)}`;
1379
+ }
1380
+ if (l.startsWith('+')) {
1381
+ return `-${l.slice(1)}`;
1382
+ }
1383
+ return l;
1384
+ })
1385
+ };
1386
+ }) });
1387
+ }
1388
+
1389
+ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1390
+ let optionsObj;
1391
+ if (!options) {
1392
+ optionsObj = {};
1393
+ }
1394
+ else if (typeof options === 'function') {
1395
+ optionsObj = { callback: options };
1396
+ }
1397
+ else {
1398
+ optionsObj = options;
1399
+ }
1400
+ if (typeof optionsObj.context === 'undefined') {
1401
+ optionsObj.context = 4;
1402
+ }
1403
+ // We copy this into its own variable to placate TypeScript, which thinks
1404
+ // optionsObj.context might be undefined in the callbacks below.
1405
+ const context = optionsObj.context;
1406
+ // @ts-expect-error (runtime check for something that is correctly a static type error)
1407
+ if (optionsObj.newlineIsToken) {
1408
+ throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions');
1409
+ }
1410
+ if (!optionsObj.callback) {
1411
+ return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));
1412
+ }
1413
+ else {
1414
+ const { callback } = optionsObj;
1415
+ diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {
1416
+ const patch = diffLinesResultToPatch(diff);
1417
+ // TypeScript is unhappy without the cast because it does not understand that `patch` may
1418
+ // be undefined here only if `callback` is StructuredPatchCallbackAbortable:
1419
+ callback(patch);
1420
+ } }));
1421
+ }
1422
+ function diffLinesResultToPatch(diff) {
1423
+ // STEP 1: Build up the patch with no "" lines and with the arrays
1424
+ // of lines containing trailing newline characters. We'll tidy up later...
1425
+ if (!diff) {
1426
+ return;
1427
+ }
1428
+ diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier
1429
+ function contextLines(lines) {
1430
+ return lines.map(function (entry) { return ' ' + entry; });
1431
+ }
1432
+ const hunks = [];
1433
+ let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
1434
+ for (let i = 0; i < diff.length; i++) {
1435
+ const current = diff[i], lines = current.lines || splitLines(current.value);
1436
+ current.lines = lines;
1437
+ if (current.added || current.removed) {
1438
+ // If we have previous context, start with that
1439
+ if (!oldRangeStart) {
1440
+ const prev = diff[i - 1];
1441
+ oldRangeStart = oldLine;
1442
+ newRangeStart = newLine;
1443
+ if (prev) {
1444
+ curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];
1445
+ oldRangeStart -= curRange.length;
1446
+ newRangeStart -= curRange.length;
1447
+ }
1448
+ }
1449
+ // Output our changes
1450
+ for (const line of lines) {
1451
+ curRange.push((current.added ? '+' : '-') + line);
1452
+ }
1453
+ // Track the updated file position
1454
+ if (current.added) {
1455
+ newLine += lines.length;
1456
+ }
1457
+ else {
1458
+ oldLine += lines.length;
1459
+ }
1460
+ }
1461
+ else {
1462
+ // Identical context lines. Track line changes
1463
+ if (oldRangeStart) {
1464
+ // Close out any changes that have been output (or join overlapping)
1465
+ if (lines.length <= context * 2 && i < diff.length - 2) {
1466
+ // Overlapping
1467
+ for (const line of contextLines(lines)) {
1468
+ curRange.push(line);
1469
+ }
1470
+ }
1471
+ else {
1472
+ // end the range and output
1473
+ const contextSize = Math.min(lines.length, context);
1474
+ for (const line of contextLines(lines.slice(0, contextSize))) {
1475
+ curRange.push(line);
1476
+ }
1477
+ const hunk = {
1478
+ oldStart: oldRangeStart,
1479
+ oldLines: (oldLine - oldRangeStart + contextSize),
1480
+ newStart: newRangeStart,
1481
+ newLines: (newLine - newRangeStart + contextSize),
1482
+ lines: curRange
1483
+ };
1484
+ hunks.push(hunk);
1485
+ oldRangeStart = 0;
1486
+ newRangeStart = 0;
1487
+ curRange = [];
1488
+ }
1489
+ }
1490
+ oldLine += lines.length;
1491
+ newLine += lines.length;
1492
+ }
1493
+ }
1494
+ // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add
1495
+ // "".
1496
+ for (const hunk of hunks) {
1497
+ for (let i = 0; i < hunk.lines.length; i++) {
1498
+ if (hunk.lines[i].endsWith('\n')) {
1499
+ hunk.lines[i] = hunk.lines[i].slice(0, -1);
1500
+ }
1501
+ else {
1502
+ hunk.lines.splice(i + 1, 0, '\');
1503
+ i++; // Skip the line we just added, then continue iterating
1504
+ }
1505
+ }
1506
+ }
1507
+ return {
1508
+ oldFileName: oldFileName, newFileName: newFileName,
1509
+ oldHeader: oldHeader, newHeader: newHeader,
1510
+ hunks: hunks
1511
+ };
1512
+ }
1513
+ }
1514
+ /**
1515
+ * creates a unified diff patch.
1516
+ * @param patch either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`)
1517
+ */
1518
+ function formatPatch(patch) {
1519
+ if (Array.isArray(patch)) {
1520
+ return patch.map(formatPatch).join('\n');
1521
+ }
1522
+ const ret = [];
1523
+ if (patch.oldFileName == patch.newFileName) {
1524
+ ret.push('Index: ' + patch.oldFileName);
1525
+ }
1526
+ ret.push('===================================================================');
1527
+ ret.push('--- ' + patch.oldFileName + (typeof patch.oldHeader === 'undefined' ? '' : '\t' + patch.oldHeader));
1528
+ ret.push('+++ ' + patch.newFileName + (typeof patch.newHeader === 'undefined' ? '' : '\t' + patch.newHeader));
1529
+ for (let i = 0; i < patch.hunks.length; i++) {
1530
+ const hunk = patch.hunks[i];
1531
+ // Unified Diff Format quirk: If the chunk size is 0,
1532
+ // the first number is one lower than one would expect.
1533
+ // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
1534
+ if (hunk.oldLines === 0) {
1535
+ hunk.oldStart -= 1;
1536
+ }
1537
+ if (hunk.newLines === 0) {
1538
+ hunk.newStart -= 1;
1539
+ }
1540
+ ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines
1541
+ + ' +' + hunk.newStart + ',' + hunk.newLines
1542
+ + ' @@');
1543
+ for (const line of hunk.lines) {
1544
+ ret.push(line);
1545
+ }
1546
+ }
1547
+ return ret.join('\n') + '\n';
1548
+ }
1549
+ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1550
+ if (typeof options === 'function') {
1551
+ options = { callback: options };
1552
+ }
1553
+ if (!(options === null || options === void 0 ? void 0 : options.callback)) {
1554
+ const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
1555
+ if (!patchObj) {
1556
+ return;
1557
+ }
1558
+ return formatPatch(patchObj);
1559
+ }
1560
+ else {
1561
+ const { callback } = options;
1562
+ structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: patchObj => {
1563
+ if (!patchObj) {
1564
+ callback(undefined);
1565
+ }
1566
+ else {
1567
+ callback(formatPatch(patchObj));
1568
+ }
1569
+ } }));
1570
+ }
1571
+ }
1572
+ function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
1573
+ return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
1574
+ }
1575
+ /**
1576
+ * Split `text` into an array of lines, including the trailing newline character (where present)
1577
+ */
1578
+ function splitLines(text) {
1579
+ const hasTrailingNl = text.endsWith('\n');
1580
+ const result = text.split('\n').map(line => line + '\n');
1581
+ if (hasTrailingNl) {
1582
+ result.pop();
1583
+ }
1584
+ else {
1585
+ result.push(result.pop().slice(0, -1));
1586
+ }
1587
+ return result;
1588
+ }
1589
+
1590
+ /**
1591
+ * converts a list of change objects to the format returned by Google's [diff-match-patch](https://github.com/google/diff-match-patch) library
1592
+ */
1593
+ function convertChangesToDMP(changes) {
1594
+ const ret = [];
1595
+ let change, operation;
1596
+ for (let i = 0; i < changes.length; i++) {
1597
+ change = changes[i];
1598
+ if (change.added) {
1599
+ operation = 1;
1600
+ }
1601
+ else if (change.removed) {
1602
+ operation = -1;
1603
+ }
1604
+ else {
1605
+ operation = 0;
1606
+ }
1607
+ ret.push([operation, change.value]);
1608
+ }
1609
+ return ret;
1610
+ }
1611
+
1612
+ /**
1613
+ * converts a list of change objects to a serialized XML format
1614
+ */
1615
+ function convertChangesToXML(changes) {
1616
+ const ret = [];
1617
+ for (let i = 0; i < changes.length; i++) {
1618
+ const change = changes[i];
1619
+ if (change.added) {
1620
+ ret.push('<ins>');
1621
+ }
1622
+ else if (change.removed) {
1623
+ ret.push('<del>');
1624
+ }
1625
+ ret.push(escapeHTML(change.value));
1626
+ if (change.added) {
1627
+ ret.push('</ins>');
1628
+ }
1629
+ else if (change.removed) {
1630
+ ret.push('</del>');
1631
+ }
1632
+ }
1633
+ return ret.join('');
1634
+ }
1635
+ function escapeHTML(s) {
1636
+ let n = s;
1637
+ n = n.replace(/&/g, '&amp;');
1638
+ n = n.replace(/</g, '&lt;');
1639
+ n = n.replace(/>/g, '&gt;');
1640
+ n = n.replace(/"/g, '&quot;');
1641
+ return n;
1642
+ }
1643
+
1644
+ exports.Diff = Diff;
1645
+ exports.applyPatch = applyPatch;
1646
+ exports.applyPatches = applyPatches;
1647
+ exports.arrayDiff = arrayDiff;
1648
+ exports.canonicalize = canonicalize;
1649
+ exports.characterDiff = characterDiff;
1650
+ exports.convertChangesToDMP = convertChangesToDMP;
1651
+ exports.convertChangesToXML = convertChangesToXML;
1652
+ exports.createPatch = createPatch;
1653
+ exports.createTwoFilesPatch = createTwoFilesPatch;
1654
+ exports.cssDiff = cssDiff;
1655
+ exports.diffArrays = diffArrays;
1656
+ exports.diffChars = diffChars;
1657
+ exports.diffCss = diffCss;
1658
+ exports.diffJson = diffJson;
1659
+ exports.diffLines = diffLines;
1660
+ exports.diffSentences = diffSentences;
1661
+ exports.diffTrimmedLines = diffTrimmedLines;
1662
+ exports.diffWords = diffWords;
1663
+ exports.diffWordsWithSpace = diffWordsWithSpace;
1664
+ exports.formatPatch = formatPatch;
1665
+ exports.jsonDiff = jsonDiff;
1666
+ exports.lineDiff = lineDiff;
1667
+ exports.parsePatch = parsePatch;
1668
+ exports.reversePatch = reversePatch;
1669
+ exports.sentenceDiff = sentenceDiff;
1670
+ exports.structuredPatch = structuredPatch;
1671
+ exports.wordDiff = wordDiff;
1672
+ exports.wordsWithSpaceDiff = wordsWithSpaceDiff;
1673
+
1674
+ }));