Simplify the repetitive portions of writing Metalsmith plugins.
npm install metalsmith-plugin-kitMetalsmith Plugin Kit
=====================
Remove the boring part of making [Metalsmith] plugins and simply your life. Rely on tested code to do the menial tasks. Reuse the same base libraries in order to try to mitigate the explosion of files in the node_modules/ folder.
This is not a plugin! It helps you make one.
[![npm version][npm-badge]][npm-link]
[![Build Status][travis-badge]][travis-link]
[![Dependencies][dependencies-badge]][dependencies-link]
[![Dev Dependencies][devdependencies-badge]][devdependencies-link]
[![codecov.io][codecov-badge]][codecov-link]
Overview
--------
An example goes a long way.
// This is based on the plugin skeleton from Metalsmith.io
var debug = require("debug")("metalsmith-myplugin");
var multimatch = require("multimatch");
module.exports = function myplugin(opts) {
var matchFunction;
if (!opts || typeof opts !== "object") {
opts = {};
}
opts.pattern = opts.pattern || [];
return function (files, metalsmith, done) {
Object.keys(files).forEach(function(file) {
if (multimatch(file, opts.pattern).length) {
debug("myplugin working on: %s", file);
//
// here would be your code
//
}
});
done();
};
}
Plugin Kit helps remove the need for a matching library and iterating over the properties of the files object. Here's the same plugin rewritten for Plugin Kit.
// Now, the same plugin written using Plugin Kit
var debug = require("debug")("metalsmith-myplugin");
var pluginKit = require("metalsmith-plugin-kit");
module.exports = function myplugin(opts) {
opts = pluginKit.defaultOptions({
pattern: []
}, opts);
return pluginKit.middleware({
each: function (filename, fileObject) {
//
// here would be your code
//
};
match: opts.pattern
});
}
There are two huge benefits to this. The first shows up when you want to perform asynchronous tasks because all of the callbacks can return a value (synchronous), return a Promise (asynchronous) or accept a node-style callback (asynchronous).
The second big bonus you get is you don't need to test the file matching code nor do you need to construct tests that confirm the order of events. That's handled and tested by metalsmith-plugin-kit.
There's additional helper methods that simplify common tasks that plugins need to perform, such as creating files, cloning data structures, matching file globs, and renaming functions. The example above shows how to default options and it illustrates the middleware function.
If that wasn't enough, you should make sure you're not underestimating the positive aspects of being able to shift responsibility away from your code and into someone else's. You no longer need to make sure you are matching files correctly. It's not a problem for you to start to use asynchronous processing. When Metalsmith requires a property for a file to be properly created, this library handles it instead of you. I take on that responsibility and will work to maintain and test the features this module exposes.
Installation
------------
Use npm to install this package easily.
$ npm install --save metalsmith-plugin-kit
Alternately you may edit your package.json and add this to your dependencies object:
{
...
"dependencies": {
...
"metalsmith-plugin-kit": "*"
...
}
...
}
If you relied on a library like micromatch, minimatch, or multimatch, you can safely remove those lines.
API
---
Example
``js`
var pluginKit = require("metalsmith-plugin-kit");
* metalsmith-plugin-kit
* _static_
* [.addFile(files, filename, contents, [options])](#module_metalsmith-plugin-kit.addFile)
[.callFunction(fn, [args])](#module_metalsmith-plugin-kit.callFunction) ⇒ Promise.<\>
* .chain() ⇒ function
.clone(original) ⇒ \
* .defaultOptions(defaults, override) ⇒ Object
* [.filenameMatcher(match, [options])](#module_metalsmith-plugin-kit.filenameMatcher) ⇒ matchFunction
* [.middleware([options])](#module_metalsmith-plugin-kit.middleware) ⇒ function
* .renameFunction(fn, name)
* _inner_
* ~metalsmithFile : Object
* ~metalsmithFileCollection : Object.<string, metalsmith-plugin-kit~metalsmithFile>
* ~matchItem : string \| RegExp \| function \| Object
* ~matchList : matchItem \| Array.<matchItem>
* ~matchOptions : Object
* ~matchFunction ⇒ boolean
* ~middlewareDefinition : Object
* ~endpointCallback : function
* ~eachCallback : function
The contents can be converted:
* Buffers remain intact.
* Strings are encoded into Buffer objects.
* All other things are passed through JSON.stringify() and then encoded
as a buffer.
Kind: static method of metalsmith-plugin-kit
Params
- files metalsmith-plugin-kit~metalsmithFileCollection
- filename string
- contents Buffer | string | \*
- [options] Object
- [.encoding] string = "utf8"
- [.mode] string = "0644"
Example
`js`
// Make a sample plugin that adds hello.txt.
return pluginKit.middleware({
after: (files) => {
pluginKit.addFile(files, "hello.txt", "Hello world!");
}
});
The result of the promise is the value provided by the returned value,
the resolved Promise, or the callback's result. If there is an error thrown
or one supplied via a Promise rejection or the callback, this function's
Promise will be rejected.
Kind: static method of metalsmith-plugin-kit
Params
- fn function - Function to call
- [args] Array.<\*> - Arguments to pass to the function.
Example
`js
function testSync(message) {
console.log(message);
}
promise = pluginKit.callFunction(testSync, [ "sample message" ]);
// sample message is printed and promise will be resolved asynchronously
``
Example js
function testPromise(message) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(message);
resolve();
}, 1000);
});
}
promise = pluginKit.callFunction(testPromise, [ "sample message" ]);
// promise will be resolved after message is printed
``
Example js
function testCallback(message, done) {
setTimeout(() => {
console.log(message);
done();
});
}
promise = pluginKit.callFunction(testCallback, [ "sample message" ]);
// promise will be resolved after message is printed
`
Kind: static method of metalsmith-plugin-kit
Returns: function - Combined function
Params
- . function - Plugins to combine
Example
`js
const plugin1 = require('metalsmith-markdown')();
const plugin2 = require('metalsmith-data-loader')();
const pluginKit = require('metalsmith-plugin-kit');
const combined = pluginKit.chain(plugin1, plugin2);
metalsmith.use(combined);
`
Copies functions, regular expressions, Buffers, and other specialty
objects; does not close those items. Does not handle circular references.
Kind: static method of metalsmith-plugin-kit
Returns: \* - clone
Params
- original \*
Example
`js
a = {};
b = pluginKit.clone(a);
a.test = true;
// This didn't update b because it's a clone.
console.log(JSON.stringify(b)); // {}
`
Kind: static method of metalsmith-plugin-kit
Params
- defaults Object
- override Object
Example
`js
result = pluginKit.defaultOptions({
a: "default",
b: {
bDefault: "default"
}
}, {
b: {
bOverride: "override"
},
c: "override but won't make it to the result"
});
// result = {
// a: "default"
// b: {
// bOverride: "override"
// }
// }
`
The chance that we switch from micromatch is extremely remote, but it could
happen. If another library is used, all existing Plugin Kit tests must
continue to pass unchanged. It is the duty of this function to remap
options or perform the calls in another way so the alternate library can
work. All of the flags documented below must continue to work as expected.
Kind: static method of metalsmith-plugin-kit
Params
- match matchList
- [options] matchOptions
Example
`js
var matcher;
matcher = pluginKit.filenameMatcher("*.txt");
[
"test.txt",
"test.html"
].forEach((fileName) => {
console.log(fileName, matcher(fileName));
// test.txt true
// test.html false
});
`
.Kind: static method of metalsmith-plugin-kit
Returns: function - middleware function
Params
- [options] middlewareDefinition
Example
`js
var fileList;return pluginKit.middleware({
after: (files) => {
pluginKit.addFile(files, "all-files.json", fileList);
},
before: () => {
fileList = [];
},
each: (filename) => {
fileList.push(filename);
}
});
`
Example
`js
// This silly plugin changes all instances of "fidian" to lower case
// in all text-like files.
return pluginKit.middleware({
each: (filename, file) => {
var contents; contents = file.contents.toString("utf8");
contents = contents.replace(/fidian/ig, "fidian");
file.contents = Buffer.from(contents, "utf8");
},
match: "*.{c,htm,html,js,json,md,txt}",
matchOptions: {
basename: true
},
// Providing a name will rename this middleware so it can be displayed
// by metalsmith-debug-ui and other tools.
name: "metalsmith-lowercase-fidian"
});
`
Example
`js
// Illustrates asynchronous processing.
return pluginKit.middleware({
after: (files) => {
// Promise-based. Delay 5 seconds when done building.
return new Promise((resolve) => {
setTimeout(() => {
console.log("I paused for 5 seconds");
resolve();
}, 5000);
});
},
before: (files, metalsmith, done) => {
// Callback-based. Add a file to the build.
fs.readFile("content.txt", (err, buffer) => {
if (!err) {
pluginKit.addFile(files, "content.txt", buffer);
}
done(err);
});
}
});
`
$3
Renames a function by assigning the name property. This isn't as simple
as just using yourFunction.name = "new name". Because it was done in
Plugin Kit, it is also exposed in the unlikely event that plugins want to
use it.Kind: static method of metalsmith-plugin-kit
Params
- fn function
- name string
Example
`js
x = () => {};
console.log(x.name); // Could be undefined, could be "x".
pluginKit.renameFunction(x, "MysteriousFunction");
console.log(x.name); // "MysteriousFunction"
`
$3
This is a typical file object from Metalsmith.Other properties may be defined, but the ones listed here must be defined.
Kind: inner typedef of metalsmith-plugin-kit
Properties
- contents Buffer
- mode string
$3
Metalsmith's collection of files.Kind: inner typedef of metalsmith-plugin-kit
$3
As a string, this is a single match pattern. It supports the following
features, which are taken from the Bash 4.3 specification. With each feature
listed, a couple sample examples are shown. Wildcards:
, .js
Negation: !a/.js, *!(b).js
* Extended globs (extglobs): +(x|y), !(a|b)
* POSIX character classes: [[:alpha:][:digit:]]
* Brace expansion: foo/{1..5}.md, bar/{a,b,c}.js
* Regular expression character classes: foo-[1-5].js
* Regular expression logical "or": foo/(abc|xyz).jsWhen a RegExp, the file is tested against the regular expression.
When this is a function, the filename is passed as the first argument and
the file contents are the second argument. If the returned value is truthy,
the file matches. This function may not be asynchronous.
When an object, this uses the object's
.test() method. Make sure one
exists.Kind: inner typedef of metalsmith-plugin-kit
See: https://github.com/micromatch/micromatch#extended-globbing for extended globbing features.
$3
This can be one matchItem or an array of matchItem values.Kind: inner typedef of metalsmith-plugin-kit
$3
These options control the matching library, which is only used when a
string is passed as the matchItem. All listed options will be
supported, even in the unlikely future that the matching library is
replaced.Other options are also available from the library itself.
Kind: inner typedef of metalsmith-plugin-kit
See: https://github.com/micromatch/micromatch#options for additional options supported by current backend library.
Properties
- basename boolean - Allow glob patterns without slashes to match a file path based on its basename.
- dot boolean - Enable searching of files and folders that start with a dot.
- nocase boolean - Enable case-insensitive searches.
$3
The function that's returned by filenameMatcher. Pass it your filenames
and it will synchronously determine if that matches any of the patterns that
were previously passed into filenameMatcher.Kind: inner typedef of metalsmith-plugin-kit
See: filenameMatcher
Params
- filename string
$3
Middleware defintion object.Kind: inner typedef of metalsmith-plugin-kit
See
- middleware
- {@link https://github.com/leviwheatcroft/metalsmith-debug-ui)
Properties
- after endpointCallback - Called after all files are processed.
- before endpointCallback - Called before any files are processed.
- each eachCallback - Called once for each file that matches.
- match matchList - Defaults to all files
- matchOptions matchOptions
- name string - When supplied, renames the middleware function that's returned to the given name. Useful for
metalsmith-debug-ui`, for instance. Uses Node-style callbacks if your function expects more than 2 parameters.
Kind: inner typedef of metalsmith-plugin-kit
See
- callFunction
- middlewareDefinition
Params
- files module:metalsmith-plugin-kit~metalsmithFiles
- metalsmith external:metalsmith
- [done] function
Uses Node-style callbacks if your function expects more than 4 parameters.
Kind: inner typedef of metalsmith-plugin-kit
See
- callFunction
- middlewareDefinition
Params
- filename string
- file metalsmithFile
- files module:metalsmith-plugin-kit~metalsmithFiles
- metalsmith external:metalsmith
- [done] function
License
-------
This software is licensed under a [MIT license][LICENSE] that contains additional non-advertising and patent-related clauses. [Read full license terms][LICENSE]
[codecov-badge]: https://img.shields.io/codecov/c/github/fidian/metalsmith-plugin-kit/master.svg
[codecov-link]: https://codecov.io/github/fidian/metalsmith-plugin-kit?branch=master
[dependencies-badge]: https://img.shields.io/david/fidian/metalsmith-plugin-kit.svg
[dependencies-link]: https://david-dm.org/fidian/metalsmith-plugin-kit
[devdependencies-badge]: https://img.shields.io/david/dev/fidian/metalsmith-plugin-kit.svg
[devdependencies-link]: https://david-dm.org/fidian/metalsmith-plugin-kit#info=devDependencies
[LICENSE]: LICENSE.md
[Metalsmith]: http://www.metalsmith.io/
[npm-badge]: https://img.shields.io/npm/v/metalsmith-plugin-kit.svg
[npm-link]: https://npmjs.org/package/metalsmith-plugin-kit
[travis-badge]: https://img.shields.io/travis/fidian/metalsmith-plugin-kit/master.svg
[travis-link]: http://travis-ci.org/fidian/metalsmith-plugin-kit