@archer-edu/dxp-directus-cli
Version:
138 lines • 6.89 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runPushPage = void 0;
const page_markdown_1 = require("./support/page-markdown");
const package_config_1 = require("./support/package-config");
const directus_page_repository_1 = require("./support/directus-page-repository");
const pull_pages_1 = require("./pull-pages");
const utils_1 = require("./support/utils");
const register = (program) => {
program
.command("push-page <filePath>")
.description("Create one brand-new Directus page from a local Markdown file")
.option("-s, --site-id <siteId>", "Directus site key override. Defaults to package.json siteId.")
.option("-T, --token <token>", "Directus API token (falls back to DIRECTUS_TOKEN)")
.option("-i, --download-images <imageDir>", "Download images to a directory relative to the src folders (ie 'assets/images'). If omitted, images use the CDN")
.option("-d, --debug", "Enable debug mode")
.option("--dry-run", "Validate and print the planned create without mutating Directus")
.action((filePath, options) => __awaiter(void 0, void 0, void 0, function* () {
try {
yield runPushPage(filePath, {
siteId: options.siteId,
token: options.token,
downloadImages: options.downloadImages,
debug: options.debug,
dryRun: options.dryRun,
});
}
catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}));
};
exports.default = register;
function runPushPage(filePath, options = {}) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const cwd = options.cwd || process.cwd();
const logger = options.logger || console.log;
const imagePath = options.downloadImages ? (0, utils_1.fixRelativePath)(options.downloadImages) : undefined;
const siteId = (0, package_config_1.resolveSiteId)({
optionSiteId: options.siteId,
env: process.env,
cwd,
});
const token = (0, directus_page_repository_1.resolveDirectusToken)(options.token);
const repository = options.repository || new directus_page_repository_1.DirectusPageRepository({
token,
debug: options.debug,
});
const mapReadBackPage = options.mapReadBackPage || pull_pages_1.mapPage;
const writeReadBackPage = options.writeReadBackPage || pull_pages_1.writePage;
const page = (0, page_markdown_1.parsePageMarkdown)(filePath, { cwd });
(0, page_markdown_1.validateNewPage)(page);
const site = yield repository.getSiteByKey(siteId);
if (!site)
throw new Error(`Directus site ${siteId} was not found`);
if (site.active === false)
throw new Error(`Directus site ${siteId} is not active`);
if (site.managed_pages === false)
throw new Error(`Directus site ${siteId} does not have managed pages enabled`);
const parentPageId = yield repository.resolveParentPageChain(siteId, page.parentPathSegments);
const existingPage = yield repository.findPageBySiteParentAndSlug(siteId, parentPageId, page.derivedSlug);
if (existingPage) {
throw new Error(`A Directus page already exists for slug /${page.derivedSlug}: ${existingPage.id}`);
}
const sort = (_a = page.frontMatter.weight) !== null && _a !== void 0 ? _a : (yield repository.getMaxSiblingSort(siteId, parentPageId)) + 1;
const payload = (0, page_markdown_1.buildPageCreatePayload)(page, {
siteId,
parentPageId,
sort,
});
if (options.dryRun) {
logger(formatDryRunSummary(site.name || siteId, page.parentPathSegments, payload));
return {
dryRun: true,
siteId,
payload,
};
}
const createdPage = yield repository.createPage(payload);
const createdIds = collectCreatedIds(createdPage);
try {
const readBackPage = yield repository.getPageForReadBack(createdPage.id);
const pageKeys = yield repository.listPageKeys(siteId);
const mappedPage = yield mapReadBackPage(readBackPage, pageKeys, imagePath, false);
mappedPage.file_path = page.filePath;
writeReadBackPage(mappedPage);
}
catch (error) {
throw new Error(`Directus page was created but local read-back failed. Created ids: ${JSON.stringify(createdIds)}. ${error.message}`);
}
logger(`Created Directus page ${createdPage.id} and updated ${page.filePath}`);
logger(`Sections: ${(createdPage.sections || []).length}; items: ${countItems(createdPage)}`);
return {
dryRun: false,
siteId,
payload,
createdPage,
};
});
}
exports.runPushPage = runPushPage;
function formatDryRunSummary(siteName, parentPathSegments, payload) {
return [
"Dry run complete. No Directus records were created.",
`Site: ${siteName}`,
`Parent: ${parentPathSegments.length ? parentPathSegments.join("/") : "(root)"}`,
`Slug: ${payload.slug}`,
`Status: ${payload.status}`,
`Sections: ${(payload.sections || []).length}`,
`Items: ${countItems(payload)}`,
].join("\n");
}
function collectCreatedIds(page) {
const sections = (page === null || page === void 0 ? void 0 : page.sections) || [];
const items = sections.flatMap((section) => section.items || []);
const junctions = sections.flatMap((section) => section.images || []);
return {
page: page === null || page === void 0 ? void 0 : page.id,
sections: sections.map((section) => section.id).filter(Boolean),
items: items.map((item) => item.id).filter(Boolean),
imageJunctions: junctions.map((junction) => junction.id).filter(Boolean),
};
}
function countItems(page) {
return (page.sections || []).reduce((count, section) => count + (section.items || []).length, 0);
}
//# sourceMappingURL=push-page.js.map