nanoflags 0.1.0 → 0.2.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.
@@ -1,531 +1,531 @@
1
- # frozen_string_literal: true
2
-
3
- module NanoFlags
4
- module Engine
5
- # JavaScript `undefined`: an absent value (a missing property, a flag that serves nothing). Distinct from +nil+
6
- # (JSON null).
7
- UNDEFINED = Object.new
8
- def UNDEFINED.inspect = "UNDEFINED"
9
- def UNDEFINED.to_s = "undefined"
10
- UNDEFINED.freeze
11
-
12
- # A function value. Only ever produced by reading a String / Array prototype method by name (e.g. `"ab".match`),
13
- # which a malformed configuration can make the engine do.
14
- JsFunction = Struct.new(:name)
15
-
16
- # The TypeError the TypeScript engine would throw for a malformed configuration (the message matches V8's).
17
- class JsTypeError < StandardError; end
18
-
19
- # The JavaScript value semantics the engine depends on.
20
- #
21
- # The reference engine is TypeScript: its results depend on truthiness, loose property access, `Number()`,
22
- # `String()`, `JSON.stringify` and UTF-16 string semantics. This module reproduces exactly those for the value
23
- # model of this gem, so the Ruby engine returns the same results as every other NanoFlags engine for the same JSON
24
- # (asserted by the shared parity fixtures):
25
- #
26
- # - `undefined` is {UNDEFINED}, `null` is +nil+, booleans are +true+/+false+, numbers are Float (always),
27
- # - strings are UTF-8; a lone UTF-16 surrogate (only expressible as a `\u` escape in JSON) is kept in its
28
- # three-byte WTF-8 form (such a string is not +valid_encoding?+),
29
- # - arrays are Array, objects are Hash with String keys in JavaScript order (array-index keys ascending first).
30
- #
31
- # @api private
32
- module Js
33
- module_function
34
-
35
- STRING_METHODS = %w[
36
- anchor at big blink bold charAt charCodeAt codePointAt concat constructor endsWith fixed fontcolor fontsize
37
- includes indexOf isWellFormed italics lastIndexOf link localeCompare match matchAll normalize padEnd padStart
38
- repeat replace replaceAll search slice small split strike sub substr substring sup toLocaleLowerCase
39
- toLocaleUpperCase toLowerCase toString toUpperCase toWellFormed trim trimEnd trimLeft trimRight trimStart valueOf
40
- ].to_h { |m| [m, true] }.freeze
41
-
42
- ARRAY_METHODS = %w[
43
- at concat constructor copyWithin entries every fill filter find findIndex findLast findLastIndex flat flatMap
44
- forEach includes indexOf join keys lastIndexOf map pop push reduce reduceRight reverse shift slice some sort
45
- splice toLocaleString toReversed toSorted toSpliced toString unshift values with
46
- ].to_h { |m| [m, true] }.freeze
47
-
48
- # Object.prototype members, as `${words[name]}` renders them in describeCondition.
49
- OBJECT_PROTO_STRINGS = {
50
- "constructor" => "function Object() { [native code] }",
51
- "__defineGetter__" => "function __defineGetter__() { [native code] }",
52
- "__defineSetter__" => "function __defineSetter__() { [native code] }",
53
- "hasOwnProperty" => "function hasOwnProperty() { [native code] }",
54
- "__lookupGetter__" => "function __lookupGetter__() { [native code] }",
55
- "__lookupSetter__" => "function __lookupSetter__() { [native code] }",
56
- "isPrototypeOf" => "function isPrototypeOf() { [native code] }",
57
- "propertyIsEnumerable" => "function propertyIsEnumerable() { [native code] }",
58
- "toString" => "function toString() { [native code] }",
59
- "valueOf" => "function valueOf() { [native code] }",
60
- "__proto__" => "[object Object]",
61
- "toLocaleString" => "function toLocaleString() { [native code] }"
62
- }.freeze
63
-
64
- WS = "\u0009-\u000D    - 

   "
65
- TRIM_RE = /\A[#{WS}]+|[#{WS}]+\z/
66
- DECIMAL_RE = /\A[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?\z/
67
- RADIX_RE = /\A0([xXoObB])(.+)\z/m
68
- UTF8 = Encoding::UTF_8
69
- REPLACEMENT = "�"
70
-
71
- def undefined?(v) = v.equal?(UNDEFINED)
72
- def nullish?(v) = v.nil? || v.equal?(UNDEFINED)
73
-
74
- # "null", "array", or the JavaScript `typeof` ("undefined", "boolean", "number", "string", "object", "function").
75
- def type_name(v)
76
- case v
77
- when UNDEFINED then "undefined"
78
- when nil then "null"
79
- when true, false then "boolean"
80
- when Float, Integer then "number"
81
- when String then "string"
82
- when Array then "array"
83
- when JsFunction then "function"
84
- else "object"
85
- end
86
- end
87
-
88
- # ToBoolean.
89
- def truthy?(v)
90
- case v
91
- when nil, false, UNDEFINED then false
92
- when true then true
93
- when Float, Integer then !(v.zero? || (v.is_a?(Float) && v.nan?))
94
- when String then !v.empty?
95
- else true
96
- end
97
- end
98
-
99
- # ---------------------------------------------------------------- numbers
100
-
101
- # Number::toString(x) for radix 10 (shortest round-trip digits), as String(x) produces it.
102
- def number_to_string(x)
103
- x = x.to_f
104
- return "NaN" if x.nan?
105
- return "0" if x.zero?
106
- return(x.positive? ? "Infinity" : "-Infinity") if x.infinite?
107
-
108
- sign = x.negative? ? "-" : ""
109
- a = x.abs
110
- return sign + a.to_i.to_s if a < 9_007_199_254_740_992.0 && a == a.floor
111
-
112
- r = a.to_s # shortest round-trip digits (dtoa mode 0), like JavaScript
113
- mantissa, exp = r.split("e")
114
- int_part, frac_part = mantissa.split(".")
115
- frac_part ||= ""
116
- if int_part.delete("0").empty?
117
- stripped = frac_part.sub(/\A0+/, "")
118
- point = exp.to_i - (frac_part.length - stripped.length)
119
- digits = stripped
120
- else
121
- digits = (int_part + frac_part).sub(/\A0+/, "")
122
- point = int_part.length + exp.to_i
123
- end
124
- digits = digits.sub(/0+\z/, "")
125
- digits = "0" if digits.empty?
126
- k = digits.length
127
- n = point
128
- out =
129
- if k <= n && n <= 21
130
- digits + ("0" * (n - k))
131
- elsif n.positive? && n <= 21
132
- "#{digits[0, n]}.#{digits[n..]}"
133
- elsif n > -6 && n <= 0
134
- "0.#{"0" * -n}#{digits}"
135
- else
136
- e = n - 1
137
- es = (e.negative? ? "-" : "+") + e.abs.to_s
138
- k == 1 ? "#{digits}e#{es}" : "#{digits[0]}.#{digits[1..]}e#{es}"
139
- end
140
- sign + out
141
- end
142
-
143
- # String.prototype.trim (ECMAScript white space and line terminators).
144
- def trim(s)
145
- return s.b.gsub(/\A[\t\n\v\f\r ]+|[\t\n\v\f\r ]+\z/n, "").force_encoding(UTF8) unless s.valid_encoding?
146
-
147
- s.gsub(TRIM_RE, "")
148
- end
149
-
150
- # ECMAScript StringToNumber: `Number(s)`.
151
- def string_to_number(input)
152
- s = trim(input)
153
- return 0.0 if s.empty?
154
- return Float::INFINITY if s == "Infinity" || s == "+Infinity"
155
- return -Float::INFINITY if s == "-Infinity"
156
- return Float::NAN unless s.valid_encoding?
157
-
158
- if (m = RADIX_RE.match(s))
159
- base = { "x" => 16, "o" => 8, "b" => 2 }.fetch(m[1].downcase)
160
- pattern = { 16 => /\A[0-9a-fA-F]+\z/, 8 => /\A[0-7]+\z/, 2 => /\A[01]+\z/ }.fetch(base)
161
- return Float::NAN unless pattern.match?(m[2])
162
-
163
- return integer_to_float(m[2].to_i(base))
164
- end
165
- return Float::NAN unless DECIMAL_RE.match?(s)
166
-
167
- s.to_f
168
- end
169
-
170
- # The double nearest to the integer i, rounding half to even.
171
- def integer_to_float(i)
172
- l = i.bit_length
173
- return i.to_f if l <= 53
174
- return Float::INFINITY if l > 1024
175
-
176
- shift = l - 53
177
- mantissa = i >> shift
178
- round = (i >> (shift - 1)) & 1
179
- sticky = (i & ((1 << (shift - 1)) - 1)) != 0
180
- mantissa += 1 if round == 1 && (sticky || mantissa.odd?)
181
- Math.ldexp(mantissa.to_f, shift)
182
- end
183
-
184
- # ToNumber(ToPrimitive(v, number)).
185
- def to_number(v)
186
- case v
187
- when UNDEFINED then Float::NAN
188
- when nil, false then 0.0
189
- when true then 1.0
190
- when Float then v
191
- when Integer then v.to_f
192
- when String then string_to_number(v)
193
- else string_to_number(to_str(v))
194
- end
195
- end
196
-
197
- # ---------------------------------------------------------------- strings
198
-
199
- # String(v).
200
- def to_str(v)
201
- case v
202
- when UNDEFINED then "undefined"
203
- when nil then "null"
204
- when true then "true"
205
- when false then "false"
206
- when Float, Integer then number_to_string(v)
207
- when String then v
208
- when Array then join(v, ",")
209
- when JsFunction then "function #{v.name}() { [native code] }"
210
- else "[object Object]"
211
- end
212
- end
213
-
214
- # Array.prototype.join.
215
- def join(items, sep)
216
- items.map { |e| nullish?(e) ? "" : to_str(e) }.join(sep)
217
- end
218
-
219
- # The code points of a WTF-8 string with their byte width: lone surrogates included, invalid bytes as U+FFFD.
220
- def code_points(s)
221
- out = []
222
- b = s.bytes
223
- n = b.length
224
- i = 0
225
- while i < n
226
- c = b[i]
227
- if c < 0x80
228
- out << [c, 1]
229
- i += 1
230
- next
231
- end
232
- need = if c >= 0xF0 then 3 elsif c >= 0xE0 then 2 elsif c >= 0xC2 then 1 else -1 end
233
- if need.negative? || c > 0xF4 || i + need >= n
234
- out << [0xFFFD, 1]
235
- i += 1
236
- next
237
- end
238
- cp = c & (0x3F >> need)
239
- ok = true
240
- (1..need).each do |j|
241
- x = b[i + j]
242
- if (x & 0xC0) != 0x80
243
- ok = false
244
- break
245
- end
246
- cp = (cp << 6) | (x & 0x3F)
247
- end
248
- min = [0, 0x80, 0x800, 0x10000][need]
249
- if !ok || cp < min || cp > 0x10FFFF
250
- out << [0xFFFD, 1]
251
- i += 1
252
- next
253
- end
254
- out << [cp, need + 1]
255
- i += need + 1
256
- end
257
- out
258
- end
259
-
260
- # UTF-16 code units of a WTF-8 string.
261
- def to_units(s)
262
- units = []
263
- code_points(s).each do |cp, _|
264
- if cp >= 0x10000
265
- cp -= 0x10000
266
- units << (0xD800 + (cp >> 10)) << (0xDC00 + (cp & 0x3FF))
267
- else
268
- units << cp
269
- end
270
- end
271
- units
272
- end
273
-
274
- # One code point (lone surrogates in WTF-8) as a UTF-8 string.
275
- def encode_unit(u)
276
- bytes =
277
- if u < 0x80 then [u]
278
- elsif u < 0x800 then [0xC0 | (u >> 6), 0x80 | (u & 0x3F)]
279
- elsif u < 0x10000 then [0xE0 | (u >> 12), 0x80 | ((u >> 6) & 0x3F), 0x80 | (u & 0x3F)]
280
- else [0xF0 | (u >> 18), 0x80 | ((u >> 12) & 0x3F), 0x80 | ((u >> 6) & 0x3F), 0x80 | (u & 0x3F)]
281
- end
282
- bytes.pack("C*").force_encoding(UTF8)
283
- end
284
-
285
- # UTF-16 code units joined back into a string (pairs combined).
286
- def units_to_string(units)
287
- out = +""
288
- i = 0
289
- while i < units.length
290
- u = units[i]
291
- if u >= 0xD800 && u <= 0xDBFF && i + 1 < units.length && units[i + 1] >= 0xDC00 && units[i + 1] <= 0xDFFF
292
- out << encode_unit(0x10000 + ((u - 0xD800) << 10) + (units[i + 1] - 0xDC00))
293
- i += 2
294
- next
295
- end
296
- out << encode_unit(u)
297
- i += 1
298
- end
299
- out.force_encoding(UTF8)
300
- end
301
-
302
- # JavaScript's string length (UTF-16 code units).
303
- def utf16_length(s)
304
- return s.bytesize if s.ascii_only?
305
- return s.length + s.count("\u{10000}-\u{10FFFF}") if s.valid_encoding?
306
-
307
- to_units(s).length
308
- end
309
-
310
- # `s[i]`: the code unit at index i as a one-unit string, or UNDEFINED.
311
- def utf16_at(s, i)
312
- units = to_units(s)
313
- i < units.length ? encode_unit(units[i]) : UNDEFINED
314
- end
315
-
316
- def well_formed?(a, b) = a.valid_encoding? && b.valid_encoding?
317
-
318
- # String.prototype.includes.
319
- def includes?(h, n)
320
- # For well-formed strings a code-unit match always starts and ends on code point boundaries.
321
- return h.include?(n) if well_formed?(h, n)
322
-
323
- hu = to_units(h)
324
- nu = to_units(n)
325
- return true if nu.empty?
326
-
327
- (0..(hu.length - nu.length)).any? { |i| hu[i, nu.length] == nu }
328
- end
329
-
330
- def starts_with?(h, n)
331
- return h.start_with?(n) if well_formed?(h, n)
332
-
333
- hu = to_units(h)
334
- nu = to_units(n)
335
- nu.length <= hu.length && hu[0, nu.length] == nu
336
- end
337
-
338
- def ends_with?(h, n)
339
- return h.end_with?(n) if well_formed?(h, n)
340
-
341
- hu = to_units(h)
342
- nu = to_units(n)
343
- nu.length <= hu.length && hu[hu.length - nu.length, nu.length] == nu
344
- end
345
-
346
- # ---------------------------------------------------------------- JSON.stringify
347
-
348
- # JSON.stringify(v), or nil where JSON.stringify returns undefined.
349
- def stringify(v)
350
- return nil if v.equal?(UNDEFINED) || v.is_a?(JsFunction)
351
-
352
- out = +""
353
- write_json(v, out)
354
- out.force_encoding(UTF8)
355
- end
356
-
357
- def write_json(v, out)
358
- case v
359
- when nil then out << "null"
360
- when true then out << "true"
361
- when false then out << "false"
362
- when Float, Integer
363
- f = v.to_f
364
- out << (f.nan? || f.infinite? ? "null" : number_to_string(f))
365
- when String then out << quote(v)
366
- when Array
367
- out << "["
368
- v.each_with_index do |e, i|
369
- out << "," if i.positive?
370
- if e.equal?(UNDEFINED) || e.is_a?(JsFunction)
371
- out << "null"
372
- else
373
- write_json(e, out)
374
- end
375
- end
376
- out << "]"
377
- when Hash
378
- out << "{"
379
- first = true
380
- v.each do |k, e|
381
- next if e.equal?(UNDEFINED) || e.is_a?(JsFunction)
382
-
383
- out << "," unless first
384
- first = false
385
- out << quote(k.to_s) << ":"
386
- write_json(e, out)
387
- end
388
- out << "}"
389
- else out << "null"
390
- end
391
- end
392
-
393
- QUOTE_NEEDED = /["\\\x00-\x1F]|\xED[\xA0-\xBF]/n
394
- QUOTE_ESCAPES = { '"' => '\\"', "\\" => "\\\\", "\b" => "\\b", "\f" => "\\f", "\n" => "\\n", "\r" => "\\r", "\t" => "\\t" }.freeze
395
-
396
- # JSON.stringify of a string (well-formed JSON.stringify: lone surrogates are escaped).
397
- def quote(s)
398
- b = s.b
399
- return "\"#{s}\"" unless QUOTE_NEEDED.match?(b)
400
-
401
- escaped = b.gsub(/["\\\x00-\x1F]|\xED[\xA0-\xBF][\x80-\xBF]/n) do |c|
402
- if (e = QUOTE_ESCAPES[c])
403
- e
404
- elsif c.bytesize == 1
405
- format("\\u%04x", c.ord)
406
- else
407
- x = c.bytes
408
- format("\\u%04x", ((x[0] & 0x0F) << 12) | ((x[1] & 0x3F) << 6) | (x[2] & 0x3F))
409
- end
410
- end
411
- "\"#{escaped.force_encoding(UTF8)}\""
412
- end
413
-
414
- # ---------------------------------------------------------------- property access
415
-
416
- # A canonical array index (0 … 2^32-2), or -1.
417
- def array_index(k)
418
- return -1 if k.empty? || k.length > 10 || (k.length > 1 && k.start_with?("0")) || !k.match?(/\A[0-9]+\z/)
419
-
420
- n = k.to_i
421
- n < 4_294_967_295 ? n : -1
422
- end
423
-
424
- # The property read `v[name]` for the fixed property names the engine reads. Plain objects only expose own
425
- # properties here: none of those names exist on Object.prototype. Raises JsTypeError for null and undefined.
426
- def get(v, name)
427
- case v
428
- when nil, UNDEFINED
429
- raise JsTypeError, "Cannot read properties of #{to_str(v)} (reading '#{name}')"
430
- when Hash
431
- v.fetch(name, UNDEFINED)
432
- when String
433
- return utf16_length(v).to_f if name == "length"
434
-
435
- n = array_index(name)
436
- return utf16_at(v, n) if n >= 0
437
- return JsFunction.new(name) if STRING_METHODS.key?(name)
438
-
439
- UNDEFINED
440
- when Array
441
- return v.length.to_f if name == "length"
442
-
443
- n = array_index(name)
444
- return(n < v.length ? v[n] : UNDEFINED) if n >= 0
445
- return JsFunction.new(name) if ARRAY_METHODS.key?(name)
446
-
447
- UNDEFINED
448
- else
449
- UNDEFINED
450
- end
451
- end
452
-
453
- # The engine's `own(obj, key)`: an own-property lookup that never reads inherited members.
454
- def own(obj, key)
455
- case obj
456
- when Hash then obj.fetch(key, UNDEFINED)
457
- when Array, String then key == "length" || array_index(key) >= 0 ? get(obj, key) : UNDEFINED
458
- else UNDEFINED
459
- end
460
- end
461
-
462
- # ---------------------------------------------------------------- conversion
463
-
464
- # A Hash in JavaScript own-property order (array-index keys ascending first).
465
- def js_order(h)
466
- return h unless h.each_key.any? { |k| array_index(k) >= 0 }
467
-
468
- index, names = h.partition { |k, _| array_index(k) >= 0 }
469
- index.sort_by! { |k, _| k.to_i }
470
- (index + names).to_h
471
- end
472
-
473
- # Converts Ruby data to an engine value: nil, booleans, Integer and Float (as Float), String (as UTF-8),
474
- # Symbol (its name), Array, Hash (String or Symbol keys), Time / Date / DateTime (ISO 8601 in UTC, as
475
- # `Date.toJSON()`), and anything with +to_h+ or +as_json+. Anything else becomes its +to_s+.
476
- def from_ruby(x, depth = 0)
477
- case x
478
- when nil, true, false, Float, UNDEFINED then x
479
- when Integer then x.to_f
480
- when String then utf8(x)
481
- when Symbol then x.to_s
482
- else
483
- return nil if depth > 32
484
-
485
- case x
486
- when Array then x.map { |e| from_ruby(e, depth + 1) }
487
- when Hash then js_order(x.each_with_object({}) { |(k, e), m| m[utf8(k.to_s)] = from_ruby(e, depth + 1) })
488
- when Time then x.getutc.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
489
- else
490
- if defined?(::DateTime) && x.is_a?(::DateTime)
491
- x.new_offset(0).strftime("%Y-%m-%dT%H:%M:%S.%LZ")
492
- elsif defined?(::Date) && x.is_a?(::Date)
493
- x.strftime("%Y-%m-%dT00:00:00.000Z")
494
- elsif x.respond_to?(:as_json)
495
- from_ruby(x.as_json, depth + 1)
496
- elsif x.respond_to?(:to_h)
497
- from_ruby(x.to_h, depth + 1)
498
- else
499
- utf8(x.to_s)
500
- end
501
- end
502
- end
503
- end
504
-
505
- def utf8(s)
506
- return s if s.encoding == UTF8 && (s.ascii_only? || s.valid_encoding?)
507
-
508
- if s.encoding == Encoding::BINARY || s.encoding == UTF8
509
- s.dup.force_encoding(UTF8).scrub(REPLACEMENT)
510
- else
511
- s.encode(UTF8, invalid: :replace, undef: :replace, replace: REPLACEMENT)
512
- end
513
- end
514
-
515
- # Converts an engine value to plain Ruby data: nil (also for undefined), booleans, Integer (whole numbers up to
516
- # 2^53) or Float, String, Array and Hash (in configuration order).
517
- def to_ruby(v)
518
- case v
519
- when Float then v.finite? && v == v.floor && v.abs <= 9_007_199_254_740_992.0 ? v.to_i : v
520
- when Array then v.map { |e| to_ruby(e) }
521
- when Hash
522
- v.each_with_object({}) do |(k, e), m|
523
- m[k] = to_ruby(e) unless e.equal?(UNDEFINED) || e.is_a?(JsFunction)
524
- end
525
- when UNDEFINED, JsFunction then nil
526
- else v
527
- end
528
- end
529
- end
530
- end
531
- end
1
+ # frozen_string_literal: true
2
+
3
+ module NanoFlags
4
+ module Engine
5
+ # JavaScript `undefined`: an absent value (a missing property, a flag that serves nothing). Distinct from +nil+
6
+ # (JSON null).
7
+ UNDEFINED = Object.new
8
+ def UNDEFINED.inspect = "UNDEFINED"
9
+ def UNDEFINED.to_s = "undefined"
10
+ UNDEFINED.freeze
11
+
12
+ # A function value. Only ever produced by reading a String / Array prototype method by name (e.g. `"ab".match`),
13
+ # which a malformed configuration can make the engine do.
14
+ JsFunction = Struct.new(:name)
15
+
16
+ # The TypeError the TypeScript engine would throw for a malformed configuration (the message matches V8's).
17
+ class JsTypeError < StandardError; end
18
+
19
+ # The JavaScript value semantics the engine depends on.
20
+ #
21
+ # The reference engine is TypeScript: its results depend on truthiness, loose property access, `Number()`,
22
+ # `String()`, `JSON.stringify` and UTF-16 string semantics. This module reproduces exactly those for the value
23
+ # model of this gem, so the Ruby engine returns the same results as every other NanoFlags engine for the same JSON
24
+ # (asserted by the shared parity fixtures):
25
+ #
26
+ # - `undefined` is {UNDEFINED}, `null` is +nil+, booleans are +true+/+false+, numbers are Float (always),
27
+ # - strings are UTF-8; a lone UTF-16 surrogate (only expressible as a `\u` escape in JSON) is kept in its
28
+ # three-byte WTF-8 form (such a string is not +valid_encoding?+),
29
+ # - arrays are Array, objects are Hash with String keys in JavaScript order (array-index keys ascending first).
30
+ #
31
+ # @api private
32
+ module Js
33
+ module_function
34
+
35
+ STRING_METHODS = %w[
36
+ anchor at big blink bold charAt charCodeAt codePointAt concat constructor endsWith fixed fontcolor fontsize
37
+ includes indexOf isWellFormed italics lastIndexOf link localeCompare match matchAll normalize padEnd padStart
38
+ repeat replace replaceAll search slice small split strike sub substr substring sup toLocaleLowerCase
39
+ toLocaleUpperCase toLowerCase toString toUpperCase toWellFormed trim trimEnd trimLeft trimRight trimStart valueOf
40
+ ].to_h { |m| [m, true] }.freeze
41
+
42
+ ARRAY_METHODS = %w[
43
+ at concat constructor copyWithin entries every fill filter find findIndex findLast findLastIndex flat flatMap
44
+ forEach includes indexOf join keys lastIndexOf map pop push reduce reduceRight reverse shift slice some sort
45
+ splice toLocaleString toReversed toSorted toSpliced toString unshift values with
46
+ ].to_h { |m| [m, true] }.freeze
47
+
48
+ # Object.prototype members, as `${words[name]}` renders them in describeCondition.
49
+ OBJECT_PROTO_STRINGS = {
50
+ "constructor" => "function Object() { [native code] }",
51
+ "__defineGetter__" => "function __defineGetter__() { [native code] }",
52
+ "__defineSetter__" => "function __defineSetter__() { [native code] }",
53
+ "hasOwnProperty" => "function hasOwnProperty() { [native code] }",
54
+ "__lookupGetter__" => "function __lookupGetter__() { [native code] }",
55
+ "__lookupSetter__" => "function __lookupSetter__() { [native code] }",
56
+ "isPrototypeOf" => "function isPrototypeOf() { [native code] }",
57
+ "propertyIsEnumerable" => "function propertyIsEnumerable() { [native code] }",
58
+ "toString" => "function toString() { [native code] }",
59
+ "valueOf" => "function valueOf() { [native code] }",
60
+ "__proto__" => "[object Object]",
61
+ "toLocaleString" => "function toLocaleString() { [native code] }"
62
+ }.freeze
63
+
64
+ WS = "\u0009-\u000D    - 

   "
65
+ TRIM_RE = /\A[#{WS}]+|[#{WS}]+\z/
66
+ DECIMAL_RE = /\A[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?\z/
67
+ RADIX_RE = /\A0([xXoObB])(.+)\z/m
68
+ UTF8 = Encoding::UTF_8
69
+ REPLACEMENT = "�"
70
+
71
+ def undefined?(v) = v.equal?(UNDEFINED)
72
+ def nullish?(v) = v.nil? || v.equal?(UNDEFINED)
73
+
74
+ # "null", "array", or the JavaScript `typeof` ("undefined", "boolean", "number", "string", "object", "function").
75
+ def type_name(v)
76
+ case v
77
+ when UNDEFINED then "undefined"
78
+ when nil then "null"
79
+ when true, false then "boolean"
80
+ when Float, Integer then "number"
81
+ when String then "string"
82
+ when Array then "array"
83
+ when JsFunction then "function"
84
+ else "object"
85
+ end
86
+ end
87
+
88
+ # ToBoolean.
89
+ def truthy?(v)
90
+ case v
91
+ when nil, false, UNDEFINED then false
92
+ when true then true
93
+ when Float, Integer then !(v.zero? || (v.is_a?(Float) && v.nan?))
94
+ when String then !v.empty?
95
+ else true
96
+ end
97
+ end
98
+
99
+ # ---------------------------------------------------------------- numbers
100
+
101
+ # Number::toString(x) for radix 10 (shortest round-trip digits), as String(x) produces it.
102
+ def number_to_string(x)
103
+ x = x.to_f
104
+ return "NaN" if x.nan?
105
+ return "0" if x.zero?
106
+ return(x.positive? ? "Infinity" : "-Infinity") if x.infinite?
107
+
108
+ sign = x.negative? ? "-" : ""
109
+ a = x.abs
110
+ return sign + a.to_i.to_s if a < 9_007_199_254_740_992.0 && a == a.floor
111
+
112
+ r = a.to_s # shortest round-trip digits (dtoa mode 0), like JavaScript
113
+ mantissa, exp = r.split("e")
114
+ int_part, frac_part = mantissa.split(".")
115
+ frac_part ||= ""
116
+ if int_part.delete("0").empty?
117
+ stripped = frac_part.sub(/\A0+/, "")
118
+ point = exp.to_i - (frac_part.length - stripped.length)
119
+ digits = stripped
120
+ else
121
+ digits = (int_part + frac_part).sub(/\A0+/, "")
122
+ point = int_part.length + exp.to_i
123
+ end
124
+ digits = digits.sub(/0+\z/, "")
125
+ digits = "0" if digits.empty?
126
+ k = digits.length
127
+ n = point
128
+ out =
129
+ if k <= n && n <= 21
130
+ digits + ("0" * (n - k))
131
+ elsif n.positive? && n <= 21
132
+ "#{digits[0, n]}.#{digits[n..]}"
133
+ elsif n > -6 && n <= 0
134
+ "0.#{"0" * -n}#{digits}"
135
+ else
136
+ e = n - 1
137
+ es = (e.negative? ? "-" : "+") + e.abs.to_s
138
+ k == 1 ? "#{digits}e#{es}" : "#{digits[0]}.#{digits[1..]}e#{es}"
139
+ end
140
+ sign + out
141
+ end
142
+
143
+ # String.prototype.trim (ECMAScript white space and line terminators).
144
+ def trim(s)
145
+ return s.b.gsub(/\A[\t\n\v\f\r ]+|[\t\n\v\f\r ]+\z/n, "").force_encoding(UTF8) unless s.valid_encoding?
146
+
147
+ s.gsub(TRIM_RE, "")
148
+ end
149
+
150
+ # ECMAScript StringToNumber: `Number(s)`.
151
+ def string_to_number(input)
152
+ s = trim(input)
153
+ return 0.0 if s.empty?
154
+ return Float::INFINITY if s == "Infinity" || s == "+Infinity"
155
+ return -Float::INFINITY if s == "-Infinity"
156
+ return Float::NAN unless s.valid_encoding?
157
+
158
+ if (m = RADIX_RE.match(s))
159
+ base = { "x" => 16, "o" => 8, "b" => 2 }.fetch(m[1].downcase)
160
+ pattern = { 16 => /\A[0-9a-fA-F]+\z/, 8 => /\A[0-7]+\z/, 2 => /\A[01]+\z/ }.fetch(base)
161
+ return Float::NAN unless pattern.match?(m[2])
162
+
163
+ return integer_to_float(m[2].to_i(base))
164
+ end
165
+ return Float::NAN unless DECIMAL_RE.match?(s)
166
+
167
+ s.to_f
168
+ end
169
+
170
+ # The double nearest to the integer i, rounding half to even.
171
+ def integer_to_float(i)
172
+ l = i.bit_length
173
+ return i.to_f if l <= 53
174
+ return Float::INFINITY if l > 1024
175
+
176
+ shift = l - 53
177
+ mantissa = i >> shift
178
+ round = (i >> (shift - 1)) & 1
179
+ sticky = (i & ((1 << (shift - 1)) - 1)) != 0
180
+ mantissa += 1 if round == 1 && (sticky || mantissa.odd?)
181
+ Math.ldexp(mantissa.to_f, shift)
182
+ end
183
+
184
+ # ToNumber(ToPrimitive(v, number)).
185
+ def to_number(v)
186
+ case v
187
+ when UNDEFINED then Float::NAN
188
+ when nil, false then 0.0
189
+ when true then 1.0
190
+ when Float then v
191
+ when Integer then v.to_f
192
+ when String then string_to_number(v)
193
+ else string_to_number(to_str(v))
194
+ end
195
+ end
196
+
197
+ # ---------------------------------------------------------------- strings
198
+
199
+ # String(v).
200
+ def to_str(v)
201
+ case v
202
+ when UNDEFINED then "undefined"
203
+ when nil then "null"
204
+ when true then "true"
205
+ when false then "false"
206
+ when Float, Integer then number_to_string(v)
207
+ when String then v
208
+ when Array then join(v, ",")
209
+ when JsFunction then "function #{v.name}() { [native code] }"
210
+ else "[object Object]"
211
+ end
212
+ end
213
+
214
+ # Array.prototype.join.
215
+ def join(items, sep)
216
+ items.map { |e| nullish?(e) ? "" : to_str(e) }.join(sep)
217
+ end
218
+
219
+ # The code points of a WTF-8 string with their byte width: lone surrogates included, invalid bytes as U+FFFD.
220
+ def code_points(s)
221
+ out = []
222
+ b = s.bytes
223
+ n = b.length
224
+ i = 0
225
+ while i < n
226
+ c = b[i]
227
+ if c < 0x80
228
+ out << [c, 1]
229
+ i += 1
230
+ next
231
+ end
232
+ need = if c >= 0xF0 then 3 elsif c >= 0xE0 then 2 elsif c >= 0xC2 then 1 else -1 end
233
+ if need.negative? || c > 0xF4 || i + need >= n
234
+ out << [0xFFFD, 1]
235
+ i += 1
236
+ next
237
+ end
238
+ cp = c & (0x3F >> need)
239
+ ok = true
240
+ (1..need).each do |j|
241
+ x = b[i + j]
242
+ if (x & 0xC0) != 0x80
243
+ ok = false
244
+ break
245
+ end
246
+ cp = (cp << 6) | (x & 0x3F)
247
+ end
248
+ min = [0, 0x80, 0x800, 0x10000][need]
249
+ if !ok || cp < min || cp > 0x10FFFF
250
+ out << [0xFFFD, 1]
251
+ i += 1
252
+ next
253
+ end
254
+ out << [cp, need + 1]
255
+ i += need + 1
256
+ end
257
+ out
258
+ end
259
+
260
+ # UTF-16 code units of a WTF-8 string.
261
+ def to_units(s)
262
+ units = []
263
+ code_points(s).each do |cp, _|
264
+ if cp >= 0x10000
265
+ cp -= 0x10000
266
+ units << (0xD800 + (cp >> 10)) << (0xDC00 + (cp & 0x3FF))
267
+ else
268
+ units << cp
269
+ end
270
+ end
271
+ units
272
+ end
273
+
274
+ # One code point (lone surrogates in WTF-8) as a UTF-8 string.
275
+ def encode_unit(u)
276
+ bytes =
277
+ if u < 0x80 then [u]
278
+ elsif u < 0x800 then [0xC0 | (u >> 6), 0x80 | (u & 0x3F)]
279
+ elsif u < 0x10000 then [0xE0 | (u >> 12), 0x80 | ((u >> 6) & 0x3F), 0x80 | (u & 0x3F)]
280
+ else [0xF0 | (u >> 18), 0x80 | ((u >> 12) & 0x3F), 0x80 | ((u >> 6) & 0x3F), 0x80 | (u & 0x3F)]
281
+ end
282
+ bytes.pack("C*").force_encoding(UTF8)
283
+ end
284
+
285
+ # UTF-16 code units joined back into a string (pairs combined).
286
+ def units_to_string(units)
287
+ out = +""
288
+ i = 0
289
+ while i < units.length
290
+ u = units[i]
291
+ if u >= 0xD800 && u <= 0xDBFF && i + 1 < units.length && units[i + 1] >= 0xDC00 && units[i + 1] <= 0xDFFF
292
+ out << encode_unit(0x10000 + ((u - 0xD800) << 10) + (units[i + 1] - 0xDC00))
293
+ i += 2
294
+ next
295
+ end
296
+ out << encode_unit(u)
297
+ i += 1
298
+ end
299
+ out.force_encoding(UTF8)
300
+ end
301
+
302
+ # JavaScript's string length (UTF-16 code units).
303
+ def utf16_length(s)
304
+ return s.bytesize if s.ascii_only?
305
+ return s.length + s.count("\u{10000}-\u{10FFFF}") if s.valid_encoding?
306
+
307
+ to_units(s).length
308
+ end
309
+
310
+ # `s[i]`: the code unit at index i as a one-unit string, or UNDEFINED.
311
+ def utf16_at(s, i)
312
+ units = to_units(s)
313
+ i < units.length ? encode_unit(units[i]) : UNDEFINED
314
+ end
315
+
316
+ def well_formed?(a, b) = a.valid_encoding? && b.valid_encoding?
317
+
318
+ # String.prototype.includes.
319
+ def includes?(h, n)
320
+ # For well-formed strings a code-unit match always starts and ends on code point boundaries.
321
+ return h.include?(n) if well_formed?(h, n)
322
+
323
+ hu = to_units(h)
324
+ nu = to_units(n)
325
+ return true if nu.empty?
326
+
327
+ (0..(hu.length - nu.length)).any? { |i| hu[i, nu.length] == nu }
328
+ end
329
+
330
+ def starts_with?(h, n)
331
+ return h.start_with?(n) if well_formed?(h, n)
332
+
333
+ hu = to_units(h)
334
+ nu = to_units(n)
335
+ nu.length <= hu.length && hu[0, nu.length] == nu
336
+ end
337
+
338
+ def ends_with?(h, n)
339
+ return h.end_with?(n) if well_formed?(h, n)
340
+
341
+ hu = to_units(h)
342
+ nu = to_units(n)
343
+ nu.length <= hu.length && hu[hu.length - nu.length, nu.length] == nu
344
+ end
345
+
346
+ # ---------------------------------------------------------------- JSON.stringify
347
+
348
+ # JSON.stringify(v), or nil where JSON.stringify returns undefined.
349
+ def stringify(v)
350
+ return nil if v.equal?(UNDEFINED) || v.is_a?(JsFunction)
351
+
352
+ out = +""
353
+ write_json(v, out)
354
+ out.force_encoding(UTF8)
355
+ end
356
+
357
+ def write_json(v, out)
358
+ case v
359
+ when nil then out << "null"
360
+ when true then out << "true"
361
+ when false then out << "false"
362
+ when Float, Integer
363
+ f = v.to_f
364
+ out << (f.nan? || f.infinite? ? "null" : number_to_string(f))
365
+ when String then out << quote(v)
366
+ when Array
367
+ out << "["
368
+ v.each_with_index do |e, i|
369
+ out << "," if i.positive?
370
+ if e.equal?(UNDEFINED) || e.is_a?(JsFunction)
371
+ out << "null"
372
+ else
373
+ write_json(e, out)
374
+ end
375
+ end
376
+ out << "]"
377
+ when Hash
378
+ out << "{"
379
+ first = true
380
+ v.each do |k, e|
381
+ next if e.equal?(UNDEFINED) || e.is_a?(JsFunction)
382
+
383
+ out << "," unless first
384
+ first = false
385
+ out << quote(k.to_s) << ":"
386
+ write_json(e, out)
387
+ end
388
+ out << "}"
389
+ else out << "null"
390
+ end
391
+ end
392
+
393
+ QUOTE_NEEDED = /["\\\x00-\x1F]|\xED[\xA0-\xBF]/n
394
+ QUOTE_ESCAPES = { '"' => '\\"', "\\" => "\\\\", "\b" => "\\b", "\f" => "\\f", "\n" => "\\n", "\r" => "\\r", "\t" => "\\t" }.freeze
395
+
396
+ # JSON.stringify of a string (well-formed JSON.stringify: lone surrogates are escaped).
397
+ def quote(s)
398
+ b = s.b
399
+ return "\"#{s}\"" unless QUOTE_NEEDED.match?(b)
400
+
401
+ escaped = b.gsub(/["\\\x00-\x1F]|\xED[\xA0-\xBF][\x80-\xBF]/n) do |c|
402
+ if (e = QUOTE_ESCAPES[c])
403
+ e
404
+ elsif c.bytesize == 1
405
+ format("\\u%04x", c.ord)
406
+ else
407
+ x = c.bytes
408
+ format("\\u%04x", ((x[0] & 0x0F) << 12) | ((x[1] & 0x3F) << 6) | (x[2] & 0x3F))
409
+ end
410
+ end
411
+ "\"#{escaped.force_encoding(UTF8)}\""
412
+ end
413
+
414
+ # ---------------------------------------------------------------- property access
415
+
416
+ # A canonical array index (0 … 2^32-2), or -1.
417
+ def array_index(k)
418
+ return -1 if k.empty? || k.length > 10 || (k.length > 1 && k.start_with?("0")) || !k.match?(/\A[0-9]+\z/)
419
+
420
+ n = k.to_i
421
+ n < 4_294_967_295 ? n : -1
422
+ end
423
+
424
+ # The property read `v[name]` for the fixed property names the engine reads. Plain objects only expose own
425
+ # properties here: none of those names exist on Object.prototype. Raises JsTypeError for null and undefined.
426
+ def get(v, name)
427
+ case v
428
+ when nil, UNDEFINED
429
+ raise JsTypeError, "Cannot read properties of #{to_str(v)} (reading '#{name}')"
430
+ when Hash
431
+ v.fetch(name, UNDEFINED)
432
+ when String
433
+ return utf16_length(v).to_f if name == "length"
434
+
435
+ n = array_index(name)
436
+ return utf16_at(v, n) if n >= 0
437
+ return JsFunction.new(name) if STRING_METHODS.key?(name)
438
+
439
+ UNDEFINED
440
+ when Array
441
+ return v.length.to_f if name == "length"
442
+
443
+ n = array_index(name)
444
+ return(n < v.length ? v[n] : UNDEFINED) if n >= 0
445
+ return JsFunction.new(name) if ARRAY_METHODS.key?(name)
446
+
447
+ UNDEFINED
448
+ else
449
+ UNDEFINED
450
+ end
451
+ end
452
+
453
+ # The engine's `own(obj, key)`: an own-property lookup that never reads inherited members.
454
+ def own(obj, key)
455
+ case obj
456
+ when Hash then obj.fetch(key, UNDEFINED)
457
+ when Array, String then key == "length" || array_index(key) >= 0 ? get(obj, key) : UNDEFINED
458
+ else UNDEFINED
459
+ end
460
+ end
461
+
462
+ # ---------------------------------------------------------------- conversion
463
+
464
+ # A Hash in JavaScript own-property order (array-index keys ascending first).
465
+ def js_order(h)
466
+ return h unless h.each_key.any? { |k| array_index(k) >= 0 }
467
+
468
+ index, names = h.partition { |k, _| array_index(k) >= 0 }
469
+ index.sort_by! { |k, _| k.to_i }
470
+ (index + names).to_h
471
+ end
472
+
473
+ # Converts Ruby data to an engine value: nil, booleans, Integer and Float (as Float), String (as UTF-8),
474
+ # Symbol (its name), Array, Hash (String or Symbol keys), Time / Date / DateTime (ISO 8601 in UTC, as
475
+ # `Date.toJSON()`), and anything with +to_h+ or +as_json+. Anything else becomes its +to_s+.
476
+ def from_ruby(x, depth = 0)
477
+ case x
478
+ when nil, true, false, Float, UNDEFINED then x
479
+ when Integer then x.to_f
480
+ when String then utf8(x)
481
+ when Symbol then x.to_s
482
+ else
483
+ return nil if depth > 32
484
+
485
+ case x
486
+ when Array then x.map { |e| from_ruby(e, depth + 1) }
487
+ when Hash then js_order(x.each_with_object({}) { |(k, e), m| m[utf8(k.to_s)] = from_ruby(e, depth + 1) })
488
+ when Time then x.getutc.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
489
+ else
490
+ if defined?(::DateTime) && x.is_a?(::DateTime)
491
+ x.new_offset(0).strftime("%Y-%m-%dT%H:%M:%S.%LZ")
492
+ elsif defined?(::Date) && x.is_a?(::Date)
493
+ x.strftime("%Y-%m-%dT00:00:00.000Z")
494
+ elsif x.respond_to?(:as_json)
495
+ from_ruby(x.as_json, depth + 1)
496
+ elsif x.respond_to?(:to_h)
497
+ from_ruby(x.to_h, depth + 1)
498
+ else
499
+ utf8(x.to_s)
500
+ end
501
+ end
502
+ end
503
+ end
504
+
505
+ def utf8(s)
506
+ return s if s.encoding == UTF8 && (s.ascii_only? || s.valid_encoding?)
507
+
508
+ if s.encoding == Encoding::BINARY || s.encoding == UTF8
509
+ s.dup.force_encoding(UTF8).scrub(REPLACEMENT)
510
+ else
511
+ s.encode(UTF8, invalid: :replace, undef: :replace, replace: REPLACEMENT)
512
+ end
513
+ end
514
+
515
+ # Converts an engine value to plain Ruby data: nil (also for undefined), booleans, Integer (whole numbers up to
516
+ # 2^53) or Float, String, Array and Hash (in configuration order).
517
+ def to_ruby(v)
518
+ case v
519
+ when Float then v.finite? && v == v.floor && v.abs <= 9_007_199_254_740_992.0 ? v.to_i : v
520
+ when Array then v.map { |e| to_ruby(e) }
521
+ when Hash
522
+ v.each_with_object({}) do |(k, e), m|
523
+ m[k] = to_ruby(e) unless e.equal?(UNDEFINED) || e.is_a?(JsFunction)
524
+ end
525
+ when UNDEFINED, JsFunction then nil
526
+ else v
527
+ end
528
+ end
529
+ end
530
+ end
531
+ end