-
Notifications
You must be signed in to change notification settings - Fork 269
Expand file tree
/
Copy pathcache.js
More file actions
419 lines (363 loc) · 12 KB
/
cache.js
File metadata and controls
419 lines (363 loc) · 12 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*******************************************************************************
Highcharts Export Server
Copyright (c) 2016-2024, Highsoft
Licenced under the MIT licence.
Additionally a valid Highcharts license is required for use.
See LICENSE file in root for details.
*******************************************************************************/
// The cache manager manages the Highcharts library and its dependencies.
// The cache itself is stored in .cache, and is checked by the config system
// before starting the service
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import { isAbsolute, join } from 'path';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { getOptions } from './config.js';
import { envs } from './envs.js';
import { fetch } from './fetch.js';
import { log } from './logger.js';
import { __dirname } from './utils.js';
import ExportError from './errors/ExportError.js';
const cache = {
cdnURL: 'https://code.highcharts.com/',
activeManifest: {},
sources: '',
hcVersion: ''
};
/**
* Extracts and caches the Highcharts version from the sources string.
*
* @returns {string} The extracted Highcharts version.
*/
export const extractVersion = (cache) => {
return cache.sources
.substring(0, cache.sources.indexOf('*/'))
.replace('/*', '')
.replace('*/', '')
.replace(/\n/g, '')
.trim();
};
/**
* Extracts the Highcharts module name based on the scriptPath.
*/
export const extractModuleName = (scriptPath) => {
return scriptPath.replace(
/(.*)\/|(.*)modules\/|stock\/(.*)indicators\/|maps\/(.*)modules\//gi,
''
);
};
/**
* Saves the provided configuration and fetched modules to the cache manifest
* file.
*
* @param {object} config - Highcharts-related configuration object.
* @param {object} fetchedModules - An object that contains mapped names of
* fetched Highcharts modules to use.
*
* @throws {ExportError} Throws an ExportError if an error occurs while writing
* the cache manifest.
*/
export const saveConfigToManifest = async (config, fetchedModules) => {
const newManifest = {
version: config.version,
modules: fetchedModules || {}
};
// Update cache object with the current modules
cache.activeManifest = newManifest;
log(3, '[cache] Writing a new manifest.');
try {
writeFileSync(
join(getCachePath(), 'manifest.json'),
JSON.stringify(newManifest),
'utf8'
);
} catch (error) {
throw new ExportError('[cache] Error writing the cache manifest.').setError(
error
);
}
};
/**
* Fetches a single script and updates the fetchedModules accordingly.
*
* @param {string} script - A path to script to get.
* @param {Object} requestOptions - Additional options for the proxy agent
* to use for a request.
* @param {Object} fetchedModules - An object which tracks which Highcharts
* modules have been fetched.
* @param {boolean} shouldThrowError - A flag to indicate if the error should be
* thrown. This should be used only for the core scripts.
*
* @returns {Promise<string>} A Promise resolving to the text representation
* of the fetched script.
*
* @throws {ExportError} Throws an ExportError if there is a problem with
* fetching the script.
*/
export const fetchAndProcessScript = async (
script,
requestOptions,
fetchedModules,
shouldThrowError = false
) => {
// Get rid of the .js from the custom strings
if (script.endsWith('.js')) {
script = script.substring(0, script.length - 3);
}
log(4, `[cache] Fetching script - ${script}.js`);
// Fetch the script
const response = await fetch(`${script}.js`, requestOptions);
// If OK, return its text representation
if (response.statusCode === 200 && typeof response.text == 'string') {
if (fetchedModules) {
const moduleName = extractModuleName(script);
fetchedModules[moduleName] = 1;
}
return response.text;
}
if (shouldThrowError) {
throw new ExportError(
`Could not fetch the ${script}.js. The script might not exist in the requested version (status code: ${response.statusCode}).`
).setError(response);
} else {
log(
2,
`[cache] Could not fetch the ${script}.js. The script might not exist in the requested version.`
);
}
return '';
};
/**
* Fetches Highcharts scripts and customScripts from the given CDNs.
*
* @param {string} coreScripts - Array of Highcharts core scripts to fetch.
* @param {string} moduleScripts - Array of Highcharts modules to fetch.
* @param {string} customScripts - Array of custom script paths to fetch
* (full URLs).
* @param {object} proxyOptions - Options for the proxy agent to use for
* a request.
* @param {object} fetchedModules - An object which tracks which Highcharts
* modules have been fetched.
*
* @returns {Promise<string>} The fetched scripts content joined.
*/
export const fetchScripts = async (
coreScripts,
moduleScripts,
customScripts,
proxyOptions,
fetchedModules
) => {
// Configure proxy if exists
let proxyAgent;
const proxyHost = proxyOptions.host;
const proxyPort = proxyOptions.port;
// Try to create a Proxy Agent
if (proxyHost && proxyPort) {
try {
proxyAgent = new HttpsProxyAgent({
host: proxyHost,
port: proxyPort
});
} catch (error) {
throw new ExportError('[cache] Could not create a Proxy Agent.').setError(
error
);
}
}
// If exists, add proxy agent to request options
const requestOptions = proxyAgent
? {
agent: proxyAgent,
timeout: envs.SERVER_PROXY_TIMEOUT
}
: {};
const allFetchPromises = [
...coreScripts.map((script) =>
fetchAndProcessScript(`${script}`, requestOptions, fetchedModules, true)
),
...moduleScripts.map((script) =>
fetchAndProcessScript(`${script}`, requestOptions, fetchedModules)
),
...customScripts.map((script) =>
fetchAndProcessScript(`${script}`, requestOptions)
)
];
const fetchedScripts = await Promise.all(allFetchPromises);
return fetchedScripts.join(';\n');
};
/**
* Updates the local cache with Highcharts scripts and their versions.
*
* @param {Object} options - Object containing all options.
* @param {string} sourcePath - The path to the source file in the cache.
*
* @returns {Promise<object>} A Promise resolving to an object representing
* the fetched modules.
*
* @throws {ExportError} Throws an ExportError if there is an issue updating
* the local Highcharts cache.
*/
export const updateCache = async (
highchartsOptions,
proxyOptions,
sourcePath
) => {
const version = highchartsOptions.version;
const hcVersion = version === 'latest' || !version ? '' : `${version}/`;
const cdnURL = highchartsOptions.cdnURL || cache.cdnURL;
log(
3,
`[cache] Updating cache version to Highcharts: ${hcVersion || 'latest'}.`
);
const fetchedModules = {};
try {
cache.sources = await fetchScripts(
[
...highchartsOptions.coreScripts.map((c) => `${cdnURL}${hcVersion}${c}`)
],
[
...highchartsOptions.moduleScripts.map((m) =>
m === 'map'
? `${cdnURL}maps/${hcVersion}modules/${m}`
: `${cdnURL}${hcVersion}modules/${m}`
),
...highchartsOptions.indicatorScripts.map(
(i) => `${cdnURL}stock/${hcVersion}indicators/${i}`
)
],
highchartsOptions.customScripts,
proxyOptions,
fetchedModules
);
cache.hcVersion = extractVersion(cache);
// Save the fetched modules into caches' source JSON
writeFileSync(sourcePath, cache.sources);
return fetchedModules;
} catch (error) {
throw new ExportError(
'[cache] Unable to update the local Highcharts cache.'
).setError(error);
}
};
/**
* Updates the Highcharts version in the applied configuration and checks
* the cache for the new version.
*
* @param {string} newVersion - The new Highcharts version to be applied.
*
* @returns {Promise<(object|boolean)>} A Promise resolving to the updated
* configuration with the new version, or false if no applied configuration
* exists.
*/
export const updateVersion = async (newVersion) => {
const options = getOptions();
if (options?.highcharts) {
options.highcharts.version = newVersion;
}
await checkAndUpdateCache(options);
};
/**
* Checks the cache for Highcharts dependencies, updates the cache if needed,
* and loads the sources.
*
* @param {Object} options - Object containing all options.
*
* @returns {Promise<void>} A Promise that resolves once the cache is checked
* and updated.
*
* @throws {ExportError} Throws an ExportError if there is an issue updating
* or reading the cache.
*/
export const checkAndUpdateCache = async (options) => {
const { highcharts, server } = options;
let fetchedModules;
// Get the cache path
const cachePath = getCachePath();
// Prepare paths to manifest and sources from the .cache folder
const manifestPath = join(cachePath, 'manifest.json');
const sourcePath = join(cachePath, 'sources.js');
// Create the cache destination if it doesn't exist already
!existsSync(cachePath) && mkdirSync(cachePath, { recursive: true });
// Fetch all the scripts either if manifest.json does not exist
// or if the forceFetch option is enabled
if (!existsSync(manifestPath) || highcharts.forceFetch) {
log(3, '[cache] Fetching and caching Highcharts dependencies.');
fetchedModules = await updateCache(highcharts, server.proxy, sourcePath);
} else {
let requestUpdate = false;
// Read the manifest JSON
const manifest = JSON.parse(readFileSync(manifestPath));
// Check if the modules is an array, if so, we rewrite it to a map to make
// it easier to resolve modules.
if (manifest.modules && Array.isArray(manifest.modules)) {
const moduleMap = {};
manifest.modules.forEach((m) => (moduleMap[m] = 1));
manifest.modules = moduleMap;
}
const { coreScripts, moduleScripts, indicatorScripts } = highcharts;
const numberOfModules =
coreScripts.length + moduleScripts.length + indicatorScripts.length;
// Compare the loaded highcharts config with the contents in cache.
// If there are changes, fetch requested modules and products,
// and bake them into a giant blob. Save the blob.
if (manifest.version !== highcharts.version) {
log(
2,
'[cache] A Highcharts version mismatch in the cache, need to re-fetch.'
);
requestUpdate = true;
} else if (Object.keys(manifest.modules || {}).length !== numberOfModules) {
log(
2,
'[cache] The cache and the requested modules do not match, need to re-fetch.'
);
requestUpdate = true;
} else {
// Check each module, if anything is missing refetch everything
requestUpdate = (moduleScripts || []).some((moduleName) => {
if (!manifest.modules[moduleName]) {
log(
2,
`[cache] The ${moduleName} is missing in the cache, need to re-fetch.`
);
return true;
}
});
}
if (requestUpdate) {
fetchedModules = await updateCache(highcharts, server.proxy, sourcePath);
} else {
log(3, '[cache] Dependency cache is up to date, proceeding.');
// Load the sources
cache.sources = readFileSync(sourcePath, 'utf8');
// Get current modules map
fetchedModules = manifest.modules;
cache.hcVersion = extractVersion(cache);
}
}
// Finally, save the new manifest, which is basically our current config
// in a slightly different format
await saveConfigToManifest(highcharts, fetchedModules);
};
/**
* Returns the path to the cache folder.
*
* @returns {string} The path to the cache folder.
*/
export const getCachePath = () => {
const cachePathOption = getOptions().highcharts.cachePath;
return isAbsolute(cachePathOption)
? cachePathOption
: join(__dirname, cachePathOption);
};
export const getCache = () => cache;
export const highcharts = () => cache.sources;
export const version = () => cache.hcVersion;
export default {
checkAndUpdateCache,
getCachePath,
updateVersion,
getCache,
highcharts,
version
};