nav tabs on admin dashboard

This commit is contained in:
2019-03-07 00:20:34 -06:00
parent f73d6ae228
commit e4f473f376
11661 changed files with 216240 additions and 1544253 deletions

View File

@@ -1,3 +1,9 @@
<div align="center">
<a href="https://github.com/webpack/webpack">
<img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
</div>
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
@@ -5,206 +11,429 @@
[![coverage][cover]][cover-url]
[![chat][chat]][chat-url]
<div align="center">
<a href="https://github.com/webpack/webpack">
<img width="200" height="200"
src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
<h1>webpack Dev Middleware</h1>
</div>
# webpack-dev-middleware
It's a simple wrapper middleware for webpack. It serves the files emitted from webpack over a connect server. This should be used for **development only**.
An express-style development middleware for use with [webpack](https://webpack.js.org)
bundles and allows for serving of the files emitted from webpack.
This should be used for **development only**.
It has a few advantages over bundling it as files:
Some of the benefits of using this middleware include:
* No files are written to disk, it handle the files in memory
* If files changed in watch mode, the middleware no longer serves the old bundle, but delays requests until the compiling has finished. You don't have to wait before refreshing the page after a file modification.
* I may add some specific optimization in future releases.
- No files are written to disk, rather it handles files in memory
- If files changed in watch mode, the middleware delays requests until compiling
has completed.
- Supports hot module reload (HMR).
<h2 align="center">Install</h2>
## Requirements
```
This module requires a minimum of Node v6.9.0 and Webpack v4.0.0, and must be used with a
server that accepts express-style middleware.
## Getting Started
First thing's first, install the module:
```console
npm install webpack-dev-middleware --save-dev
```
<h2 align="center">Usage</h2>
_Note: We do not recommend installing this module globally._
``` javascript
var webpackMiddleware = require("webpack-dev-middleware");
app.use(webpackMiddleware(...));
```
## Usage
Example usage:
```js
const webpack = require('webpack');
const middleware = require('webpack-dev-middleware');
const compiler = webpack({ .. webpack options .. });
const express = require('express');
const app = express();
``` javascript
app.use(webpackMiddleware(webpack({
// webpack options
// webpackMiddleware takes a Compiler object as first parameter
// which is returned by webpack(...) without callback.
entry: "...",
output: {
path: "/"
// no real path is required, just pass "/"
// but it will work with other paths too.
}
}), {
// publicPath is required, whereas all other options are optional
noInfo: false,
// display no info to console (only warnings and errors)
quiet: false,
// display nothing to the console
lazy: true,
// switch into lazy mode
// that means no watching, but recompilation on every request
watchOptions: {
aggregateTimeout: 300,
poll: true
},
// watch options (only lazy: false)
publicPath: "/assets/",
// public path to bind the middleware to
// use the same as in webpack
index: "index.html",
// The index path for web server, defaults to "index.html".
// If falsy (but not undefined), the server will not respond to requests to the root URL.
headers: { "X-Custom-Header": "yes" },
// custom headers
mimeTypes: { "text/html": [ "phtml" ] },
// Add custom mime/extension mappings
// https://github.com/broofa/node-mime#mimedefine
// https://github.com/webpack/webpack-dev-middleware/pull/150
stats: {
colors: true
},
// options for formating the statistics
reporter: null,
// Provide a custom reporter to change the way how logs are shown.
serverSideRender: false,
// Turn off the server-side rendering mode. See Server-Side Rendering part for more info.
app.use(middleware(compiler, {
// webpack-dev-middleware options
}));
app.listen(3000, () => console.log('Example app listening on port 3000!'))
```
## Advanced API
## Options
This part shows how you might interact with the middleware during runtime:
The middleware accepts an `options` Object. The following is a property reference
for the Object.
* `close(callback)` - stop watching for file changes
```js
var webpackDevMiddlewareInstance = webpackMiddleware(/* see example usage */);
app.use(webpackDevMiddlewareInstance);
// After 10 seconds stop watching for file changes:
setTimeout(function(){
webpackDevMiddlewareInstance.close();
}, 10000);
```
_Note: The `publicPath` property is required, whereas all other options are optional_
* `invalidate()` - recompile the bundle - e.g. after you changed the configuration
```js
var compiler = webpack(/* see example usage */);
var webpackDevMiddlewareInstance = webpackMiddleware(compiler);
app.use(webpackDevMiddlewareInstance);
setTimeout(function(){
// After a short delay the configuration is changed
// in this example we will just add a banner plugin:
compiler.apply(new webpack.BannerPlugin('A new banner'));
// Recompile the bundle with the banner plugin:
webpackDevMiddlewareInstance.invalidate();
}, 1000);
```
### methods
* `waitUntilValid(callback)` - executes the `callback` if the bundle is valid or after it is valid again:
```js
var webpackDevMiddlewareInstance = webpackMiddleware(/* see example usage */);
app.use(webpackDevMiddlewareInstance);
webpackDevMiddlewareInstance.waitUntilValid(function(){
console.log('Package is in a valid state');
});
```
Type: `Array`
Default: `[ 'GET' ]`
This property allows a user to pass the list of HTTP request methods accepted by the server.
### headers
Type: `Object`
Default: `undefined`
This property allows a user to pass custom HTTP headers on each request. eg.
`{ "X-Custom-Header": "yes" }`
### index
Type: `String`
Default: `undefined`
"index.html",
// The index path for web server, defaults to "index.html".
// If falsy (but not undefined), the server will not respond to requests to the root URL.
### lazy
Type: `Boolean`
Default: `undefined`
This option instructs the module to operate in 'lazy' mode, meaning that it won't
recompile when files change, but rather on each request.
### logger
Type: `Object`
Default: [`webpack-log`](https://github.com/webpack-contrib/webpack-log/blob/master/index.js)
In the rare event that a user would like to provide a custom logging interface,
this property allows the user to assign one. The module leverages
[`webpack-log`](https://github.com/webpack-contrib/webpack-log#readme)
for creating the [`loglevelnext`](https://github.com/shellscape/loglevelnext#readme)
logging management by default. Any custom logger must adhere to the same
exports for compatibility. Specifically, all custom loggers must have the
following exported methods at a minimum:
- `log.trace`
- `log.debug`
- `log.info`
- `log.warn`
- `log.error`
Please see the documentation for `loglevel` for more information.
### logLevel
Type: `String`
Default: `'info'`
This property defines the level of messages that the module will log. Valid levels
include:
- `trace`
- `debug`
- `info`
- `warn`
- `error`
- `silent`
Setting a log level means that all other levels below it will be visible in the
console. Setting `logLevel: 'silent'` will hide all console output. The module
leverages [`webpack-log`](https://github.com/webpack-contrib/webpack-log#readme)
for logging management, and more information can be found on its page.
### logTime
Type: `Boolean`
Default: `false`
If `true` the log output of the module will be prefixed by a timestamp in the
`HH:mm:ss` format.
### mimeTypes
Type: `Object`
Default: `null`
This property allows a user to register custom mime types or extension mappings.
eg. `mimeTypes: { 'text/html': [ 'phtml' ] }`.
By default node-mime will throw an error if you try to map a type to an extension
that is already assigned to another type. Passing `force: true` will suppress this behavior
(overriding any previous mapping).
eg. `mimeTypes: { typeMap: { 'text/html': [ 'phtml' ] } }, force: true }`.
Please see the documentation for
[`node-mime`](https://github.com/broofa/node-mime#mimedefinetypemap-force--false) for more information.
### publicPath
Type: `String`
_Required_
The public path that the middleware is bound to. _Best Practice: use the same
`publicPath` defined in your webpack config. For more information about
`publicPath`, please see
[the webpack documentation](https://webpack.js.org/guides/public-path)._
### reporter
Type: `Object`
Default: `undefined`
Allows users to provide a custom reporter to handle logging within the module.
Please see the [default reporter](/lib/reporter.js)
for an example.
### serverSideRender
Type: `Boolean`
Default: `undefined`
Instructs the module to enable or disable the server-side rendering mode. Please
see [Server-Side Rendering](#server-side-rendering) for more information.
### stats
Type: `Object`
Default: `{ context: process.cwd() }`
Options for formatting statistics displayed during and after compile. For more
information and property details, please see the
[webpack documentation](https://webpack.js.org/configuration/stats/#stats).
### watchOptions
Type: `Object`
Default: `{ aggregateTimeout: 200 }`
The module accepts an `Object` containing options for file watching, which is
passed directly to the compiler provided. For more information on watch options
please see the [webpack documentation](https://webpack.js.org/configuration/watch/#watchoptions)
### writeToDisk
Type: `Boolean|Function`
Default: `false`
If `true`, the option will instruct the module to write files to the configured
location on disk as specified in your `webpack` config file. _Setting
`writeToDisk: true` won't change the behavior of the `webpack-dev-middleware`,
and bundle files accessed through the browser will still be served from memory._
This option provides the same capabilities as the
[`WriteFilePlugin`](https://github.com/gajus/write-file-webpack-plugin/pulls).
This option also accepts a `Function` value, which can be used to filter which
files are written to disk. The function follows the same premise as
[`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
in which a return value of `false` _will not_ write the file, and a return value
of `true` _will_ write the file to disk. eg.
```js
{
writeToDisk: (filePath) => {
return /superman\.css$/.test(filePath);
}
}
```
### fs
Type: `Object`
Default: `MemoryFileSystem`
Set the default file system which will be used by webpack as primary destination of generated files. Default is set to webpack's default file system: [memory-fs](https://github.com/webpack/memory-fs). This option isn't affected by the [writeToDisk](#writeToDisk) option.
**Note:** As of 3.5.x version of the middleware you have to provide `.join()` method to the `fs` instance manually. This can be done simply by using `path.join`:
```js
fs.join = path.join // no need to bind
```
## API
`webpack-dev-middleware` also provides convenience methods that can be use to
interact with the middleware at runtime:
### `close(callback)`
Instructs a webpack-dev-middleware instance to stop watching for file changes.
### Parameters
#### callback
Type: `Function`
A function executed once the middleware has stopped watching.
### `invalidate()`
Instructs a webpack-dev-middleware instance to recompile the bundle.
e.g. after a change to the configuration.
```js
const webpack = require('webpack');
const compiler = webpack({ ... });
const middleware = require('webpack-dev-middleware');
const instance = middleware(compiler);
app.use(instance);
setTimeout(() => {
// After a short delay the configuration is changed and a banner plugin is added
// to the config
compiler.apply(new webpack.BannerPlugin('A new banner'));
// Recompile the bundle with the banner plugin:
instance.invalidate();
}, 1000);
```
### `waitUntilValid(callback)`
Executes a callback function when the compiler bundle is valid, typically after
compilation.
### Parameters
#### callback
Type: `Function`
A function executed when the bundle becomes valid. If the bundle is
valid at the time of calling, the callback is executed immediately.
```js
const webpack = require('webpack');
const compiler = webpack({ ... });
const middleware = require('webpack-dev-middleware');
const instance = middleware(compiler);
app.use(instance);
instance.waitUntilValid(() => {
console.log('Package is in a valid state');
});
```
## Known Issues
### Multiple Successive Builds
Watching (by means of `lazy: false`) will frequently cause multiple compilations
as the bundle changes during compilation. This is due in part to cross-platform
differences in file watchers, so that webpack doesn't loose file changes when
watched files change rapidly. If you run into this situation, please make use of
the [`TimeFixPlugin`](https://github.com/egoist/time-fix-plugin).
## Server-Side Rendering
**Note: this feature is experimental and may be removed or changed completely in the future.**
_Note: this feature is experimental and may be removed or changed completely in the future._
In order to develop a server-side rendering application, we need access to the [`stats`](https://github.com/webpack/docs/wiki/node.js-api#stats), which is generated with the latest build.
In order to develop an app using server-side rendering, we need access to the
[`stats`](https://github.com/webpack/docs/wiki/node.js-api#stats), which is
generated with each build.
In the server-side rendering mode, __webpack-dev-middleware__ sets the `stat` to `res.locals.webpackStats` before invoking the next middleware, allowing a developer to render the page body and manage the response to clients.
With server-side rendering enabled, `webpack-dev-middleware` sets the `stat` to
`res.locals.webpackStats` and the memory filesystem to `res.locals.fs` before invoking the next middleware, allowing a
developer to render the page body and manage the response to clients.
Notice that requests for bundle files would still be responded by __webpack-dev-middleware__ and all requests will be pending until the building process is finished in the server-side rendering mode.
_Note: Requests for bundle files will still be handled by
`webpack-dev-middleware` and all requests will be pending until the build
process is finished with server-side rendering enabled._
Example Implementation:
```js
const webpack = require('webpack');
const compiler = webpack({ ... });
const isObject = require('is-object');
const middleware = require('webpack-dev-middleware');
```javascript
// This function makes server rendering of asset references consistent with different webpack chunk/entry configurations
function normalizeAssets(assets) {
if (isObject(assets)) {
return Object.values(assets)
}
return Array.isArray(assets) ? assets : [assets]
}
app.use(webpackMiddleware(compiler, { serverSideRender: true })
app.use(middleware(compiler, { serverSideRender: true }))
// The following middleware would not be invoked until the latest build is finished.
app.use((req, res) => {
const assetsByChunkName = res.locals.webpackStats.toJson().assetsByChunkName
const fs = res.locals.fs
const outputPath = res.locals.webpackStats.toJson().outputPath
// then use `assetsByChunkName` for server-sider rendering
// For example, if you have only one main chunk:
res.send(`
res.send(`
<html>
<head>
<title>My App</title>
${
normalizeAssets(assetsByChunkName.main)
.filter(path => path.endsWith('.css'))
.map(path => `<link rel="stylesheet" href="${path}" />`)
.join('\n')
}
<style>
${normalizeAssets(assetsByChunkName.main)
.filter(path => path.endsWith('.css'))
.map(path => fs.readFileSync(outputPath + '/' + path))
.join('\n')}
</style>
</head>
<body>
<div id="root"></div>
${
normalizeAssets(assetsByChunkName.main)
.filter(path => path.endsWith('.js'))
.map(path => `<script src="${path}"></script>`)
.join('\n')
}
${normalizeAssets(assetsByChunkName.main)
.filter(path => path.endsWith('.js'))
.map(path => `<script src="${path}"></script>`)
.join('\n')}
</body>
</html>
`)
</html>
`)
})
```
<h2 align="center">Contributing</h2>
## Support
Don't hesitate to create a pull request. Every contribution is appreciated. In development you can start the tests by calling `npm test`.
We do our best to keep Issues in the repository focused on bugs, features, and
needed modifications to the code for the module. Because of that, we ask users
with general support, "how-to", or "why isn't this working" questions to try one
of the other support channels that are available.
<h2 align="center">Maintainers</h2>
Your first-stop-shop for support for webpack-dev-server should by the excellent
[documentation][docs-url] for the module. If you see an opportunity for improvement
of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a
pull request.
From there, we encourage users to visit the [webpack Gitter chat][chat-url] and
talk to the fine folks there. If your quest for answers comes up dry in chat,
head over to [StackOverflow][stack-url] and do a quick search or open a new
question. Remember; It's always much easier to answer questions that include your
`webpack.config.js` and relevant files!
If you're twitter-savvy you can tweet [#webpack][hash-url] with your question
and someone should be able to reach out and lend a hand.
If you have discovered a :bug:, have a feature suggestion, of would like to see
a modification, please feel free to create an issue on Github. _Note: The issue
template isn't optional, so please be sure not to remove it, and please fill it
out completely._
## Contributing
We welcome your contributions! Please have a read of [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to get involved.
## Maintainers
<table>
<tbody>
<tr>
<td align="center">
<img width="150 height="150"
src="https://avatars.githubusercontent.com/SpaceK33z?v=3">
<img src="https://avatars.githubusercontent.com/SpaceK33z?v=4&s=150">
<br />
<a href="https://github.com/SpaceK33z">Kees Kluskens</a>
</td>
<tr>
<tbody>
<td align="center">
<img src="https://i.imgur.com/4v6pgxh.png">
<br />
<a href="https://github.com/shellscape">Andrew Powell</a>
</td>
</tr>
</tbody>
</table>
<h2 align="center">LICENSE</h2>
## License
#### [MIT](./LICENSE)
@@ -225,3 +454,10 @@ Don't hesitate to create a pull request. Every contribution is appreciated. In d
[chat]: https://badges.gitter.im/webpack/webpack.svg
[chat-url]: https://gitter.im/webpack/webpack
[docs-url]: https://webpack.js.org/guides/development/#using-webpack-dev-middleware
[hash-url]: https://twitter.com/search?q=webpack
[middleware-url]: https://github.com/webpack/webpack-dev-middleware
[stack-url]: https://stackoverflow.com/questions/tagged/webpack-dev-middleware
[uglify-url]: https://github.com/webpack-contrib/uglifyjs-webpack-plugin
[wjo-url]: https://github.com/webpack/webpack.js.org

View File

@@ -1,63 +0,0 @@
var pathJoin = require("./PathJoin");
var querystring = require("querystring");
var urlParse = require("url").parse;
function getFilenameFromUrl(publicPath, outputPath, url) {
var filename;
// localPrefix is the folder our bundle should be in
var localPrefix = urlParse(publicPath || "/", false, true);
var urlObject = urlParse(url);
// publicPath has the hostname that is not the same as request url's, should fail
if(localPrefix.hostname !== null && urlObject.hostname !== null &&
localPrefix.hostname !== urlObject.hostname) {
return false;
}
// publicPath is not in url, so it should fail
if(publicPath && localPrefix.hostname === urlObject.hostname && url.indexOf(publicPath) !== 0) {
return false;
}
// strip localPrefix from the start of url
if(urlObject.pathname.indexOf(localPrefix.pathname) === 0) {
filename = urlObject.pathname.substr(localPrefix.pathname.length);
}
if(!urlObject.hostname && localPrefix.hostname &&
url.indexOf(localPrefix.path) !== 0) {
return false;
}
// and if not match, use outputPath as filename
return querystring.unescape(filename ? pathJoin(outputPath, filename) : outputPath);
}
// support for multi-compiler configuration
// see: https://github.com/webpack/webpack-dev-server/issues/641
function getPaths(publicPath, compiler, url) {
var compilers = compiler && compiler.compilers;
if(Array.isArray(compilers)) {
var compilerPublicPath;
for(var i = 0; i < compilers.length; i++) {
compilerPublicPath = compilers[i].options
&& compilers[i].options.output
&& compilers[i].options.output.publicPath;
if(url.indexOf(compilerPublicPath) === 0) {
return {
publicPath: compilerPublicPath,
outputPath: compilers[i].outputPath
};
}
}
}
return {
publicPath: publicPath,
outputPath: compiler.outputPath
};
}
module.exports = function(publicPath, compiler, url) {
var paths = getPaths(publicPath, compiler, url);
return getFilenameFromUrl(paths.publicPath, paths.outputPath, url);
};

View File

@@ -1,5 +0,0 @@
function pathJoin(a, b) {
return a == "/" ? "/" + b : (a || "") + "/" + b;
}
module.exports = pathJoin;

View File

@@ -1,240 +0,0 @@
var mime = require("mime");
var parseRange = require("range-parser");
var pathIsAbsolute = require("path-is-absolute");
var MemoryFileSystem = require("memory-fs");
var timestamp = require("time-stamp");
var HASH_REGEXP = /[0-9a-f]{10,}/;
module.exports = function Shared(context) {
var share = {
setOptions: function(options) {
if(!options) options = {};
if(typeof options.reportTime === "undefined") options.reportTime = false;
if(typeof options.watchOptions === "undefined") options.watchOptions = {};
if(typeof options.reporter !== "function") options.reporter = share.defaultReporter;
if(typeof options.log !== "function") options.log = console.log.bind(console);
if(typeof options.warn !== "function") options.warn = console.warn.bind(console);
if(typeof options.error !== "function") options.error = console.error.bind(console);
if(typeof options.watchDelay !== "undefined") {
// TODO remove this in next major version
options.warn("options.watchDelay is deprecated: Use 'options.watchOptions.aggregateTimeout' instead");
options.watchOptions.aggregateTimeout = options.watchDelay;
}
if(typeof options.watchOptions.aggregateTimeout === "undefined") options.watchOptions.aggregateTimeout = 200;
if(typeof options.stats === "undefined") options.stats = {};
if(!options.stats.context) options.stats.context = process.cwd();
if(options.lazy) {
if(typeof options.filename === "string") {
var str = options.filename
.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
.replace(/\\\[[a-z]+\\\]/ig, ".+");
options.filename = new RegExp("^[\/]{0,1}" + str + "$");
}
}
// defining custom MIME type
if(options.mimeTypes) mime.define(options.mimeTypes);
context.options = options;
},
defaultReporter: function(reporterOptions) {
var time = "";
var state = reporterOptions.state;
var stats = reporterOptions.stats;
var options = reporterOptions.options;
if(!!options.reportTime) {
time = "[" + timestamp("HH:mm:ss") + "] ";
}
if(state) {
var displayStats = (!options.quiet && options.stats !== false);
if(displayStats && !(stats.hasErrors() || stats.hasWarnings()) &&
options.noInfo)
displayStats = false;
if(displayStats) {
if(stats.hasErrors()) {
options.error(stats.toString(options.stats));
} else if(stats.hasWarnings()) {
options.warn(stats.toString(options.stats));
} else {
options.log(stats.toString(options.stats));
}
}
if(!options.noInfo && !options.quiet) {
var msg = "Compiled successfully.";
if(stats.hasErrors()) {
msg = "Failed to compile.";
} else if(stats.hasWarnings()) {
msg = "Compiled with warnings.";
}
options.log(time + "webpack: " + msg);
}
} else {
options.log(time + "webpack: Compiling...");
}
},
handleRangeHeaders: function handleRangeHeaders(content, req, res) {
//assumes express API. For other servers, need to add logic to access alternative header APIs
res.setHeader("Accept-Ranges", "bytes");
if(req.headers.range) {
var ranges = parseRange(content.length, req.headers.range);
// unsatisfiable
if(-1 == ranges) {
res.setHeader("Content-Range", "bytes */" + content.length);
res.statusCode = 416;
}
// valid (syntactically invalid/multiple ranges are treated as a regular response)
if(-2 != ranges && ranges.length === 1) {
// Content-Range
res.statusCode = 206;
var length = content.length;
res.setHeader(
"Content-Range",
"bytes " + ranges[0].start + "-" + ranges[0].end + "/" + length
);
content = content.slice(ranges[0].start, ranges[0].end + 1);
}
}
return content;
},
setFs: function(compiler) {
if(typeof compiler.outputPath === "string" && !pathIsAbsolute.posix(compiler.outputPath) && !pathIsAbsolute.win32(compiler.outputPath)) {
throw new Error("`output.path` needs to be an absolute path or `/`.");
}
// store our files in memory
var fs;
var isMemoryFs = !compiler.compilers && compiler.outputFileSystem instanceof MemoryFileSystem;
if(isMemoryFs) {
fs = compiler.outputFileSystem;
} else {
fs = compiler.outputFileSystem = new MemoryFileSystem();
}
context.fs = fs;
},
compilerDone: function(stats) {
// We are now on valid state
context.state = true;
context.webpackStats = stats;
// Do the stuff in nextTick, because bundle may be invalidated
// if a change happened while compiling
process.nextTick(function() {
// check if still in valid state
if(!context.state) return;
// print webpack output
context.options.reporter({
state: true,
stats: stats,
options: context.options
});
// execute callback that are delayed
var cbs = context.callbacks;
context.callbacks = [];
cbs.forEach(function continueBecauseBundleAvailable(cb) {
cb(stats);
});
});
// In lazy mode, we may issue another rebuild
if(context.forceRebuild) {
context.forceRebuild = false;
share.rebuild();
}
},
compilerInvalid: function() {
if(context.state && (!context.options.noInfo && !context.options.quiet))
context.options.reporter({
state: false,
options: context.options
});
// We are now in invalid state
context.state = false;
//resolve async
if(arguments.length === 2 && typeof arguments[1] === "function") {
var callback = arguments[1];
callback();
}
},
ready: function ready(fn, req) {
var options = context.options;
if(context.state) return fn(context.webpackStats);
if(!options.noInfo && !options.quiet)
options.log("webpack: wait until bundle finished: " + (req.url || fn.name));
context.callbacks.push(fn);
},
startWatch: function() {
var options = context.options;
var compiler = context.compiler;
// start watching
if(!options.lazy) {
var watching = compiler.watch(options.watchOptions, share.handleCompilerCallback);
context.watching = watching;
} else {
context.state = true;
}
},
rebuild: function rebuild() {
if(context.state) {
context.state = false;
context.compiler.run(share.handleCompilerCallback);
} else {
context.forceRebuild = true;
}
},
handleCompilerCallback: function(err) {
if(err) {
context.options.error(err.stack || err);
if(err.details) context.options.error(err.details);
}
},
handleRequest: function(filename, processRequest, req) {
// in lazy mode, rebuild on bundle request
if(context.options.lazy && (!context.options.filename || context.options.filename.test(filename)))
share.rebuild();
if(HASH_REGEXP.test(filename)) {
try {
if(context.fs.statSync(filename).isFile()) {
processRequest();
return;
}
} catch(e) {
}
}
share.ready(processRequest, req);
},
waitUntilValid: function(callback) {
callback = callback || function() {};
share.ready(callback, {});
},
invalidate: function(callback) {
callback = callback || function() {};
if(context.watching) {
share.ready(callback, {});
context.watching.invalidate();
} else {
callback();
}
},
close: function(callback) {
callback = callback || function() {};
if(context.watching) context.watching.close(callback);
else callback();
}
};
share.setOptions(context.options);
share.setFs(context.compiler);
context.compiler.plugin("done", share.compilerDone);
context.compiler.plugin("invalid", share.compilerInvalid);
context.compiler.plugin("watch-run", share.compilerInvalid);
context.compiler.plugin("run", share.compilerInvalid);
share.startWatch();
return share;
};

View File

@@ -1,99 +0,0 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var mime = require("mime");
var getFilenameFromUrl = require("./lib/GetFilenameFromUrl");
var Shared = require("./lib/Shared");
var pathJoin = require("./lib/PathJoin");
// constructor for the middleware
module.exports = function(compiler, options) {
var context = {
state: false,
webpackStats: undefined,
callbacks: [],
options: options,
compiler: compiler,
watching: undefined,
forceRebuild: false
};
var shared = Shared(context);
// The middleware function
function webpackDevMiddleware(req, res, next) {
function goNext() {
if(!context.options.serverSideRender) return next();
return new Promise(function(resolve) {
shared.ready(function() {
res.locals.webpackStats = context.webpackStats;
resolve(next());
}, req);
});
}
if(req.method !== "GET") {
return goNext();
}
var filename = getFilenameFromUrl(context.options.publicPath, context.compiler, req.url);
if(filename === false) return goNext();
return new Promise(function(resolve) {
shared.handleRequest(filename, processRequest, req);
function processRequest() {
try {
var stat = context.fs.statSync(filename);
if(!stat.isFile()) {
if(stat.isDirectory()) {
var index = context.options.index;
if(index === undefined || index === true) {
index = "index.html";
} else if(!index) {
throw "next";
}
filename = pathJoin(filename, index);
stat = context.fs.statSync(filename);
if(!stat.isFile()) throw "next";
} else {
throw "next";
}
}
} catch(e) {
return resolve(goNext());
}
// server content
var content = context.fs.readFileSync(filename);
content = shared.handleRangeHeaders(content, req, res);
var contentType = mime.lookup(filename);
// do not add charset to WebAssembly files, otherwise compileStreaming will fail in the client
if(!/\.wasm$/.test(filename)) {
contentType += "; charset=UTF-8";
}
res.setHeader("Content-Type", contentType);
res.setHeader("Content-Length", content.length);
if(context.options.headers) {
for(var name in context.options.headers) {
res.setHeader(name, context.options.headers[name]);
}
}
// Express automatically sets the statusCode to 200, but not all servers do (Koa).
res.statusCode = res.statusCode || 200;
if(res.send) res.send(content);
else res.end(content);
resolve();
}
});
}
webpackDevMiddleware.getFilenameFromUrl = getFilenameFromUrl.bind(this, context.options.publicPath, context.compiler);
webpackDevMiddleware.waitUntilValid = shared.waitUntilValid;
webpackDevMiddleware.invalidate = shared.invalidate;
webpackDevMiddleware.close = shared.close;
webpackDevMiddleware.fileSystem = context.fs;
return webpackDevMiddleware;
};

View File

@@ -1,10 +1,95 @@
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="2.4.0"></a>
# [2.4.0](https://github.com/broofa/node-mime/compare/v2.3.1...v2.4.0) (2018-11-26)
### Features
* Bind exported methods ([9d2a7b8](https://github.com/broofa/node-mime/commit/9d2a7b8))
* update to mime-db@1.37.0 ([49e6e41](https://github.com/broofa/node-mime/commit/49e6e41))
<a name="2.3.1"></a>
## [2.3.1](https://github.com/broofa/node-mime/compare/v2.3.0...v2.3.1) (2018-04-11)
### Bug Fixes
* fix [#198](https://github.com/broofa/node-mime/issues/198) ([25ca180](https://github.com/broofa/node-mime/commit/25ca180))
<a name="2.3.0"></a>
# [2.3.0](https://github.com/broofa/node-mime/compare/v2.2.2...v2.3.0) (2018-04-11)
### Bug Fixes
* fix [#192](https://github.com/broofa/node-mime/issues/192) ([5c35df6](https://github.com/broofa/node-mime/commit/5c35df6))
### Features
* add travis-ci testing ([d64160f](https://github.com/broofa/node-mime/commit/d64160f))
<a name="2.2.2"></a>
## [2.2.2](https://github.com/broofa/node-mime/compare/v2.2.1...v2.2.2) (2018-03-30)
### Bug Fixes
* update types files to mime-db@1.32.0 ([85aac16](https://github.com/broofa/node-mime/commit/85aac16))
<a name="2.2.1"></a>
## [2.2.1](https://github.com/broofa/node-mime/compare/v2.2.0...v2.2.1) (2018-03-30)
### Bug Fixes
* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/node-mime/issues/180) ([b5c83fb](https://github.com/broofa/node-mime/commit/b5c83fb))
<a name="2.2.0"></a>
# [2.2.0](https://github.com/broofa/node-mime/compare/v2.1.0...v2.2.0) (2018-01-04)
### Features
* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/node-mime/issues/180) ([10f82ac](https://github.com/broofa/node-mime/commit/10f82ac))
<a name="2.1.0"></a>
# [2.1.0](https://github.com/broofa/node-mime/compare/v2.0.5...v2.1.0) (2017-12-22)
### Features
* Upgrade to mime-db@1.32.0. Fixes [#185](https://github.com/broofa/node-mime/issues/185) ([3f775ba](https://github.com/broofa/node-mime/commit/3f775ba))
<a name="2.0.5"></a>
## [2.0.5](https://github.com/broofa/node-mime/compare/v2.0.1...v2.0.5) (2017-12-22)
### Bug Fixes
* ES5 support (back to node v0.4) ([f14ccb6](https://github.com/broofa/node-mime/commit/f14ccb6))
# Changelog
## v1.6.0 (24/11/2017)
*No changelog for this release.*
---
## v2.0.4 (24/11/2017)
- [**closed**] Switch to mime-score module for resolving extension contention issues. [#182](https://github.com/broofa/node-mime/issues/182)
- [**closed**] Update mime-db to 1.31.0 in v1.x branch [#181](https://github.com/broofa/node-mime/issues/181)
@@ -149,16 +234,3 @@
- [**closed**] Transfer ownership to @broofa [#36](https://github.com/broofa/node-mime/issues/36)
- [**closed**] it's wrong to set charset to UTF-8 for text [#30](https://github.com/broofa/node-mime/issues/30)
- [**closed**] Allow multiple instances of MIME types container [#27](https://github.com/broofa/node-mime/issues/27)
---
## v1.2.5 (16/02/2012)
- [**closed**] When looking up a types, check hasOwnProperty [#23](https://github.com/broofa/node-mime/issues/23)
- [**closed**] Bump version to 1.2.2 [#18](https://github.com/broofa/node-mime/issues/18)
- [**closed**] No license [#16](https://github.com/broofa/node-mime/issues/16)
- [**closed**] Some types missing that are used by html5/css3 [#13](https://github.com/broofa/node-mime/issues/13)
- [**closed**] npm install fails for 1.2.1 [#12](https://github.com/broofa/node-mime/issues/12)
- [**closed**] image/pjpeg + image/x-png [#10](https://github.com/broofa/node-mime/issues/10)
- [**closed**] symlink [#8](https://github.com/broofa/node-mime/issues/8)
- [**closed**] gzip [#2](https://github.com/broofa/node-mime/issues/2)
- [**closed**] ALL CAPS filenames return incorrect mime type [#1](https://github.com/broofa/node-mime/issues/1)

View File

@@ -1,90 +1,190 @@
# mime
<!--
-- This file is auto-generated from src/README_js.md. Changes should be made there.
-->
# Mime
Comprehensive MIME type mapping API based on mime-db module.
A comprehensive, compact MIME type module.
[![Build Status](https://travis-ci.org/broofa/node-mime.svg?branch=master)](https://travis-ci.org/broofa/node-mime)
## Version 2 Notes
Version 2 is a breaking change from 1.x as the semver implies. Specifically:
* `lookup()` renamed to `getType()`
* `extension()` renamed to `getExtension()`
* `charset()` and `load()` methods have been removed
If you prefer the legacy version of this module please `npm install mime@^1`. Version 1 docs may be found [here](https://github.com/broofa/node-mime/tree/v1.4.0).
## Install
Install with [npm](http://github.com/isaacs/npm):
### NPM
```
npm install mime
```
npm install mime
### Browser
## Contributing / Testing
It is recommended that you use a bundler such as
[webpack](https://webpack.github.io/) or [browserify](http://browserify.org/) to
package your code. However, browser-ready versions are available via wzrd.in.
E.g. For the full version:
npm run test
<script src="https://wzrd.in/standalone/mime@latest"></script>
<script>
mime.getType(...); // etc.
<script>
Or, for the `mime/lite` version:
<script src="https://wzrd.in/standalone/mime%2flite@latest"></script>
<script>
mimelite.getType(...); // (Note `mimelite` here)
<script>
## Quick Start
For the full version (800+ MIME types, 1,000+ extensions):
```javascript
const mime = require('mime');
mime.getType('txt'); // ⇨ 'text/plain'
mime.getExtension('text/plain'); // ⇨ 'txt'
```
See [Mime API](#mime-api) below for API details.
## Lite Version
There is also a "lite" version of this module that omits vendor-specific
(`*/vnd.*`) and experimental (`*/x-*`) types. It weighs in at ~2.5KB, compared
to 8KB for the full version. To load the lite version:
```javascript
const mime = require('mime/lite');
```
## Mime .vs. mime-types .vs. mime-db modules
For those of you wondering about the difference between these [popular] NPM modules,
here's a brief rundown ...
[`mime-db`](https://github.com/jshttp/mime-db) is "the source of
truth" for MIME type information. It is not an API. Rather, it is a canonical
dataset of mime type definitions pulled from IANA, Apache, NGINX, and custom mappings
submitted by the Node.js community.
[`mime-types`](https://github.com/jshttp/mime-types) is a thin
wrapper around mime-db that provides an API drop-in compatible(ish) with `mime @ < v1.3.6` API.
`mime` is, as of v2, a self-contained module bundled with a pre-optimized version
of the `mime-db` dataset. It provides a simplified API with the following characteristics:
* Intelligently resolved type conflicts (See [mime-score](https://github.com/broofa/mime-score) for details)
* Method naming consistent with industry best-practices
* Compact footprint. E.g. The minified+compressed sizes of the various modules:
Module | Size
--- | ---
`mime-db` | 18 KB
`mime-types` | same as mime-db
`mime` | 8 KB
`mime/lite` | 2 KB
## Mime API
Both `require('mime')` and `require('mime/lite')` return instances of the MIME
class, documented below.
### new Mime(typeMap, ... more maps)
Most users of this module will not need to create Mime instances directly.
However if you would like to create custom mappings, you may do so as follows
...
```javascript
// Require Mime class
const Mime = require('mime/Mime');
// Define mime type -> extensions map
const typeMap = {
'text/abc': ['abc', 'alpha', 'bet'],
'text/def': ['leppard']
};
// Create and use Mime instance
const myMime = new Mime(typeMap);
myMime.getType('abc'); // ⇨ 'text/abc'
myMime.getExtension('text/def'); // ⇨ 'leppard'
```
If more than one map argument is provided, each map is `define()`ed (see below), in order.
### mime.getType(pathOrExtension)
Get mime type for the given path or extension. E.g.
```javascript
mime.getType('js'); // ⇨ 'application/javascript'
mime.getType('json'); // ⇨ 'application/json'
mime.getType('txt'); // ⇨ 'text/plain'
mime.getType('dir/text.txt'); // ⇨ 'text/plain'
mime.getType('dir\\text.txt'); // ⇨ 'text/plain'
mime.getType('.text.txt'); // ⇨ 'text/plain'
mime.getType('.txt'); // ⇨ 'text/plain'
```
`null` is returned in cases where an extension is not detected or recognized
```javascript
mime.getType('foo/txt'); // ⇨ null
mime.getType('bogus_type'); // ⇨ null
```
### mime.getExtension(type)
Get extension for the given mime type. Charset options (often included in
Content-Type headers) are ignored.
```javascript
mime.getExtension('text/plain'); // ⇨ 'txt'
mime.getExtension('application/json'); // ⇨ 'json'
mime.getExtension('text/html; charset=utf8'); // ⇨ 'html'
```
### mime.define(typeMap[, force = false])
Define [more] type mappings.
`typeMap` is a map of type -> extensions, as documented in `new Mime`, above.
By default this method will throw an error if you try to map a type to an
extension that is already assigned to another type. Passing `true` for the
`force` argument will suppress this behavior (overriding any previous mapping).
```javascript
mime.define({'text/x-abc': ['abc', 'abcd']});
mime.getType('abcd'); // ⇨ 'text/x-abc'
mime.getExtension('text/x-abc') // ⇨ 'abc'
```
## Command Line
mime [path_string]
mime [path_or_extension]
E.g.
> mime scripts/jquery.js
application/javascript
## API - Queries
### mime.lookup(path)
Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g.
```js
var mime = require('mime');
mime.lookup('/path/to/file.txt'); // => 'text/plain'
mime.lookup('file.txt'); // => 'text/plain'
mime.lookup('.TXT'); // => 'text/plain'
mime.lookup('htm'); // => 'text/html'
```
### mime.default_type
Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.)
### mime.extension(type)
Get the default extension for `type`
```js
mime.extension('text/html'); // => 'html'
mime.extension('application/octet-stream'); // => 'bin'
```
### mime.charsets.lookup()
Map mime-type to charset
```js
mime.charsets.lookup('text/plain'); // => 'UTF-8'
```
(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.)
## API - Defining Custom Types
Custom type mappings can be added on a per-project basis via the following APIs.
### mime.define()
Add custom mime/extension mappings
```js
mime.define({
'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],
'application/x-my-type': ['x-mt', 'x-mtt'],
// etc ...
});
mime.lookup('x-sft'); // => 'text/x-some-format'
```
The first entry in the extensions array is returned by `mime.extension()`. E.g.
```js
mime.extension('text/x-some-format'); // => 'x-sf'
```
### mime.load(filepath)
Load mappings from an Apache ".types" format file
```js
mime.load('./my_project.types');
```
The .types file format is simple - See the `types` dir for examples.
----
Markdown generated from [src/README_js.md](src/README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd)

View File

@@ -1,8 +1,10 @@
#!/usr/bin/env node
var mime = require('./mime.js');
'use strict';
var mime = require('.');
var file = process.argv[2];
var type = mime.lookup(file);
var type = mime.getType(file);
process.stdout.write(type + '\n');

View File

@@ -1,108 +1,93 @@
var path = require('path');
var fs = require('fs');
'use strict';
/**
* @param typeMap [Object] Map of MIME type -> Array[extensions]
* @param ...
*/
function Mime() {
// Map of extension -> mime type
this.types = Object.create(null);
this._types = Object.create(null);
this._extensions = Object.create(null);
// Map of mime type -> extension
this.extensions = Object.create(null);
for (var i = 0; i < arguments.length; i++) {
this.define(arguments[i]);
}
this.define = this.define.bind(this);
this.getType = this.getType.bind(this);
this.getExtension = this.getExtension.bind(this);
}
/**
* Define mimetype -> extension mappings. Each key is a mime-type that maps
* Define mimetype -> xtension mappings. Each key is a mime-type that maps
* to an array of extensions associated with the type. The first extension is
* used as the default extension for the type.
*
* e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
*
* If a type declares an extension that has already been defined, an error will
* be thrown. To suppress this error and force the extension to be associated
* with the new type, pass `force`=true. Alternatively, you may prefix the
* extension with "*" to map the type to extension, without mapping the
* extension to the type.
*
* e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
*
*
* @param map (Object) type definitions
* @param force (Boolean) if true, force overriding of existing definitions
*/
Mime.prototype.define = function (map) {
for (var type in map) {
var exts = map[type];
for (var i = 0; i < exts.length; i++) {
if (process.env.DEBUG_MIME && this.types[exts[i]]) {
console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' +
this.types[exts[i]] + ' to ' + type);
Mime.prototype.define = function(typeMap, force) {
for (var type in typeMap) {
var extensions = typeMap[type];
for (var i = 0; i < extensions.length; i++) {
var ext = extensions[i];
// '*' prefix = not the preferred type for this extension. So fixup the
// extension, and skip it.
if (ext[0] == '*') {
continue;
}
this.types[exts[i]] = type;
if (!force && (ext in this._types)) {
throw new Error(
'Attempt to change mapping for "' + ext +
'" extension from "' + this._types[ext] + '" to "' + type +
'". Pass `force=true` to allow this, otherwise remove "' + ext +
'" from the list of extensions for "' + type + '".'
);
}
this._types[ext] = type;
}
// Default extension is the first one we encounter
if (!this.extensions[type]) {
this.extensions[type] = exts[0];
// Use first extension as default
if (force || !this._extensions[type]) {
var ext = extensions[0];
this._extensions[type] = (ext[0] != '*') ? ext : ext.substr(1)
}
}
};
/**
* Load an Apache2-style ".types" file
*
* This may be called multiple times (it's expected). Where files declare
* overlapping types/extensions, the last file wins.
*
* @param file (String) path of file to load.
*/
Mime.prototype.load = function(file) {
this._loading = file;
// Read file and split into lines
var map = {},
content = fs.readFileSync(file, 'ascii'),
lines = content.split(/[\r\n]+/);
lines.forEach(function(line) {
// Clean up whitespace/comments, and split into fields
var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/);
map[fields.shift()] = fields;
});
this.define(map);
this._loading = null;
};
/**
* Lookup a mime type based on extension
*/
Mime.prototype.lookup = function(path, fallback) {
var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase();
Mime.prototype.getType = function(path) {
path = String(path);
var last = path.replace(/^.*[/\\]/, '').toLowerCase();
var ext = last.replace(/^.*\./, '').toLowerCase();
return this.types[ext] || fallback || this.default_type;
var hasPath = last.length < path.length;
var hasDot = ext.length < last.length - 1;
return (hasDot || !hasPath) && this._types[ext] || null;
};
/**
* Return file extension associated with a mime type
*/
Mime.prototype.extension = function(mimeType) {
var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
return this.extensions[type];
Mime.prototype.getExtension = function(type) {
type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
return type && this._extensions[type.toLowerCase()] || null;
};
// Default instance
var mime = new Mime();
// Define built-in types
mime.define(require('./types.json'));
// Default type
mime.default_type = mime.lookup('bin');
//
// Additional API specific to the default instance
//
mime.Mime = Mime;
/**
* Lookup a charset based on mime type.
*/
mime.charsets = {
lookup: function(mimeType, fallback) {
// Assume text types are utf8
return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback;
}
};
module.exports = mime;
module.exports = Mime;

View File

@@ -1,26 +1,26 @@
{
"_from": "mime@^1.5.0",
"_id": "mime@1.6.0",
"_from": "mime@^2.3.1",
"_id": "mime@2.4.0",
"_inBundle": false,
"_integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"_integrity": "sha512-ikBcWwyqXQSHKtciCcctu9YfPbFYZ4+gbHEmE0Q8jzcTYQg5dHCr3g2wwAZjPoJfQVXZq6KXAjpXOTf5/cjT7w==",
"_location": "/webpack-dev-middleware/mime",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "mime@^1.5.0",
"raw": "mime@^2.3.1",
"name": "mime",
"escapedName": "mime",
"rawSpec": "^1.5.0",
"rawSpec": "^2.3.1",
"saveSpec": null,
"fetchSpec": "^1.5.0"
"fetchSpec": "^2.3.1"
},
"_requiredBy": [
"/webpack-dev-middleware"
],
"_resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"_shasum": "32cd9e5c64553bd58d19a568af452acff04981b1",
"_spec": "mime@^1.5.0",
"_resolved": "https://registry.npmjs.org/mime/-/mime-2.4.0.tgz",
"_shasum": "e051fd881358585f3279df333fe694da0bcffdd6",
"_spec": "mime@^2.3.1",
"_where": "C:\\xampp\\htdocs\\w4rpservices\\node_modules\\webpack-dev-middleware",
"author": {
"name": "Robert Kieffer",
@@ -34,23 +34,22 @@
"url": "https://github.com/broofa/node-mime/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Benjamin Thomas",
"email": "benjamin@benjaminthomas.org",
"url": "http://github.com/bentomas"
}
],
"contributors": [],
"dependencies": {},
"deprecated": false,
"description": "A comprehensive library for mime-type mapping",
"devDependencies": {
"github-release-notes": "0.13.1",
"mime-db": "1.31.0",
"mime-score": "1.1.0"
"chalk": "1.1.3",
"eslint": "^5.9.0",
"mime-db": "^1.37.0",
"mime-score": "1.0.1",
"mime-types": "2.1.15",
"mocha": "5.2.0",
"runmd": "1.0.1",
"standard-version": "^4.4.0"
},
"engines": {
"node": ">=4"
"node": ">=4.0.0"
},
"homepage": "https://github.com/broofa/node-mime#readme",
"keywords": [
@@ -58,16 +57,16 @@
"mime"
],
"license": "MIT",
"main": "mime.js",
"name": "mime",
"repository": {
"url": "git+https://github.com/broofa/node-mime.git",
"type": "git"
},
"scripts": {
"changelog": "gren changelog --tags=all --generate --override",
"prepare": "node src/build.js",
"test": "node src/test.js"
"md": "runmd --watch --output README.md src/README_js.md",
"prepare": "node src/build.js && runmd --output README.md src/README_js.md",
"release": "standard-version",
"test": "mocha src/test.js"
},
"version": "1.6.0"
"version": "2.4.0"
}

View File

@@ -2,38 +2,47 @@
'use strict';
const fs = require('fs');
const path = require('path');
const mimeScore = require('mime-score');
var fs = require('fs');
var path = require('path');
var mimeScore = require('mime-score');
let db = require('mime-db');
let chalk = require('chalk');
var db = require('mime-db');
var chalk = require('chalk');
const STANDARD_FACET_SCORE = 900;
var STANDARD_FACET_SCORE = 900;
const byExtension = {};
var byExtension = {};
// Clear out any conflict extensions in mime-db
for (let type in db) {
let entry = db[type];
for (var type in db) {
var entry = db[type];
entry.type = type;
if (!entry.extensions) continue;
entry.extensions.forEach(ext => {
entry.extensions.forEach(function(ext) {
var drop;
var keep = entry;
if (ext in byExtension) {
const e0 = entry;
const e1 = byExtension[ext];
var e0 = entry;
var e1 = byExtension[ext];
e0.pri = mimeScore(e0.type, e0.source);
e1.pri = mimeScore(e1.type, e1.source);
let drop = e0.pri < e1.pri ? e0 : e1;
let keep = e0.pri >= e1.pri ? e0 : e1;
drop.extensions = drop.extensions.filter(e => e !== ext);
drop = e0.pri < e1.pri ? e0 : e1;
keep = e0.pri >= e1.pri ? e0 : e1;
console.log(`${ext}: Keeping ${chalk.green(keep.type)} (${keep.pri}), dropping ${chalk.red(drop.type)} (${drop.pri})`);
// Prefix lower-priority extensions with '*'
drop.extensions = drop.extensions.map(function(e) {return e == ext ? '*' + e : e});
console.log(
ext + ': Preferring ' + chalk.green(keep.type) + ' (' + keep.pri +
') over ' + chalk.red(drop.type) + ' (' + drop.pri + ')' + ' for ' + ext
);
}
byExtension[ext] = entry;
// Cache the hightest ranking type for this extension
if (keep == entry) byExtension[ext] = entry;
});
}
@@ -43,11 +52,20 @@ function writeTypesFile(types, path) {
// Segregate into standard and non-standard types based on facet per
// https://tools.ietf.org/html/rfc6838#section-3.1
const types = {};
var standard = {};
var other = {};
Object.keys(db).sort().forEach(k => {
const entry = db[k];
types[entry.type] = entry.extensions;
Object.keys(db).sort().forEach(function(k) {
var entry = db[k];
if (entry.extensions) {
if (mimeScore(entry.type, entry.source) >= STANDARD_FACET_SCORE) {
standard[entry.type] = entry.extensions;
} else {
other[entry.type] = entry.extensions;
}
}
});
writeTypesFile(types, path.join(__dirname, '..', 'types.json'));
writeTypesFile(standard, path.join(__dirname, '../types', 'standard.json'));
writeTypesFile(other, path.join(__dirname, '../types', 'other.json'));

View File

@@ -1,60 +1,257 @@
/**
* Usage: node test.js
*/
'use strict';
var mime = require('../mime');
var mime = require('..');
var mimeTypes = require('../node_modules/mime-types');
var assert = require('assert');
var path = require('path');
var chalk = require('chalk');
//
// Test mime lookups
//
describe('class Mime', function() {
it('mime and mime/lite coexist', function() {
assert.doesNotThrow(function() {
require('../lite');
});
});
assert.equal('text/plain', mime.lookup('text.txt')); // normal file
assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase
assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file
assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file
assert.equal('text/plain', mime.lookup('.txt')); // nameless
assert.equal('text/plain', mime.lookup('txt')); // extension-only
assert.equal('text/plain', mime.lookup('/txt')); // extension-less ()
assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less
assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized
assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default
it('new constructor()', function() {
var Mime = require('../Mime');
//
// Test extensions
//
var mime = new Mime(
{'text/a': ['a', 'a1']},
{'text/b': ['b', 'b1']}
);
assert.equal('txt', mime.extension(mime.types.text));
assert.equal('html', mime.extension(mime.types.htm));
assert.equal('bin', mime.extension('application/octet-stream'));
assert.equal('bin', mime.extension('application/octet-stream '));
assert.equal('html', mime.extension(' text/html; charset=UTF-8'));
assert.equal('html', mime.extension('text/html; charset=UTF-8 '));
assert.equal('html', mime.extension('text/html; charset=UTF-8'));
assert.equal('html', mime.extension('text/html ; charset=UTF-8'));
assert.equal('html', mime.extension('text/html;charset=UTF-8'));
assert.equal('html', mime.extension('text/Html;charset=UTF-8'));
assert.equal(undefined, mime.extension('unrecognized'));
assert.deepEqual(mime._types, {
a: 'text/a',
a1: 'text/a',
b: 'text/b',
b1: 'text/b',
});
//
// Test node.types lookups
//
assert.deepEqual(mime._extensions, {
'text/a': 'a',
'text/b': 'b',
});
});
assert.equal('font/woff', mime.lookup('file.woff'));
assert.equal('application/octet-stream', mime.lookup('file.buffer'));
// TODO: Uncomment once #157 is resolved
// assert.equal('audio/mp4', mime.lookup('file.m4a'));
assert.equal('font/otf', mime.lookup('file.otf'));
it('define()', function() {
var Mime = require('../Mime');
//
// Test charsets
//
var mime = new Mime({'text/a': ['a']}, {'text/b': ['b']});
assert.equal('UTF-8', mime.charsets.lookup('text/plain'));
assert.equal('UTF-8', mime.charsets.lookup(mime.types.js));
assert.equal('UTF-8', mime.charsets.lookup(mime.types.json));
assert.equal(undefined, mime.charsets.lookup(mime.types.bin));
assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback'));
assert.throws(function() {
mime.define({'text/c': ['b']});
});
console.log('\nAll tests passed');
assert.doesNotThrow(function() {
mime.define({'text/c': ['b']}, true);
});
assert.deepEqual(mime._types, {
a: 'text/a',
b: 'text/c',
});
assert.deepEqual(mime._extensions, {
'text/a': 'a',
'text/b': 'b',
'text/c': 'b',
});
});
it('define() *\'ed types', function() {
var Mime = require('../Mime');
var mime = new Mime(
{'text/a': ['*b']},
{'text/b': ['b']}
);
assert.deepEqual(mime._types, {
b: 'text/b',
});
assert.deepEqual(mime._extensions, {
'text/a': 'b',
'text/b': 'b',
});
});
it('getType()', function() {
// Upper/lower case
assert.equal(mime.getType('text.txt'), 'text/plain');
assert.equal(mime.getType('TEXT.TXT'), 'text/plain');
// Bare extension
assert.equal(mime.getType('txt'), 'text/plain');
assert.equal(mime.getType('.txt'), 'text/plain');
assert.strictEqual(mime.getType('.bogus'), null);
assert.strictEqual(mime.getType('bogus'), null);
// Non-sensical
assert.strictEqual(mime.getType(null), null);
assert.strictEqual(mime.getType(undefined), null);
assert.strictEqual(mime.getType(42), null);
assert.strictEqual(mime.getType({}), null);
// File paths
assert.equal(mime.getType('dir/text.txt'), 'text/plain');
assert.equal(mime.getType('dir\\text.txt'), 'text/plain');
assert.equal(mime.getType('.text.txt'), 'text/plain');
assert.equal(mime.getType('.txt'), 'text/plain');
assert.equal(mime.getType('txt'), 'text/plain');
assert.equal(mime.getType('/path/to/page.html'), 'text/html');
assert.equal(mime.getType('c:\\path\\to\\page.html'), 'text/html');
assert.equal(mime.getType('page.html'), 'text/html');
assert.equal(mime.getType('path/to/page.html'), 'text/html');
assert.equal(mime.getType('path\\to\\page.html'), 'text/html');
assert.strictEqual(mime.getType('/txt'), null);
assert.strictEqual(mime.getType('\\txt'), null);
assert.strictEqual(mime.getType('text.nope'), null);
assert.strictEqual(mime.getType('/path/to/file.bogus'), null);
assert.strictEqual(mime.getType('/path/to/json'), null);
assert.strictEqual(mime.getType('/path/to/.json'), null);
assert.strictEqual(mime.getType('/path/to/.config.json'), 'application/json');
assert.strictEqual(mime.getType('.config.json'), 'application/json');
});
it('getExtension()', function() {
assert.equal(mime.getExtension('text/html'), 'html');
assert.equal(mime.getExtension(' text/html'), 'html');
assert.equal(mime.getExtension('text/html '), 'html');
assert.strictEqual(mime.getExtension('application/x-bogus'), null);
assert.strictEqual(mime.getExtension('bogus'), null);
assert.strictEqual(mime.getExtension(null), null);
assert.strictEqual(mime.getExtension(undefined), null);
assert.strictEqual(mime.getExtension(42), null);
assert.strictEqual(mime.getExtension({}), null);
});
});
describe('DB', function() {
var diffs = [];
after(function() {
if (diffs.length) {
console.log('\n[INFO] The following inconsistencies with MDN (https://goo.gl/lHrFU6) and/or mime-types (https://github.com/jshttp/mime-types) are expected:');
diffs.forEach(function(d) {
console.warn(
' ' + d[0]+ '[' + chalk.blue(d[1]) + '] = ' + chalk.red(d[2]) +
', mime[' + d[1] + '] = ' + chalk.green(d[3])
);
});
}
});
it('Consistency', function() {
for (var ext in this.types) {
assert.equal(ext, this.extensions[this.types[ext]], '${ext} does not have consistent ext->type->ext mapping');
}
});
it('MDN types', function() {
// MDN types listed at https://goo.gl/lHrFU6
var MDN = {
'aac': 'audio/aac',
'abw': 'application/x-abiword',
'arc': 'application/octet-stream',
'avi': 'video/x-msvideo',
'azw': 'application/vnd.amazon.ebook',
'bin': 'application/octet-stream',
'bz': 'application/x-bzip',
'bz2': 'application/x-bzip2',
'csh': 'application/x-csh',
'css': 'text/css',
'csv': 'text/csv',
'doc': 'application/msword',
'epub': 'application/epub+zip',
'gif': 'image/gif',
'html': 'text/html',
'ico': 'image/x-icon',
'ics': 'text/calendar',
'jar': 'application/java-archive',
'jpg': 'image/jpeg',
'js': 'application/javascript',
'json': 'application/json',
'midi': 'audio/midi',
'mpeg': 'video/mpeg',
'mpkg': 'application/vnd.apple.installer+xml',
'odp': 'application/vnd.oasis.opendocument.presentation',
'ods': 'application/vnd.oasis.opendocument.spreadsheet',
'odt': 'application/vnd.oasis.opendocument.text',
'oga': 'audio/ogg',
'ogv': 'video/ogg',
'ogx': 'application/ogg',
'png': 'image/png',
'pdf': 'application/pdf',
'ppt': 'application/vnd.ms-powerpoint',
'rar': 'application/x-rar-compressed',
'rtf': 'application/rtf',
'sh': 'application/x-sh',
'svg': 'image/svg+xml',
'swf': 'application/x-shockwave-flash',
'tar': 'application/x-tar',
'tiff': 'image/tiff',
'ttf': 'font/ttf',
'vsd': 'application/vnd.visio',
'wav': 'audio/x-wav',
'weba': 'audio/webm',
'webm': 'video/webm',
'webp': 'image/webp',
'woff': 'font/woff',
'woff2': 'font/woff2',
'xhtml': 'application/xhtml+xml',
'xls': 'application/vnd.ms-excel',
'xml': 'application/xml',
'xul': 'application/vnd.mozilla.xul+xml',
'zip': 'application/zip',
'3gp': 'video/3gpp',
'3g2': 'video/3gpp2',
'7z': 'application/x-7z-compressed',
};
for (var ext in MDN) {
var expected = MDN[ext];
var actual = mime.getType(ext);
if (actual !== expected) diffs.push(['MDN', ext, expected, actual]);
}
for (var ext in mimeTypes.types) {
var expected = mimeTypes.types[ext];
var actual = mime.getType(ext);
if (actual !== expected) diffs.push(['mime-types', ext, expected, actual]);
}
});
it('Specific types', function() {
// Assortment of types we sanity check for good measure
assert.equal(mime.getType('html'), 'text/html');
assert.equal(mime.getType('js'), 'application/javascript');
assert.equal(mime.getType('json'), 'application/json');
assert.equal(mime.getType('rtf'), 'application/rtf');
assert.equal(mime.getType('txt'), 'text/plain');
assert.equal(mime.getType('xml'), 'application/xml');
assert.equal(mime.getType('wasm'), 'application/wasm');
});
it('Specific extensions', function() {
assert.equal(mime.getExtension('text/html;charset=UTF-8'), 'html');
assert.equal(mime.getExtension('text/HTML; charset=UTF-8'), 'html');
assert.equal(mime.getExtension('text/html; charset=UTF-8'), 'html');
assert.equal(mime.getExtension('text/html; charset=UTF-8 '), 'html');
assert.equal(mime.getExtension('text/html ; charset=UTF-8'), 'html');
assert.equal(mime.getExtension(mime._types.text), 'txt');
assert.equal(mime.getExtension(mime._types.htm), 'html');
assert.equal(mime.getExtension('application/octet-stream'), 'bin');
assert.equal(mime.getExtension('application/octet-stream '), 'bin');
assert.equal(mime.getExtension(' text/html; charset=UTF-8'), 'html');
assert.equal(mime.getExtension('text/html; charset=UTF-8 '), 'html');
assert.equal(mime.getExtension('text/html; charset=UTF-8'), 'html');
assert.equal(mime.getExtension('text/html ; charset=UTF-8'), 'html');
assert.equal(mime.getExtension('text/html;charset=UTF-8'), 'html');
assert.equal(mime.getExtension('text/Html;charset=UTF-8'), 'html');
assert.equal(mime.getExtension('unrecognized'), null);
assert.equal(mime.getExtension('text/xml'), 'xml'); // See #180
});
});

File diff suppressed because one or more lines are too long

View File

@@ -1,26 +1,26 @@
{
"_from": "webpack-dev-middleware@1.12.2",
"_id": "webpack-dev-middleware@1.12.2",
"_from": "webpack-dev-middleware@^3.5.1",
"_id": "webpack-dev-middleware@3.6.1",
"_inBundle": false,
"_integrity": "sha512-FCrqPy1yy/sN6U/SaEZcHKRXGlqU0DUaEBL45jkUYoB8foVb6wCnbIJ1HKIx+qUFTW+3JpVcCJCxZ8VATL4e+A==",
"_integrity": "sha512-XQmemun8QJexMEvNFbD2BIg4eSKrmSIMrTfnl2nql2Sc6OGAYFyb8rwuYrCjl/IiEYYuyTEiimMscu7EXji/Dw==",
"_location": "/webpack-dev-middleware",
"_phantomChildren": {},
"_requested": {
"type": "version",
"type": "range",
"registry": true,
"raw": "webpack-dev-middleware@1.12.2",
"raw": "webpack-dev-middleware@^3.5.1",
"name": "webpack-dev-middleware",
"escapedName": "webpack-dev-middleware",
"rawSpec": "1.12.2",
"rawSpec": "^3.5.1",
"saveSpec": null,
"fetchSpec": "1.12.2"
"fetchSpec": "^3.5.1"
},
"_requiredBy": [
"/webpack-dev-server"
],
"_resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-1.12.2.tgz",
"_shasum": "f8fc1120ce3b4fc5680ceecb43d777966b21105e",
"_spec": "webpack-dev-middleware@1.12.2",
"_resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-3.6.1.tgz",
"_shasum": "91f2531218a633a99189f7de36045a331a4b9cd4",
"_spec": "webpack-dev-middleware@^3.5.1",
"_where": "C:\\xampp\\htdocs\\w4rpservices\\node_modules\\webpack-dev-server",
"author": {
"name": "Tobias Koppers @sokra"
@@ -30,52 +30,49 @@
},
"bundleDependencies": false,
"dependencies": {
"memory-fs": "~0.4.1",
"mime": "^1.5.0",
"path-is-absolute": "^1.0.0",
"memory-fs": "^0.4.1",
"mime": "^2.3.1",
"range-parser": "^1.0.3",
"time-stamp": "^2.0.0"
"webpack-log": "^2.0.0"
},
"deprecated": false,
"description": "Offers a dev middleware for webpack, which arguments a live bundle to a directory",
"description": "A development middleware for webpack",
"devDependencies": {
"codecov.io": "^0.1.6",
"eslint": "^4.0.0",
"assert": "^1.4.1",
"eslint": "^5.4.0",
"eslint-config-webpack": "^1.2.5",
"eslint-plugin-import": "^2.14.0",
"express": "^4.14.0",
"file-loader": "^0.11.2",
"istanbul": "^0.4.5",
"mocha": "^3.0.2",
"mocha-sinon": "^2.0.0",
"should": "^11.1.0",
"sinon": "^2.3.8",
"supertest": "^3.0.0",
"webpack": "^3.0.0"
"file-loader": "^3.0.1",
"mocha": "^6.0.0",
"nyc": "^13.1.0",
"sinon": "^7.2.2",
"standard-version": "^5.0.0",
"supertest": "^3.1.0",
"webpack": "^4.17.1"
},
"engines": {
"node": ">=0.6"
"node": ">= 6"
},
"files": [
"middleware.js",
"lib/"
"lib",
"index.js"
],
"homepage": "http://github.com/webpack/webpack-dev-middleware",
"homepage": "https://github.com/webpack/webpack-dev-middleware",
"license": "MIT",
"main": "middleware.js",
"main": "index.js",
"name": "webpack-dev-middleware",
"peerDependencies": {
"webpack": "^1.0.0 || ^2.0.0 || ^3.0.0"
"webpack": "^4.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/webpack/webpack-dev-middleware.git"
},
"scripts": {
"beautify": "npm run lint -- --fix",
"cover": "istanbul cover node_modules/mocha/bin/_mocha",
"lint": "eslint *.js lib test",
"posttest": "npm run -s lint",
"test": "mocha --full-trace --check-leaks",
"travis": "npm run cover -- --report lcovonly && npm run lint"
"lint": "eslint index.js lib test",
"release": "standard-version",
"test": "nyc --reporter lcovonly mocha --full-trace --check-leaks --exit"
},
"version": "1.12.2"
"version": "3.6.1"
}