summaryrefslogtreecommitdiffstats
path: root/lib/generate/plugin.js
blob: 19eec8627e667ae67d41cb132275521fb59e4111 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
var _ = require("lodash");
var Q = require("q");
var semver = require("semver");
var path = require("path");
var url = require("url");
var fs = require("./fs");
var resolve = require('resolve');

var pkg = require("../../package.json");

var  RESOURCES = ["js", "css"];

var Plugin = function(name, root) {
    this.name = name;
    this.root = root;
    this.packageInfos = {};
    this.infos = {};

    _.each([
        "gitbook-plugin-"+name,
        "gitbook-theme-"+name,
        "gitbook-"+name,
        name,
    ], function(_name) {
        if (this.load(_name, __dirname)) return false;
        if (this.load(_name, path.resolve(root))) return false;
    }, this);
};

// Load from a name
Plugin.prototype.load = function(name, baseDir) {
    try {
        var res = resolve.sync(name+"/package.json", { basedir: baseDir });

        this.baseDir = path.dirname(res);
        this.packageInfos = require(res);
        this.infos = require(resolve.sync(name, { basedir: baseDir }));
        this.name = name;

        return true;
    } catch (e) {
        return false;
    }
};

// Return resources
Plugin.prototype.getResources = function(resource) {
    if (!this.infos.book || !this.infos.book[resource]) {
        return [];
    }
    return _.chain(this.infos.book[resource])
    .map(function(resource) {
        var parsed = url.parse(resource);
        if (parsed.protocol) return {"url": resource}
        else return { "path": this.name+"/"+resource };
    }.bind(this))
    .value();
};

// Test if it's a valid plugin
Plugin.prototype.isValid = function() {
    return (
        this.packageInfos
        && this.packageInfos.name
        && this.packageInfos.engines
        && this.packageInfos.engines.gitbook
        && semver.satisfies(pkg.version, this.packageInfos.engines.gitbook)
    );
};

// Resolve file path
Plugin.prototype.resolveFile = function(filename) {
    return path.resolve(this.baseDir, filename);
};

// Resolve file path
Plugin.prototype.callHook = function(name, context, data) {
    var hookFunc = this.infos.hooks? this.infos.hooks[name] : null;
    data = data || {};

    if (!hookFunc) return Q(data);

    return Q()
    .then(function() {
        return hookFunc.apply(context, [data]);
    });
};

// Has assets
Plugin.prototype.hasAssets = function(out) {
    return (this.infos.book && this.infos.book.assets);
};

// Copy plugin assets fodler
Plugin.prototype.copyAssets = function(out) {
    if (!this.hasAssets()) return Q();
    return fs.copy(
        this.resolveFile(this.infos.book.assets),
        out
    );
};




// Normalize a list of plugin name to use
Plugin.normalizeNames = function(names) {
    // Normalize list to an array
    names = _.isString(names) ? names.split(",") : (names || []);

    // List plugins to remove
    var toremove = _.chain(names)
    .filter(function(name) {
        return name.length > 0 && name[0] == "-";
    })
    .map(function(name) {
        return name.slice(1)
    })
    .value();

    // Merge with defaults
    names = _.chain(names)
    .concat(Plugin.defaults)
    .uniq()
    .value();

    // Remove plugins starting with
    names = _.filter(names, function(name) {
        return !_.contains(toremove, name) && !(name.length > 0 && name[0] == "-");
    });

    return names;
};

// Extract data from a list of plugin
Plugin.fromList = function(names, root) {
    var failed = [];

    // Load plugins
    var plugins = _.map(names, function(name) {
        var plugin = new Plugin(name, root);
        if (!plugin.isValid()) failed.push(name);
        return plugin;
    });

    if (_.size(failed) > 0) return Q.reject(new Error("Error loading plugins: "+failed.join(",")));

    // Get all resources
    var resources = _.chain(RESOURCES)
    .map(function(resource) {
        return [
            resource,
            _.chain(plugins)
            .map(function(plugin) {
                return plugin.getResources(resource);
            })
            .flatten()
            .value()
        ];
    })
    .object()
    .value();
    resources.html = {}

    _.each(plugins, function(plugin) {
        var html = plugin.infos.book.html || {};
        _.each(html, function(code, key) {
            if (!_.isFunction(code)) code = _.constant(code);
            if (!resources.html[key]) resources.html[key] = [];
            resources.html[key].push(code);
        })
    });

    return Q({
        'list': plugins,
        'resources': resources,
        'hook': function(name, context, data) {
            return _.reduce(plugins, function(prev, plugin) {
                return prev.then(function(ret) {
                    return plugin.callHook(name, context, ret);
                })
            }, Q(data));
        },
        'template': function(name) {
            var withTpl = _.find(plugins, function(plugin) {
                return (plugin.infos.templates
                    && plugin.infos.templates[name]);
            });

            if (!withTpl) return null;
            return withTpl.resolveFile(withTpl.infos.templates[name]);
        },
        'html': function(tag, context, options) {
            return _.map(resources.html[tag] || [], function(code) {
                return code.call(context, options);
            }).join("\n");
        }
    });
};

// Default plugins
Plugin.defaults = [
    "mixpanel",
    "mathjax"
];

module.exports = Plugin;