🐛 Update: Added support for the 'find' command in settings.local.json. Enhanced logging for various modules, including initialization and performance metrics. Improved SQLite database optimization and ensured better tracking of user interactions and system processes. 📚

This commit is contained in:
2025-06-14 16:26:43 +02:00
parent ee54bc273c
commit 89037861e3
2472 changed files with 691099 additions and 1 deletions

View File

@@ -0,0 +1,16 @@
root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[{package,bower}.json]
indent_style = space
indent_size = 2

View File

@@ -0,0 +1,19 @@
Contributing Guidelines
=======================
When implementing a new feature or a bugfix, consider these points:
* Is this thing useful to other people, or is it just catering for an obscure corner case resulting from e.g. weirdness in personal dev environment?
* Should the thing be live-server's responsibility at all, or is it better served by other tools?
* Am I introducing unnecessary dependencies when the same thing could easily be done using normal JavaScript / node.js features?
* Does the naming (e.g. command line parameters) make sense and uses same style as other similar ones?
* Does my code adhere to the project's coding style (observable from surrounding code)?
* Can backwards compatibility be preserved?
A few guiding principles: keep the app simple and small, focusing on what it's meant to provide: live reloading development web server. Avoid extra dependencies and the need to do configuration when possible and it makes sense. Minimize bloat.
If you are adding a feature, think about if it could be an extenral middleware instead, possible bundled with `live-server` in its `middleware` folder.
**New features should come with test cases!**
**Run `npm test` to check that you are not introducing new bugs or style issues!**

View File

@@ -0,0 +1,11 @@
###### Before submitting an issue, please, see https://github.com/tapio/live-server#troubleshooting
## Issue description
## Software details
* Command line used for launching `live-server`:
* OS:
* Browser (if browser related):
* Node.js version:
* `live-server` version:

View File

@@ -0,0 +1,5 @@
sudo: false
language: node_js
node_js:
- "node"
- "lts/*"

View File

@@ -0,0 +1,274 @@
[![view on npm](http://img.shields.io/npm/v/live-server.svg)](https://www.npmjs.org/package/live-server)
[![npm module downloads per month](http://img.shields.io/npm/dm/live-server.svg)](https://www.npmjs.org/package/live-server)
[![build status](https://travis-ci.org/tapio/live-server.svg)](https://travis-ci.org/tapio/live-server)
Live Server
===========
This is a little development server with live reload capability. Use it for hacking your HTML/JavaScript/CSS files, but not for deploying the final site.
There are two reasons for using this:
1. AJAX requests don't work with the `file://` protocol due to security restrictions, i.e. you need a server if your site fetches content through JavaScript.
2. Having the page reload automatically after changes to files can accelerate development.
You don't need to install any browser plugins or manually add code snippets to your pages for the reload functionality to work, see "How it works" section below for more information. If you don't want/need the live reload, you should probably use something even simpler, like the following Python-based one-liner:
python -m SimpleHTTPServer
Installation
------------
You need node.js and npm. You should probably install this globally.
**Npm way**
npm install -g live-server
**Manual way**
git clone https://github.com/tapio/live-server
cd live-server
npm install # Local dependencies if you want to hack
npm install -g # Install globally
Usage from command line
-----------------------
Issue the command `live-server` in your project's directory. Alternatively you can add the path to serve as a command line parameter.
This will automatically launch the default browser. When you make a change to any file, the browser will reload the page - unless it was a CSS file in which case the changes are applied without a reload.
Command line parameters:
* `--port=NUMBER` - select port to use, default: PORT env var or 8080
* `--host=ADDRESS` - select host address to bind to, default: IP env var or 0.0.0.0 ("any address")
* `--no-browser` - suppress automatic web browser launching
* `--browser=BROWSER` - specify browser to use instead of system default
* `--quiet | -q` - suppress logging
* `--verbose | -V` - more logging (logs all requests, shows all listening IPv4 interfaces, etc.)
* `--open=PATH` - launch browser to PATH instead of server root
* `--watch=PATH` - comma-separated string of paths to exclusively watch for changes (default: watch everything)
* `--ignore=PATH` - comma-separated string of paths to ignore ([anymatch](https://github.com/es128/anymatch)-compatible definition)
* `--ignorePattern=RGXP` - Regular expression of files to ignore (ie `.*\.jade`) (**DEPRECATED** in favor of `--ignore`)
* `--no-css-inject` - reload page on CSS change, rather than injecting changed CSS
* `--middleware=PATH` - path to .js file exporting a middleware function to add; can be a name without path nor extension to reference bundled middlewares in `middleware` folder
* `--entry-file=PATH` - serve this file (server root relative) in place of missing files (useful for single page apps)
* `--mount=ROUTE:PATH` - serve the paths contents under the defined route (multiple definitions possible)
* `--spa` - translate requests from /abc to /#/abc (handy for Single Page Apps)
* `--wait=MILLISECONDS` - (default 100ms) wait for all changes, before reloading
* `--htpasswd=PATH` - Enables http-auth expecting htpasswd file located at PATH
* `--cors` - Enables CORS for any origin (reflects request origin, requests with credentials are supported)
* `--https=PATH` - PATH to a HTTPS configuration module
* `--https-module=MODULE_NAME` - Custom HTTPS module (e.g. `spdy`)
* `--proxy=ROUTE:URL` - proxy all requests for ROUTE to URL
* `--help | -h` - display terse usage hint and exit
* `--version | -v` - display version and exit
Default options:
If a file `~/.live-server.json` exists it will be loaded and used as default options for live-server on the command line. See "Usage from node" for option names.
Usage from node
---------------
```javascript
var liveServer = require("live-server");
var params = {
port: 8181, // Set the server port. Defaults to 8080.
host: "0.0.0.0", // Set the address to bind to. Defaults to 0.0.0.0 or process.env.IP.
root: "/public", // Set root directory that's being served. Defaults to cwd.
open: false, // When false, it won't load your browser by default.
ignore: 'scss,my/templates', // comma-separated string for paths to ignore
file: "index.html", // When set, serve this file (server root relative) for every 404 (useful for single-page applications)
wait: 1000, // Waits for all changes, before reloading. Defaults to 0 sec.
mount: [['/components', './node_modules']], // Mount a directory to a route.
logLevel: 2, // 0 = errors only, 1 = some, 2 = lots
middleware: [function(req, res, next) { next(); }] // Takes an array of Connect-compatible middleware that are injected into the server middleware stack
};
liveServer.start(params);
```
HTTPS
---------------
In order to enable HTTPS support, you'll need to create a configuration module.
The module must export an object that will be used to configure a HTTPS server.
The keys are the same as the keys in `options` for [tls.createServer](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener).
For example:
```javascript
var fs = require("fs");
module.exports = {
cert: fs.readFileSync(__dirname + "/server.cert"),
key: fs.readFileSync(__dirname + "/server.key"),
passphrase: "12345"
};
```
If using the node API, you can also directly pass a configuration object instead of a path to the module.
HTTP/2
---------------
To get HTTP/2 support one can provide a custom HTTPS module via `--https-module` CLI parameter (`httpsModule` option for Node.js script). **Be sure to install the module first.**
HTTP/2 unencrypted mode is not supported by browsers, thus not supported by `live-server`. See [this question](https://http2.github.io/faq/#does-http2-require-encryption) and [can I use page on HTTP/2](http://caniuse.com/#search=http2) for more details.
For example from CLI(bash):
live-server \
--https=path/to/https.conf.js \
--https-module=spdy \
my-app-folder/
Troubleshooting
---------------
* No reload on changes
* Open your browser's console: there should be a message at the top stating that live reload is enabled. Note that you will need a browser that supports WebSockets. If there are errors, deal with them. If it's still not working, [file an issue](https://github.com/tapio/live-server/issues).
* Error: watch <PATH> ENOSPC
* See [this suggested solution](http://stackoverflow.com/questions/22475849/node-js-error-enospc/32600959#32600959).
* Reload works but changes are missing or outdated
* Try using `--wait=MS` option. Where `MS` is time in milliseconds to wait before issuing a reload.
How it works
------------
The server is a simple node app that serves the working directory and its subdirectories. It also watches the files for changes and when that happens, it sends a message through a web socket connection to the browser instructing it to reload. In order for the client side to support this, the server injects a small piece of JavaScript code to each requested html file. This script establishes the web socket connection and listens to the reload requests. CSS files can be refreshed without a full page reload by finding the referenced stylesheets from the DOM and tricking the browser to fetch and parse them again.
Contributing
------------
We welcome contributions! See [CONTRIBUTING.md](.github/CONTRIBUTING.md) for details.
Version history
---------------
* v1.2.2
- Fix dependency problem
* v1.2.1
- `--https-module=MODULE_NAME` to specify custom HTTPS module (e.g. `spdy`) (@pavel)
- `--no-css-inject` to reload page on css change instead of injecting the changes (@kylecordes)
- Dependencies updated to get rid of vulnerabilities in deps
* v1.2.0
- Add `--middleware` parameter to use external middlewares
- `middleware` API parameter now also accepts strings similar to `--middleware`
- Changed file watcher to improve speed (@pavel)
- `--ignore` now accepts regexps and globs, `--ignorePattern` deprecated (@pavel)
- Added `--verbose` cli option (logLevel 3) (@pavel)
- Logs all requests, displays warning when can't inject html file, displays all listening IPv4 interfaces...
- HTTPS configuration now also accepts a plain object (@pavel)
- Move `--spa` to a bundled middleware file
- New bundled `spa-no-assets` middleware that works like `spa` but ignores requests with extension
- Allow multiple `--open` arguments (@PirtleShell)
- Inject to `head` if `body` not found (@pmd1991)
- Update dependencies
* v1.1.0
- Proxy support (@pavel)
- Middleware support (@achandrasekar)
- Dependency updates (@tapio, @rahatarmanahmed)
- Using Travis CI
* v1.0.0
- HTTPS support (@pavel)
- HTTP Basic authentication support (@hey-johnnypark)
- CORS support (@pavel)
- Support mounting single files (@pavel)
- `--spa` cli option for single page apps, translates requests from /abc to /#/abc (@evanplaice)
- Check `IP` env var for default host (@dotnetCarpenter)
- Fix `ignorePattern` from config file (@cyfersystems)
- Fix test running for Windows (@peterhull90)
* v0.9.2
- Updated most dependencies to latest versions
- `--quiet` now silences warning about injection failure
- Giving explicit `--watch` paths now disables adding mounted paths to watching
* v0.9.1
- `--ignorePattern=RGXP` exclude files from watching by regexp (@psi-4ward)
- `--watch=PATH` cli option to only watch given paths
* v0.9.0
- `--mount=ROUTE:PATH` cli option to specify alternative routes to paths (@pmentz)
- `--browser=BROWSER` cli option to specify browser to use (@sakiv)
- Improved error reporting
- Basic support for injecting the reload code to SVG files (@dotnetCarpenter, @tapio)
- LiveServer.shutdown() function to close down the server and file watchers
- If host parameter is given, use it for browser URL instead of resolved IP
- Initial testing framework (@harrytruong, @evanplaice, @tapio)
* v0.8.2
- Load initial settings from `~/.live-server.json` if exists (@mikker)
- Allow `--port=0` to select random port (@viqueen)
- Fix injecting when file extension is not lower case (@gusgard)
- Fail gracefully if browser does not support WebSockets (@mattymaloney)
- Switched to a more maintained browser opening library
* v0.8.1
- Add `--version / -v` command line flags to display version
- Add `--host` cli option to mirror the API parameter
- Once again use 127.0.0.1 instead of 0.0.0.0 as the browser URL
* v0.8.0
- Support multiple clients simultaneously (@dvv)
- Pick a random available port if the default is in use (@oliverzy, @harrytruong)
- Fix Chrome sometimes not applying CSS changes (@harrytruong)
- `--ignore=PATH` cli option to not watch given server root relative paths (@richardgoater)
- `--entry-file=PATH` cli option to specify file to use when request is not found (@izeau)
- `--wait=MSECS` cli option to wait specified time before reloading (@leolower, @harrytruong)
* v0.7.1
- Fix hang caused by trying to inject into fragment html files without `</body>`
- `logLevel` parameter in library to control amount of console spam
- `--quiet` cli option to suppress console spam
- `--open=PATH` cli option to launch browser in specified path instead of root (@richardgoater)
- Library's `noBrowser: true` option is deprecated in favor of `open: false`
* v0.7.0
- API BREAKAGE: LiveServer library now takes parameters in an object
- Add possibility to specify host to the lib
- Only inject to host page when working with web components (e.g. Polymer) (@davej)
- Open browser to 127.0.0.1, as 0.0.0.0 has issues
- `--no-browser` command line flag to suppress browser launch
- `--help` command line flag to display usage
* v0.6.4
- Allow specifying port from the command line: `live-server --port=3000` (@Pomax)
- Don't inject script as the first thing so that DOCTYPE remains valid (@wmira)
- Be more explicit with listening to all interfaces (@inadarei)
* v0.6.3
- Fix multiple _cacheOverride parameters polluting css requests
- Don't create global variables in the injected script
* v0.6.2
- Fix a deprecation warning from `send`
* v0.6.1
- Republish to fix npm troubles
* v0.6.0
- Support for using as node library (@dpgraham)
* v0.5.0
- Watching was broken with new versions of `watchr` > 2.3.3
- Added some logging to console
* v0.4.0
- Allow specifying directory to serve from command line
* v0.3.0
- Directory listings
* v0.2.0
- On-the-fly CSS refresh (no page reload)
- Refactoring
* v0.1.1
- Documentation and meta tweaks
* v0.1.0
- Initial release
License
-------
Uses MIT licensed code from [Connect](https://github.com/senchalabs/connect/) and [Roots](https://github.com/jenius/roots).
(MIT License)
Copyright (c) 2012 Tapio Vierros
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

399
network-visualization/node_modules/live-server/index.js generated vendored Normal file
View File

@@ -0,0 +1,399 @@
#!/usr/bin/env node
var fs = require('fs'),
connect = require('connect'),
serveIndex = require('serve-index'),
logger = require('morgan'),
WebSocket = require('faye-websocket'),
path = require('path'),
url = require('url'),
http = require('http'),
send = require('send'),
open = require('opn'),
es = require("event-stream"),
os = require('os'),
chokidar = require('chokidar');
require('colors');
var INJECTED_CODE = fs.readFileSync(path.join(__dirname, "injected.html"), "utf8");
var LiveServer = {
server: null,
watcher: null,
logLevel: 2
};
function escape(html){
return String(html)
.replace(/&(?!\w+;)/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
// Based on connect.static(), but streamlined and with added code injecter
function staticServer(root) {
var isFile = false;
try { // For supporting mounting files instead of just directories
isFile = fs.statSync(root).isFile();
} catch (e) {
if (e.code !== "ENOENT") throw e;
}
return function(req, res, next) {
if (req.method !== "GET" && req.method !== "HEAD") return next();
var reqpath = isFile ? "" : url.parse(req.url).pathname;
var hasNoOrigin = !req.headers.origin;
var injectCandidates = [ new RegExp("</body>", "i"), new RegExp("</svg>"), new RegExp("</head>", "i")];
var injectTag = null;
function directory() {
var pathname = url.parse(req.originalUrl).pathname;
res.statusCode = 301;
res.setHeader('Location', pathname + '/');
res.end('Redirecting to ' + escape(pathname) + '/');
}
function file(filepath /*, stat*/) {
var x = path.extname(filepath).toLocaleLowerCase(), match,
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
var contents = fs.readFileSync(filepath, "utf8");
for (var i = 0; i < injectCandidates.length; ++i) {
match = injectCandidates[i].exec(contents);
if (match) {
injectTag = match[0];
break;
}
}
if (injectTag === null && LiveServer.logLevel >= 3) {
console.warn("Failed to inject refresh script!".yellow,
"Couldn't find any of the tags ", injectCandidates, "from", filepath);
}
}
}
function error(err) {
if (err.status === 404) return next();
next(err);
}
function inject(stream) {
if (injectTag) {
// We need to modify the length given to browser
var len = INJECTED_CODE.length + res.getHeader('Content-Length');
res.setHeader('Content-Length', len);
var originalPipe = stream.pipe;
stream.pipe = function(resp) {
originalPipe.call(stream, es.replace(new RegExp(injectTag, "i"), INJECTED_CODE + injectTag)).pipe(resp);
};
}
}
send(req, reqpath, { root: root })
.on('error', error)
.on('directory', directory)
.on('file', file)
.on('stream', inject)
.pipe(res);
};
}
/**
* Rewrite request URL and pass it back to the static handler.
* @param staticHandler {function} Next handler
* @param file {string} Path to the entry point file
*/
function entryPoint(staticHandler, file) {
if (!file) return function(req, res, next) { next(); };
return function(req, res, next) {
req.url = "/" + file;
staticHandler(req, res, next);
};
}
/**
* Start a live server with parameters given as an object
* @param host {string} Address to bind to (default: 0.0.0.0)
* @param port {number} Port number (default: 8080)
* @param root {string} Path to root directory (default: cwd)
* @param watch {array} Paths to exclusively watch for changes
* @param ignore {array} Paths to ignore when watching files for changes
* @param ignorePattern {regexp} Ignore files by RegExp
* @param noCssInject Don't inject CSS changes, just reload as with any other file change
* @param open {(string|string[])} Subpath(s) to open in browser, use false to suppress launch (default: server root)
* @param mount {array} Mount directories onto a route, e.g. [['/components', './node_modules']].
* @param logLevel {number} 0 = errors only, 1 = some, 2 = lots
* @param file {string} Path to the entry point 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(); }].
*/
LiveServer.start = function(options) {
options = options || {};
var host = options.host || '0.0.0.0';
var port = options.port !== undefined ? options.port : 8080; // 0 means random
var root = options.root || process.cwd();
var mount = options.mount || [];
var watchPaths = options.watch || [root];
LiveServer.logLevel = options.logLevel === undefined ? 2 : options.logLevel;
var openPath = (options.open === undefined || options.open === true) ?
"" : ((options.open === null || options.open === false) ? null : options.open);
if (options.noBrowser) openPath = null; // Backwards compatibility with 0.7.0
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);
console.error("Did you do", "\"npm install " + httpsModule + "\"?");
return;
}
} else {
httpsModule = "https";
}
// Setup a web server
var app = connect();
// Add logger. Level 2 logs only errors
if (LiveServer.logLevel === 2) {
app.use(logger('dev', {
skip: function (req, res) { return res.statusCode < 400; }
}));
// Level 2 or above logs all requests
} else if (LiveServer.logLevel > 2) {
app.use(logger('dev'));
}
if (options.spa) {
middleware.push("spa");
}
// Add middleware
middleware.map(function(mw) {
if (typeof mw === "string") {
var ext = path.extname(mw).toLocaleLowerCase();
if (ext !== ".js") {
mw = require(path.join(__dirname, "middleware", mw + ".js"));
} else {
mw = require(mw);
}
}
app.use(mw);
});
// Use http-auth if configured
if (htpasswd !== null) {
var auth = require('http-auth');
var basic = auth.basic({
realm: "Please authorize",
file: htpasswd
});
app.use(auth.connect(basic));
}
if (cors) {
app.use(require("cors")({
origin: true, // reflecting request origin
credentials: true // allowing requests with credentials
}));
}
mount.forEach(function(mountRule) {
var mountPath = path.resolve(process.cwd(), mountRule[1]);
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)
console.log('Mapping %s to "%s"', mountRule[0], mountPath);
});
proxy.forEach(function(proxyRule) {
var proxyOpts = url.parse(proxyRule[1]);
proxyOpts.via = true;
proxyOpts.preserveHost = true;
app.use(proxyRule[0], require('proxy-middleware')(proxyOpts));
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 }));
var server, protocol;
if (https !== null) {
var httpsConfig = https;
if (typeof https === "string") {
httpsConfig = require(path.resolve(process.cwd(), https));
}
server = require(httpsModule).createServer(httpsConfig, app);
protocol = "https";
} else {
server = http.createServer(app);
protocol = "http";
}
// 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, serveURL);
setTimeout(function() {
server.listen(0, host);
}, 1000);
} else {
console.error(e.toString().red);
LiveServer.shutdown();
}
});
// Handle successful server
server.addListener('listening', function(/*e*/) {
LiveServer.server = server;
var address = server.address();
var serveHost = address.address === "0.0.0.0" ? "127.0.0.1" : address.address;
var openHost = host === "0.0.0.0" ? "127.0.0.1" : host;
var serveURL = protocol + '://' + serveHost + ':' + address.port;
var openURL = protocol + '://' + openHost + ':' + address.port;
var serveURLs = [ serveURL ];
if (LiveServer.logLevel > 2 && address.address === "0.0.0.0") {
var ifaces = os.networkInterfaces();
serveURLs = Object.keys(ifaces)
.map(function(iface) {
return ifaces[iface];
})
// flatten address data, use only IPv4
.reduce(function(data, addresses) {
addresses.filter(function(addr) {
return addr.family === "IPv4";
}).forEach(function(addr) {
data.push(addr);
});
return data;
}, [])
.map(function(addr) {
return protocol + "://" + addr.address + ":" + address.port;
});
}
// Output
if (LiveServer.logLevel >= 1) {
if (serveURL === openURL)
if (serveURLs.length === 1) {
console.log(("Serving \"%s\" at %s").green, root, serveURLs[0]);
} else {
console.log(("Serving \"%s\" at\n\t%s").green, root, serveURLs.join("\n\t"));
}
else
console.log(("Serving \"%s\" at %s (%s)").green, root, openURL, serveURL);
}
// Launch browser
if (openPath !== null)
if (typeof openPath === "object") {
openPath.forEach(function(p) {
open(openURL + p, {app: browser});
});
} else {
open(openURL + openPath, {app: browser});
}
});
// Setup server to listen at port
server.listen(port, host);
// WebSocket
var clients = [];
server.addListener('upgrade', function(request, socket, head) {
var ws = new WebSocket(request, socket, head);
ws.onopen = function() { ws.send('connected'); };
if (wait > 0) {
(function() {
var wssend = ws.send;
var waitTimeout;
ws.send = function() {
var args = arguments;
if (waitTimeout) clearTimeout(waitTimeout);
waitTimeout = setTimeout(function(){
wssend.apply(ws, args);
}, wait);
};
})();
}
ws.onclose = function() {
clients = clients.filter(function (x) {
return x !== ws;
});
};
clients.push(ws);
});
var ignored = [
function(testPath) { // Always ignore dotfiles (important e.g. because editor hidden temp files)
return testPath !== "." && /(^[.#]|(?:__|~)$)/.test(path.basename(testPath));
}
];
if (options.ignore) {
ignored = ignored.concat(options.ignore);
}
if (options.ignorePattern) {
ignored.push(options.ignorePattern);
}
// Setup file watcher
LiveServer.watcher = chokidar.watch(watchPaths, {
ignored: ignored,
ignoreInitial: true
});
function handleChange(changePath) {
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);
}
clients.forEach(function(ws) {
if (ws)
ws.send(cssChange ? 'refreshcss' : 'reload');
});
}
LiveServer.watcher
.on("change", handleChange)
.on("add", handleChange)
.on("unlink", handleChange)
.on("addDir", handleChange)
.on("unlinkDir", handleChange)
.on("ready", function () {
if (LiveServer.logLevel >= 1)
console.log("Ready for changes".cyan);
})
.on("error", function (err) {
console.log("ERROR:".red, err);
});
return server;
};
LiveServer.shutdown = function() {
var watcher = LiveServer.watcher;
if (watcher) {
watcher.close();
}
var server = LiveServer.server;
if (server)
server.close();
};
module.exports = LiveServer;

View File

@@ -0,0 +1,31 @@
<!-- Code injected by live-server -->
<script type="text/javascript">
// <![CDATA[ <-- For SVG support
if ('WebSocket' in window) {
(function() {
function refreshCSS() {
var sheets = [].slice.call(document.getElementsByTagName("link"));
var head = document.getElementsByTagName("head")[0];
for (var i = 0; i < sheets.length; ++i) {
var elem = sheets[i];
head.removeChild(elem);
var rel = elem.rel;
if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
}
head.appendChild(elem);
}
}
var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
var address = protocol + window.location.host + window.location.pathname + '/ws';
var socket = new WebSocket(address);
socket.onmessage = function(msg) {
if (msg.data == 'reload') window.location.reload();
else if (msg.data == 'refreshcss') refreshCSS();
};
console.log('Live reload enabled.');
})();
}
// ]]>
</script>

174
network-visualization/node_modules/live-server/live-server.js generated vendored Executable file
View File

@@ -0,0 +1,174 @@
#!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var assign = require('object-assign');
var liveServer = require("./index");
var opts = {
host: process.env.IP,
port: process.env.PORT,
open: true,
mount: [],
proxy: [],
middleware: [],
logLevel: 2,
};
var homeDir = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
var configPath = path.join(homeDir, '.live-server.json');
if (fs.existsSync(configPath)) {
var userConfig = fs.readFileSync(configPath, 'utf8');
assign(opts, JSON.parse(userConfig));
if (opts.ignorePattern) opts.ignorePattern = new RegExp(opts.ignorePattern);
}
for (var i = process.argv.length - 1; i >= 2; --i) {
var arg = process.argv[i];
if (arg.indexOf("--port=") > -1) {
var portString = arg.substring(7);
var portNumber = parseInt(portString, 10);
if (portNumber === +portString) {
opts.port = portNumber;
process.argv.splice(i, 1);
}
}
else if (arg.indexOf("--host=") > -1) {
opts.host = arg.substring(7);
process.argv.splice(i, 1);
}
else if (arg.indexOf("--open=") > -1) {
var open = arg.substring(7);
if (open.indexOf('/') !== 0) {
open = '/' + open;
}
switch (typeof opts.open) {
case "boolean":
opts.open = open;
break;
case "string":
opts.open = [opts.open, open];
break;
case "object":
opts.open.push(open);
break;
}
process.argv.splice(i, 1);
}
else if (arg.indexOf("--watch=") > -1) {
// Will be modified later when cwd is known
opts.watch = arg.substring(8).split(",");
process.argv.splice(i, 1);
}
else if (arg.indexOf("--ignore=") > -1) {
// Will be modified later when cwd is known
opts.ignore = arg.substring(9).split(",");
process.argv.splice(i, 1);
}
else if (arg.indexOf("--ignorePattern=") > -1) {
opts.ignorePattern = new RegExp(arg.substring(16));
process.argv.splice(i, 1);
}
else if (arg === "--no-css-inject") {
opts.noCssInject = true;
process.argv.splice(i, 1);
}
else if (arg === "--no-browser") {
opts.open = false;
process.argv.splice(i, 1);
}
else if (arg.indexOf("--browser=") > -1) {
opts.browser = arg.substring(10).split(",");
process.argv.splice(i, 1);
}
else if (arg.indexOf("--entry-file=") > -1) {
var file = arg.substring(13);
if (file.length) {
opts.file = file;
process.argv.splice(i, 1);
}
}
else if (arg === "--spa") {
opts.middleware.push("spa");
process.argv.splice(i, 1);
}
else if (arg === "--quiet" || arg === "-q") {
opts.logLevel = 0;
process.argv.splice(i, 1);
}
else if (arg === "--verbose" || arg === "-V") {
opts.logLevel = 3;
process.argv.splice(i, 1);
}
else if (arg.indexOf("--mount=") > -1) {
// e.g. "--mount=/components:./node_modules" will be ['/components', '<process.cwd()>/node_modules']
// split only on the first ":", as the path may contain ":" as well (e.g. C:\file.txt)
var match = arg.substring(8).match(/([^:]+):(.+)$/);
match[2] = path.resolve(process.cwd(), match[2]);
opts.mount.push([ match[1], match[2] ]);
process.argv.splice(i, 1);
}
else if (arg.indexOf("--wait=") > -1) {
var waitString = arg.substring(7);
var waitNumber = parseInt(waitString, 10);
if (waitNumber === +waitString) {
opts.wait = waitNumber;
process.argv.splice(i, 1);
}
}
else if (arg === "--version" || arg === "-v") {
var packageJson = require('./package.json');
console.log(packageJson.name, packageJson.version);
process.exit();
}
else if (arg.indexOf("--htpasswd=") > -1) {
opts.htpasswd = arg.substring(11);
process.argv.splice(i, 1);
}
else if (arg === "--cors") {
opts.cors = true;
process.argv.splice(i, 1);
}
else if (arg.indexOf("--https=") > -1) {
opts.https = arg.substring(8);
process.argv.splice(i, 1);
}
else if (arg.indexOf("--https-module=") > -1) {
opts.httpsModule = arg.substring(15);
process.argv.splice(i, 1);
}
else if (arg.indexOf("--proxy=") > -1) {
// split only on the first ":", as the URL will contain ":" as well
var match = arg.substring(8).match(/([^:]+):(.+)$/);
opts.proxy.push([ match[1], match[2] ]);
process.argv.splice(i, 1);
}
else if (arg.indexOf("--middleware=") > -1) {
opts.middleware.push(arg.substring(13));
process.argv.splice(i, 1);
}
else if (arg === "--help" || arg === "-h") {
console.log('Usage: live-server [-v|--version] [-h|--help] [-q|--quiet] [--port=PORT] [--host=HOST] [--open=PATH] [--no-browser] [--browser=BROWSER] [--ignore=PATH] [--ignorePattern=RGXP] [--no-css-inject] [--entry-file=PATH] [--spa] [--mount=ROUTE:PATH] [--wait=MILLISECONDS] [--htpasswd=PATH] [--cors] [--https=PATH] [--https-module=MODULE_NAME] [--proxy=PATH] [PATH]');
process.exit();
}
else if (arg === "--test") {
// Hidden param for tests to exit automatically
setTimeout(liveServer.shutdown, 500);
process.argv.splice(i, 1);
}
}
// Patch paths
var dir = opts.root = process.argv[2] || "";
if (opts.watch) {
opts.watch = opts.watch.map(function(relativePath) {
return path.join(dir, relativePath);
});
}
if (opts.ignore) {
opts.ignore = opts.ignore.map(function(relativePath) {
return path.join(dir, relativePath);
});
}
liveServer.start(opts);

View File

@@ -0,0 +1,5 @@
module.exports = function(req, res, next) {
res.statusCode = 202;
next();
}

View File

@@ -0,0 +1,14 @@
// Single Page Apps - redirect to /#/ except when a file extension is given
var path = require('path');
module.exports = function(req, res, next) {
if (req.method !== "GET" && req.method !== "HEAD")
next();
if (req.url !== '/' && path.extname(req.url) === '') {
var route = req.url;
req.url = '/';
res.statusCode = 302;
res.setHeader('Location', req.url + '#' + route);
res.end();
}
else next();
}

View File

@@ -0,0 +1,13 @@
// Single Page Apps - redirect to /#/
module.exports = function(req, res, next) {
if (req.method !== "GET" && req.method !== "HEAD")
next();
if (req.url !== '/') {
var route = req.url;
req.url = '/';
res.statusCode = 302;
res.setHeader('Location', req.url + '#' + route);
res.end();
}
else next();
}

View File

@@ -0,0 +1,66 @@
{
"name": "live-server",
"version": "1.2.2",
"description": "simple development http server with live reload capability",
"keywords": [
"front-end",
"development",
"tool",
"server",
"http",
"cli"
],
"author": "Tapio Vierros",
"dependencies": {
"chokidar": "^2.0.4",
"colors": "1.4.0",
"connect": "^3.6.6",
"cors": "latest",
"event-stream": "3.3.4",
"faye-websocket": "0.11.x",
"http-auth": "3.1.x",
"morgan": "^1.9.1",
"object-assign": "latest",
"opn": "latest",
"proxy-middleware": "latest",
"send": "latest",
"serve-index": "^1.9.1"
},
"devDependencies": {
"eslint": "^5.9.0",
"jshint": "^2.9.6",
"mocha": "^5.2.0",
"supertest": "^3.3.0"
},
"scripts": {
"lint": "eslint live-server.js index.js",
"hint": "jshint live-server.js index.js",
"test": "mocha test --exit && npm run lint"
},
"bin": {
"live-server": "./live-server.js"
},
"repository": {
"type": "git",
"url": "https://github.com/tapio/live-server.git"
},
"engines": {
"node": ">=0.10.0"
},
"preferGlobal": true,
"license": "MIT",
"eslintConfig": {
"env": {
"node": true
},
"rules": {
"quotes": 0,
"curly": 0,
"strict": 0,
"no-process-exit": 0,
"eqeqeq": 1,
"no-unused-vars": 1,
"no-shadow": 1
}
}
}

View File

@@ -0,0 +1,67 @@
var request = require('supertest');
var path = require('path');
var liveServer = require('..').start({
root: path.join(__dirname, "data"),
port: 0,
open: false
});
describe('basic functional tests', function(){
it('should respond with index.html', function(done){
request(liveServer)
.get('/')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect(/hello world/i)
.expect(200, done);
});
it('should have injected script', function(done){
request(liveServer)
.get('/')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect(/<script [^]+?live reload enabled[^]+?<\/script>/i)
.expect(200, done);
});
it('should inject script when tags are in CAPS', function(done){
request(liveServer)
.get('/index-caps.htm')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect(/<script [^]+?live reload enabled[^]+?<\/script>/i)
.expect(200, done);
});
it('should inject to <head> when no <body>', function(done){
request(liveServer)
.get('/index-head.html')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect(/<script [^]+?live reload enabled[^]+?<\/script>/i)
.expect(200, done);
});
it('should inject also svg files', function(done){
request(liveServer)
.get('/test.svg')
.expect('Content-Type', 'image/svg+xml')
.expect(function(res) {
if (res.body.toString().indexOf("Live reload enabled") == -1)
throw new Error("injected code not found");
})
.expect(200, done);
});
it('should not inject html fragments', function(done){
request(liveServer)
.get('/fragment.html')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect(function(res) {
if (res.text.toString().indexOf("Live reload enabled") > -1)
throw new Error("injected code should not be found");
})
.expect(200, done);
});
xit('should have WebSocket connection', function(done){
done(); // todo
});
xit('should reload on page change', function(done){
done(); // todo
});
xit('should reload (without refreshing) on css change', function(done){
done(); // todo
});
});

View File

@@ -0,0 +1,65 @@
var assert = require('assert');
var path = require('path');
var exec = require('child_process').execFile;
var cmd = path.join(__dirname, "..", "live-server.js");
var opts = {
timeout: 2000,
maxBuffer: 1024
};
function exec_test(args, callback) {
if (process.platform === 'win32')
exec(process.execPath, [ cmd ].concat(args), opts, callback);
else
exec(cmd, args, opts, callback);
}
describe('command line usage', function() {
it('--version', function(done) {
exec_test([ "--version" ], function(error, stdout, stdin) {
assert(!error, error);
assert(stdout.indexOf("live-server") === 0, "version not found");
done();
});
});
it('--help', function(done) {
exec_test([ "--help" ], function(error, stdout, stdin) {
assert(!error, error);
assert(stdout.indexOf("Usage: live-server") === 0, "usage not found");
done();
});
});
it('--quiet', function(done) {
exec_test([ "--quiet", "--no-browser", "--test" ], function(error, stdout, stdin) {
assert(!error, error);
assert(stdout === "", "stdout not empty");
done();
});
});
it('--port', function(done) {
exec_test([ "--port=16123", "--no-browser", "--test" ], function(error, stdout, stdin) {
assert(!error, error);
assert(stdout.indexOf("Serving") >= 0, "serving string not found");
assert(stdout.indexOf("at http://127.0.0.1:16123") != -1, "port string not found");
done();
});
});
it('--host', function(done) {
exec_test([ "--host=localhost", "--no-browser", "--test" ], function(error, stdout, stdin) {
assert(!error, error);
assert(stdout.indexOf("Serving") >= 0, "serving string not found");
assert(stdout.indexOf("at http://localhost:") != -1, "host string not found");
done();
});
});
it('--htpasswd', function(done) {
exec_test(
[ "--htpasswd=" + path.join(__dirname, "data/htpasswd-test"),
"--no-browser",
"--test"
], function(error, stdout, stdin) {
assert(!error, error);
assert(stdout.indexOf("Serving") >= 0, "serving string not found");
done();
});
});
});

View File

@@ -0,0 +1,7 @@
var fs = require("fs");
module.exports = {
cert: fs.readFileSync(__dirname + "/server.cert"),
key: fs.readFileSync(__dirname + "/server.key"),
passphrase: "12345"
};

View File

@@ -0,0 +1,21 @@
-----BEGIN CERTIFICATE-----
MIIDbzCCAlegAwIBAgIJAITs++EKEa1pMA0GCSqGSIb3DQEBCwUAME4xCzAJBgNV
BAYTAlVTMQ0wCwYDVQQIDAR0ZXN0MQ0wCwYDVQQHDAR0ZXN0MSEwHwYDVQQKDBhJ
bnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwHhcNMTYwNDIzMDgwMDM0WhcNMTYwNTIz
MDgwMDM0WjBOMQswCQYDVQQGEwJVUzENMAsGA1UECAwEdGVzdDENMAsGA1UEBwwE
dGVzdDEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkq
hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnq4nI7HM0JITcpDrBPGBXl6ieVmsboKv
rTDJpLkDj+0kdDYMcdUhBuu4rpuUHnIZMHwPAYPx/uc5jr0OksAUqOmWXdZAgWUb
f7jBzaEQZb1CY8bbv/E/LlRSojPCJZYlQqcS3McGoSV01hPGMVNV3L3rVZGOKIdm
kpjbu/JppCLWpfA7OT/kUAjMnGSgOLMVpc76mUNeDG9ObhArrXImTjvUXntmUFbZ
W9mxgnRCJRK/ttWQp/KSlVJUxtXGCf1u+U9m5tl+/4LqRIfdTvy4NBxg/su3cdgq
Q/McAarhkgc1F141n7T9q7N8/nc2XsYWdMqLAn7NxIEJSUOmS8At/wIDAQABo1Aw
TjAdBgNVHQ4EFgQU+YZux6UXl7e9+rabdFH19GpcaNwwHwYDVR0jBBgwFoAU+YZu
x6UXl7e9+rabdFH19GpcaNwwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC
AQEAQFL7tjp6NQjyoAmuaDyp7PXXVsGNKsN6zmGvdVrF9MVWhKnit0ByO/ytPxVX
ll+7RuKZqrhqm9HA1pStWbBI4P/mcYBqOyafb610DmGukM/++rdIBRQ9acGnIU0M
eg5finMBS4Rc2kmSz5tyHX+taX7J68Y3DUvBCC6VEb6ox+qJsQVVDEadeHjAr8wN
0SJK8/nKQBm7Tk0fEdBfUyyLdOz77i0+tmsJ8PIvPxYF1EVsgBDSz+6DS+Fjmps8
4/wfMM+ai+zBwf9H3bIu5XsHwbTEbLnYpFklwVeHM0sxEk/ZlSEMA9mtXBXaQOWd
yIo6uIKHbMrjbUmj3p65MFhaGQ==
-----END CERTIFICATE-----

View File

@@ -0,0 +1,30 @@
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIHqsvOM36+5UCAggA
MBQGCCqGSIb3DQMHBAgWDDD0SuRyYQSCBMifpjUCkt5NQYPATyi337ouCzeGt/Lw
jhgIUq8UelCGoQFz9omzOfm8XQmkhcwDRl1PX50HTdPeeRuEGs00/6ZjigakHQ+/
CIFhEo9WzjsrZZbUU+wMF1o5eelEmo3bIjUb55VNi60c0Mb8KUE8jnNlZmbcQEjL
wGpqph5moE/EFUmBTIza78XH51BpiSRo2/1mICAbR8k613mQc6eRaTJroleYulnE
+7wEVRTdW9dzt5oWcdK23g+1ayg00Rg9CRDQS85BvyrcSCBvp5HirV3VQWgdgPY/
9AFEogE1uyODp6yHW0RWoj0ycpafJVsQvGkI4tOu+gy38LI2gr4gA2fUEpcyZXiw
eTfQzlSKbsL9Dr1xHFe1o4S/NyFYKW/FJFUkJaskpHTkYBTWeqfqQnOVBv70juyQ
fGKnKaEX+AZj0Huj0bda1Uui8qnkkL3JkZ+AxhlXFkolVuUccIinTvwr3BuxpcBH
6T1hSpnjBf/QAMg5vO165k5dE6JOJb3zQ9byK2md6VDUpwHbubtEa4FdLxOa/6q1
SB/UABnPpyN2c0a1/UxF/PDDe6+Fb2rIIBYx5tB7dATFr6ZhFDh7c77jzZ80g06Z
lOYhV2nB8IT1/mTkq8Apxkw2/aB6W0FIPxTNIGfUsA2be6AFb0a0TiM9XqzTpTNL
6CufCeNUnplf8rbwMsaDU3V3hnPwlStkdLl+7+ipY9FOA7kbTQdBJX8/GWgByZKw
U9AKAGXcNfHKaCpOT83q1XaYQ8Vj1tlC/wSXA8/3ZvX7kRZr5K+iLxUV5UfSA1h0
9C4UUx4rwliWITMFdCTGn1jZbokQo/HX2cF5C5Q2VFtuFz099MykmRgOgcZbFSAo
ioRWfuMyQvhuzEchr08n0WU1FQOrHc/jjHjCKQECQjHAcvHDUwr+Bcbym6n7jSIQ
8NySJcfPS/F5PxSlisuzJzwWJxx3Nqv/KWfMR0wJuKYLyn5P7a6wAg7BZmxmb4TH
0OmaIzeNuy0qMF774fESXTLrk3i9AffXAbIuHTKiYp+QKfIOjLZ4vTr3iZdaOLNw
SSdsLwBgPH8st1MWR+qnk4ry44DE72hW5/uELmfENq9IPc1vA4V88qCTXFNFlYvY
HBTmA7jiLTzyqAVgmXTv5fw7iQ3+1NLNBPNN45rFmWEQcQvqfvla7COxtREAWDh3
1apQJ1A5DIZir5Y2QNFUGgcX8T7tWsE2cWEUqwTGwUQq4ovwkf53+nqnuRJ7In7S
YFTXy2fCDCjuB7GsgGPa4cNH4L1ru85+CQtVOW7FjdmVvrm2cyvtzoYKb/BOLnNO
PVjWb7gTBxEqKv2LnxdTb+RwtSn7T3cjBTgXHqR97ZNru9CMKtRVlR6b+H/1pbyJ
2fd6AdWRDNAPmDkEY+jADANoiMqlfkQU1UsCkDZu/4EpB80u5OZmeOQitmQIDK0d
kl2Wwmat2jHQrL1sPnbLGMan8g8c3cU6bBqoiJcDlRKu0FMyHTqY4f297XJLi8v9
vk5j6F1buFnnJ3nXtPZBA5W03/G5CyXx6M65dUXV/3ZtukQYE6n68FvU9ADRCm/y
QxohXz60JhV8V9Gailc17ZiiZUXQ6SOfZ1NCHXjbLfDiHDwL3VADnpC2rB2xg7tX
GKQ=
-----END ENCRYPTED PRIVATE KEY-----

View File

@@ -0,0 +1,42 @@
var request = require('supertest');
var path = require('path');
var liveServer = require('..').start({
root: path.join(__dirname, "data"),
port: 0,
open: false,
cors: true
});
describe('cors tests', function() {
it('should respond with appropriate header', function(done) {
request(liveServer)
.get('/index.html')
.set('Origin', 'http://example.com')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect('Access-Control-Allow-Origin', 'http://example.com')
.expect(/Hello world/i)
.expect(200, done);
});
it('should support preflighted requests', function(done) {
request(liveServer)
.options('/index.html')
.set('Origin', 'http://example.com')
.set('Access-Control-Request-Method', 'POST')
.set('Access-Control-Request-Headers', 'X-PINGOTHER')
.expect('Access-Control-Allow-Origin', 'http://example.com')
.expect('Access-Control-Allow-Methods', /POST/)
.expect('Access-Control-Allow-Headers', 'X-PINGOTHER')
.expect(204, done);
});
it('should support requests with credentials', function(done) {
request(liveServer)
.options('/index.html')
.set('Origin', 'http://example.com')
.set('Cookie', 'foo=bar')
.expect('Access-Control-Allow-Origin', 'http://example.com')
.expect('Access-Control-Allow-Credentials', 'true')
.expect(204, done);
});
});

View File

@@ -0,0 +1,3 @@
<h1>
{{this imitates some kind of template fragment}}
</h1>

View File

@@ -0,0 +1 @@
test:$apr1$edJu7/51$LVD5BTHDtDMzzeeYnWXCL1

View File

@@ -0,0 +1,13 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML lang="en">
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=utf-8" >
<TITLE>Live-server Test Page</TITLE>
<LINK rel="stylesheet" href="style.css" >
</HEAD>
<BODY>
<H1>Hello world.</H1>
<P>These tags are in capitals.</P>
</BODY>
</HTML>

View File

@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live-server Test Page</title>
<link rel="stylesheet" href="style.css" />
</head>
</html>

View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live-server Test Page</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Hello world.</h1>
<p>Edit my css for a live-reload without refreshing.</p>
</body>
</html>

View File

@@ -0,0 +1,5 @@
module.exports = function(req, res, next) {
res.statusCode = 203;
next();
}

View File

@@ -0,0 +1 @@
h1 { color: red; }

View File

@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live-server Test Page</title>
</head>
<body>
<h1>Subdirectory</h1>
</body>
</html>

View File

@@ -0,0 +1,14 @@
<svg width="100%" height="100%" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<script type="text/javascript">
// <![CDATA[
function change(evt) {
var target = evt.target;
var radius = target.getAttribute("r");
radius = (radius == 15) ? 45 : 15
target.setAttribute("r", radius);
}
// ]]>
</script>
<circle cx="50" cy="50" r="45" fill="green" onclick="change(evt)" />
</svg>

After

Width:  |  Height:  |  Size: 415 B

View File

@@ -0,0 +1,28 @@
var request = require('supertest');
var path = require('path');
var liveServer = require('..').start({
root: path.join(__dirname, "data"),
port: 0,
open: false,
htpasswd: path.join(__dirname, "data", "htpasswd-test")
});
describe('htpasswd tests', function() {
it('should respond with 401 since no password is given', function(done) {
request(liveServer)
.get('/')
.expect(401, done);
});
it('should respond with 401 since wrong password is given', function(done) {
request(liveServer)
.get('/')
.auth("test", "not-real-password")
.expect(401, done);
});
it('should respond with 200 since correct password is given', function(done) {
request(liveServer)
.get('/')
.auth("test", "test")
.expect(200, done);
});
});

View File

@@ -0,0 +1,48 @@
var request = require('supertest');
var path = require('path');
// accept self-signed certificates
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
function tests(liveServer) {
it('should reply with a correct index file', function(done) {
request(liveServer)
.get('/index.html')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect(/Hello world/i)
.expect(200, done);
});
it('should support head request', function(done) {
request(liveServer)
.head('/index.html')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect(200, done);
});
}
describe('https tests with external module', function() {
var opts = {
root: path.join(__dirname, 'data'),
port: 0,
open: false,
https: path.join(__dirname, 'conf/https.conf.js')
};
var liveServer = require("..").start(opts);
tests(liveServer);
after(function () {
liveServer.close()
});
});
describe('https tests with object', function() {
var opts = {
root: path.join(__dirname, 'data'),
port: 0,
open: false,
https: require(path.join(__dirname, 'conf/https.conf.js'))
};
var liveServer = require("..").start(opts);
tests(liveServer);
after(function () {
liveServer.close()
});
});

View File

@@ -0,0 +1,43 @@
var request = require('supertest');
var path = require('path');
var liveServer1 = require('..').start({
root: path.join(__dirname, 'data'),
port: 0,
open: false,
middleware: [
function setStatus(req, res, next) {
res.statusCode = 201;
next();
}
]
});
var liveServer2 = require('..').start({
root: path.join(__dirname, 'data'),
port: 0,
open: false,
middleware: [ "example" ]
});
var liveServer3 = require('..').start({
root: path.join(__dirname, 'data'),
port: 0,
open: false,
middleware: [ path.join(__dirname, 'data', 'middleware.js') ]
});
describe('middleware tests', function() {
it("should respond with middleware function's status code", function(done) {
request(liveServer1)
.get('/')
.expect(201, done);
});
it("should respond with built-in middleware's status code", function(done) {
request(liveServer2)
.get('/')
.expect(202, done);
});
it("should respond with external middleware's status code", function(done) {
request(liveServer3)
.get('/')
.expect(203, done);
});
});

View File

@@ -0,0 +1,30 @@
var request = require('supertest');
var path = require('path');
var liveServer = require('..').start({
root: path.join(__dirname, "data"),
port: 0,
open: false,
mount: [
[ "/mounted", path.join(__dirname, "data", "sub") ],
[ "/style", path.join(__dirname, "data", "style.css") ]
]
});
describe('mount tests', function() {
it('should respond with sub.html', function(done) {
request(liveServer)
.get('/mounted/sub.html')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect(/Subdirectory/i)
.expect(200, done);
});
it('should respond with style.css', function(done) {
request(liveServer)
.get('/style')
.expect('Content-Type', 'text/css; charset=UTF-8')
.expect(/color/i)
.expect(200, done);
});
});

View File

@@ -0,0 +1,28 @@
var request = require('supertest');
var path = require('path');
var port = 40200;
var server1 = require('..').start({
root: path.join(__dirname, "data"),
port: port,
open: false
});
var server2 = require('..').start({
root: path.join(__dirname, "data"),
port: 0,
open: false,
proxy: [
["/server1", "http://localhost:" + port]
]
});
describe('proxy tests', function() {
it('should respond with proxied content', function(done) {
request(server2)
.get('/server1/index.html')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect(/Hello world/i)
.expect(200, done);
});
});

View File

@@ -0,0 +1,40 @@
var request = require('supertest');
var path = require('path');
var liveServerSpa = require('..').start({
root: path.join(__dirname, "data"),
port: 0,
open: false,
middleware: [ "spa" ]
});
var liveServerSpaIgnoreAssets = require('..').start({
root: path.join(__dirname, "data"),
port: 0,
open: false,
middleware: [ "spa-ignore-assets" ]
});
describe('spa tests', function(){
it('spa should redirect', function(done){
request(liveServerSpa)
.get('/api')
.expect('Location', /\/#\//)
.expect(302, done);
});
it('spa should redirect everything', function(done){
request(liveServerSpa)
.get('/style.css')
.expect('Location', /\/#\//)
.expect(302, done);
});
it('spa-ignore-assets should redirect something', function(done){
request(liveServerSpaIgnoreAssets)
.get('/api')
.expect('Location', /\/#\//)
.expect(302, done);
});
it('spa-ignore-assets should not redirect .css', function(done){
request(liveServerSpaIgnoreAssets)
.get('/style.css')
.expect(200, done);
});
});