blob: bcbaad8d8e0aed7a7e4cff78d1e1c3f4b6cdecbe [file] [log] [blame]
Jack Franklin0155f7d2021-03-02 09:11:22 +00001// Copyright 2021 The Chromium Authors. All rights reserved.
Jack Franklin1557a1c2020-06-08 15:22:13 +01002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5const fs = require('fs');
6const http = require('http');
7const path = require('path');
8const parseURL = require('url').parse;
9const {argv} = require('yargs');
Jack Franklina3dd06a2021-03-18 10:47:16 +000010const {getTestRunnerConfigSetting} = require('../test/test_config_helpers.js');
Jack Franklin1557a1c2020-06-08 15:22:13 +010011
Jack Franklin1557a1c2020-06-08 15:22:13 +010012
Jack Franklinfe65bc62021-03-16 11:23:20 +000013const serverPort = parseInt(process.env.PORT, 10) || 8090;
Jack Franklin8742dc82021-02-26 09:17:59 +000014const target = argv.target || process.env.TARGET || 'Default';
15
16/**
17 * This configures the base of the URLs that are injected into each component
18 * doc example to load. By default it's /, so that we load /front_end/..., but
19 * this can be configured if you have a different file structure.
20 */
Jack Franklinfe65bc62021-03-16 11:23:20 +000021const sharedResourcesBase =
22 argv.sharedResourcesBase || getTestRunnerConfigSetting('component-server-shared-resources-path', '/');
Jack Franklin086ccd52020-11-27 11:00:14 +000023
24/**
Jack Franklin0155f7d2021-03-02 09:11:22 +000025 * The server assumes that examples live in
Jack Franklinfe65bc62021-03-16 11:23:20 +000026 * devtoolsRoot/out/Target/gen/front_end/component_docs, but if you need to add a
Jack Franklin0155f7d2021-03-02 09:11:22 +000027 * prefix you can pass this argument. Passing `foo` will redirect the server to
Jack Franklinfe65bc62021-03-16 11:23:20 +000028 * look in devtoolsRoot/out/Target/gen/foo/front_end/component_docs.
Jack Franklin0155f7d2021-03-02 09:11:22 +000029 */
Jack Franklinfe65bc62021-03-16 11:23:20 +000030const componentDocsBaseArg = argv.componentDocsBase || process.env.COMPONENT_DOCS_BASE ||
31 getTestRunnerConfigSetting('component-server-base-path', '');
Jack Franklin0155f7d2021-03-02 09:11:22 +000032
33/**
Jack Franklin086ccd52020-11-27 11:00:14 +000034 * When you run npm run components-server we run the script as is from scripts/,
35 * but when this server is run as part of a test suite it's run from
36 * out/Default/gen/scripts, so we have to do a bit of path mangling to figure
37 * out where we are.
38 */
Jack Franklin8742dc82021-02-26 09:17:59 +000039const isRunningInGen = __dirname.includes(path.join('out', path.sep, target));
Jack Franklinb36ad7e2020-12-07 10:20:52 +000040
Jack Franklin8742dc82021-02-26 09:17:59 +000041let pathToOutTargetDir = __dirname;
42/**
43 * If we are in the gen directory, we need to find the out/Default folder to use
44 * as our base to find files from. We could do this with path.join(x, '..',
45 * '..') until we get the right folder, but that's brittle. It's better to
46 * search up for out/Default to be robust to any folder structures.
47 */
48while (isRunningInGen && !pathToOutTargetDir.endsWith(`out${path.sep}${target}`)) {
49 pathToOutTargetDir = path.resolve(pathToOutTargetDir, '..');
50}
Jack Franklin0943df42021-02-26 11:12:13 +000051
52/* If we are not running in out/Default, we'll assume the script is running from the repo root, and navigate to {CWD}/out/Target */
Jack Franklin8742dc82021-02-26 09:17:59 +000053const pathToBuiltOutTargetDirectory =
Jack Franklin0943df42021-02-26 11:12:13 +000054 isRunningInGen ? pathToOutTargetDir : path.resolve(path.join(process.cwd(), 'out', target));
Jack Franklin8742dc82021-02-26 09:17:59 +000055
Jack Franklin90b66132021-01-05 11:33:43 +000056const devtoolsRootFolder = path.resolve(path.join(pathToBuiltOutTargetDirectory, 'gen'));
Jack Franklin0155f7d2021-03-02 09:11:22 +000057const componentDocsBaseFolder = path.join(devtoolsRootFolder, componentDocsBaseArg);
Jack Franklin1557a1c2020-06-08 15:22:13 +010058
Jack Franklin90b66132021-01-05 11:33:43 +000059if (!fs.existsSync(devtoolsRootFolder)) {
60 console.error(`ERROR: Generated front_end folder (${devtoolsRootFolder}) does not exist.`);
Jack Franklin1557a1c2020-06-08 15:22:13 +010061 console.log(
62 'The components server works from the built Ninja output; you may need to run Ninja to update your built DevTools.');
63 console.log('If you build to a target other than default, you need to pass --target=X as an argument');
64 process.exit(1);
65}
66
Jack Franklin086ccd52020-11-27 11:00:14 +000067const server = http.createServer(requestHandler);
68server.listen(serverPort);
69server.once('listening', () => {
70 if (process.send) {
71 process.send(serverPort);
72 }
73 console.log(`Started components server at http://localhost:${serverPort}\n`);
Jack Franklin0155f7d2021-03-02 09:11:22 +000074 console.log(`component_docs location: ${
75 path.relative(process.cwd(), path.join(componentDocsBaseFolder, 'front_end', 'component_docs'))}`);
Jack Franklin086ccd52020-11-27 11:00:14 +000076});
77
78server.once('error', error => {
79 if (process.send) {
80 process.send('ERROR');
81 }
82 throw error;
83});
Jack Franklin1557a1c2020-06-08 15:22:13 +010084
85function createComponentIndexFile(componentPath, componentExamples) {
Jack Franklin7a75e462021-01-08 16:17:13 +000086 const componentName = componentPath.replace('/front_end/component_docs/', '').replace(/_/g, ' ').replace('/', '');
Jack Franklin1557a1c2020-06-08 15:22:13 +010087 // clang-format off
88 return `<!DOCTYPE html>
89 <html>
90 <head>
91 <meta charset="UTF-8" />
92 <meta name="viewport" content="width=device-width" />
93 <title>DevTools component: ${componentName}</title>
94 <style>
95 h1 { text-transform: capitalize; }
96
97 .example {
98 padding: 5px;
99 margin: 10px;
100 }
Jack Franklin7a75e462021-01-08 16:17:13 +0000101
102 a:link,
103 a:visited {
104 color: blue;
105 text-decoration: underline;
106 }
107
108 a:hover {
109 text-decoration: none;
110 }
111 .example summary {
112 font-size: 20px;
113 }
114
115 .back-link {
116 padding-left: 5px;
117 font-size: 16px;
118 font-style: italic;
119 }
120
121 iframe { display: block; width: 100%; height: 400px; }
Jack Franklin1557a1c2020-06-08 15:22:13 +0100122 </style>
123 </head>
124 <body>
Jack Franklin7a75e462021-01-08 16:17:13 +0000125 <h1>
126 ${componentName}
127 <a class="back-link" href="/">Back to index</a>
128 </h1>
Jack Franklin1557a1c2020-06-08 15:22:13 +0100129 ${componentExamples.map(example => {
Jack Franklin90b66132021-01-05 11:33:43 +0000130 const fullPath = path.join(componentPath, example);
Jack Franklin7a75e462021-01-08 16:17:13 +0000131 return `<details class="example">
132 <summary><a href="${fullPath}">${example.replace('.html', '').replace(/-|_/g, ' ')}</a></summary>
Jack Franklin1557a1c2020-06-08 15:22:13 +0100133 <iframe src="${fullPath}"></iframe>
Jack Franklin7a75e462021-01-08 16:17:13 +0000134 </details>`;
Jack Franklin1557a1c2020-06-08 15:22:13 +0100135 }).join('\n')}
136 </body>
137 </html>`;
138 // clang-format on
139}
140
141function createServerIndexFile(componentNames) {
142 // clang-format off
143 return `<!DOCTYPE html>
144 <html>
145 <head>
146 <meta charset="UTF-8" />
147 <meta name="viewport" content="width=device-width" />
148 <title>DevTools components</title>
149 <style>
Jack Franklinb5997162020-11-25 17:28:51 +0000150 a:link, a:visited {
151 color: blue;
152 text-transform: capitalize;
153 text-decoration: none;
154 }
155 a:hover {
156 text-decoration: underline;
157 }
Jack Franklin1557a1c2020-06-08 15:22:13 +0100158 </style>
159 </head>
160 <body>
161 <h1>DevTools components</h1>
162 <ul>
163 ${componentNames.map(name => {
Jack Franklinb5997162020-11-25 17:28:51 +0000164 const niceName = name.replace(/_/g, ' ');
Jack Franklin90b66132021-01-05 11:33:43 +0000165 return `<li><a href='/front_end/component_docs/${name}'>${niceName}</a></li>`;
Jack Franklin1557a1c2020-06-08 15:22:13 +0100166 }).join('\n')}
167 </ul>
168 </body>
169 </html>`;
170 // clang-format on
171}
172
173async function getExamplesForPath(filePath) {
Jack Franklin0155f7d2021-03-02 09:11:22 +0000174 const componentDirectory = path.join(componentDocsBaseFolder, filePath);
Jack Franklinc1501222020-10-02 09:42:08 +0100175 const allFiles = await fs.promises.readdir(componentDirectory);
176 const htmlExampleFiles = allFiles.filter(file => {
177 return path.extname(file) === '.html';
178 });
Jack Franklin1557a1c2020-06-08 15:22:13 +0100179
Jack Franklinc1501222020-10-02 09:42:08 +0100180 return createComponentIndexFile(filePath, htmlExampleFiles);
Jack Franklin1557a1c2020-06-08 15:22:13 +0100181}
182
183function respondWithHtml(response, html) {
184 response.setHeader('Content-Type', 'text/html; charset=utf-8');
185 response.writeHead(200);
186 response.write(html, 'utf8');
187 response.end();
188}
189
190function send404(response, message) {
191 response.writeHead(404);
192 response.write(message, 'utf8');
193 response.end();
194}
195
Jack Franklin279564e2020-07-06 15:25:18 +0100196async function checkFileExists(filePath) {
197 try {
198 const errorsAccessingFile = await fs.promises.access(filePath, fs.constants.R_OK);
199 return !errorsAccessingFile;
200 } catch (e) {
201 return false;
202 }
203}
204
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100205/**
206 * In Devtools-Frontend we load images without a leading slash, e.g.
Tim van der Lippe88ba72d2021-03-04 14:54:14 +0000207 * var(--image-file-checker). This works within devtools, but breaks this component
Jack Franklin4738bc72020-09-17 09:51:24 +0100208 * server as the path ends up as /component_docs/my_component/Images/checker.png.
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100209 * So we check if the path ends in Images/*.* and if so, remove anything before
210 * it. Then it will be resolved correctly.
211 */
212function normalizeImagePathIfRequired(filePath) {
213 const imagePathRegex = /\/Images\/(\S+)\.(\w{3})/;
214 const match = imagePathRegex.exec(filePath);
215 if (!match) {
216 return filePath;
217 }
218
219 const [, imageName, imageExt] = match;
Jack Franklin90b66132021-01-05 11:33:43 +0000220 const normalizedPath = path.join('front_end', 'Images', `${imageName}.${imageExt}`);
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100221 return normalizedPath;
222}
223
Jack Franklin1557a1c2020-06-08 15:22:13 +0100224async function requestHandler(request, response) {
225 const filePath = parseURL(request.url).pathname;
Jack Franklin1557a1c2020-06-08 15:22:13 +0100226 if (filePath === '/favicon.ico') {
227 send404(response, '404, no favicon');
228 return;
229 }
230
231 if (filePath === '/' || filePath === '/index.html') {
Jack Franklin0155f7d2021-03-02 09:11:22 +0000232 const components = await fs.promises.readdir(path.join(componentDocsBaseFolder, 'front_end', 'component_docs'));
Jack Franklinb5997162020-11-25 17:28:51 +0000233 const html = createServerIndexFile(components.filter(filePath => {
Jack Franklin0155f7d2021-03-02 09:11:22 +0000234 const stats = fs.lstatSync(path.join(componentDocsBaseFolder, 'front_end', 'component_docs', filePath));
Jack Franklinb5997162020-11-25 17:28:51 +0000235 // Filter out some build config files (tsconfig, d.ts, etc), and just list the directories.
236 return stats.isDirectory();
237 }));
Jack Franklin1557a1c2020-06-08 15:22:13 +0100238 respondWithHtml(response, html);
Jack Franklin90b66132021-01-05 11:33:43 +0000239 } else if (filePath.startsWith('/front_end/component_docs') && path.extname(filePath) === '') {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100240 // This means it's a component path like /breadcrumbs.
241 const componentHtml = await getExamplesForPath(filePath);
242 respondWithHtml(response, componentHtml);
Jack Franklin36429002020-11-25 15:07:26 +0000243 return;
244 } else if (/component_docs\/(.+)\/(.+)\.html/.test(filePath)) {
245 /** This conditional checks if we are viewing an individual example's HTML
Jack Franklin90b66132021-01-05 11:33:43 +0000246 * file. e.g. localhost:8090/front_end/component_docs/data_grid/basic.html For each
Jack Franklin36429002020-11-25 15:07:26 +0000247 * example we inject themeColors.css into the page so all CSS variables
248 * that components use are available.
249 */
Jack Franklin8742dc82021-02-26 09:17:59 +0000250
Jack Franklin0155f7d2021-03-02 09:11:22 +0000251 /**
252 * We also let the user provide a different base path for any shared
253 * resources that we load. But if this is provided along with the
254 * componentDocsBaseArg, and the two are the same, we don't want to use the
255 * shared resources base, as it's part of the componentDocsBaseArg and
256 * therefore the URL is already correct.
257 *
258 * If we didn't get a componentDocsBaseArg or we did and it's different to
259 * the sharedResourcesBase, we use sharedResourcesBase.
260 */
261 const baseUrlForSharedResource =
262 componentDocsBaseArg && componentDocsBaseArg.endsWith(sharedResourcesBase) ? '/' : `/${sharedResourcesBase}`;
263 const fileContents = await fs.promises.readFile(path.join(componentDocsBaseFolder, filePath), {encoding: 'utf8'});
Jack Franklin8742dc82021-02-26 09:17:59 +0000264 const themeColoursLink = `<link rel="stylesheet" href="${
Jack Franklin0155f7d2021-03-02 09:11:22 +0000265 path.join(baseUrlForSharedResource, 'front_end', 'ui', 'themeColors.css')}" type="text/css" />`;
Jack Franklin343c1412021-02-26 15:08:10 +0000266 const inspectorCommonLink = `<link rel="stylesheet" href="${
Jack Franklin0155f7d2021-03-02 09:11:22 +0000267 path.join(baseUrlForSharedResource, 'front_end', 'ui', 'inspectorCommon.css')}" type="text/css" />`;
Jack Franklin8742dc82021-02-26 09:17:59 +0000268 const toggleDarkModeScript = `<script type="module" src="${
Jack Franklin0155f7d2021-03-02 09:11:22 +0000269 path.join(baseUrlForSharedResource, 'front_end', 'component_docs', 'component_docs.js')}"></script>`;
Jack Franklin343c1412021-02-26 15:08:10 +0000270 const newFileContents = fileContents.replace('<style>', `${themeColoursLink}\n${inspectorCommonLink}\n<style>`)
Jack Franklin36429002020-11-25 15:07:26 +0000271 .replace('<script', toggleDarkModeScript + '\n<script');
272 respondWithHtml(response, newFileContents);
273
Jack Franklin1557a1c2020-06-08 15:22:13 +0100274 } else {
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100275 // This means it's an asset like a JS file or an image.
276 const normalizedPath = normalizeImagePathIfRequired(filePath);
Jack Franklin1557a1c2020-06-08 15:22:13 +0100277
Jack Franklin0155f7d2021-03-02 09:11:22 +0000278 let fullPath = path.join(componentDocsBaseFolder, normalizedPath);
Jack Franklind0345122020-12-21 09:12:04 +0000279 if (fullPath.endsWith(path.join('locales', 'en-US.json'))) {
280 // Rewrite this path so we can load up the locale in the component-docs
Jack Franklin0155f7d2021-03-02 09:11:22 +0000281 fullPath = path.join(componentDocsBaseFolder, 'front_end', 'i18n', 'locales', 'en-US.json');
Jack Franklind0345122020-12-21 09:12:04 +0000282 }
283
Jack Franklin90b66132021-01-05 11:33:43 +0000284 if (!fullPath.startsWith(devtoolsRootFolder) && !fileIsInTestFolder) {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100285 console.error(`Path ${fullPath} is outside the DevTools Frontend root dir.`);
286 process.exit(1);
287 }
Jack Franklin1557a1c2020-06-08 15:22:13 +0100288
Jack Franklin279564e2020-07-06 15:25:18 +0100289 const fileExists = await checkFileExists(fullPath);
290
291 if (!fileExists) {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100292 send404(response, '404, File not found');
293 return;
294 }
295
296 let encoding = 'utf8';
Mathias Bynensc38abd42020-12-24 08:20:05 +0100297 if (fullPath.endsWith('.wasm') || fullPath.endsWith('.png') || fullPath.endsWith('.jpg') ||
298 fullPath.endsWith('.avif')) {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100299 encoding = 'binary';
300 }
301
302 const fileContents = await fs.promises.readFile(fullPath, encoding);
303
304 encoding = 'utf8';
305 if (fullPath.endsWith('.js')) {
306 response.setHeader('Content-Type', 'text/javascript; charset=utf-8');
307 } else if (fullPath.endsWith('.css')) {
308 response.setHeader('Content-Type', 'text/css; charset=utf-8');
309 } else if (fullPath.endsWith('.wasm')) {
310 response.setHeader('Content-Type', 'application/wasm');
311 encoding = 'binary';
312 } else if (fullPath.endsWith('.svg')) {
313 response.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
314 } else if (fullPath.endsWith('.png')) {
315 response.setHeader('Content-Type', 'image/png');
316 encoding = 'binary';
317 } else if (fullPath.endsWith('.jpg')) {
318 response.setHeader('Content-Type', 'image/jpg');
319 encoding = 'binary';
Mathias Bynensc38abd42020-12-24 08:20:05 +0100320 } else if (fullPath.endsWith('.avif')) {
321 response.setHeader('Content-Type', 'image/avif');
322 encoding = 'binary';
Jack Franklin1557a1c2020-06-08 15:22:13 +0100323 }
324
325 response.writeHead(200);
326 response.write(fileContents, encoding);
327 response.end();
328 }
329}