forked from 11ty/eleventy-fetch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheleventy-fetch.js
88 lines (71 loc) · 1.96 KB
/
eleventy-fetch.js
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
const { default: PQueue } = require("p-queue");
const debug = require("debug")("Eleventy:Fetch");
const RemoteAssetCache = require("./src/RemoteAssetCache");
const AssetCache = require("./src/AssetCache");
const globalOptions = {
type: "buffer",
directory: ".cache",
concurrency: 10,
fetchOptions: {},
dryRun: false, // don’t write anything to the file system
// *does* affect cache key hash
removeUrlQueryParams: false,
// runs after removeUrlQueryParams, does not affect cache key hash
// formatUrlForDisplay: function(url) {
// return url;
// },
verbose: false, // Changed in 3.0+
hashLength: 30,
};
function isFullUrl(url) {
try {
new URL(url);
return true;
} catch (e) {
// invalid url OR already a local path
return false;
}
}
async function save(source, options) {
if (!isFullUrl(source)) {
return Promise.reject(new Error("Caching an already local asset is not yet supported."));
}
let asset = new RemoteAssetCache(source, options.directory, options);
return asset.fetch(options);
}
/* Queue */
let queue = new PQueue({
concurrency: globalOptions.concurrency,
});
queue.on("active", () => {
debug(`Concurrency: ${queue.concurrency}, Size: ${queue.size}, Pending: ${queue.pending}`);
});
let inProgress = {};
function queueSave(source, queueCallback) {
if (!inProgress[source]) {
inProgress[source] = queue.add(queueCallback).finally(() => {
delete inProgress[source];
});
}
return inProgress[source];
}
module.exports = function (source, options) {
let mergedOptions = Object.assign({}, globalOptions, options);
return queueSave(source, () => {
return save(source, mergedOptions);
});
};
Object.defineProperty(module.exports, "concurrency", {
get: function () {
return queue.concurrency;
},
set: function (concurrency) {
queue.concurrency = concurrency;
},
});
module.exports.queue = queueSave;
module.exports.Util = {
isFullUrl,
};
module.exports.RemoteAssetCache = RemoteAssetCache;
module.exports.AssetCache = AssetCache;