-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathsourcebit.js
More file actions
388 lines (301 loc) · 12.4 KB
/
sourcebit.js
File metadata and controls
388 lines (301 loc) · 12.4 KB
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
const { cloneDeep } = require('lodash');
const debug = require('debug');
const { diff: generateDiff } = require('deep-diff');
const fs = require('fs');
const mkdirp = require('mkdirp');
const ora = require('ora');
const path = require('path');
const util = require('util');
const { writeFrontmatterMarkdown, writeJSON, writeYAML } = require('./file-writers');
const fileWriters = {
'frontmatter-md': writeFrontmatterMarkdown,
json: writeJSON,
yml: writeYAML
};
const writeFile = util.promisify(fs.writeFile);
class Sourcebit {
constructor({ cacheFile = path.join(process.cwd(), '.sourcebit-cache.json'), runtimeParameters = {}, transformCallback } = {}) {
this.cacheFilePath = cacheFile;
this.context = {};
this.dataForPlugin = [];
this.fileWriterCache = new Map();
this.onTransform = transformCallback;
this.pluginBlocks = [];
this.pluginModules = {};
this.runtimeParameters = runtimeParameters;
this.isCacheEnabled = Boolean(runtimeParameters.cache === undefined ? runtimeParameters.watch : runtimeParameters.cache);
}
async bootstrapAll() {
this.isBootstrapping = true;
let queue = Promise.resolve();
this.context = this.loadContextFromCache() || {};
this.pluginBlocks.forEach((_, pluginIndex) => {
queue = queue.then(() => this.bootstrapPluginAtIndex(pluginIndex));
});
await queue;
this.isBootstrapping = false;
this.saveContextToCache();
}
async bootstrapPluginAtIndex(index) {
const pluginBlock = this.pluginBlocks[index];
const { options } = pluginBlock;
const plugin = this.pluginModules[index];
const pluginName = this.getNameOfPluginAtIndex(index);
if (typeof plugin.bootstrap === 'function') {
await plugin.bootstrap({
debug: this.getDebugMethodForPlugin(pluginName),
getPluginContext: this.getContextForNamespace.bind(this, pluginName),
log: this.logFromPlugin.bind(this),
options: this.parsePluginOptions(plugin, options),
refresh: this.transform.bind(this),
setPluginContext: this.setContextForNamespace.bind(this, pluginName)
});
}
pluginBlock._isBootstrapped = true;
}
debug(...parameters) {
return this.getDebugMethodForCore().call(this, parameters);
}
getContext() {
return cloneDeep(this.context);
}
getContextForNamespace(namespace) {
return this.context[namespace] ? cloneDeep(this.context[namespace]) : {};
}
getDebugMethodForCore() {
return debug('core');
}
getDebugMethodForPlugin(pluginName) {
return debug(`plugin:${pluginName}`);
}
getNameOfPluginAtIndex(index) {
return this.pluginModules[index].name || `plugin-${index}`;
}
loadContextFromCache() {
if (!this.isCacheEnabled) return;
try {
const data = fs.readFileSync(this.cacheFilePath, 'utf8');
return JSON.parse(data);
} catch (error) {
this.debug(error);
}
}
loadPlugins(plugins) {
this.pluginBlocks = plugins;
this.pluginModules = plugins.map(plugin => {
if (typeof plugin === 'function') {
return { transform: plugin };
}
return plugin.module;
});
}
log(message, messageType = 'info') {
if (this.runtimeParameters.quiet) {
return;
}
const oraMethod = ['succeed', 'fail', 'warn', 'info'].includes(messageType) ? messageType : 'info';
return ora(message)[oraMethod]();
}
logFromPlugin(message, messageType) {
this.log(`${message}`, messageType);
}
parsePluginOptions(plugin, optionsFromConfig) {
const { options: optionsSchema = {} } = plugin;
const defaults = {};
const overrides = {};
Object.keys(optionsSchema).forEach(key => {
if (optionsSchema[key].default !== undefined) {
defaults[key] = optionsSchema[key].default;
}
if (
typeof optionsSchema[key].runtimeParameter === 'string' &&
this.runtimeParameters[optionsSchema[key].runtimeParameter] !== undefined
) {
overrides[key] = this.runtimeParameters[optionsSchema[key].runtimeParameter];
}
});
return Object.assign({}, defaults, optionsFromConfig, overrides);
}
saveContextToCache() {
if (!this.isCacheEnabled) return;
const serializedCache = JSON.stringify(this.context);
try {
fs.writeFileSync(this.cacheFilePath, serializedCache);
} catch (error) {
this.debug(error);
}
}
setContextForNamespace(namespace, data) {
this.context[namespace] = { ...this.context[namespace], ...data };
}
setOptionsForPluginAtIndex(index, options) {
this.pluginBlocks[index].options = options;
}
async transform() {
if (this.isBootstrapping || this.isTransforming) {
if (this.isTransforming) {
this.isTransformQueued = true;
}
return;
}
this.isTransforming = true;
const initialData = {
files: [],
models: [],
objects: []
};
const contextSnapshot = cloneDeep(this.context);
this.pluginBlocks.forEach((pluginBlock, index) => {
const plugin = this.pluginModules[index];
const pluginName = this.getNameOfPluginAtIndex(index);
if (typeof plugin.onTransformStart === 'function') {
plugin.onTransformStart({
debug: this.getDebugMethodForPlugin(pluginName),
getPluginContext: () => contextSnapshot[pluginName] || {},
log: this.logFromPlugin.bind(this),
options: this.parsePluginOptions(plugin, pluginBlock.options)
});
}
});
const onTransformEndCallbacks = [];
const queue = this.pluginBlocks.reduce((queue, pluginBlock, index) => {
// If the plugin hasn't been bootstrapped, we don't want to run its
// transform method just yet.
if (!pluginBlock._isBootstrapped) {
return queue;
}
return queue.then(async data => {
const plugin = this.pluginModules[index];
const pluginName = this.getNameOfPluginAtIndex(index);
if (typeof plugin.onTransformEnd === 'function') {
onTransformEndCallbacks.push({
args: {
debug: this.getDebugMethodForPlugin(pluginName),
getPluginContext: () => contextSnapshot[pluginName] || {},
log: this.logFromPlugin.bind(this),
options: this.parsePluginOptions(plugin, pluginBlock.options)
},
callback: plugin.onTransformEnd
});
}
if (typeof plugin.transform !== 'function') {
return data;
}
const { __diff, ...currentDataForPlugin } = data;
const previousData = this.dataForPlugin[index] || initialData;
const diffs = Object.keys(currentDataForPlugin).reduce((diffs, dataBucketKey) => {
return {
...diffs,
[dataBucketKey]: generateDiff(previousData[dataBucketKey], currentDataForPlugin[dataBucketKey]) || []
};
}, {});
this.dataForPlugin[index] = currentDataForPlugin;
const transformedData = await plugin.transform({
data: {
...data,
__diff: diffs
},
debug: this.getDebugMethodForPlugin(pluginName),
getPluginContext: () => contextSnapshot[pluginName] || {},
log: this.logFromPlugin.bind(this),
options: this.parsePluginOptions(plugin, pluginBlock.options)
});
return transformedData;
});
}, Promise.resolve(initialData));
const finishTransform = () => {
this.isTransforming = false;
if (this.isTransformQueued) {
this.isTransformQueued = false;
this.transform();
}
};
try {
const data = await queue;
finishTransform();
if (Array.isArray(data.files)) {
await this.writeFiles(data.files);
}
onTransformEndCallbacks.forEach(({ args, callback }) => {
callback({ ...args, data });
});
if (typeof this.onTransform === 'function') {
this.onTransform(null, data);
}
return data;
} catch (error) {
this.log(`An error occurred when processing the plugins: ${error.message}.`, 'fail');
this.debug(error);
finishTransform();
if (typeof this.onTransform === 'function') {
this.onTransform(error);
}
}
}
writeFiles(files) {
const filesByPath = files.reduce((result, file) => {
if (!file.path || typeof file.path !== 'string') {
this.log(
'One of the plugins tried to write a file but failed to provide a valid file path. Please check your configuration.',
'warn'
);
return result;
}
const fullPath = path.resolve(process.cwd(), file.path);
// If `append: true`, we'll append the content of the new writer to any
// existing content at this path. If not, we'll overwrite it.
if (result[fullPath] && file.append) {
// Ensuring the existing content for this path is an array.
result[fullPath].content = Array.isArray(result[fullPath].content) ? result[fullPath].content : [result[fullPath].content];
result[fullPath].content.push(file.content);
} else {
result[fullPath] = file;
}
return result;
}, {});
// We start by deleting any files that were previously created by this plugin
// but that are not part of the site after the update.
this.fileWriterCache.forEach((_, filePath) => {
if (!filesByPath[filePath]) {
try {
fs.unlinkSync(filePath);
this.fileWriterCache.delete(filePath);
this.log(`Deleted ${filePath}`, 'info');
} catch (error) {
this.debug(error);
this.log(`Could not delete ${filePath}`, 'fail');
}
}
});
// Now we write all the files that need to be created.
const queue = Object.keys(filesByPath).map(async filePath => {
const file = filesByPath[filePath];
const writerFunction = fileWriters[file.format];
if (typeof writerFunction !== 'function') {
this.log(`Could not create ${filePath}. "${file.format}" is not a supported format.`, 'fail');
return;
}
// Ensuring the directory exists.
mkdirp.sync(path.dirname(filePath));
try {
const fileContent = await writerFunction(file.content);
const hasDiff = this.fileWriterCache.get(filePath) !== fileContent;
// If the contents of the file hasn't changed since we last wrote it, we skip it.
if (!hasDiff) {
return true;
}
writeFile(filePath, fileContent);
const isNewFile = Boolean(this.fileWriterCache.get(filePath));
this.fileWriterCache.set(filePath, fileContent);
this.log(`${isNewFile ? 'Updated' : 'Created'} ${filePath}`, 'succeed');
return true;
} catch (error) {
this.debug(error);
this.log(`Could not create ${filePath}`, 'fail');
return false;
}
});
return Promise.all(queue);
}
}
module.exports = Sourcebit;