unstorage
Version:
Universal Storage Layer
111 lines (110 loc) • 2.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
module.exports = void 0;
var _utils = require("./utils/index.cjs");
var _ofetch = require("ofetch");
var _ufo = require("ufo");
const defaultOptions = {
repo: null,
branch: "main",
ttl: 600,
dir: "",
apiURL: "https://api.github.com",
cdnURL: "https://raw.githubusercontent.com"
};
var _default = (0, _utils.defineDriver)(_opts => {
const opts = {
...defaultOptions,
..._opts
};
const rawUrl = (0, _ufo.joinURL)(opts.cdnURL, opts.repo, opts.branch, opts.dir);
let files = {};
let lastCheck = 0;
let syncPromise;
if (!opts.repo) {
throw new Error('[unstorage] [github] Missing required option "repo"');
}
const syncFiles = async () => {
if (lastCheck + opts.ttl * 1e3 > Date.now()) {
return;
}
if (!syncPromise) {
syncPromise = fetchFiles(opts);
}
files = await syncPromise;
lastCheck = Date.now();
syncPromise = void 0;
};
return {
name: "github",
options: opts,
async getKeys() {
await syncFiles();
return Object.keys(files);
},
async hasItem(key) {
await syncFiles();
return key in files;
},
async getItem(key) {
await syncFiles();
const item = files[key];
if (!item) {
return null;
}
if (!item.body) {
try {
item.body = await (0, _ofetch.$fetch)(key.replace(/:/g, "/"), {
baseURL: rawUrl,
headers: {
Authorization: opts.token ? `token ${opts.token}` : void 0
}
});
} catch (err) {
throw new Error(`[unstorage] [github] Failed to fetch "${key}"`, {
cause: err
});
}
}
return item.body;
},
async getMeta(key) {
await syncFiles();
const item = files[key];
return item ? item.meta : null;
}
};
});
module.exports = _default;
async function fetchFiles(opts) {
const prefix = (0, _ufo.withTrailingSlash)(opts.dir).replace(/^\//, "");
const files = {};
try {
const trees = await (0, _ofetch.$fetch)(`/repos/${opts.repo}/git/trees/${opts.branch}?recursive=1`, {
baseURL: opts.apiURL,
headers: {
Authorization: opts.token ? `token ${opts.token}` : void 0
}
});
for (const node of trees.tree) {
if (node.type !== "blob" || !node.path.startsWith(prefix)) {
continue;
}
const key = node.path.substring(prefix.length).replace(/\//g, ":");
files[key] = {
meta: {
sha: node.sha,
mode: node.mode,
size: node.size
}
};
}
} catch (err) {
throw new Error(`[unstorage] [github] Failed to fetch git tree`, {
cause: err
});
}
return files;
}