forked from adobe/adobe-io-website
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev.mjs
More file actions
174 lines (149 loc) · 5.39 KB
/
dev.mjs
File metadata and controls
174 lines (149 loc) · 5.39 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
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import cors from 'cors';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = process.env.DEV_PORT || 3000;
const corsOptions = {
origin: 'http://127.0.0.1:3000/',
credentials: true,
};
const app = express();
app.use(cors(corsOptions));
let devsitePaths = {};
// TODO: should this switch between stage/prod version of this file or always pull from stage?
const devsitePathsUrl = `https://main--adp-devsite-stage--adobedocs.aem.page/franklin_assets/devsitepaths.json`;
// Function to fetch devsite paths
async function fetchDevsitePaths() {
try {
console.log(`Fetching devsite paths from: ${devsitePathsUrl}`);
const response = await fetch(devsitePathsUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
devsitePaths = data?.data || {};
console.log(`Successfully loaded ${Object.keys(devsitePaths).length} devsite paths`);
return devsitePaths;
} catch (error) {
console.error(`Failed to fetch devsite paths: ${error.message}`);
// Set empty object as fallback so server can still run
devsitePaths = {};
return devsitePaths;
}
}
// Initialize devsite paths when server starts
let isInitialized = false;
// Middleware to ensure devsite paths are loaded
app.use(async (req, res, next) => {
if (!isInitialized) {
await fetchDevsitePaths();
isInitialized = true;
}
next();
});
app.use(async (req, res) => {
// if path prefix matches something in the devsitePaths
// route request to the connector on port 3002
// otherwise serve from aem-cli on port 3001
const suffixSplit = req.url.split('/');
let suffixSplitRest = suffixSplit.slice(1);
let devsitePathMatch;
let devsitePathMatchFlag = false;
// find match based on level 3, 2, or 1 transclusion rule
// if match found in higher level don't do lower level
if (suffixSplit.length > 2) {
devsitePathMatch = devsitePaths.find((element) => element.pathPrefix === `/${suffixSplit[1]}/${suffixSplit[2]}/${suffixSplit[3]}`);
devsitePathMatchFlag = !!devsitePathMatch;
if (devsitePathMatchFlag) {
console.log('rest 3');
suffixSplitRest = suffixSplit.slice(4);
}
}
if (suffixSplit.length > 1 && !devsitePathMatchFlag) {
devsitePathMatch = devsitePaths.find((element) => element.pathPrefix === `/${suffixSplit[1]}/${suffixSplit[2]}`);
devsitePathMatchFlag = !!devsitePathMatch;
if (devsitePathMatchFlag) {
console.log('rest 2');
suffixSplitRest = suffixSplit.slice(3);
}
}
if (suffixSplit.length > 0 && !devsitePathMatchFlag) {
devsitePathMatch = devsitePaths.find((element) => element.pathPrefix === `/${suffixSplit[1]}`);
devsitePathMatchFlag = !!devsitePathMatch;
if (devsitePathMatchFlag) {
console.log('rest 1');
suffixSplitRest = suffixSplit.slice(2);
}
}
let upstreamUrl;
let source;
if (devsitePathMatchFlag && devsitePathMatch !== 'undefined') {
source = 'docs';
upstreamUrl = `http://127.0.0.1:3002${req.path}`;
} else {
source = 'aem';
upstreamUrl = `http://127.0.0.1:3001${req.path}`;
}
console.log(`Fetching upstream url: ${upstreamUrl}`);
// For font files, request uncompressed data to avoid decoding issues
const fetchOptions = {};
if (req.path.includes('.otf') || req.path.includes('.woff2') || req.path.includes('.ttf')) {
fetchOptions.headers = {
'Accept-Encoding': 'identity'
};
}
const resp = await fetch(upstreamUrl, fetchOptions);
let body;
const contentType = resp.headers.get('content-type') || '';
const isFont = contentType.includes('font') || contentType.includes('woff2') || contentType.includes('otf');
// Handle headers differently for fonts vs other files
const headers = new Map();
if (isFont) {
// For fonts, only copy essential headers and ensure no compression
headers.set('content-type', contentType);
headers.set('content-length', resp.headers.get('content-length') || '');
// Explicitly remove any compression headers
headers.delete('content-encoding');
} else {
// For non-fonts, copy all headers
resp.headers.forEach((value, key) => headers.set(key, value));
}
if (source === 'docs' && contentType.includes('text/html')) {
body = await resp.text();
// inject the head.html
const [pre, post] = body.split('</head>');
body = `${pre}
<link rel="stylesheet" href="/hlx_statics/styles/styles.css"/>
<script src="/hlx_statics/scripts/scripts.js" type="module"></script>
</head>
${post}`;
} else {
// Handle binary files (like fonts) properly
if (isFont) {
// For font files, preserve content-encoding and get binary data
body = await resp.arrayBuffer();
} else {
// For text files, get as text and remove content-encoding if needed
body = await resp.text();
headers.delete('content-encoding');
}
}
res.status(resp.status);
// Set headers properly for Express
headers.forEach((value, key) => {
res.set(key, value);
});
if (isFont) {
res.send(Buffer.from(body));
} else {
res.send(body);
}
});
// Start server and initialize devsite paths
app.listen(PORT, async () => {
console.debug(`Website dev server is running on port ${PORT}`);
// Initialize devsite paths after server starts
await fetchDevsitePaths();
isInitialized = true;
});