@agility/nextjs
Version:
Agility CMS support for NextJS 16 and Next Image
529 lines (528 loc) • 29.8 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDynamicPageURL = exports.generatePreviewKey = exports.validatePreview = exports.getAgilityPaths = exports.getAgilityPageProps = void 0;
var utils_1 = require("./utils");
//Agility API stuff
var config_1 = require("./config");
var agilityRestAPI = __importStar(require("@agility/content-fetch"));
var securityKey = config_1.agilityConfig.securityKey;
var channelName = config_1.agilityConfig.channelName;
var isDevelopmentMode = process.env.NODE_ENV === "development";
var cacheDuration = config_1.agilityConfig.defaultCacheDuration;
var getAgilityPageProps = function (_a) {
var params = _a.params, preview = _a.preview, locale = _a.locale, defaultLocale = _a.defaultLocale, getModule = _a.getModule, globalComponents = _a.globalComponents, apiOptions = _a.apiOptions;
return __awaiter(void 0, void 0, void 0, function () {
var defaultAPIOptions, languageCode, path, slugAry, isPreview, isDebugMode, agilityRestClient, sitemap, notFound, pageInSitemap, page, dynamicPageItem, firstPagePathInSitemap, pageID, contentLinkDepth, expandAllContentLinks, globalData, keys, i, key, fnc, retData, error_1, pageTemplateName;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
defaultAPIOptions = {
onSitemapRetrieved: null,
expandAllContentLinks: true,
contentLinkDepth: 3,
};
apiOptions = __assign(__assign({}, defaultAPIOptions), apiOptions);
languageCode = (locale ||
defaultLocale ||
config_1.agilityConfig.locales[0]).toLowerCase();
path = "/";
if (params) {
//build path by iterating through slugs
path = "";
if (params.slug instanceof String) {
//slug is a flat string...
path = params.slug;
}
else {
slugAry = params.slug;
slugAry.map(function (slug) {
path += "/" + slug;
});
}
}
isPreview = preview || isDevelopmentMode;
isDebugMode = config_1.agilityConfig.debug || isDevelopmentMode;
if (isDebugMode) {
console.log("AgilityCMS => getAgilityPageProps [".concat(languageCode, "] [").concat(path, "]"));
}
agilityRestClient = agilityRestAPI.getApi({
guid: config_1.agilityConfig.guid,
apiKey: isPreview
? config_1.agilityConfig.previewAPIKey
: config_1.agilityConfig.fetchAPIKey,
isPreview: isPreview,
debug: config_1.agilityConfig.debug,
});
//set the cache options for this page
if (cacheDuration > 0) {
agilityRestClient.config.fetchConfig = {
next: {
tags: ["agility-sitemap-flat-".concat(languageCode)],
revalidate: cacheDuration
}
};
}
else {
agilityRestClient.config.fetchConfig = {
cache: "no-store"
};
}
return [4 /*yield*/, agilityRestClient.getSitemapFlat({ channelName: channelName, languageCode: languageCode })];
case 1:
sitemap = _b.sent();
notFound = false;
if (!sitemap) {
//no sitemap!
console.warn("AgilityCMS => WARNING: No sitemap found for '".concat(channelName, ".'"));
notFound = true;
}
if (apiOptions && apiOptions.onSitemapRetrieved) {
apiOptions.onSitemapRetrieved({ sitemap: sitemap, isPreview: isPreview, isDevelopmentMode: isDevelopmentMode });
}
pageInSitemap = null;
dynamicPageItem = null;
if (sitemap) {
if (path === "/") {
firstPagePathInSitemap = Object.keys(sitemap)[0];
pageInSitemap = sitemap[firstPagePathInSitemap];
}
else {
//all other pages
pageInSitemap = sitemap[path];
}
}
if (!pageInSitemap) return [3 /*break*/, 3];
pageID = pageInSitemap.pageID;
contentLinkDepth = apiOptions.contentLinkDepth;
expandAllContentLinks = apiOptions.expandAllContentLinks;
//set the cache options for this page
if (cacheDuration > 0) {
agilityRestClient.config.fetchConfig = {
next: {
tags: ["agility-page-".concat(pageID, "-").concat(languageCode)],
revalidate: cacheDuration
}
};
}
else {
agilityRestClient.config.fetchConfig = {
cache: "no-store"
};
}
return [4 /*yield*/, agilityRestClient.getPage({ pageID: pageID, languageCode: languageCode, contentLinkDepth: contentLinkDepth, expandAllContentLinks: expandAllContentLinks })];
case 2:
//get the page
page = _b.sent();
return [3 /*break*/, 4];
case 3:
//Could not find page
console.warn("AgilityCMS => Page [".concat(path, "] not found in sitemap channel '").concat(channelName, ".' ."));
notFound = true;
_b.label = 4;
case 4:
if (!page && pageInSitemap) {
console.warn("AgilityCMS => page [".concat(path, "] with id [").concat(pageInSitemap.pageID, "] was not able to be accessed."));
notFound = true;
}
globalData = {};
if (!globalComponents) return [3 /*break*/, 11];
keys = Object.keys(globalComponents);
i = 0;
_b.label = 5;
case 5:
if (!(i < keys.length)) return [3 /*break*/, 11];
key = keys[i];
_b.label = 6;
case 6:
_b.trys.push([6, 9, , 10]);
fnc = globalComponents[key].getCustomInitialProps;
if (!fnc) return [3 /*break*/, 8];
if (isDebugMode) {
console.log("AgilityCMS => Fetching global data for ".concat(key, "..."));
}
return [4 /*yield*/, fnc({
agility: agilityRestClient,
languageCode: languageCode,
channelName: channelName,
page: page,
sitemapNode: pageInSitemap,
dynamicPageItem: dynamicPageItem,
})];
case 7:
retData = _b.sent();
globalData[key] = retData;
_b.label = 8;
case 8: return [3 /*break*/, 10];
case 9:
error_1 = _b.sent();
throw new Error("AgilityCMS => Error calling global data function ".concat(key, ": ").concat(error_1));
case 10:
i++;
return [3 /*break*/, 5];
case 11:
pageTemplateName = null;
if (!!notFound) return [3 /*break*/, 15];
if (!(pageInSitemap.contentID > 0)) return [3 /*break*/, 13];
return [4 /*yield*/, agilityRestClient.getContentItem({
contentID: pageInSitemap.contentID,
languageCode: languageCode,
})];
case 12:
dynamicPageItem = _b.sent();
_b.label = 13;
case 13:
//resolve the page template
pageTemplateName = page.templateName.replace(/[^0-9a-zA-Z]/g, "");
//resolve the modules per content zone
return [4 /*yield*/, (0, utils_1.asyncForEach)(Object.keys(page.zones), function (zoneName) { return __awaiter(void 0, void 0, void 0, function () {
var modules, modulesForThisContentZone;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
modules = [];
modulesForThisContentZone = page.zones[zoneName];
//only proceeed if we have a getModule function to execute
if (!getModule)
return [2 /*return*/];
//loop through the zone's modules
return [4 /*yield*/, (0, utils_1.asyncForEach)(modulesForThisContentZone, function (moduleItem) { return __awaiter(void 0, void 0, void 0, function () {
var moduleComponent, moduleData, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
moduleComponent = getModule ? getModule(moduleItem.module) : null;
if (!(moduleComponent && moduleComponent.getCustomInitialProps)) return [3 /*break*/, 4];
//resolve any additional data for the modules
//we have some additional data in the module we'll need, execute that method now, so it can be included in SSG
if (isDebugMode) {
console.log("AgilityCMS => Fetching additional data for ".concat(moduleItem.module, "..."));
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, moduleComponent.getCustomInitialProps({
page: page,
item: moduleItem.item,
agility: agilityRestClient,
languageCode: languageCode,
channelName: channelName,
sitemapNode: pageInSitemap,
dynamicPageItem: dynamicPageItem,
})];
case 2:
moduleData = _a.sent();
//if we have additional module data, then add it to the module props using 'customData'
if (moduleData != null) {
moduleItem.customData = moduleData;
}
return [3 /*break*/, 4];
case 3:
error_2 = _a.sent();
throw new Error("AgilityCMS => Error getting custom data for module ".concat(moduleItem.module, ": ").concat(error_2));
case 4:
modules.push({
module: moduleItem.module,
item: moduleItem.item,
customData: moduleItem.customData || null,
});
return [2 /*return*/];
}
});
}); })];
case 1:
//loop through the zone's modules
_a.sent();
//store as dictionary
page.zones[zoneName] = modules;
return [2 /*return*/];
}
});
}); })];
case 14:
//resolve the modules per content zone
_b.sent();
_b.label = 15;
case 15: return [2 /*return*/, {
sitemapNode: pageInSitemap || null,
page: page,
dynamicPageItem: dynamicPageItem,
pageTemplateName: pageTemplateName,
globalData: globalData,
languageCode: languageCode,
channelName: channelName,
isPreview: isPreview,
isDevelopmentMode: isDevelopmentMode,
notFound: notFound,
}];
}
});
});
};
exports.getAgilityPageProps = getAgilityPageProps;
var getAgilityPaths = function (_a) {
var preview = _a.preview, locales = _a.locales, defaultLocale = _a.defaultLocale;
return __awaiter(void 0, void 0, void 0, function () {
var isPreview, agilityRestClient, paths, _loop_1, i;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
isPreview = isDevelopmentMode || preview;
if (!defaultLocale)
defaultLocale = config_1.agilityConfig.locales[0];
if (!locales)
locales = config_1.agilityConfig.locales;
agilityRestClient = agilityRestAPI.getApi({
guid: config_1.agilityConfig.guid,
apiKey: isPreview ? config_1.agilityConfig.previewAPIKey : config_1.agilityConfig.fetchAPIKey,
isPreview: isPreview,
debug: config_1.agilityConfig.debug,
});
paths = [];
_loop_1 = function (i) {
var languageCode, sitemapFlat, thesePaths;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
languageCode = locales[i].toLowerCase();
//set the cache options for this page
if (cacheDuration > 0) {
agilityRestClient.config.fetchConfig = {
next: {
tags: ["agility-sitemap-flat-".concat(languageCode)],
revalidate: cacheDuration
}
};
}
else {
agilityRestClient.config.fetchConfig = {
cache: "no-store"
};
}
console.log("AgilityCMS => `getAgilityPaths` *** USING REST API ***");
return [4 /*yield*/, agilityRestClient.getSitemapFlat({
channelName: channelName,
languageCode: languageCode,
})];
case 1:
sitemapFlat = _c.sent();
if (!sitemapFlat) {
console.warn("AgilityCMS => No Sitemap found for locale ".concat(languageCode, ". Make sure your locales and environment variables are setup correctly."));
return [2 /*return*/, "continue"];
}
thesePaths = Object.keys(sitemapFlat).filter(function (path) {
var sitemapNode = sitemapFlat[path];
return !sitemapNode.redirect && !sitemapNode.isFolder;
});
if (languageCode !== defaultLocale.toLowerCase()) {
//prepend
paths = paths.concat(thesePaths.map(function (path) { return "/".concat(languageCode).concat(path); }));
}
else {
paths = paths.concat(thesePaths);
}
return [2 /*return*/];
}
});
};
i = 0;
_b.label = 1;
case 1:
if (!(i < locales.length)) return [3 /*break*/, 4];
return [5 /*yield**/, _loop_1(i)];
case 2:
_b.sent();
_b.label = 3;
case 3:
i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, paths];
}
});
});
};
exports.getAgilityPaths = getAgilityPaths;
var validatePreview = function (_a) {
var agilityPreviewKey = _a.agilityPreviewKey, slug = _a.slug;
return __awaiter(void 0, void 0, void 0, function () {
var correctPreviewKey;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
//Validate the preview key
if (!agilityPreviewKey) {
return [2 /*return*/, {
error: true,
message: "Missing agilitypreviewkey.",
}];
}
//sanitize incoming key (replace spaces with '+')
if (agilityPreviewKey.indexOf(" ") > -1) {
agilityPreviewKey = agilityPreviewKey.split(" ").join("+");
}
return [4 /*yield*/, generatePreviewKey()];
case 1:
correctPreviewKey = _b.sent();
if (agilityPreviewKey !== correctPreviewKey) {
return [2 /*return*/, {
error: true,
message: "Invalid agilitypreviewkey.",
//message: `Invalid agilitypreviewkey. Incoming key is=${agilityPreviewKey} compared to=${correctPreviewKey}...`
}];
}
//return success
return [2 /*return*/, {
error: false,
message: null,
}];
}
});
});
};
exports.validatePreview = validatePreview;
var generatePreviewKey = function () { return __awaiter(void 0, void 0, void 0, function () {
var str, data, i, strBuffer, crypto, previewKey;
return __generator(this, function (_a) {
str = "-1_".concat(securityKey, "_Preview");
data = [];
for (i = 0; i < str.length; ++i) {
data.push(str.charCodeAt(i));
data.push(0);
}
strBuffer = Buffer.from(data);
crypto = require("crypto");
previewKey = crypto
.createHash("sha512")
.update(strBuffer)
.digest("base64");
return [2 /*return*/, previewKey];
});
}); };
exports.generatePreviewKey = generatePreviewKey;
var getDynamicPageURL = function (_a) {
var contentID = _a.contentID, preview = _a.preview, slug = _a.slug, locale = _a.locale;
return __awaiter(void 0, void 0, void 0, function () {
var isPreview, defaultLocale, languageCode, agilityRestClient, sitemapFlat, dynamicPaths;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
console.log("Agility CMS => Retrieving Dynamic Page URL by ContentID...");
isPreview = preview || isDevelopmentMode;
defaultLocale = config_1.agilityConfig.locales[0];
languageCode = (!locale) ? defaultLocale : config_1.agilityConfig.locales.find(function (l) { return l.toLowerCase() === locale.toLowerCase(); });
if (!languageCode) {
console.warn("AgilityCMS => Locale ".concat(locale, " not found in locales array."));
languageCode = defaultLocale;
}
agilityRestClient = agilityRestAPI.getApi({
guid: config_1.agilityConfig.guid,
apiKey: isPreview ? config_1.agilityConfig.previewAPIKey : config_1.agilityConfig.fetchAPIKey,
isPreview: isPreview,
debug: config_1.agilityConfig.debug,
});
//set the cache options for this page
if (cacheDuration > 0) {
agilityRestClient.config.fetchConfig = {
next: {
tags: ["agility-sitemap-flat-".concat(languageCode)],
revalidate: cacheDuration
}
};
}
else {
agilityRestClient.config.fetchConfig = {
cache: "no-store"
};
}
return [4 /*yield*/, agilityRestClient.getSitemapFlat({
channelName: channelName,
languageCode: languageCode,
})];
case 1:
sitemapFlat = _b.sent();
dynamicPaths = Object.keys(sitemapFlat).filter(function (s) {
if (sitemapFlat[s].contentID == contentID) {
return s;
}
});
if (dynamicPaths.length > 0) {
return [2 /*return*/, dynamicPaths[0]]; //return the first one found
}
else {
return [2 /*return*/, null]; //no dynamic path
}
return [2 /*return*/];
}
});
});
};
exports.getDynamicPageURL = getDynamicPageURL;