-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathserver.ts
More file actions
296 lines (263 loc) · 9.2 KB
/
server.ts
File metadata and controls
296 lines (263 loc) · 9.2 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
import { MCEventListener } from '@managed-components/types'
import express, { Request, Response, RequestHandler } from 'express'
import { IncomingMessage, ClientRequest } from 'http'
import {
createProxyMiddleware,
responseInterceptor,
} from 'http-proxy-middleware'
import * as path from 'path'
import { Client, ClientGeneric } from './client'
import { ManagerGeneric, MCEvent } from './manager'
import { getConfig } from './config'
import { PERMISSIONS } from './constants'
import { StaticServer } from './static-server'
import _locreq from 'locreq'
const locreq = _locreq(__dirname)
const DEFAULT_TARGET = 'http://localhost:8000'
if (process.env.NODE_ENV === 'production') {
process.on('unhandledRejection', (reason: Error) => {
console.log('Unhandled Rejection at:', reason.stack || reason)
})
}
type BasicServerConfig = {
configPath?: string
componentsFolderPath?: string
url?: string
}
type CustomComponentServerConfig = BasicServerConfig & {
customComponentPath?: string
customComponentSettings?: Record<string, unknown>
}
type ServerConfig = BasicServerConfig | CustomComponentServerConfig
export async function startServerFromConfig({
configPath,
componentsFolderPath,
url,
...args
}: ServerConfig) {
const config = getConfig(configPath)
let componentsPath = ''
if (componentsFolderPath) {
componentsPath = path.resolve(componentsFolderPath)
} else {
console.log('Components folder path not provided')
}
const { hostname, port, trackPath, components } = config
if ('customComponentPath' in args && args.customComponentPath) {
console.log(
`⚠️ Custom component ${args.customComponentPath} will run with all permissions enabled, use webcm.config.ts to change what permissions it gets`
)
components.push({
path: path.resolve(args.customComponentPath),
permissions: Object.values(PERMISSIONS), // use all permissions, it's just for testing
settings: args.customComponentSettings || {},
})
}
if (url) {
if (!(url.startsWith('http://') || url.startsWith('https://'))) {
url = 'http://' + url
}
config.target = url
} else if (!config.target) {
const server = new StaticServer(8000)
server.start()
console.log('Started a demo static server at localhost:8000')
config.target = DEFAULT_TARGET
}
const manager = new ManagerGeneric({
components,
trackPath,
componentsFolderPath: componentsPath,
})
await manager.init()
const getDefaultPayload = () => ({
pageVars: [],
fetch: [],
execute: [],
return: undefined,
})
const handleClientCreated = (
req: Request,
_: Response,
clientGeneric: ClientGeneric
) => {
const cookieName = 'webcm_clientcreated'
const eventName = 'clientcreated'
let clientAlreadyCreated = clientGeneric.cookies.get(cookieName) || ''
if (!manager.listeners[eventName]) return
for (const componentName of Object.keys(manager.listeners[eventName])) {
if (clientAlreadyCreated.split(',')?.includes(componentName)) continue
const event = new MCEvent(eventName, req)
event.client = new Client(componentName as string, clientGeneric)
clientAlreadyCreated = Array.from(
new Set([...clientAlreadyCreated.split(','), componentName])
).join(',')
clientGeneric.set(cookieName, clientAlreadyCreated)
manager.listeners[eventName][componentName]?.forEach(
(fn: MCEventListener) => fn(event)
)
}
}
const handleEvent = async (
eventType: string,
req: Request,
res: Response
) => {
res.payload = getDefaultPayload()
const clientGeneric = new ClientGeneric(req, res, manager, config)
handleClientCreated(req, res, clientGeneric)
if (manager.listeners[eventType]) {
// slightly alter ecommerce payload
if (eventType === 'ecommerce') {
req.body.payload.ecommerce = { ...req.body.payload.data }
delete req.body.payload.data
}
const event = new MCEvent(eventType, req)
for (const componentName of Object.keys(manager.listeners[eventType])) {
event.client = new Client(componentName, clientGeneric)
await Promise.all(
manager.listeners[eventType][componentName].map(
(fn: MCEventListener) => fn(event)
)
)
}
res.payload.execute.push(manager.getInjectedScript(clientGeneric))
}
return res.end(JSON.stringify(res.payload))
}
const handleClientEvent = async (req: Request, res: Response) => {
res.payload = getDefaultPayload()
const event = new MCEvent(req.body.payload.event, req)
const clientGeneric = new ClientGeneric(req, res, manager, config)
const clientComponentNames = Object.entries(
clientGeneric.webcmPrefs.listeners
)
.filter(([, events]) => events.includes(req.body.payload.event))
.map(([componentName]) => componentName)
for (const component of clientComponentNames) {
event.client = new Client(component, clientGeneric)
try {
await manager.clientListeners[
req.body.payload.event + '__' + component
](event)
} catch {
console.error(
`Error dispatching ${req.body.payload.event} to ${component}: it isn't registered`
)
}
}
res.payload.execute.push(manager.getInjectedScript(clientGeneric))
res.end(JSON.stringify(res.payload))
}
// 'event', 'ecommerce' 'pageview', 'client' are the standard types
// 'remarketing', 'identify' or any other event type
const handleTrack: RequestHandler = (req, res) => {
const eventType = req.body.eventType
if (eventType === 'client') {
return handleClientEvent(req, res)
} else {
return handleEvent(eventType, req, res)
}
}
const handleRequest = (req: Request, clientGeneric: ClientGeneric) => {
if (!manager.listeners['request']) return
const requestEvent = new MCEvent('request', req)
for (const componentName of Object.keys(manager.listeners['request'])) {
requestEvent.client = new Client(componentName, clientGeneric)
manager.listeners['request'][componentName]?.forEach(
(fn: MCEventListener) => fn(requestEvent)
)
}
}
const app = express().use(express.json())
app.set('trust proxy', true)
// Mount WebCM endpoint
app.post(trackPath, handleTrack)
// Mount components endpoints
for (const route of Object.keys(manager.mappedEndpoints)) {
app.all(route, async (req, res) => {
const response = await manager.mappedEndpoints[route](req)
for (const [headerName, headerValue] of response.headers.entries()) {
res.set(headerName, headerValue)
}
res.status(response.status)
let isDone = false
const reader = response.body?.getReader()
while (!isDone && reader) {
const { value, done } = await reader.read()
if (value) res.write(Buffer.from(value))
isDone = done
}
res.end()
})
}
// Mount components proxied endpoints
for (const component of Object.keys(manager.proxiedEndpoints)) {
for (const [path, proxyTarget] of Object.entries(
manager.proxiedEndpoints[component]
)) {
const proxyEndpoint = '/webcm/' + component + path
app.all(proxyEndpoint + '*', async (req, res, next) => {
const proxy = createProxyMiddleware({
target: proxyTarget + req.path.replace(proxyEndpoint, ''),
ignorePath: true,
followRedirects: true,
changeOrigin: true,
})
proxy(req, res, next)
})
}
}
// Mount static files
for (const [filePath, fileTarget] of Object.entries(manager.staticFiles)) {
app.use(filePath, express.static(path.join(componentsPath, fileTarget)))
}
// Listen to all normal requests
app.use('**', (req, res, next) => {
res.payload = getDefaultPayload()
const clientGeneric = new ClientGeneric(req, res, manager, config)
const proxySettings = {
target: config.target,
changeOrigin: true,
selfHandleResponse: true,
onProxyReq: (
_proxyReq: ClientRequest,
req: IncomingMessage,
_res: Response
) => {
handleRequest(req as Request, clientGeneric)
},
onProxyRes: responseInterceptor(
async (responseBuffer, _proxyRes, proxyReq, _res) => {
if (proxyReq.headers['accept']?.toLowerCase().includes('text/html')) {
let response_str = responseBuffer.toString('utf8') as string
response_str = await manager.processEmbeds(
clientGeneric,
response_str
)
response_str = await manager.processWidgets(response_str)
return response_str.replace(
'<head>',
`<head><script>${manager.getInjectedScript(
clientGeneric
)};webcm._processServerResponse(${JSON.stringify(
res.payload
)})</script>`
)
}
return responseBuffer
}
),
}
const proxy = createProxyMiddleware(proxySettings)
proxy(req, res, next)
})
console.info(
'\nWebCM, version',
process.env.npm_package_version || locreq('package.json').version
)
app.listen(port, hostname)
console.info(
`\n🚀 WebCM is now proxying ${config.target} at http://${hostname}:${port}\n\n`
)
}