import { __awaiter } from "tslib";
import { QoreClient } from "@qorebase/client";
import Cors from "cors";
import { qoreConfig } from "../../../../../app/hooks/qoreStorageClient";
const client = new QoreClient(qoreConfig);
const runMiddleware = (req, res, fn) => {
    return new Promise((resolve, reject) => {
        fn(req, res, (result) => {
            if (result instanceof Error) {
                return reject(result);
            }
            return resolve(result);
        });
    });
};
const cors = Cors({
    methods: ["GET", "HEAD"],
});
export default function handler(req, res) {
    var _a, _b;
    return __awaiter(this, void 0, void 0, function* () {
        yield runMiddleware(req, res, cors);
        const result = yield (req.query.version === "latest"
            ? client
                .view("component_version_list")
                .readRows({
                params: {
                    user_external_id: req.query.author,
                    identifier: req.query.name,
                },
                limit: 1,
            })
                .toPromise()
            : client
                .view("component_version_by_hash")
                .readRows({
                params: {
                    user_external_id: req.query.author,
                    identifier: req.query.name,
                    hash: req.query.version,
                },
                limit: 1,
            })
                .toPromise());
        const file = (_b = (_a = result.data) === null || _a === void 0 ? void 0 : _a.nodes) === null || _b === void 0 ? void 0 : _b[0];
        if (!file) {
            res.status(404).json({ error: "Not found" });
            return;
        }
        const component = yield client.project.axios.get(`/v1/files/public/component_versions/${file.id}/component/${req.query.name}`);
        res.setHeader("Content-Type", "application/javascript");
        res.send(component.data);
    });
}
//# sourceMappingURL=%5Bname%5D.js.map