-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathsearch.js
More file actions
80 lines (68 loc) · 2.33 KB
/
search.js
File metadata and controls
80 lines (68 loc) · 2.33 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
// Import Third-party Dependencies
import * as Scanner from "@nodesecure/scanner";
// Import Internal Dependencies
import { logger } from "../logger.js";
import { appCache } from "../cache.js";
export async function search(ws, pkg) {
logger.info(`[ws|search](pkg: ${pkg})`);
const cache = await appCache.getPayloadOrNull(pkg);
if (cache) {
logger.info(`[ws|search](payload: ${pkg} found in cache)`);
const cacheList = await appCache.payloadsList();
if (cacheList.lru.includes(pkg)) {
logger.info(`[ws|search](payload: ${pkg} is already in the LRU)`);
const updatedList = {
...cacheList,
current: pkg,
lastUsed: { ...cacheList.lastUsed, [pkg]: Date.now() }
};
await appCache.updatePayloadsList(updatedList);
ws.send(JSON.stringify(cache));
return;
}
const { lru, older, lastUsed, root } = await appCache.removeLastLRU();
const updatedList = {
lru: [...new Set([...lru, pkg])],
current: pkg,
older: older.filter((pckg) => pckg !== pkg),
lastUsed: { ...lastUsed, [pkg]: Date.now() },
root
};
await appCache.updatePayloadsList(updatedList);
ws.send(JSON.stringify(cache));
ws.send(JSON.stringify({
status: "RELOAD",
...updatedList
}));
return;
}
// at this point we don't have the payload in cache so we have to scan it.
logger.info(`[ws|search](scan ${pkg} in progress)`);
ws.send(JSON.stringify({ status: "SCAN", pkg }));
const payload = await Scanner.from(pkg, { maxDepth: 4 });
const name = payload.rootDependencyName;
const version = Object.keys(payload.dependencies[name].versions)[0];
{
// save the payload in cache
const pkg = `${name}@${version}`;
logger.info(`[ws|search](scan ${pkg} done|cache: updated)`);
// update the payloads list
const { lru, older, lastUsed, root } = await appCache.removeLastLRU();
lru.push(pkg);
appCache.updatePayload(pkg, payload);
const updatedList = {
lru: [...new Set(lru)],
older,
lastUsed: { ...lastUsed, [pkg]: Date.now() },
current: pkg,
root
};
await appCache.updatePayloadsList(updatedList);
ws.send(JSON.stringify(payload));
ws.send(JSON.stringify({
status: "RELOAD",
...updatedList
}));
logger.info(`[ws|search](data sent to client|cache: updated)`);
}
}