53 lines
2.3 KiB
JavaScript
53 lines
2.3 KiB
JavaScript
import { readdir, readFile } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { zipSync } from "fflate";
|
|
|
|
export const archivePath = "downloads/questiongraph-library.zip";
|
|
|
|
export async function createLibraryArchive(root) {
|
|
const files = {};
|
|
async function collect(directory, prefix) {
|
|
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
const path = join(directory, entry.name);
|
|
const name = prefix + "/" + entry.name;
|
|
if (entry.isDirectory()) await collect(path, name);
|
|
else if (entry.isFile() && /\.(ts|tsx|json)$/.test(entry.name))
|
|
files[name] = new Uint8Array(await readFile(path));
|
|
}
|
|
}
|
|
await collect(join(root, "src/lib"), "questiongraph/lib");
|
|
files["questiongraph/README.md"] = new Uint8Array(await readFile(join(root, "scripts/library-README.md")));
|
|
return zipSync(files, { level: 6 });
|
|
}
|
|
|
|
// Build-time asset generation keeps the ZIP in sync with the shipped source.
|
|
// Dev requests generate it afresh; no generated ZIP is committed.
|
|
export function libraryDownload() {
|
|
let root;
|
|
let base;
|
|
return {
|
|
name: "questiongraph-library-download",
|
|
configResolved(config) { root = config.root; base = config.base; },
|
|
configureServer(server) {
|
|
server.middlewares.use(async (request, response, next) => {
|
|
const pathname = (request.url ?? "").split("?")[0];
|
|
if (pathname !== "/" + archivePath && pathname !== base + archivePath) return next();
|
|
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
response.statusCode = 405; response.setHeader("Allow", "GET, HEAD"); response.end(); return;
|
|
}
|
|
try {
|
|
const archive = await createLibraryArchive(root);
|
|
response.setHeader("Content-Type", "application/zip");
|
|
response.setHeader("Content-Disposition", 'attachment; filename="questiongraph-library.zip"');
|
|
response.setHeader("Cache-Control", "no-store");
|
|
response.setHeader("Content-Length", archive.length);
|
|
response.end(request.method === "HEAD" ? undefined : Buffer.from(archive));
|
|
} catch (error) { next(error); }
|
|
});
|
|
},
|
|
async generateBundle() {
|
|
this.emitFile({ type: "asset", fileName: archivePath, source: await createLibraryArchive(root) });
|
|
},
|
|
};
|
|
}
|