@braintree/asset-loader 2.0.4 → 2.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.
package/README.md CHANGED
@@ -20,17 +20,24 @@ loadScript({
20
20
  // optional
21
21
  foo: "value", // adds data-foo="value" to script tag
22
22
  },
23
- // optional, by default the module will resolve with an existing script
24
- // node if a script tag with the same src exists on the page, by setting
25
- // this value to `true`, it will add the script to the page even if an
26
- // identical script tag already exists on the page.
23
+ // optional, by default a repeated call with the same options reuses the
24
+ // earlier load. Setting this to `true` always adds a new script tag and
25
+ // replaces the reused load for later calls with the same options.
27
26
  forceScriptReload: true,
27
+ // optional, milliseconds to wait before giving up on a load that never
28
+ // finishes. There is no timeout by default. The script tag can't be
29
+ // cancelled, so a retry after a slow load may run the script twice.
30
+ timeout: 60000,
28
31
  })
29
32
  .then(function (script) {
30
33
  script; // a reference to the dom node
31
34
  })
32
35
  .catch(function (err) {
33
- // occurs when script fails to load or is aborted
36
+ // occurs when the script fails to load, is aborted or times out.
37
+ // err is an AssetLoadError with `src`, `failureKind` ("error", "abort"
38
+ // or "timeout"), `timing` (ms until failure) and `onLine`
39
+ // (navigator.onLine at failure). Calling loadScript again with the
40
+ // same options starts a new load.
34
41
  });
35
42
  ```
36
43
 
package/dist/index.d.ts CHANGED
@@ -2,3 +2,4 @@ import loadScript = require("./load-script");
2
2
  import loadStylesheet = require("./load-stylesheet");
3
3
  export { loadScript };
4
4
  export { loadStylesheet };
5
+ export type { AssetLoadError, AssetLoadFailureKind } from "./types";
@@ -1,13 +1,42 @@
1
1
  "use strict";
2
- var scriptPromiseCache = {};
3
- function loadScript(options) {
4
- var scriptLoadPromise;
5
- var stringifiedOptions = JSON.stringify(options);
6
- if (!options.forceScriptReload) {
7
- scriptLoadPromise = scriptPromiseCache[stringifiedOptions];
8
- if (scriptLoadPromise) {
9
- return scriptLoadPromise;
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
10
  }
11
+ return t;
12
+ };
13
+ var scriptCache = {};
14
+ function canReuse(entry, forceReload) {
15
+ return !forceReload && entry.state !== "failed";
16
+ }
17
+ function buildLoadError(src, failureKind, startTime) {
18
+ var suffixes = {
19
+ abort: "has aborted.",
20
+ error: "failed to load.",
21
+ timeout: "timed out.",
22
+ };
23
+ var suffix = suffixes[failureKind];
24
+ var error = new Error("".concat(src, " ").concat(suffix));
25
+ error.src = src;
26
+ error.failureKind = failureKind;
27
+ error.timing = performance.now() - startTime;
28
+ error.onLine = navigator.onLine;
29
+ return error;
30
+ }
31
+ function loadScript(options) {
32
+ // forceScriptReload only controls whether the cache is read, so it must not
33
+ // be part of the key, otherwise a forced load can never replace the entry.
34
+ // timeout is left out too, so callers share the load that started first.
35
+ var forceScriptReload = options.forceScriptReload, timeout = options.timeout, cacheableOptions = __rest(options, ["forceScriptReload", "timeout"]);
36
+ var stringifiedOptions = JSON.stringify(cacheableOptions);
37
+ var existing = scriptCache[stringifiedOptions];
38
+ if (existing && canReuse(existing, forceScriptReload)) {
39
+ return existing.promise;
11
40
  }
12
41
  var script = document.createElement("script");
13
42
  var attrs = options.dataAttributes || {};
@@ -27,22 +56,60 @@ function loadScript(options) {
27
56
  Object.keys(attrs).forEach(function (key) {
28
57
  script.setAttribute("data-".concat(key), "".concat(attrs[key]));
29
58
  });
30
- scriptLoadPromise = new Promise(function (resolve, reject) {
59
+ // Handlers only update their own entry and never touch the cache, so a
60
+ // forced reload replacing the cached entry can't be undone by an old load.
61
+ // State is set before settling so callers retrying from a catch see it.
62
+ var entry = { state: "pending" };
63
+ entry.promise = new Promise(function (resolve, reject) {
64
+ var startTime = performance.now();
65
+ var timedOut = false;
66
+ var timer;
67
+ // The first event decides the outcome; later ones can't override it.
31
68
  script.addEventListener("load", function () {
69
+ if (timedOut) {
70
+ // A script can't be cancelled once inserted, so it may still finish.
71
+ // Fix the entry so the next call reuses it instead of adding a tag.
72
+ entry.state = "loaded";
73
+ entry.promise = Promise.resolve(script);
74
+ return;
75
+ }
76
+ if (entry.state !== "pending") {
77
+ return;
78
+ }
79
+ clearTimeout(timer);
80
+ entry.state = "loaded";
32
81
  resolve(script);
33
82
  });
34
83
  script.addEventListener("error", function () {
35
- reject(new Error("".concat(options.src, " failed to load.")));
84
+ if (entry.state !== "pending") {
85
+ return;
86
+ }
87
+ clearTimeout(timer);
88
+ entry.state = "failed";
89
+ container.removeChild(script);
90
+ reject(buildLoadError(options.src, "error", startTime));
36
91
  });
37
92
  script.addEventListener("abort", function () {
38
- reject(new Error("".concat(options.src, " has aborted.")));
93
+ if (entry.state !== "pending") {
94
+ return;
95
+ }
96
+ clearTimeout(timer);
97
+ entry.state = "failed";
98
+ reject(buildLoadError(options.src, "abort", startTime));
39
99
  });
100
+ if (timeout) {
101
+ timer = setTimeout(function () {
102
+ timedOut = true;
103
+ entry.state = "failed";
104
+ reject(buildLoadError(options.src, "timeout", startTime));
105
+ }, timeout);
106
+ }
40
107
  container.appendChild(script);
41
108
  });
42
- scriptPromiseCache[stringifiedOptions] = scriptLoadPromise;
43
- return scriptLoadPromise;
109
+ scriptCache[stringifiedOptions] = entry;
110
+ return entry.promise;
44
111
  }
45
112
  loadScript.clearCache = function () {
46
- scriptPromiseCache = {};
113
+ scriptCache = {};
47
114
  };
48
115
  module.exports = loadScript;
package/dist/types.d.ts CHANGED
@@ -5,9 +5,17 @@ export type LoadScriptOptions = {
5
5
  forceScriptReload?: boolean;
6
6
  integrity?: string;
7
7
  src: string;
8
+ timeout?: number;
8
9
  type?: string;
9
10
  id?: string;
10
11
  };
12
+ export type AssetLoadFailureKind = "error" | "abort" | "timeout";
13
+ export type AssetLoadError = Error & {
14
+ src: string;
15
+ failureKind: AssetLoadFailureKind;
16
+ timing: number;
17
+ onLine: boolean;
18
+ };
11
19
  export type LoadStylesheetOptions = {
12
20
  href: string;
13
21
  container?: HTMLElement;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@braintree/asset-loader",
3
- "version": "2.0.4",
3
+ "version": "2.2.0",
4
4
  "description": "A module to load frontend assets.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -15,7 +15,9 @@
15
15
  "build": "tsc --declaration",
16
16
  "lint": "eslint --ext js,ts .",
17
17
  "posttest": "npm run lint",
18
- "test": "jest"
18
+ "test": "jest",
19
+ "prepare": "husky",
20
+ "commit": "cz"
19
21
  },
20
22
  "repository": {
21
23
  "type": "git",
@@ -29,12 +31,17 @@
29
31
  },
30
32
  "homepage": "https://github.com/braintree/asset-loader#readme",
31
33
  "devDependencies": {
34
+ "@commitlint/cli": "^20.5.0",
35
+ "@commitlint/config-conventional": "^20.5.0",
32
36
  "@types/jest": "^30.0.0",
33
37
  "@types/promise-polyfill": "^6.0.6",
34
38
  "@typescript-eslint/eslint-plugin": "^5.62.0",
39
+ "commitizen": "^4.3.1",
40
+ "cz-customizable": "^7.5.4",
35
41
  "eslint": "^8.57.1",
36
42
  "eslint-config-braintree": "^6.0.1",
37
43
  "eslint-plugin-prettier": "^5.5.4",
44
+ "husky": "^9.1.7",
38
45
  "jest": "^30.2.0",
39
46
  "jest-environment-jsdom": "^30.2.0",
40
47
  "prettier": "^3.7.4",
@@ -51,6 +58,24 @@
51
58
  "tsconfig": "src/__tests__/tsconfig.test.json"
52
59
  }
53
60
  }
61
+ },
62
+ "collectCoverage": true,
63
+ "collectCoverageFrom": [
64
+ "src/**/*.ts",
65
+ "!src/__tests__/**"
66
+ ],
67
+ "coverageThreshold": {
68
+ "global": {
69
+ "lines": 80,
70
+ "statements": 80,
71
+ "branches": 80,
72
+ "functions": 80
73
+ }
74
+ }
75
+ },
76
+ "config": {
77
+ "commitizen": {
78
+ "path": "./node_modules/cz-customizable"
54
79
  }
55
80
  }
56
81
  }