@opensearch-project/opensearch 2.2.1 → 2.3.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/CHANGELOG.md CHANGED
@@ -3,10 +3,25 @@
3
3
  Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
4
4
 
5
5
  ## [Unreleased]
6
+ ### Added
7
+ ### Dependencies
8
+ ### Changed
9
+ ### Deprecated
10
+ ### Removed
11
+ ### Fixed
12
+ ### Security
13
+
14
+ ## [2.3.0]
6
15
 
7
16
  ### Added
17
+
18
+ - Add serialization and deserialization of numerals larger than `Number.MAX_SAFE_INTEGER` ([#544](https://github.com/opensearch-project/opensearch-js/pull/544))
19
+
8
20
  ### Dependencies
9
21
  ### Changed
22
+
23
+ - Add upgrading NPM to all workflows running older Node.js versions ([#545](https://github.com/opensearch-project/opensearch-js/issues/545))
24
+
10
25
  ### Deprecated
11
26
  ### Removed
12
27
  ### Fixed
package/lib/Serializer.js CHANGED
@@ -35,6 +35,60 @@ const sjson = require('secure-json-parse');
35
35
  const { SerializationError, DeserializationError } = require('./errors');
36
36
  const kJsonOptions = Symbol('secure json parse options');
37
37
 
38
+ /* In JavaScript, a `Number` is a 64-bit floating-point value which can store 16 digits. However, the
39
+ * serializer and deserializer will need to cater to numeric values generated by other languages which
40
+ * can have up to 19 digits. Native JSON parser and stringifier, incapable of handling the extra
41
+ * digits, corrupt the values, making them unusable.
42
+ *
43
+ * To work around this limitation, the deserializer converts long sequences of digits into strings and
44
+ * marks them before applying the parser. During the parsing, string values that begin with the mark
45
+ * are converted to `BigInt` values.
46
+ * Similarly, during stringification, the serializer converts `BigInt` values to marked strings and
47
+ * when done, it replaces them with plain numerals.
48
+ *
49
+ * `Number.MAX_SAFE_INTEGER`, 9,007,199,254,740,991, is the largest number that the native methods can
50
+ * parse and stringify, and any numeral greater than that would need to be translated using the
51
+ * workaround; all 17-digits or longer and only tail-end of the 16-digits need translation. It would
52
+ * be unfair to all the 16-digit numbers if the translation applied to `\d{16,}` only to cover the
53
+ * less than 10%. Hence, a RegExp is created to only match numerals too long to be a number.
54
+ *
55
+ * To make the explanation simpler, let's assume that MAX_SAFE_INTEGER is 8921 which has 4 digits.
56
+ * Starting from the right, we take each digit onwards, `[<start>-9]`:
57
+ * 1) 7922 - 7929: 792[2-9]\d{0}
58
+ * 2) 7930 - 7999: 79[3-9]\d{1}
59
+ * 9) 9 + 1 = 10 which results in a rollover; no need to do anything.
60
+ * 8) 9000 - 9999: [9-9]\d{3}
61
+ * Finally we add anything 5 digits or longer: `\d{5,}
62
+ *
63
+ * PS, a better solution would use AST but considering its performance penalty, RegExp is the next
64
+ * the best solution.
65
+ */
66
+ const isBigIntSupported = typeof BigInt !== 'undefined';
67
+ const maxIntAsString = String(Number.MAX_SAFE_INTEGER);
68
+ const maxIntLength = maxIntAsString.length;
69
+ // Sub-patterns for each digit
70
+ const bigIntMatcherTokens = [`\\d{${maxIntAsString.length + 1},}`];
71
+ for (let i = 0; i < maxIntLength; i++) {
72
+ if (maxIntAsString[i] !== '9') {
73
+ bigIntMatcherTokens.push(
74
+ maxIntAsString.substring(0, i) +
75
+ `[${parseInt(maxIntAsString[i], 10) + 1}-9]` +
76
+ `\\d{${maxIntLength - i - 1}}`
77
+ );
78
+ }
79
+ }
80
+
81
+ /* The matcher that looks for `": <numerals>, ...}` and `[..., <numeral>, ...]`
82
+ *
83
+ * The pattern starts by looking for `":` not immediately preceded by a `\`. That should be
84
+ * followed by any of the numeric sub-patterns. A comma, end of an array, end of an object, or
85
+ * the end of the input are the only acceptable elements after it.
86
+ */
87
+ const bigIntMatcher = new RegExp(
88
+ `((?:\\[|,|(?<!\\\\)"\\s*:)\\s*)(-?(?:${bigIntMatcherTokens.join('|')}))(\\s*)(?=,|}|]|$)`,
89
+ 'g'
90
+ );
91
+
38
92
  class Serializer {
39
93
  constructor(opts = {}) {
40
94
  const disable = opts.disablePrototypePoisoningProtection;
@@ -44,11 +98,173 @@ class Serializer {
44
98
  };
45
99
  }
46
100
 
101
+ /* The characters with a highly unlikely chance of occurrence in strings, alone or in combination.
102
+ *
103
+ * ToDo: When support for ancient versions of Node.js are dropped, replace with
104
+ * _bigIntMarkChars = ['෴', '߷', '֍'];
105
+ */
106
+ get _bigIntMarkChars() {
107
+ return ['෴', '߷', '֍'];
108
+ }
109
+
110
+ /* Generates an array of all combinations of `_bigIntMarkChars` with the requested length. */
111
+ _bigIntMarkerCombinations(length = 3) {
112
+ const results = [];
113
+ const arr = this._bigIntMarkChars;
114
+ const arrLength = arr.length;
115
+ const temp = Array(length);
116
+
117
+ (function fill(pos, start) {
118
+ if (pos === length) return results.push(temp.join(''));
119
+
120
+ for (let i = start; i < arrLength; i++) {
121
+ temp[pos] = arr[i];
122
+ fill(pos + 1, i);
123
+ }
124
+ })(0, 0);
125
+
126
+ return results;
127
+ }
128
+
129
+ /* Experiments with different combinations of various lengths, until one is found to not be in
130
+ * the input string.
131
+ */
132
+ _getSuitableBigIntMarker(json) {
133
+ let bigIntMarker;
134
+ let length = 0;
135
+ do {
136
+ length++;
137
+ this._bigIntMarkerCombinations(length).some((marker) => {
138
+ if (json.indexOf(marker) === -1) {
139
+ bigIntMarker = marker;
140
+ return true;
141
+ }
142
+ });
143
+ } while (!bigIntMarker);
144
+
145
+ return {
146
+ bigIntMarker,
147
+ length,
148
+ };
149
+ }
150
+
151
+ _parseWithBigInt(json) {
152
+ const { bigIntMarker, length } = this._getSuitableBigIntMarker(json);
153
+
154
+ let hadException;
155
+ let markedJSON = json.replace(bigIntMatcher, `$1"${bigIntMarker}$2"$3`);
156
+
157
+ /* RegExp cannot replace AST and the process of marking adds quotes. So, any false-positive hit
158
+ * will make the JSON string unparseable.
159
+ *
160
+ * To find those instances, we try to parse and watch for the location of any errors. If an error
161
+ * is caused by the marking, we remove that single marking and try again.
162
+ */
163
+ do {
164
+ try {
165
+ hadException = false;
166
+ JSON.parse(markedJSON);
167
+ } catch (e) {
168
+ hadException = true;
169
+ /* There are two types of exception objects that can be raised:
170
+ * 1) a proper object with lineNumber and columnNumber which we can use
171
+ * 2) a textual message with the position that we need to parse
172
+ */
173
+ let { lineNumber, columnNumber } = e;
174
+ if (!lineNumber || !columnNumber) {
175
+ const match =
176
+ // ToDo: When support for ancient versions of Node.js are dropped, replace with
177
+ // e?.message?.match?.()
178
+ e &&
179
+ e.message &&
180
+ typeof e.message.match === 'function' &&
181
+ e.message.match(/^Unexpected token.*at position (\d+)$/);
182
+ if (match) {
183
+ lineNumber = 1;
184
+ // The position is zero-indexed; adding 1 to normalize it for the -2 that comes later
185
+ columnNumber = parseInt(match[1], 10) + 1;
186
+ }
187
+ }
188
+
189
+ if (lineNumber < 1 || columnNumber < 2) {
190
+ // The problem is not with this replacement; just return a failure.
191
+ return;
192
+ }
193
+
194
+ /* We need to skip e.lineNumber - 1 number of `\n` occurrences.
195
+ * Then, we need to go to e.columnNumber - 2 to look for `"<mark>\d+"`; we need to `-1` to
196
+ * account for the quote but an additional `-1` is needed because columnNumber starts from 1.
197
+ */
198
+ const re = new RegExp(
199
+ `^((?:.*\\n){${lineNumber - 1}}[^\\n]{${columnNumber - 2}})"${bigIntMarker}(-?\\d+)"`
200
+ );
201
+ if (!re.test(markedJSON)) {
202
+ // The exception is not caused by adding the marker
203
+ return;
204
+ }
205
+
206
+ // We have found a bad replacement; let's remove it.
207
+ markedJSON = markedJSON.replace(re, '$1$2');
208
+ }
209
+ } while (hadException);
210
+
211
+ const bigIntMarkFinder = new RegExp(`^${bigIntMarker}-?\\d+$`);
212
+
213
+ // Exceptions will trickle up to the caller
214
+ return sjson.parse(
215
+ markedJSON,
216
+ (key, val) =>
217
+ /* Convert marked values to BigInt values.
218
+ * The `startsWith` is purely for performance, to avoid running `test` if not needed.
219
+ */
220
+ typeof val === 'string' && val.startsWith(bigIntMarker) && bigIntMarkFinder.test(val)
221
+ ? BigInt(val.substring(length)) // eslint-disable-line no-undef
222
+ : val,
223
+ this[kJsonOptions]
224
+ );
225
+ }
226
+
227
+ _stringifyWithBigInt(object, candidate) {
228
+ const { bigIntMarker } = this._getSuitableBigIntMarker(candidate);
229
+
230
+ /* The matcher that looks for "<marker><numerals>"
231
+ * Because we have made sure that `bigIntMarker` was never present in the original object, we can
232
+ * carelessly assume every "<marker><numerals>" is due to our marking.
233
+ */
234
+ const markedBigIntMatcher = new RegExp(`"${bigIntMarker}(-?\\d+)"`, 'g');
235
+
236
+ return (
237
+ JSON.stringify(
238
+ object,
239
+ /* Convert BigInt values to a string and mark them.
240
+ * Can't be bothered with Number values beyond safe values because they are already corrupted.
241
+ */
242
+ (key, val) => (typeof val === 'bigint' ? `${bigIntMarker}${val.toString()}` : val)
243
+ )
244
+ // Replace marked substrings with just the numerals
245
+ .replace(markedBigIntMatcher, '$1')
246
+ );
247
+ }
248
+
47
249
  serialize(object) {
48
250
  debug('Serializing', object);
49
251
  let json;
252
+ let numeralsAreNumbers = true;
253
+ const checkForBigInts = (key, val) => {
254
+ if (typeof val === 'bigint') {
255
+ numeralsAreNumbers = false;
256
+ // Number() is much faster than parseInt() on BigInt values
257
+ return Number(val);
258
+ }
259
+ return val;
260
+ };
50
261
  try {
51
- json = JSON.stringify(object);
262
+ json = JSON.stringify(object, isBigIntSupported ? checkForBigInts : null);
263
+
264
+ if (isBigIntSupported && !numeralsAreNumbers) {
265
+ const temp = this._stringifyWithBigInt(object, json);
266
+ if (temp) json = temp;
267
+ }
52
268
  } catch (err) {
53
269
  throw new SerializationError(err.message, object);
54
270
  }
@@ -58,8 +274,31 @@ class Serializer {
58
274
  deserialize(json) {
59
275
  debug('Deserializing', json);
60
276
  let object;
277
+ let numeralsAreNumbers = true;
278
+ const checkForLargeNumerals = (key, val) => {
279
+ if (
280
+ numeralsAreNumbers &&
281
+ typeof val === 'number' &&
282
+ (val < Number.MAX_SAFE_INTEGER || val > Number.MAX_SAFE_INTEGER)
283
+ ) {
284
+ numeralsAreNumbers = false;
285
+ }
286
+
287
+ return val;
288
+ };
61
289
  try {
62
- object = sjson.parse(json, this[kJsonOptions]);
290
+ object = sjson.parse(
291
+ json,
292
+ isBigIntSupported ? checkForLargeNumerals : null,
293
+ this[kJsonOptions]
294
+ );
295
+
296
+ if (isBigIntSupported && !numeralsAreNumbers) {
297
+ const temp = this._parseWithBigInt(json);
298
+ if (temp) {
299
+ object = temp;
300
+ }
301
+ }
63
302
  } catch (err) {
64
303
  throw new DeserializationError(err.message, json);
65
304
  }
package/package.json CHANGED
@@ -23,7 +23,7 @@
23
23
  }
24
24
  },
25
25
  "homepage": "https://www.opensearch.org/",
26
- "version": "2.2.1",
26
+ "version": "2.3.0",
27
27
  "versionCanary": "7.10.0-canary.6",
28
28
  "keywords": [
29
29
  "opensearch",