-
Notifications
You must be signed in to change notification settings - Fork 2
/
plugins.ts
69 lines (56 loc) · 1.64 KB
/
plugins.ts
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
import path from 'path'
export type Request = {
host: string
https: boolean
} & RelativeRequest
export type RelativeRequest = {
version: string
parameters?: {
repository: string
method: Method
tag: string
}
}
export enum Method {
'manifests',
'blobs',
}
export interface Plugin {
name: string
description?: string
requestPipe: RequestPipe
}
type RequestPipe = (req: Request) => Promise<Request | undefined>
const identityPlugin: Plugin = {
name: 'identity plugin',
description: 'this plugin does not alter anything',
requestPipe: async (req) => req,
}
/**
* Chains the functionality of two plugins into one.
*/
const combinePlugins = (p1: Plugin, p2: Plugin): Plugin => ({
name: `${p1.name}+${p2.name}`,
requestPipe: async (req) => {
const resultP1 = await p1.requestPipe(req)
// Abort the pipe when one plugin requested to drop the request
if (resultP1 === undefined) {
return undefined
}
return p2.requestPipe(resultP1)
},
})
export const loadPlugins: (pluginNames: string[], customPluginPaths: string[]) => Plugin = (
pluginNames,
customPluginPaths
) => {
const pluginPaths = pluginNames
.map((name) => `./plugins/${name}`)
.concat(customPluginPaths.map((customPluginPath) => path.resolve(customPluginPath)))
const plugins: Plugin[] = pluginPaths.map((pluginPath) => <Plugin>require(pluginPath).default)
plugins.forEach(({ name, description }) =>
console.log(`Loading plugin "${name}"`, description ? `: ${description}` : '')
)
console.log() // Insert empty line for better log formatting
return (plugins.length ? plugins : [identityPlugin]).reduce(combinePlugins)
}