1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.polyfill;
16
17 import java.io.IOException;
18 import java.nio.charset.StandardCharsets;
19 import java.util.HashMap;
20 import java.util.Map;
21
22 import org.apache.commons.io.IOUtils;
23 import org.htmlunit.corejs.javascript.Context;
24 import org.htmlunit.corejs.javascript.Script;
25 import org.htmlunit.corejs.javascript.Scriptable;
26 import org.htmlunit.corejs.javascript.VarScope;
27
28
29
30
31
32
33
34 public class Polyfill {
35
36 private static final Map<String, Polyfill> CACHE = new HashMap<>();
37
38 private String url_;
39 private String source_;
40 private Script script_;
41
42
43
44
45
46
47
48 public static Polyfill getFetchPolyfill() throws IOException {
49 return getPolyfill("fetch/fetch.umd.js");
50 }
51
52 private static Polyfill getPolyfill(final String resouceName) throws IOException {
53 Polyfill poly = CACHE.get(resouceName);
54 if (poly != null) {
55 return poly;
56 }
57
58 poly = new Polyfill();
59 poly.source_ = IOUtils.toString(poly.getClass().getResourceAsStream(resouceName), StandardCharsets.UTF_8);
60 poly.url_ = poly.getClass().getResource(resouceName).toExternalForm();
61
62 CACHE.put(resouceName, poly);
63 return poly;
64 }
65
66
67
68
69
70
71
72
73 public void apply(final Context context, final VarScope scope, final Scriptable thisObject) {
74 if (script_ == null) {
75 script_ = context.compileString(source_, url_, 0, null);
76 }
77
78 if (script_ != null) {
79 script_.exec(context, scope, thisObject);
80 }
81 }
82 }