-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathDynamicResourceLoader.ts
More file actions
144 lines (125 loc) · 4.22 KB
/
DynamicResourceLoader.ts
File metadata and controls
144 lines (125 loc) · 4.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import { EnumOutOfRangeArgumentError } from 'src/shared/errors/common';
import {
BUILD_ORIGIN,
BUILD_TYPE,
IS_HTTPS,
NO_DEV_PORT,
VERSION,
} from 'src/shared/utils/env';
export const ResourceType = {
_Stylesheet: 0,
_Script: 1,
} as const;
export type ResourceTypeValue =
(typeof ResourceType)[keyof typeof ResourceType];
export const ResourceLoadState = {
/**
* The remote resource was fetched and loaded successfully.
*/
_Loaded: 0,
/**
* The remote resource failed to be loaded (e.g. not found or network offline).
*/
_Failed: 1,
} as const;
export type ResourceLoadStateValue =
(typeof ResourceLoadState)[keyof typeof ResourceLoadState];
interface DynamicResourceLoaderCache {
[key: string]: Promise<ResourceLoadStateValue>;
}
const getOneSignalCssFileName = () => {
const baseFileName = 'OneSignalSDK.page.styles.css';
// using if statements to have better dead code elimination
if (BUILD_TYPE === 'development') return `Dev-${baseFileName}`;
if (BUILD_TYPE === 'staging') return `Staging-${baseFileName}`;
if (BUILD_TYPE === 'production') return baseFileName;
};
const RESOURCE_HTTP_PORT = 4000;
const RESOURCE_HTTPS_PORT = 4001;
const getOneSignalResourceUrlPath = () => {
const protocol = IS_HTTPS ? 'https' : 'http';
const port = IS_HTTPS ? RESOURCE_HTTPS_PORT : RESOURCE_HTTP_PORT;
let origin: string;
// using if statements to have better dead code elimination
if (BUILD_TYPE === 'development') {
origin = NO_DEV_PORT
? `${protocol}://${BUILD_ORIGIN}`
: `${protocol}://${BUILD_ORIGIN}:${port}`;
} else if (BUILD_TYPE === 'staging') {
origin = `https://${BUILD_ORIGIN}`;
} else if (BUILD_TYPE === 'production') {
origin = 'https://onesignal.com';
} else {
throw EnumOutOfRangeArgumentError('buildEnv');
}
return new URL(`${origin}/sdks/web/v16`);
};
export class DynamicResourceLoader {
private _cache: DynamicResourceLoaderCache;
constructor() {
this._cache = {};
}
_getCache(): DynamicResourceLoaderCache {
// Cache is private; return a cloned copy just for testing
return { ...this._cache };
}
async _loadSdkStylesheet(): Promise<ResourceLoadStateValue> {
if (import.meta.env.MODE === 'development')
return ResourceLoadState._Loaded;
const pathForEnv = getOneSignalResourceUrlPath();
const cssFileForEnv = getOneSignalCssFileName();
return this._loadIfNew(
ResourceType._Stylesheet,
new URL(`${pathForEnv}/${cssFileForEnv}?v=${VERSION}`),
);
}
/**
* Attempts to load a resource by adding it to the document's <head>.
* Caches any previous load attempt's result and does not retry loading a previous resource.
*/
async _loadIfNew(
type: ResourceTypeValue,
url: URL,
): Promise<ResourceLoadStateValue> {
// Load for first time
if (!this._cache[url.toString()]) {
this._cache[url.toString()] = DynamicResourceLoader._load(type, url);
}
// Resource is loading; multiple calls can be made to this while the same resource is loading
// Waiting on the Promise is what we want here
return this._cache[url.toString()];
}
/**
* Attempts to load a resource by adding it to the document's <head>.
* Each call creates a new DOM element and fetch attempt.
*/
static async _load(
type: ResourceTypeValue,
url: URL,
): Promise<ResourceLoadStateValue> {
try {
let domElement: HTMLElement;
await new Promise((resolve, reject) => {
switch (type) {
case ResourceType._Script:
domElement = document.createElement('script');
domElement.setAttribute('type', 'text/javascript');
domElement.setAttribute('async', 'async');
domElement.setAttribute('src', url.toString());
break;
case ResourceType._Stylesheet:
domElement = document.createElement('link');
domElement.setAttribute('rel', 'stylesheet');
domElement.setAttribute('href', url.toString());
break;
}
domElement.onerror = reject;
domElement.onload = resolve;
document.querySelector('head')?.appendChild(domElement);
});
return ResourceLoadState._Loaded;
} catch {
return ResourceLoadState._Failed;
}
}
}