-
Notifications
You must be signed in to change notification settings - Fork 0
/
Builderio-CF-Worker.js
68 lines (59 loc) · 2.6 KB
/
Builderio-CF-Worker.js
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
export default {
async fetch(request, env, ctx) {
// Configurable Values
const BUILDERIO_USE_STATIC_URL = false;
const BUILDERIO_STATIC_URL = '/builderio-page'
const BUILDERIO_API_URL = 'https://cdn.builder.io/api/v1/html';
const BUILDER_IO_MODEL_TYPE = 'page'
const PLACEHOLDER_TOKEN = '{{builderio}}'
const REPLACE_PLACEHOLDER_INSTANCE_POSITION_INDEX = 1
const REPLACE_ALL_PLACEHOLDER_INSTANCES = false
const REPLACE_IGNORED_PLACEHOLDERS_WITH_CONTENT = ''
const SHOW_ERROR_WARNING = true
const WARNING_MESSAGE_CONTENT = '<div>Error loading content</div>'
const url = new URL(request.url)
const originResponse = await fetch(request)
let originResponseHtml = await originResponse.text()
if (originResponseHtml.includes(PLACEHOLDER_TOKEN)) {
let builderApiUrl = BUILDERIO_USE_STATIC_URL ? BUILDERIO_STATIC_URL : url.pathname;
builderApiUrl = `${BUILDERIO_API_URL}/${BUILDER_IO_MODEL_TYPE}?apiKey=${env.BUILDER_API_KEY}&url=${builderApiUrl}`
const builderResponse = await fetch(builderApiUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
})
const builderData = await builderResponse.json();
const error = SHOW_ERROR_WARNING ? WARNING_MESSAGE_CONTENT : ''
const builderHtml = builderData?.data?.html || error
const replaceWidgetInstances = (html, widgetHtml, positionIndex, replaceAll) => {
if (replaceAll) {
const placeholderRegex = new RegExp(PLACEHOLDER_TOKEN.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
return html.replace(placeholderRegex, widgetHtml);
} else {
let matchCount = 0;
const placeholderRegex = new RegExp(PLACEHOLDER_TOKEN.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
return html.replace(placeholderRegex, (match) => {
matchCount++;
if (matchCount === positionIndex) {
return widgetHtml;
}
return match;
});
}
};
originResponseHtml = replaceWidgetInstances(originResponseHtml,
builderHtml,
REPLACE_PLACEHOLDER_INSTANCE_POSITION_INDEX,
REPLACE_ALL_PLACEHOLDER_INSTANCES
);
if (REPLACE_IGNORED_PLACEHOLDERS_WITH_CONTENT) {
const placeholderRegex = new RegExp(PLACEHOLDER_TOKEN, 'g');
originResponseHtml = originResponseHtml.replace(placeholderRegex,REPLACE_IGNORED_PLACEHOLDERS_WITH_CONTENT);
}
}
return new Response(originResponseHtml, {
headers: { 'Content-Type': 'text/html; charset=UTF-8' },
});
},
}