Skip to content

Commit

Permalink
feat(serve): Add working livereload server
Browse files Browse the repository at this point in the history
  • Loading branch information
pixelastic committed Apr 11, 2021
1 parent 86ba13d commit c8c4296
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 21 deletions.
69 changes: 69 additions & 0 deletions modules/serve/lib/__tests__/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,16 @@ const assets = require('norska-assets');
const js = require('norska-js');
const css = require('norska-css');
const html = require('norska-html');
const config = require('norska-config');
const emptyDir = require('firost/emptyDir');
const readUrl = require('firost/readUrl');
const write = require('firost/write');
const getPort = require('get-port');

describe('norska-serve', () => {
const tmpDirectory = './tmp/norska-serve';
let staticServerUrl;

describe('watchFiles', () => {
it('should listen to changes', async () => {
jest.spyOn(html, 'watch').mockReturnValue();
Expand All @@ -20,4 +28,65 @@ describe('norska-serve', () => {
expect(assets.watch).toHaveBeenCalled();
});
});
describe('startStaticServer', () => {
beforeEach(async () => {
await emptyDir(tmpDirectory);

const staticServerPort = await getPort();
staticServerUrl = `http://127.0.0.1:${staticServerPort}`;
await config.init({
from: `${tmpDirectory}/src`,
to: `${tmpDirectory}/dist`,
port: staticServerPort,
});

jest.spyOn(current, '__consoleInfo').mockReturnValue();
jest.spyOn(current, '__open').mockReturnValue();
});
afterEach(async () => {
await current.closeStaticServer();
});
it('should serve files from the dist folder', async () => {
await write('some content', config.toPath('index.html'));

await current.startStaticServer();

const actual = await readUrl(staticServerUrl);
expect(actual).toEqual('some content');
});
it('should serve fresh content', async () => {
await write('some content', config.toPath('index.html'));
await current.startStaticServer();

const firstRead = await readUrl(staticServerUrl);
expect(firstRead).toEqual('some content');

await write('updated content', config.toPath('index.html'));
const secondRead = await readUrl(staticServerUrl, { memoryCache: false });
expect(secondRead).toEqual('updated content');
});
it('should serve content added after server starts', async () => {
await current.startStaticServer();

await write('some content', config.toPath('index.html'));

const actual = await readUrl(staticServerUrl);
expect(actual).toEqual('some content');
});
it('should add liveReload script to html pages', async () => {
await write(
'<!DOCTYPE html><html><body>some content</body></html>',
config.toPath('index.html')
);

await current.startStaticServer();

const actual = await readUrl(staticServerUrl, {
headers: { Accept: 'text/html' },
});
expect(actual).toInclude(
'<script src="//127.0.0.1:35729/livereload.js?snipver=1"'
);
});
});
});
60 changes: 45 additions & 15 deletions modules/serve/lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,21 @@ const express = require('express');
const open = require('open');
const livereload = require('livereload');
const connectLivereload = require('connect-livereload');
const consoleInfo = require('firost/consoleInfo');

module.exports = {
/**
* Start live reload server.
* Listen to file changes, serve them locally, and refresh browser on change
**/
async run() {
await this.watchFiles();
await this.startStaticServer();
await this.startLivereloadServer();
},
/**
* Watch for changes in any source file and rebuild them in destination folder
**/
async watchFiles() {
await pAll([
async () => await html.watch(),
Expand All @@ -23,40 +31,62 @@ module.exports = {
async () => await assets.watch(),
]);
},
async startLivereloadServer() {
const livereloadOptions = {
delay: 200,
};
const watchedDirectories = [config.to()];

this.__livereload()
.createServer(livereloadOptions)
.watch(watchedDirectories);
},
/**
* Start a server rendering any file located in destination folder
* @returns {Promise} Resolves when the server is started
**/
async startStaticServer() {
return new Promise((resolve, _reject) => {
const app = express();

// Add the livereload.js script to the pages
app.use(connectLivereload());

app.use(express.static(config.to()));
app.use(express.static(config.toPath()));

// Start the server
const cmsPort = config.get('port');
app.listen(cmsPort, async () => {
const cmsUrl = `http://127.0.0.1:${cmsPort}/`;
console.info(`Dev server available at ${cmsUrl}`);
await open(cmsUrl);
this.__staticServer = app.listen(cmsPort, async () => {
const serverUrl = `http://127.0.0.1:${cmsPort}/`;
this.__consoleInfo(`Dev server available at ${serverUrl}`);
await this.__open(serverUrl);
resolve();
});
});
},
/**
* Close the previously opened static server
* @returns {Promise} Resolve when the server is closed
**/
async closeStaticServer() {
if (!this.__staticServer) {
return;
}
// We give it the order to close, but only resolve once it is closed for
// real
return await new Promise((resolve) => {
this.__staticServer.on('close', resolve);
this.__staticServer.close();
});
},
async startLivereloadServer() {
const livereloadOptions = {
delay: 200,
};
const watchedDirectories = [config.to()];

this.__livereload()
.createServer(livereloadOptions)
.watch(watchedDirectories);
},
/**
* Wrapping the livereload dependency so we can mock it in tests
* @returns {object} Livereload object
**/
__livereload() {
return livereload;
},
__open: open,
__server: null,
__consoleInfo: consoleInfo,
};
5 changes: 4 additions & 1 deletion modules/serve/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,8 @@
"test": "../../scripts/local/test",
"test:watch": "../../scripts/local/test-watch"
},
"version": "1.0.0"
"version": "1.0.0",
"devDependencies": {
"get-port": "5.1.1"
}
}
10 changes: 5 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8247,16 +8247,16 @@ get-pkg-repo@^1.0.0:
parse-github-repo-url "^1.3.0"
through2 "^2.0.0"

get-port@5.1.1, get-port@^5.1.0:
version "5.1.1"
resolved "https://registry.npmjs.org/get-port/-/get-port-5.1.1.tgz#0469ed07563479de6efb986baf053dcd7d4e3193"
integrity sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==

get-port@^4.2.0:
version "4.2.0"
resolved "https://registry.npmjs.org/get-port/-/get-port-4.2.0.tgz#e37368b1e863b7629c43c5a323625f95cf24b119"
integrity sha512-/b3jarXkH8KJoOMQc3uVGHASwGLPq3gSFJ7tgJm2diza+bydJPTGOibin2steecKeOylE8oY2JERlVWkAJO6yw==

get-port@^5.1.0:
version "5.1.1"
resolved "https://registry.npmjs.org/get-port/-/get-port-5.1.1.tgz#0469ed07563479de6efb986baf053dcd7d4e3193"
integrity sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==

get-proxy@^2.0.0:
version "2.1.0"
resolved "https://registry.npmjs.org/get-proxy/-/get-proxy-2.1.0.tgz#349f2b4d91d44c4d4d4e9cba2ad90143fac5ef93"
Expand Down

0 comments on commit c8c4296

Please sign in to comment.