"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const path_1 = __importDefault(require("path")); const nunjucks_1 = __importDefault(require("nunjucks")); const fs_1 = __importDefault(require("../utils/fs")); const git_1 = __importDefault(require("../utils/git")); const location_1 = __importDefault(require("../utils/location")); const path_2 = __importDefault(require("../utils/path")); /** * Template loader resolving both: * - relative url ("./test.md") * - absolute url ("/test.md") * - git url ("") * * @param {string} rootFolder * @param {Function(filePath, source)} transformFn (optional) * @param {Logger} logger (optional) */ const ConrefsLoader = nunjucks_1.default.Loader.extend({ async: true, // @ts-expect-error types is wrong init: function (rootFolder, transformFn, logger) { this.rootFolder = rootFolder; this.transformFn = transformFn; this.logger = logger; this.git = new git_1.default(); }, getSource: function (sourceURL, callback) { const that = this; this.git .resolve(sourceURL) .then((filepath) => { // Is local file if (!filepath) { filepath = path_1.default.resolve(sourceURL); } else { if (that.logger) that.logger.debug.ln("resolve from git", sourceURL, "to", filepath); } // Read file from absolute path return fs_1.default .readFile(filepath) .then((source) => { source = source.toString("utf8"); if (that.transformFn) { return that.transformFn(filepath, source); } return source; }) .then((source) => { return { src: source, path: filepath }; }); }) .nodeify(callback); }, resolve: function (from, to) { // If origin is in the book, we enforce result file to be in the book if (path_2.default.isInRoot(this.rootFolder, from)) { // Path of current template in the rootFolder (not absolute to fs) const fromRelative = path_1.default.relative(this.rootFolder, from); // Resolve "to" to a filepath relative to rootFolder const href = location_1.default.toAbsolute(to, path_1.default.dirname(fromRelative), ""); // Return absolute path // @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 2. return path_2.default.resolveInRoot(this.rootFolder, href); } // If origin is in a git repository, we resolve file in the git repository const gitRoot = this.git.resolveRoot(from); if (gitRoot) { // @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 2. return path_2.default.resolveInRoot(gitRoot, to); } // If origin is not in the book (include from a git content ref) return path_1.default.resolve(path_1.default.dirname(from), to); }, // Handle all files as relative, so that nunjucks pass responsability to 'resolve' isRelative: function (filename) { return location_1.default.isRelative(filename); } }); exports.default = ConrefsLoader;