keycloakify
Version:
Framework to create custom Keycloak UIs
1,055 lines (977 loc) • 104 kB
JavaScript
"use strict";
exports.id = 712;
exports.ids = [712];
exports.modules = {
/***/ 73817:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "k": () => (/* binding */ generateMessageProperties)
/* harmony export */ });
/* harmony import */ var _shared_constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(173);
/* harmony import */ var _tools_crawl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(73036);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(71017);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var tsafe_symToStr__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(76030);
/* harmony import */ var recast__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48128);
/* harmony import */ var _babel_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(85026);
/* harmony import */ var _babel_generator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(92332);
/* harmony import */ var _babel_types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7912);
/* harmony import */ var _babel_types__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_types__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _tools_escapeStringForPropertiesFile__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(27190);
/* harmony import */ var _tools_getThisCodebaseRootDirPath__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(58822);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(57147);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var tsafe_assert__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(29041);
/* harmony import */ var _tools_getAbsoluteAndInOsFormatPath__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(84794);
/* harmony import */ var json5__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(86904);
/* harmony import */ var json5__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(json5__WEBPACK_IMPORTED_MODULE_11__);
(0,tsafe_assert__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .h)();
function generateMessageProperties(params) {
const { buildContext, themeType } = params;
const baseMessagesDirPath = (0,path__WEBPACK_IMPORTED_MODULE_2__.join)((0,_tools_getThisCodebaseRootDirPath__WEBPACK_IMPORTED_MODULE_7__/* .getThisCodebaseRootDirPath */ .e)(), "src", themeType, "i18n", "messages_defaultSet");
const messages_defaultSet_by_languageTag_defaultSet = Object.fromEntries(fs__WEBPACK_IMPORTED_MODULE_8__.readdirSync(baseMessagesDirPath)
.filter(basename => basename !== "index.ts" && basename !== "types.ts")
.map(basename => ({
languageTag: basename.replace(/\.ts$/, ""),
filePath: (0,path__WEBPACK_IMPORTED_MODULE_2__.join)(baseMessagesDirPath, basename)
}))
.map(({ languageTag, filePath }) => {
const lines = fs__WEBPACK_IMPORTED_MODULE_8__.readFileSync(filePath).toString("utf8").split(/\r?\n/);
let messagesJson = "{";
let isInDeclaration = false;
for (const line of lines) {
if (!isInDeclaration) {
if (line.startsWith("const messages")) {
isInDeclaration = true;
}
continue;
}
if (line.startsWith("}")) {
messagesJson += "}";
break;
}
messagesJson += line;
}
const messages = json5__WEBPACK_IMPORTED_MODULE_11___default().parse(messagesJson);
return [languageTag, messages];
}));
const { i18nTsFilePath } = (() => {
let files = (0,_tools_crawl__WEBPACK_IMPORTED_MODULE_1__/* .crawl */ .J)({
dirPath: (0,path__WEBPACK_IMPORTED_MODULE_2__.join)(buildContext.themeSrcDirPath, themeType),
returnedPathsType: "absolute"
});
files = files.filter(file => {
const regex = /\.(js|ts|tsx)$/;
return regex.test(file);
});
files = files.sort((a, b) => {
const regex = /\.i18n\.(ts|js|tsx)$/;
const aIsI18nFile = regex.test(a);
const bIsI18nFile = regex.test(b);
return aIsI18nFile === bIsI18nFile ? 0 : aIsI18nFile ? -1 : 1;
});
files = files.sort((a, b) => a.length - b.length);
files = files.filter(file => fs__WEBPACK_IMPORTED_MODULE_8__.readFileSync(file).toString("utf8").includes("i18nBuilder"));
const i18nTsFilePath = files[0];
return { i18nTsFilePath };
})();
const i18nTsRoot = (() => {
if (i18nTsFilePath === undefined) {
return undefined;
}
const root = recastParseTs(i18nTsFilePath);
return root;
})();
const messages_defaultSet_by_languageTag_notInDefaultSet = (() => {
if (i18nTsRoot === undefined) {
return undefined;
}
let extraLanguageEntryByLanguageTag = {};
recast__WEBPACK_IMPORTED_MODULE_3__/* .visit */ .Vn(i18nTsRoot, {
visitCallExpression: function (path) {
const node = path.node;
// Check if the callee is a MemberExpression with property 'withExtraLanguages'
if (node.callee.type === "MemberExpression" &&
node.callee.property.type === "Identifier" &&
node.callee.property.name === "withExtraLanguages") {
const arg = node.arguments[0];
if (arg && arg.type === "ObjectExpression") {
// Iterate over the properties of the object
arg.properties.forEach(prop => {
if (prop.type === "ObjectProperty" &&
prop.key.type === "Identifier") {
const lang = prop.key.name;
const value = prop.value;
if (value.type === "ObjectExpression") {
let label = undefined;
let pathStr = undefined;
// Iterate over the properties of the language object
value.properties.forEach(p => {
if (p.type === "ObjectProperty" &&
p.key.type === "Identifier") {
if (p.key.name === "label" &&
p.value.type === "StringLiteral") {
label = p.value.value;
}
if (p.key.name === "getMessages" &&
(p.value.type ===
"ArrowFunctionExpression" ||
p.value.type === "FunctionExpression")) {
// Extract the import path from the function body
const body = p.value.body;
if (body.type === "CallExpression" &&
body.callee.type === "Import") {
const importArg = body.arguments[0];
if (importArg.type === "StringLiteral") {
pathStr = importArg.value;
}
}
else if (body.type === "BlockStatement") {
// If the function body is a block (e.g., function with braces {})
// Look for return statement
body.body.forEach(statement => {
if (statement.type ===
"ReturnStatement" &&
statement.argument &&
statement.argument.type ===
"CallExpression" &&
statement.argument.callee
.type === "Import") {
const importArg = statement.argument
.arguments[0];
if (importArg.type ===
"StringLiteral") {
pathStr = importArg.value;
}
}
});
}
}
}
});
if (label && pathStr) {
extraLanguageEntryByLanguageTag[lang] = {
label,
path: pathStr
};
}
}
}
});
}
return false; // Stop traversing this path
}
this.traverse(path); // Continue traversing other paths
}
});
const messages_defaultSet_by_languageTag_notInDefaultSet = Object.fromEntries(Object.entries(extraLanguageEntryByLanguageTag).map(([languageTag, { path: relativePathWithoutExt }]) => [
languageTag,
(() => {
const filePath = (0,_tools_getAbsoluteAndInOsFormatPath__WEBPACK_IMPORTED_MODULE_10__/* .getAbsoluteAndInOsFormatPath */ .c)({
pathIsh: relativePathWithoutExt.endsWith(".ts")
? relativePathWithoutExt
: `${relativePathWithoutExt}.ts`,
cwd: (0,path__WEBPACK_IMPORTED_MODULE_2__.dirname)(i18nTsFilePath)
});
const root = recastParseTs(filePath);
let declarationCode = "";
recast__WEBPACK_IMPORTED_MODULE_3__/* .visit */ .Vn(root, {
visitVariableDeclarator: function (path) {
const node = path.node;
// Check if the variable name is 'messages'
if (node.id.type === "Identifier" &&
node.id.name === "messages") {
// Ensure there is an initializer
if (node.init) {
// Generate code from the initializer, preserving comments
declarationCode = recast__WEBPACK_IMPORTED_MODULE_3__/* .print */ .S0(node.init)
.code.replace(/}.*$/, "}");
}
return false; // Stop traversing this path
}
this.traverse(path); // Continue traversing other paths
}
});
(0,tsafe_assert__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .h)(declarationCode !== undefined, `${filePath} does not contain a 'messages' variable declaration`);
let messages = {};
try {
eval(`${(0,tsafe_symToStr__WEBPACK_IMPORTED_MODULE_12__/* .symToStr */ .r)({ messages })} = ${declarationCode};`);
}
catch (_a) {
throw new Error(`The declaration of 'message' in ${filePath} cannot be statically evaluated: ${declarationCode}`);
}
return messages;
})()
]));
return messages_defaultSet_by_languageTag_notInDefaultSet;
})();
const messages_defaultSet_by_languageTag = Object.assign(Object.assign({}, messages_defaultSet_by_languageTag_defaultSet), messages_defaultSet_by_languageTag_notInDefaultSet);
const messages_themeDefined_by_languageTag = (() => {
if (i18nTsRoot === undefined) {
return undefined;
}
let firstArgumentCode = undefined;
recast__WEBPACK_IMPORTED_MODULE_3__/* .visit */ .Vn(i18nTsRoot, {
visitCallExpression: function (path) {
const node = path.node;
if (node.callee.type === "MemberExpression" &&
node.callee.property.type === "Identifier" &&
node.callee.property.name === "withCustomTranslations") {
firstArgumentCode = (0,_babel_generator__WEBPACK_IMPORTED_MODULE_5__/* ["default"] */ .ZP)(node.arguments[0]).code;
return false;
}
this.traverse(path);
}
});
if (firstArgumentCode === undefined) {
return undefined;
}
let messages_themeDefined_by_languageTag = {};
try {
eval(`${(0,tsafe_symToStr__WEBPACK_IMPORTED_MODULE_12__/* .symToStr */ .r)({ messages_themeDefined_by_languageTag })} = ${firstArgumentCode}`);
}
catch (_a) {
console.warn([
"WARNING: The argument of withCustomTranslations can't be statically evaluated!",
"This needs to be fixed refer to the documentation: https://docs.keycloakify.dev/i18n",
firstArgumentCode
].join(" "));
return undefined;
}
return messages_themeDefined_by_languageTag;
})();
const languageTags = Object.keys(messages_defaultSet_by_languageTag);
return {
languageTags,
writeMessagePropertiesFiles: ({ messageDirPath, themeName }) => {
for (const languageTag of languageTags) {
const messages = Object.assign({}, messages_defaultSet_by_languageTag[languageTag]);
add_theme_defined_messages: {
if (messages_themeDefined_by_languageTag === undefined) {
break add_theme_defined_messages;
}
let messages_themeDefined = messages_themeDefined_by_languageTag[languageTag];
if (messages_themeDefined === undefined) {
messages_themeDefined =
messages_themeDefined_by_languageTag[_shared_constants__WEBPACK_IMPORTED_MODULE_0__/* .FALLBACK_LANGUAGE_TAG */ ._L];
}
if (messages_themeDefined === undefined) {
messages_themeDefined =
messages_themeDefined_by_languageTag[Object.keys(messages_themeDefined_by_languageTag)[0]];
}
if (messages_themeDefined === undefined) {
break add_theme_defined_messages;
}
for (const [key, messageOrMessageByThemeName] of Object.entries(messages_themeDefined)) {
const message = (() => {
if (typeof messageOrMessageByThemeName === "string") {
return messageOrMessageByThemeName;
}
const message = messageOrMessageByThemeName[themeName];
(0,tsafe_assert__WEBPACK_IMPORTED_MODULE_9__/* .assert */ .h)(message !== undefined);
return message;
})();
messages[key] = message;
}
}
const propertiesFileSource = [
"",
...Object.entries(messages).map(([key, value]) => `${key}=${(0,_tools_escapeStringForPropertiesFile__WEBPACK_IMPORTED_MODULE_13__/* .escapeStringForPropertiesFile */ .y)(value)}`),
""
].join("\n");
fs__WEBPACK_IMPORTED_MODULE_8__.mkdirSync(messageDirPath, { recursive: true });
fs__WEBPACK_IMPORTED_MODULE_8__.writeFileSync((0,path__WEBPACK_IMPORTED_MODULE_2__.join)(messageDirPath, `messages_${languageTag.replace(/\-/g, "_")}.properties`), Buffer.from(propertiesFileSource, "utf8"));
}
}
};
}
function recastParseTs(filePath) {
return recast__WEBPACK_IMPORTED_MODULE_3__/* .parse */ .Qc(fs__WEBPACK_IMPORTED_MODULE_8__.readFileSync(filePath).toString("utf8"), {
parser: {
parse: (code) => _babel_parser__WEBPACK_IMPORTED_MODULE_4__/* .parse */ .Qc(code, {
sourceType: "module",
plugins: ["typescript"]
}),
generator: _babel_generator__WEBPACK_IMPORTED_MODULE_5__/* ["default"] */ .ZP,
types: _babel_types__WEBPACK_IMPORTED_MODULE_6__
}
});
}
//# sourceMappingURL=generateMessageProperties.js.map
/***/ }),
/***/ 35712:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"command": () => (/* reexport */ command)
});
// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(57147);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
// EXTERNAL MODULE: ./dist/bin/tools/fs.rmSync.js
var fs_rmSync = __webpack_require__(89693);
// EXTERNAL MODULE: ./dist/bin/tools/transformCodebase.js
var transformCodebase = __webpack_require__(60332);
// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(71017);
// EXTERNAL MODULE: ./node_modules/tsafe/esm/assert.mjs + 1 modules
var assert = __webpack_require__(29041);
// EXTERNAL MODULE: ./dist/bin/shared/constants.js
var constants = __webpack_require__(173);
;// CONCATENATED MODULE: ./dist/bin/tools/String.prototype.replaceAll.js
function replaceAll(string, searchValue, replaceValue) {
if (string.replaceAll !== undefined) {
return string.replaceAll(searchValue, replaceValue);
}
// If the searchValue is a string
if (typeof searchValue === "string") {
// Escape special characters in the string to be used in a regex
var escapedSearchValue = searchValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
var regex = new RegExp(escapedSearchValue, "g");
return string.replace(regex, replaceValue);
}
// If the searchValue is a global RegExp, use it directly
if (searchValue instanceof RegExp && searchValue.global) {
return string.replace(searchValue, replaceValue);
}
// If the searchValue is a non-global RegExp, throw an error
if (searchValue instanceof RegExp) {
throw new TypeError("replaceAll must be called with a global RegExp");
}
// Convert searchValue to string if it's not a string or RegExp
var searchString = String(searchValue);
var regexFromString = new RegExp(searchString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
return string.replace(regexFromString, replaceValue);
}
//# sourceMappingURL=String.prototype.replaceAll.js.map
;// CONCATENATED MODULE: ./dist/bin/keycloakify/replacers/replaceImportsInJsCode/vite.js
(0,assert/* assert */.h)();
function replaceImportsInJsCode_vite(params) {
const { jsCode, buildContext, basenameOfAssetsFiles, systemType = external_path_.sep === "/" ? "posix" : "win32" } = params;
const { relative: pathRelative, sep: pathSep } = external_path_[systemType];
let fixedJsCode = jsCode;
replace_base_js_import: {
if (buildContext.urlPathname === undefined) {
break replace_base_js_import;
}
// Optimization
if (!jsCode.includes(buildContext.urlPathname)) {
break replace_base_js_import;
}
// Replace `Hv=function(e){return"/abcde12345/"+e}` by `Hv=function(e){return"/"+e}`
fixedJsCode = fixedJsCode.replace(new RegExp(`([\\w\\$][\\w\\d\\$]*)=function\\(([\\w\\$][\\w\\d\\$]*)\\)\\{return"${replaceAll(buildContext.urlPathname, "/", "\\/")}"\\+\\2\\}`, "g"), (...[, funcName, paramName]) => `${funcName}=function(${paramName}){return"/"+${paramName}}`);
}
replace_javascript_relatives_import_paths: {
// Example: "assets/ or "foo/bar/"
const staticDir = (() => {
let out = pathRelative(buildContext.projectBuildDirPath, buildContext.assetsDirPath);
out = replaceAll(out, pathSep, "/") + "/";
if (out === "/") {
throw new Error(`The assetsDirPath must be a subdirectory of projectBuildDirPath`);
}
return out;
})();
// Optimization
if (!jsCode.includes(staticDir)) {
break replace_javascript_relatives_import_paths;
}
basenameOfAssetsFiles
.map(basenameOfAssetsFile => `${staticDir}${basenameOfAssetsFile}`)
.forEach(relativePathOfAssetFile => {
var _a;
fixedJsCode = replaceAll(fixedJsCode, `"${relativePathOfAssetFile}"`, `(window.kcContext["x-keycloakify"].resourcesPath.substring(1) + "/${constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.DIST */.Ju.DIST}/${relativePathOfAssetFile}")`);
fixedJsCode = replaceAll(fixedJsCode, `"${(_a = buildContext.urlPathname) !== null && _a !== void 0 ? _a : "/"}${relativePathOfAssetFile}"`, `(window.kcContext["x-keycloakify"].resourcesPath + "/${constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.DIST */.Ju.DIST}/${relativePathOfAssetFile}")`);
});
}
return { fixedJsCode };
}
//# sourceMappingURL=vite.js.map
;// CONCATENATED MODULE: ./dist/bin/keycloakify/replacers/replaceImportsInJsCode/webpack.js
(0,assert/* assert */.h)();
function replaceImportsInJsCode_webpack(params) {
const { jsCode, buildContext, systemType = external_path_.sep === "/" ? "posix" : "win32" } = params;
const { relative: pathRelative, sep: pathSep } = external_path_[systemType];
let fixedJsCode = jsCode;
if (buildContext.urlPathname !== undefined) {
// "__esModule",{value:!0})},n.p="/foo-bar/",function(){if("undefined" -> ... n.p="/" ...
fixedJsCode = fixedJsCode.replace(new RegExp(`,([a-zA-Z]\\.[a-zA-Z])="${replaceAll(buildContext.urlPathname, "/", "\\/")}",`, "g"), (...[, assignTo]) => `,${assignTo}="/",`);
}
// Example: "static/ or "foo/bar/"
const staticDir = (() => {
let out = pathRelative(buildContext.projectBuildDirPath, buildContext.assetsDirPath);
out = replaceAll(out, pathSep, "/") + "/";
if (out === "/") {
throw new Error(`The assetsDirPath must be a subdirectory of projectBuildDirPath`);
}
return out;
})();
const getReplaceArgs = (language) => [
new RegExp(`([a-zA-Z_]+)\\.([a-zA-Z]+)=(function\\(([a-z]+)\\){return|([a-z]+)=>)"${staticDir.replace(/\//g, "\\/")}${language}\\/"`, "g"),
(...[, n, u, matchedFunction, eForFunction]) => {
const isArrowFunction = matchedFunction.includes("=>");
const e = isArrowFunction
? matchedFunction.replace("=>", "").trim()
: eForFunction;
return `
${n}[(function(){
var pd = Object.getOwnPropertyDescriptor(${n}, "p");
if( pd === undefined || pd.configurable ){
Object.defineProperty(${n}, "p", {
get: function() { return window.kcContext["x-keycloakify"].resourcesPath; },
set: function() {}
});
}
return "${u}";
})()] = ${isArrowFunction ? `${e} =>` : `function(${e}) { return `} "/${constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.DIST */.Ju.DIST}/${staticDir}${language}/"`
.replace(/\s+/g, " ")
.trim();
}
];
fixedJsCode = fixedJsCode
.replace(...getReplaceArgs("js"))
.replace(...getReplaceArgs("css"))
.replace(new RegExp(`[a-zA-Z]+\\.[a-zA-Z]+\\+"${staticDir.replace(/\//g, "\\/")}`, "g"), `window.kcContext["x-keycloakify"].resourcesPath + "/${constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.DIST */.Ju.DIST}/${staticDir}`);
return { fixedJsCode };
}
//# sourceMappingURL=webpack.js.map
;// CONCATENATED MODULE: ./dist/bin/keycloakify/replacers/replaceImportsInJsCode/replaceImportsInJsCode.js
(0,assert/* assert */.h)();
function replaceImportsInJsCode(params) {
const { jsCode, buildContext } = params;
const { fixedJsCode } = (() => {
switch (buildContext.bundler) {
case "vite":
return replaceImportsInJsCode_vite({
jsCode,
buildContext,
basenameOfAssetsFiles: readAssetsDirSync({
assetsDirPath: params.buildContext.assetsDirPath
})
});
case "webpack":
return replaceImportsInJsCode_webpack({
jsCode,
buildContext
});
}
})();
return { fixedJsCode };
}
const { readAssetsDirSync } = (() => {
let cache = undefined;
function readAssetsDirSync(params) {
const { assetsDirPath } = params;
if (cache !== undefined && cache.assetsDirPath === assetsDirPath) {
return cache.basenameOfAssetsFiles;
}
const basenameOfAssetsFiles = external_fs_.readdirSync(assetsDirPath);
cache = {
assetsDirPath,
basenameOfAssetsFiles
};
return basenameOfAssetsFiles;
}
return { readAssetsDirSync };
})();
//# sourceMappingURL=replaceImportsInJsCode.js.map
;// CONCATENATED MODULE: ./dist/bin/keycloakify/replacers/replaceImportsInJsCode/index.js
//# sourceMappingURL=index.js.map
;// CONCATENATED MODULE: ./dist/bin/keycloakify/replacers/replaceImportsInCssCode.js
(0,assert/* assert */.h)();
function replaceImportsInCssCode(params) {
const { cssCode, cssFileRelativeDirPath, buildContext } = params;
let fixedCssCode = cssCode;
[
/url\("(\/[^/][^"]+)"\)/g,
/url\('(\/[^/][^']+)'\)/g,
/url\((\/[^/][^)]+)\)/g
].forEach(regex => (fixedCssCode = fixedCssCode.replace(regex, (match, assetFileAbsoluteUrlPathname) => {
if (buildContext.urlPathname !== undefined) {
if (!assetFileAbsoluteUrlPathname.startsWith(buildContext.urlPathname)) {
// NOTE: Should never happen
return match;
}
assetFileAbsoluteUrlPathname =
assetFileAbsoluteUrlPathname.replace(buildContext.urlPathname, "/");
}
inline_style_in_html: {
if (cssFileRelativeDirPath !== undefined) {
break inline_style_in_html;
}
return `url("\${xKeycloakify.resourcesPath}/${constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.DIST */.Ju.DIST}${assetFileAbsoluteUrlPathname}")`;
}
const assetFileRelativeUrlPathname = external_path_.posix.relative(cssFileRelativeDirPath.replace(/\\/g, "/"), assetFileAbsoluteUrlPathname.replace(/^\//, ""));
return `url("${assetFileRelativeUrlPathname}")`;
})));
return { fixedCssCode };
}
//# sourceMappingURL=replaceImportsInCssCode.js.map
// EXTERNAL MODULE: ./node_modules/cheerio/lib/esm/index.js + 76 modules
var esm = __webpack_require__(87182);
// EXTERNAL MODULE: ./dist/bin/tools/getThisCodebaseRootDirPath.js
var getThisCodebaseRootDirPath = __webpack_require__(58822);
;// CONCATENATED MODULE: ./dist/bin/keycloakify/generateFtl/generateFtl.js
(0,assert/* assert */.h)();
function generateFtlFilesCodeFactory(params) {
var _a;
const { themeName, indexHtmlCode, buildContext, keycloakifyVersion, themeType, fieldNames } = params;
const $ = esm/* load */.zD(indexHtmlCode);
fix_imports_statements: {
$("script:not([src])").each((...[, element]) => {
const jsCode = $(element).html();
(0,assert/* assert */.h)(jsCode !== null);
const { fixedJsCode } = replaceImportsInJsCode({
jsCode,
buildContext
});
$(element).text(fixedJsCode);
});
$("style").each((...[, element]) => {
const cssCode = $(element).html();
(0,assert/* assert */.h)(cssCode !== null);
const { fixedCssCode } = replaceImportsInCssCode({
cssCode,
cssFileRelativeDirPath: undefined,
buildContext
});
$(element).text(fixedCssCode);
});
[
["link", "href"],
["script", "src"],
["script", "data-src"]
].forEach(([selector, attrName]) => $(selector).each((...[, element]) => {
var _a;
const href = $(element).attr(attrName);
if (href === undefined) {
return;
}
$(element).attr(attrName, href.replace(new RegExp(`^${((_a = buildContext.urlPathname) !== null && _a !== void 0 ? _a : "/").replace(/\//g, "\\/")}`), `\${xKeycloakify.resourcesPath}/${constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.DIST */.Ju.DIST}/`));
}));
}
$("head base").remove();
//FTL is no valid html, we can't insert with cheerio, we put placeholder for injecting later.
const kcContextDeclarationTemplateFtl = external_fs_.readFileSync((0,external_path_.join)((0,getThisCodebaseRootDirPath/* getThisCodebaseRootDirPath */.e)(), "src", "bin", "keycloakify", "generateFtl", "kcContextDeclarationTemplate.ftl"))
.toString("utf8")
.replace("{{themeType}}", themeType)
.replace("{{themeName}}", themeName)
.replace("{{keycloakifyVersion}}", keycloakifyVersion)
.replace("{{themeVersion}}", buildContext.themeVersion)
.replace("{{fieldNames}}", fieldNames.map(name => `"${name}"`).join(", "))
.replace("{{RESOURCES_COMMON}}", constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.RESOURCES_COMMON */.Ju.RESOURCES_COMMON)
.replace("{{KEYCLOAKIFY_SPA_DEV_SERVER_PORT}}", constants/* KEYCLOAKIFY_SPA_DEV_SERVER_PORT */.Sz)
.replace("{{userDefinedExclusions}}", (_a = buildContext.kcContextExclusionsFtlCode) !== null && _a !== void 0 ? _a : "");
const ftlObjectToJsCodeDeclaringAnObjectPlaceholder = '{ "x": "vIdLqMeOed9sdLdIdOxdK0d" }';
$("head").prepend([
`<script>\n${ftlObjectToJsCodeDeclaringAnObjectPlaceholder}\n</script>`,
`<base href="\${xKeycloakify.resourcesPath}/${constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.DIST */.Ju.DIST}/" />`
].join("\n"));
// Remove part of the document marked as ignored.
{
const startTags = $('meta[name="keycloakify-ignore-start"]');
startTags.each((...[, startTag]) => {
const $startTag = $(startTag);
const $endTag = $startTag
.nextAll('meta[name="keycloakify-ignore-end"]')
.first();
if ($endTag.length) {
let currentNode = $startTag.next();
while (currentNode.length && !currentNode.is($endTag)) {
currentNode.remove();
currentNode = $startTag.next();
}
$startTag.remove();
$endTag.remove();
}
});
}
const partiallyFixedIndexHtmlCode = $.html();
function generateFtlFilesCode(params) {
const { pageId } = params;
const $ = esm/* load */.zD(partiallyFixedIndexHtmlCode);
let ftlCode = $.html();
Object.entries({
[ftlObjectToJsCodeDeclaringAnObjectPlaceholder]: kcContextDeclarationTemplateFtl,
"{{pageId}}": pageId,
"{{ftlTemplateFileName}}": pageId
}).map(([searchValue, replaceValue]) => (ftlCode = ftlCode.replace(searchValue, replaceValue)));
return { ftlCode };
}
return { generateFtlFilesCode };
}
//# sourceMappingURL=generateFtl.js.map
;// CONCATENATED MODULE: ./dist/bin/keycloakify/generateFtl/index.js
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: ./dist/bin/tools/crawl.js
var crawl = __webpack_require__(73036);
;// CONCATENATED MODULE: ./dist/bin/keycloakify/generateResources/readFieldNameUsage.js
/** Assumes the theme type exists */
function readFieldNameUsage(params) {
const { themeSrcDirPath, themeType } = params;
// NOTE: We pre-populate with the synthetic user attributes defined in useUserProfileForm (can't be parsed automatically)
const fieldNames = new Set([
"firstName",
"lastName",
"email",
"username",
"password",
"password-confirm"
]);
for (const srcDirPath of [
(0,external_path_.join)((0,getThisCodebaseRootDirPath/* getThisCodebaseRootDirPath */.e)(), "src", themeType),
(0,external_path_.join)(themeSrcDirPath, themeType)
]) {
const filePaths = (0,crawl/* crawl */.J)({
dirPath: srcDirPath,
returnedPathsType: "absolute"
}).filter(filePath => /\.(ts|tsx|js|jsx)$/.test(filePath));
for (const filePath of filePaths) {
const rawSourceFile = external_fs_.readFileSync(filePath).toString("utf8");
if (!rawSourceFile.includes("messagesPerField")) {
continue;
}
for (const functionName of [
"printIfExists",
"existsError",
"get",
"exists",
"getFirstError"
]) {
if (!rawSourceFile.includes(functionName)) {
continue;
}
try {
rawSourceFile
.split(functionName)
.filter(part => part.startsWith("("))
.map(part => {
let [p1] = part.split(")");
p1 = p1.slice(1);
return p1;
})
.map(part => {
return part
.split(",")
.map(a => a.trim())
.filter((...[, i]) => functionName !== "printIfExists" ? true : i === 0)
.filter(a => a.startsWith('"') ||
a.startsWith("'") ||
a.startsWith("`"))
.filter(a => a.endsWith('"') ||
a.endsWith("'") ||
a.endsWith("`"))
.map(a => a.slice(1).slice(0, -1));
})
.flat()
.forEach(fieldName => fieldNames.add(fieldName));
}
catch (_a) { }
}
}
}
return Array.from(fieldNames);
}
//# sourceMappingURL=readFieldNameUsage.js.map
// EXTERNAL MODULE: ./node_modules/tsafe/esm/id.mjs
var id = __webpack_require__(38469);
// EXTERNAL MODULE: ./node_modules/evt/tools/reducers/removeDuplicates.js
var removeDuplicates = __webpack_require__(78300);
;// CONCATENATED MODULE: ./dist/bin/keycloakify/generateResources/readExtraPageNames.js
function readExtraPagesNames(params) {
const { themeSrcDirPath, themeType } = params;
const filePaths = (0,crawl/* crawl */.J)({
dirPath: (0,external_path_.join)(themeSrcDirPath, themeType),
returnedPathsType: "absolute"
}).filter(filePath => /\.(ts|tsx|js|jsx)$/.test(filePath));
const candidateFilePaths = filePaths.filter(filePath => /[kK]cContext\.[^.]+$/.test(filePath));
if (candidateFilePaths.length === 0) {
candidateFilePaths.push(...filePaths);
}
const extraPages = [];
for (const candidateFilPath of candidateFilePaths) {
const rawSourceFile = external_fs_.readFileSync(candidateFilPath).toString("utf8");
extraPages.push(...Array.from(rawSourceFile.matchAll(/["']([^.\s]+.ftl)["']:/g), m => m[1]));
}
return extraPages.reduce(...(0,removeDuplicates.removeDuplicates)()).filter(pageId => {
switch (themeType) {
case "account":
return !(0,id.id)(constants/* ACCOUNT_THEME_PAGE_IDS */.yV).includes(pageId);
case "login":
return !(0,id.id)(constants/* LOGIN_THEME_PAGE_IDS */.XV).includes(pageId);
}
});
}
//# sourceMappingURL=readExtraPageNames.js.map
// EXTERNAL MODULE: ./dist/bin/keycloakify/generateResources/generateMessageProperties.js
var generateMessageProperties = __webpack_require__(73817);
// EXTERNAL MODULE: ./dist/bin/tools/readThisNpmPackageVersion.js
var readThisNpmPackageVersion = __webpack_require__(64795);
// EXTERNAL MODULE: ./dist/bin/tools/escapeStringForPropertiesFile.js
var escapeStringForPropertiesFile = __webpack_require__(27190);
// EXTERNAL MODULE: ./node_modules/properties-parser/index.js
var properties_parser = __webpack_require__(44414);
var properties_parser_default = /*#__PURE__*/__webpack_require__.n(properties_parser);
;// CONCATENATED MODULE: ./dist/bin/tools/createObjectThatThrowsIfAccessed.js
const keyIsTrapped = "isTrapped_zSskDe9d";
class AccessError extends Error {
constructor(message) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
}
}
function createObjectThatThrowsIfAccessed(params) {
const { debugMessage = "", isPropertyWhitelisted = () => false } = params !== null && params !== void 0 ? params : {};
const get = (...args) => {
const [, prop] = args;
if (isPropertyWhitelisted(prop)) {
return Reflect.get(...args);
}
if (prop === keyIsTrapped) {
return true;
}
throw new AccessError(`Cannot access ${String(prop)} yet ${debugMessage}`);
};
const trappedObject = new Proxy({}, {
get,
set: get
});
return trappedObject;
}
function createObjectThatThrowsIfAccessedFactory(params) {
const { isPropertyWhitelisted } = params;
return {
createObjectThatThrowsIfAccessed: (params) => {
const { debugMessage } = params !== null && params !== void 0 ? params : {};
return createObjectThatThrowsIfAccessed({
debugMessage,
isPropertyWhitelisted
});
}
};
}
function isObjectThatThrowIfAccessed(obj) {
return obj[keyIsTrapped] === true;
}
const THROW_IF_ACCESSED = {
__brand: "THROW_IF_ACCESSED"
};
function createObjectWithSomePropertiesThatThrowIfAccessed(obj, debugMessage) {
return Object.defineProperties(obj, Object.fromEntries(Object.entries(obj)
.filter(([, value]) => value === THROW_IF_ACCESSED)
.map(([key]) => {
const getAndSet = () => {
throw new AccessError(`Cannot access ${key} yet ${debugMessage !== null && debugMessage !== void 0 ? debugMessage : ""}`);
};
const pd = {
get: getAndSet,
set: getAndSet,
enumerable: true
};
return [key, pd];
})));
}
//# sourceMappingURL=createObjectThatThrowsIfAccessed.js.map
// EXTERNAL MODULE: ./dist/bin/tools/listInstalledModules.js
var listInstalledModules = __webpack_require__(75564);
// EXTERNAL MODULE: ./dist/bin/tools/isInside.js
var isInside = __webpack_require__(90665);
;// CONCATENATED MODULE: ./dist/bin/keycloakify/generateResources/generateResources.js
(0,assert/* assert */.h)();
async function generateResources(params) {
var _a;
const start = Date.now();
const { resourcesDirPath, buildContext } = params;
const [themeName] = buildContext.themeNames;
if (external_fs_default().existsSync(resourcesDirPath)) {
(0,fs_rmSync/* rmSync */.a)(resourcesDirPath, { recursive: true });
}
const getThemeTypeDirPath = (params) => {
const { themeType, themeName } = params;
return (0,external_path_.join)(resourcesDirPath, "theme", themeName, themeType);
};
const writeMessagePropertiesFilesByThemeType = {};
for (const themeType of [...constants/* THEME_TYPES */.Jh, "email"]) {
let isNative;
{
const v = buildContext.implementedThemeTypes[themeType];
if (!v.isImplemented && !v.isImplemented_native) {
continue;
}
isNative = !v.isImplemented && v.isImplemented_native;
}
const getAccountThemeType = () => {
(0,assert/* assert */.h)(themeType === "account");
(0,assert/* assert */.h)(buildContext.implementedThemeTypes.account.isImplemented);
return buildContext.implementedThemeTypes.account.type;
};
const isSpa = (() => {
switch (themeType) {
case "login":
return false;
case "account":
return getAccountThemeType() === "Single-Page";
case "admin":
return true;
case "email":
return false;
}
})();
const themeTypeDirPath = getThemeTypeDirPath({ themeName, themeType });
apply_replacers_and_move_to_theme_resources: {
if (isNative) {
break apply_replacers_and_move_to_theme_resources;
}
const destDirPath = (0,external_path_.join)(themeTypeDirPath, "resources", constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.DIST */.Ju.DIST);
// NOTE: Prevent accumulation of files in the assets dir, as names are hashed they pile up.
(0,fs_rmSync/* rmSync */.a)(destDirPath, { recursive: true, force: true });
if (themeType !== "login" &&
buildContext.implementedThemeTypes.login.isImplemented) {
// NOTE: We prevent doing it twice, it has been done for the login theme.
(0,transformCodebase/* transformCodebase */.N)({
srcDirPath: (0,external_path_.join)(getThemeTypeDirPath({
themeName,
themeType: "login"
}), "resources", constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.DIST */.Ju.DIST),
destDirPath
});
break apply_replacers_and_move_to_theme_resources;
}
for (const directoryBasename of [
constants/* KEYCLOAK_THEME */.PC,
// NOTE: This is legacy and should eventually be removed
constants/* WELL_KNOWN_DIRECTORY_BASE_NAME.KEYCLOAKIFY_DEV_RESOURCES */.Ju.KEYCLOAKIFY_DEV_RESOURCES
]) {
const dirPath = (0,external_path_.join)(buildContext.projectBuildDirPath, directoryBasename);
if (external_fs_default().existsSync(dirPath)) {
(0,assert/* assert */.h)(buildContext.bundler === "webpack");
throw new Error([
`Keycloakify build error: The ${directoryBasename} directory shouldn't exist in your build directory.`,
`(${(0,external_path_.relative)(process.cwd(), dirPath)}).\n`,
`Theses assets are only required for local development with Storybook.",
"Please remove this directory as an additional step of your command.\n`,
`For example: \`"build": "... && rimraf ${(0,external_path_.relative)(buildContext.projectDirPath, dirPath)}"\``
].join(" "));
}
}
(0,transformCodebase/* transformCodebase */.N)({
srcDirPath: buildContext.projectBuildDirPath,
destDirPath,
transformSourceCode: ({ filePath, fileRelativePath, sourceCode }) => {
if (filePath.endsWith(".css")) {
const { fixedCssCode } = replaceImportsInCssCode({
cssCode: sourceCode.toString("utf8"),
cssFileRelativeDirPath: (0,external_path_.dirname)(fileRelativePath),
buildContext
});
return {
modifiedSourceCode: Buffer.from(fixedCssCode, "utf8")
};
}
if (filePath.endsWith(".js")) {
const { fixedJsCode } = replaceImportsInJsCode({
jsCode: sourceCode.toString("utf8"),
buildContext
});
return {
modifiedSourceCode: Buffer.from(fixedJsCode, "utf8")
};
}
return { modifiedSourceCode: sourceCode };
}
});
}
generate_ftl_files: {
if (isNative) {
break generate_ftl_files;
}
(0,assert/* assert */.h)(themeType !== "email");
const { generateFtlFilesCode } = generateFtlFilesCodeFactory({
themeName,
indexHtmlCode: external_fs_default().readFileSync((0,external_path_.join)(buildContext.projectBuildDirPath, "index.html"))
.toString("utf8"),
buildContext,
keycloakifyVersion: (0,readThisNpmPackageVersion/* readThisNpmPackageVersion */.K)(),
themeType,
fieldNames: isSpa
? []
: ((0,assert/* assert */.h)(themeType !== "admin"),
readFieldNameUsage({
themeSrcDirPath: buildContext.themeSrcDirPath,
themeType
}))
});
[
...(() => {
switch (themeType) {
case "login":
return constants/* LOGIN_THEME_PAGE_IDS */.XV;
case "account":
return getAccountThemeType() === "Single-Page"
? ["index.ftl"]
: constants/* ACCOUNT_THEME_PAGE_IDS */.yV;
case "admin":
return ["index.ftl"];
}
})(),
...(isSpa
? []
: readExtraPagesNames({
themeType,
themeSrcDirPath: buildContext.themeSrcDirPath
}))
].forEach(pageId => {
const { ftlCode } = generateFtlFilesCode({ pageId });
external_fs_default().writeFileSync((0,external_path_.join)(themeTypeDirPath, pageId), Buffer.from(ftlCode, "utf8"));
});
}
copy_native_theme: {
if (!isNative) {
break copy_native_theme;
}
const dirPath = (0,external_path_.join)(buildContext.themeSrcDirPath, themeType);
(0,transformCodebase/* transformCodebase */.N)({
srcDirPath: dirPath,
destDirPath: getThemeTypeDirPath({ themeName, themeType }),
transformSourceCode: ({ fileRelativePath, sourceCode }) => {
if ((0,isInside/* isInside */.V)({ dirPath: "messages", filePath: fileRelativePath })) {
return undefined;
}
return { modifiedSourceCode: sourceCode };
}
});
}
let languageTags = undefined;
i18n_multi_page: {
if (isNative) {
break i18n_multi_page;
}
if (isSpa) {
break i18n_multi_page;
}
(0,assert/* assert */.h)(themeType !== "admin" && themeType !== "email");
const wrap = (0,generateMessageProperties/* generateMessageProperties */.k)({
buildContext,
themeType
});
languageTags = wrap.languageTags;
const { writeMessagePropertiesFiles } = wrap;
writeMessagePropertiesFilesByThemeType[themeType] =
writeMessagePropertiesFiles;
}
let isLegacyAccountSpa = false;
// NOTE: Eventually remove this block.
i18n_single_page_account_legacy: {
if (!isSpa) {
break i18n_single_page_account_legacy;
}
if (themeType !== "account") {
break i18n_single_page_account_legacy;
}
const [moduleMeta] = await (0,listInstalledModules/* listInstalledModules */.P)({
packageJsonFilePath: buildContext.packageJsonFilePath,
filter: ({ moduleName }) => moduleName === "@keycloakify/keycloak-account-ui"
});
(0,assert/* assert */.h)(moduleMeta !== undefined, `@keycloakify/keycloak-account-ui is supposed to be installed`);
{