Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/scripts/code-sessions-web.js
13371 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
// @ts-check
7
8
const http = require('http');
9
const fs = require('fs');
10
const path = require('path');
11
const open = require('open');
12
const minimist = require('minimist');
13
14
const APP_ROOT = path.join(__dirname, '..');
15
16
async function main() {
17
const args = minimist(process.argv.slice(2), {
18
boolean: ['help', 'no-open', 'skip-welcome', 'mock'],
19
string: ['host', 'port'],
20
});
21
22
if (args.help) {
23
console.log(
24
'./scripts/code-sessions-web.sh [options]\n' +
25
' --host <host> Host to bind to (default: localhost)\n' +
26
' --port <port> Port to bind to (default: 8081)\n' +
27
' --no-open Do not open browser automatically\n' +
28
' --skip-welcome Skip the sessions welcome overlay\n' +
29
' --mock Load mock extension for E2E testing\n'
30
);
31
return;
32
}
33
34
const HOST = args['host'] ?? 'localhost';
35
const PORT = parseInt(args['port'] ?? '8081', 10);
36
37
// Collect CSS module paths from the compiled output (same as @vscode/test-web does).
38
// These are turned into an import map so the browser can load `import './foo.css'`
39
// statements as JavaScript shims that inject the CSS via `_VSCODE_CSS_LOAD`.
40
let cssModules = [];
41
try {
42
const { glob } = require('tinyglobby');
43
cssModules = await glob('**/*.css', { cwd: path.join(APP_ROOT, 'out') });
44
} catch {
45
// tinyglobby may not be installed; fall back to a recursive fs walk
46
cssModules = collectCssFiles(path.join(APP_ROOT, 'out'), '');
47
}
48
49
const server = http.createServer((req, res) => {
50
const url = new URL(req.url, `http://${HOST}:${PORT}`);
51
52
// Serve the sessions workbench HTML at the root
53
if (url.pathname === '/' || url.pathname === '/index.html') {
54
res.writeHead(200, { 'Content-Type': 'text/html' });
55
res.end(getSessionsHTML(HOST, PORT, cssModules, args['mock']));
56
return;
57
}
58
59
// Serve static files from the repo root (out/, src/, node_modules/, etc.)
60
const filePath = path.join(APP_ROOT, url.pathname);
61
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
62
const ext = path.extname(filePath);
63
const contentType = {
64
'.js': 'application/javascript',
65
'.mjs': 'application/javascript',
66
'.css': 'text/css',
67
'.html': 'text/html',
68
'.json': 'application/json',
69
'.svg': 'image/svg+xml',
70
'.png': 'image/png',
71
'.ttf': 'font/ttf',
72
'.woff': 'font/woff',
73
'.woff2': 'font/woff2',
74
}[ext] || 'application/octet-stream';
75
76
res.writeHead(200, {
77
'Content-Type': contentType,
78
'Access-Control-Allow-Origin': '*',
79
});
80
fs.createReadStream(filePath).pipe(res);
81
return;
82
}
83
84
res.writeHead(404);
85
res.end('Not found');
86
});
87
88
server.listen(PORT, HOST, () => {
89
console.log(`\n Sessions Web running at: http://${HOST}:${PORT}/\n`);
90
if (!args['no-open'] && args.open !== false) {
91
const query = args['skip-welcome'] ? '?skip-sessions-welcome' : '';
92
open.default(`http://${HOST}:${PORT}/${query}`);
93
}
94
});
95
96
process.on('SIGINT', () => { server.close(); process.exit(0); });
97
process.on('SIGTERM', () => { server.close(); process.exit(0); });
98
}
99
100
function getSessionsHTML(host, port, cssModules, useMock) {
101
const baseUrl = `http://${host}:${port}`;
102
const fileRoot = `${baseUrl}/out`;
103
104
// Build the import map server-side. Each CSS file gets mapped to a
105
// data: URI containing a JS module that injects the stylesheet via
106
// a global helper function. This must be a static <script type="importmap">
107
// declared before any <script type="module"> tags.
108
const imports = {};
109
for (const cssModule of cssModules) {
110
const cssUrl = `${fileRoot}/${cssModule}`;
111
const jsSrc = `globalThis._VSCODE_CSS_LOAD('${cssUrl}');\n`;
112
const encoded = Buffer.from(jsSrc).toString('base64');
113
imports[cssUrl] = `data:application/javascript;base64,${encoded}`;
114
}
115
const importMapJson = JSON.stringify({ imports }, null, 2);
116
117
// When --mock is passed, load the E2E mock extension
118
const additionalBuiltinExtensions = useMock
119
? `additionalBuiltinExtensions: [{ scheme: 'http', authority: '${host}:${port}', path: '/src/vs/sessions/test/e2e/extensions/sessions-e2e-mock' }],`
120
: '';
121
122
return `<!DOCTYPE html>
123
<html>
124
<head>
125
<meta charset="utf-8" />
126
<meta name="viewport" content="width=device-width, initial-scale=1" />
127
<title>Sessions</title>
128
<style id="vscode-css-modules"></style>
129
<script>
130
globalThis._VSCODE_FILE_ROOT = '${fileRoot}';
131
const sheet = document.getElementById('vscode-css-modules').sheet;
132
globalThis._VSCODE_CSS_LOAD = function (url) { sheet.insertRule(\`@import url(\${url});\`); };
133
</script>
134
<script type="importmap">
135
${importMapJson}
136
</script>
137
</head>
138
<body aria-label="">
139
<script type="module">
140
import { create, URI } from '${fileRoot}/vs/sessions/${useMock ? 'test/sessions.web.test.internal' : 'sessions.web.main.internal'}.js';
141
create(document.body, {
142
productConfiguration: {
143
nameShort: 'Sessions (Web)',
144
nameLong: 'Sessions (Web)',
145
enableTelemetry: false,
146
},
147
${additionalBuiltinExtensions}
148
workspaceProvider: {
149
workspace: ${useMock
150
? `{ folderUri: URI.parse('mock-fs://mock-repo/mock-repo') }`
151
: 'undefined'},
152
open: async () => false,
153
payload: [['isSessionsWindow', 'true']],
154
},
155
});
156
</script>
157
</body>
158
</html>`;
159
}
160
161
/** Recursively collect *.css paths relative to `dir`. */
162
function collectCssFiles(dir, prefix) {
163
let results = [];
164
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
165
const rel = prefix ? prefix + '/' + entry.name : entry.name;
166
if (entry.isDirectory()) {
167
results = results.concat(collectCssFiles(path.join(dir, entry.name), rel));
168
} else if (entry.name.endsWith('.css')) {
169
results.push(rel);
170
}
171
}
172
return results;
173
}
174
175
main();
176
177
178