metalsmith-plugin-kit
Simplify the repetitive portions of writing Metalsmith plugins.
Last updated 2 months ago by fidian .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install metalsmith-plugin-kit 
SYNC missed versions from official npm registry.

Metalsmith 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 Build Status Dependencies Dev Dependencies codecov.io

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

metalsmith-plugin-kit

Metalsmith Plugin Kit

Example

var pluginKit = require("metalsmith-plugin-kit");

metalsmith-plugin-kit.addFile(files, filename, contents, [options])

Adds a file to the files object. Converts the contents for you automatically. Sets the file mode to 0644 as well.

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

// Make a sample plugin that adds hello.txt.
return pluginKit.middleware({
    after: (files) => {
        pluginKit.addFile(files, "hello.txt", "Hello world!");
    }
});

metalsmith-plugin-kit.callFunction(fn, args) ⇒ Promise.<*>

Calls a function and passes it a number of arguments. The function can be synchronous and return a value, asynchronous and return a Promise, or asynchronous and support a Node-style callback.

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

function testSync(message) {
    console.log(message);
}

promise = pluginKit.callFunction(testSync, [ "sample message" ]);
// sample message is printed and promise will be resolved asynchronously

Example

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

function testCallback(message, done) {
    setTimeout(() => {
        console.log(message);
        done();
    });
}

promise = pluginKit.callFunction(testCallback, [ "sample message" ]);
// promise will be resolved after message is printed

metalsmith-plugin-kit.chain() ⇒ function

Chains multiple plugins into one

Kind: static method of metalsmith-plugin-kit
Returns: function - Combined function
Params

        - . <code>function</code> - Plugins to combine

Example

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);

metalsmith-plugin-kit.clone(original) ⇒ *

Lightweight object clone function, primarily designed for plain objects, expecially targeted for options to middleware.

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

a = {};
b = pluginKit.clone(a);
a.test = true;

// This didn't update b because it's a clone.
console.log(JSON.stringify(b)); // {}

metalsmith-plugin-kit.defaultOptions(defaults, override) ⇒ Object

Defaults options by performing a limited, shallow merge of two objects. Returns a new object. Will not assign properties that are not defined in the defaults.

Kind: static method of metalsmith-plugin-kit
Params

  • defaults Object
  • override Object

Example

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"
//     }
// }

metalsmith-plugin-kit.filenameMatcher(match, [options]) ⇒ matchFunction

Builds a function to determine if a file matches patterns.

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

Example

var matcher;

matcher = pluginKit.filenameMatcher("*.txt");
[
    "test.txt",
    "test.html"
].forEach((fileName) => {
    console.log(fileName, matcher(fileName));
    // test.txt true
    // test.html false
});

metalsmith-plugin-kit.middleware([options]) ⇒ function

Return middleware function. This is why Plugin Kit was created. It helps handle asynchronous tasks, eliminates the need for using your own matcher and you no longer iterate through the files with Object.keys().

Kind: static method of metalsmith-plugin-kit
Returns: function - middleware function
Params

Example

var fileList;

return pluginKit.middleware({
    after: (files) => {
        pluginKit.addFile(files, "all-files.json", fileList);
    },
    before: () => {
        fileList = [];
    },
    each: (filename) => {
        fileList.push(filename);
    }
});

Example

// Renames the returned function so it can be displayed by
// metalsmith-debug-ui and other tools.
// 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
    },
    name: "metalsmith-lowercase-fidian"
});

Example

// 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);
        });
    }
});

metalsmith-plugin-kit.renameFunction(fn, name)

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

x = () => {};
console.log(x.name); // Could be undefined, could be "x".
pluginKit.renameFunction(x, "MysteriousFunction");
console.log(x.name); // "MysteriousFunction"

metalsmith-plugin-kit~metalsmithFile : Object

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

metalsmith-plugin-kit~metalsmithFileCollection : Object.<string, metalsmith-plugin-kit~metalsmithFile>

Metalsmith's collection of files.

Kind: inner typedef of metalsmith-plugin-kit

metalsmith-plugin-kit~matchItem : string | RegExp | function | Object

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).js

When 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.

metalsmith-plugin-kit~matchList : matchItem | Array.<matchItem>

This can be one matchItem or an array of matchItem values.

Kind: inner typedef of metalsmith-plugin-kit

metalsmith-plugin-kit~matchOptions : Object

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.

metalsmith-plugin-kit~matchFunction ⇒ boolean

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

metalsmith-plugin-kit~middlewareDefinition : Object

Middleware defintion object.

Kind: inner typedef of metalsmith-plugin-kit
See

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.

metalsmith-plugin-kit~endpointCallback : function

A callback that is called before processing any file or after processing any file.

Uses Node-style callbacks if your function expects more than 2 parameters.

Kind: inner typedef of metalsmith-plugin-kit
See

Params

  • files module:metalsmith-plugin-kit~metalsmithFiles
  • metalsmith external:metalsmith
  • [done] function

metalsmith-plugin-kit~eachCallback : function

This is the function that will be fired when a file matches your match criteria. It will be executed once for each file. It also could run concurrently with other functions when you are performing asynchronous work.

Uses Node-style callbacks if your function expects more than 4 parameters.

Kind: inner typedef of metalsmith-plugin-kit
See

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 that contains additional non-advertising and patent-related clauses. Read full license terms

Current Tags

  • 1.1.4                                ...           latest (2 months ago)

7 Versions

  • 1.1.4                                ...           2 months ago
  • 1.1.3                                ...           2 months ago
  • 1.1.2                                ...           2 months ago
  • 1.1.1                                ...           2 months ago
  • 1.1.0                                ...           2 months ago
  • 1.0.1                                ...           3 years ago
  • 1.0.0                                ...           3 years ago

Copyright 2014 - 2017 © taobao.org |