Skip to content

Commit

Permalink
Revert "Merge pull request #2 from pattern-lab/dev"
Browse files Browse the repository at this point in the history
This reverts commit 7812878, reversing
changes made to 26db979.
  • Loading branch information
Maximilian authored and mfranzke committed Dec 29, 2022
1 parent 566485a commit fd8eb66
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 108 deletions.
24 changes: 0 additions & 24 deletions packages/core/src/lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,30 +36,6 @@ const server = (patternlab) => {
patternlab.config.paths.public.root
)
);
defaults.assets = [
path.resolve(
path.join(
process.cwd(),
patternlab.config.paths.source.js,
'**',
'*.js' // prevent preprocessors like typescript from reloading
)
),
path.resolve(
path.join(process.cwd(), patternlab.config.paths.source.images)
),
path.resolve(
path.join(process.cwd(), patternlab.config.paths.source.fonts)
),
path.resolve(
path.join(
process.cwd(),
patternlab.config.paths.source.css,
'**',
'*.css' // prevent preprocessors from reloading
)
),
];

// allow for overrides should they exist inside patternlab-config.json
const liveServerConfig = Object.assign(
Expand Down
1 change: 0 additions & 1 deletion packages/edition-node-gulp/gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ function serve() {
return patternlab.server
.serve({
cleanPublic: config.cleanPublic,
watch: true,
})
.then(() => {
// do something else when this promise resolves
Expand Down
140 changes: 57 additions & 83 deletions packages/live-server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ const chokidar = require('chokidar');

require('colors');

const INJECTED_CODE = fs.readFileSync(
var INJECTED_CODE = fs.readFileSync(
path.join(__dirname, 'injected.html'),
'utf8'
);

const LiveServer = {
var LiveServer = {
server: null,
watcher: null,
logLevel: 2,
Expand All @@ -36,7 +36,7 @@ function escape(html) {

// Based on connect.static(), but streamlined and with added code injecter
function staticServer(root) {
let isFile = false;
var isFile = false;
try {
// For supporting mounting files instead of just directories
isFile = fs.statSync(root).isFile();
Expand All @@ -45,48 +45,37 @@ function staticServer(root) {
}
return function (req, res, next) {
if (req.method !== 'GET' && req.method !== 'HEAD') return next();

const reqpath = isFile ? '' : url.parse(req.url).pathname;
const hasNoOrigin = !req.headers.origin;
const injectCandidates = [
var reqpath = isFile ? '' : url.parse(req.url).pathname;
var hasNoOrigin = !req.headers.origin;
var injectCandidates = [
new RegExp('</body>', 'i'),
new RegExp('</head>', 'i'),
];

let injectTag = null;
let injectCount = 0;
var injectTag = null;
var injectCount = 0;

function directory() {
const pathname = url.parse(req.originalUrl).pathname;
var pathname = url.parse(req.originalUrl).pathname;
res.statusCode = 301;
res.setHeader('Location', pathname + '/');
res.end('Redirecting to ' + escape(pathname) + '/');
}

function file(filepath /*, stat*/) {
const x = path.extname(filepath).toLocaleLowerCase();
const possibleExtensions = [
'',
'.html',
'.htm',
'.xhtml',
'.php',
'.svg',
];

let matches;
var x = path.extname(filepath).toLocaleLowerCase(),
matches,
possibleExtensions = ['', '.html', '.htm', '.xhtml', '.php', '.svg'];
if (hasNoOrigin && possibleExtensions.indexOf(x) > -1) {
// TODO: Sync file read here is not nice, but we need to determine if the html should be injected or not
const contents = fs.readFileSync(filepath, 'utf8');
for (let i = 0; i < injectCandidates.length; ++i) {
var contents = fs.readFileSync(filepath, 'utf8');
for (var i = 0; i < injectCandidates.length; ++i) {
matches = contents.match(injectCandidates[i]);
injectCount = (matches && matches.length) || 0;
injectCount = matches && matches.length || 0;
if (injectCount) {
injectTag = matches[0];
break;
}
}

if (injectTag === null && LiveServer.logLevel >= 3) {
console.warn(
'Failed to inject refresh script!'.yellow,
Expand All @@ -101,14 +90,13 @@ function staticServer(root) {

function error(err) {
if (err.status === 404) return next();
return next(err);
next(err);
}

function inject(stream) {
if (injectTag) {
// We need to modify the length given to browser
const len =
INJECTED_CODE.length * injectCount + res.getHeader('Content-Length');
var len = INJECTED_CODE.length * injectCount + res.getHeader('Content-Length');
res.setHeader('Content-Length', len);

const originalPipe = stream.pipe;
Expand All @@ -123,7 +111,7 @@ function staticServer(root) {
}
}

return send(req, reqpath, { root: root })
send(req, reqpath, { root: root })
.on('error', error)
.on('directory', directory)
.on('file', file)
Expand Down Expand Up @@ -165,7 +153,6 @@ function entryPoint(staticHandler, file) {
* @param wait {number} Server will wait for all changes, before reloading
* @param htpasswd {string} Path to htpasswd file to enable HTTP Basic authentication
* @param middleware {array} Append middleware to stack, e.g. [function(req, res, next) { next(); }].
* @param assets {String[]} path of asset directories to watch
*/
LiveServer.start = function (options) {
const host = options.host || '0.0.0.0';
Expand All @@ -175,43 +162,40 @@ LiveServer.start = function (options) {
const watchPaths =
options.watch || (options.assets ? [root, ...options.assets] : [root]);
LiveServer.logLevel = options.logLevel === undefined ? 2 : options.logLevel;

let openPath =
var openPath =
options.open === undefined || options.open === true
? ''
: options.open === null || options.open === false
? null
: options.open;
: options.open === null || options.open === false ? null : options.open;
if (options.noBrowser) openPath = null; // Backwards compatibility with 0.7.0

const file = options.file;
const staticServerHandler = staticServer(root);
const wait = options.wait === undefined ? 100 : options.wait;
const browser = options.browser || null;
const htpasswd = options.htpasswd || null;
const cors = options.cors || false;
const https = options.https || null;
const proxy = options.proxy || [];
const middleware = options.middleware || [];
const noCssInject = options.noCssInject;
let httpsModule = options.httpsModule;
var file = options.file;
var staticServerHandler = staticServer(root);
var wait = options.wait === undefined ? 100 : options.wait;
var browser = options.browser || null;
var htpasswd = options.htpasswd || null;
var cors = options.cors || false;
var https = options.https || null;
var proxy = options.proxy || [];
var middleware = options.middleware || [];
var noCssInject = options.noCssInject;
var httpsModule = options.httpsModule;

if (httpsModule) {
try {
require.resolve(httpsModule);
} catch (e) {
console.error(
`HTTPS module "${httpsModule}" you've provided was not found.`.red
('HTTPS module "' + httpsModule + '" you\'ve provided was not found.')
.red
);
console.error('Did you do', `"npm install ${httpsModule}"?`);
console.error('Did you do', '"npm install ' + httpsModule + '"?');
return;
}
} else {
httpsModule = 'https';
}

// Setup a web server
const app = connect();
var app = connect();

// Add logger. Level 2 logs only errors
if (LiveServer.logLevel === 2) {
Expand All @@ -226,22 +210,21 @@ LiveServer.start = function (options) {
} else if (LiveServer.logLevel > 2) {
app.use(logger('dev'));
}

if (options.spa) {
middleware.push('spa');
}

// Add middleware
middleware.map((mw) => {
let mwm = mw;
if (typeof mw === 'string') {
if (path.extname(mw).toLocaleLowerCase() !== '.js') {
mwm = require(path.join(__dirname, 'middleware', mw + '.js'));
var ext = path.extname(mw).toLocaleLowerCase();
if (ext !== '.js') {
mw = require(path.join(__dirname, 'middleware', mw + '.js'));
} else {
mwm = require(mw);
mw = require(mw);
}
}
app.use(mwm);
app.use(mw);
});

// Use http-auth if configured
Expand All @@ -254,7 +237,6 @@ LiveServer.start = function (options) {
});
app.use(authConnect(basic));
}

if (cors) {
app.use(
require('cors')({
Expand All @@ -269,37 +251,30 @@ LiveServer.start = function (options) {
if (!options.watch) {
// Auto add mount paths to wathing but only if exclusive path option is not given
watchPaths.push(mountPath);
}

app.use(mountRule[0], staticServer(mountPath));
if (LiveServer.logLevel >= 1) {
if (LiveServer.logLevel >= 1)
console.log('Mapping %s to "%s"', mountRule[0], mountPath);
}
});

proxy.forEach((proxyRule) => {
const proxyOpts = url.parse(proxyRule[1]);
proxyOpts.via = true;
proxyOpts.preserveHost = true;
app.use(proxyRule[0], require('proxy-middleware')(proxyOpts));

if (LiveServer.logLevel >= 1) {
if (LiveServer.logLevel >= 1)
console.log('Mapping %s to "%s"', proxyRule[0], proxyRule[1]);
}
});

app
.use(staticServerHandler) // Custom static server
.use(entryPoint(staticServerHandler, file))
.use(serveIndex(root, { icons: true }));

let server, protocol;
var server, protocol;
if (https !== null) {
let httpsConfig = https;
var httpsConfig = https;
if (typeof https === 'string') {
httpsConfig = require(path.resolve(process.cwd(), https));
}

server = require(httpsModule).createServer(httpsConfig, app);
protocol = 'https';
} else {
Expand All @@ -310,9 +285,10 @@ LiveServer.start = function (options) {
// Handle server startup errors
server.addListener('error', function (e) {
if (e.code === 'EADDRINUSE') {
var serveURL = protocol + '://' + host + ':' + port;
console.log(
'%s is already in use. Trying another port.'.yellow,
`${protocol}://${host}:${port}`
serveURL
);
setTimeout(function () {
server.listen(0, host);
Expand All @@ -327,21 +303,21 @@ LiveServer.start = function (options) {
server.addListener('listening', function (/*e*/) {
LiveServer.server = server;

const address = server.address();
const serveHost =
var address = server.address();
var serveHost =
address.address === '0.0.0.0' ? '127.0.0.1' : address.address;
const openHost = host === '0.0.0.0' ? '127.0.0.1' : host;
var openHost = host === '0.0.0.0' ? '127.0.0.1' : host;

const serveURL = `${protocol}://${serveHost}:${address.port}`;
const openURL = `${protocol}://${openHost}:${address.port}`;
var serveURL = protocol + '://' + serveHost + ':' + address.port;
var openURL = protocol + '://' + openHost + ':' + address.port;

let serveURLs = [serveURL];
var serveURLs = [serveURL];
if (LiveServer.logLevel > 2 && address.address === '0.0.0.0') {
const ifaces = os.networkInterfaces();
var ifaces = os.networkInterfaces();
serveURLs = Object.keys(ifaces)
.map((iface) => ifaces[iface])
// flatten address data, use only IPv4
.reduce((data, addresses) => {
.reduce(function(data, addresses) {
addresses
.filter((addr) => addr.family === 'IPv4')
.forEach((addr) => data.push(addr));
Expand Down Expand Up @@ -423,15 +399,12 @@ LiveServer.start = function (options) {
);
},
];

if (options.ignore) {
ignored = ignored.concat(options.ignore);
}

if (options.ignorePattern) {
ignored.push(options.ignorePattern);
}

// Setup file watcher
LiveServer.watcher = chokidar.watch(
// Replace backslashes with slashes, because chokidar pattern
Expand All @@ -445,7 +418,7 @@ LiveServer.start = function (options) {
);

function handleChange(changePath) {
const cssChange = path.extname(changePath) === '.css' && !noCssInject;
var cssChange = path.extname(changePath) === '.css' && !noCssInject;
if (LiveServer.logLevel >= 1) {
if (cssChange) console.log('CSS change detected'.magenta, changePath);
else console.log('Change detected'.cyan, changePath);
Expand All @@ -455,7 +428,6 @@ LiveServer.start = function (options) {
if (ws) ws.send(cssChange ? 'refreshcss' : 'reload');
});
}

LiveServer.watcher
.on('change', handleChange)
.on('add', handleChange)
Expand Down Expand Up @@ -496,6 +468,8 @@ LiveServer.shutdown = function () {
if (LiveServer.server) {
LiveServer.server.close();
}
var server = LiveServer.server;
if (server) server.close();
};

module.exports = LiveServer;

0 comments on commit fd8eb66

Please sign in to comment.