Settle on calling the global 'kcContext' and reduce levels of indirections

This commit is contained in:
Joseph Garrone 2024-06-14 22:24:51 +02:00
parent d04724c70a
commit f1475e5cdf
9 changed files with 55 additions and 75 deletions

View File

@ -1,7 +1,4 @@
import { import { basenameOfTheKeycloakifyResourcesDir } from "keycloakify/bin/shared/constants";
nameOfTheGlobal,
basenameOfTheKeycloakifyResourcesDir
} from "keycloakify/bin/shared/constants";
import { assert } from "tsafe/assert"; import { assert } from "tsafe/assert";
/** /**
@ -9,7 +6,7 @@ import { assert } from "tsafe/assert";
* This works both in your main app and in your Keycloak theme. * This works both in your main app and in your Keycloak theme.
*/ */
export const PUBLIC_URL = (() => { export const PUBLIC_URL = (() => {
const kcContext = (window as any)[nameOfTheGlobal]; const kcContext = (window as any).kcContext;
if (kcContext === undefined || process.env.NODE_ENV === "development") { if (kcContext === undefined || process.env.NODE_ENV === "development") {
assert( assert(

View File

@ -168,8 +168,8 @@ export async function buildJar(params: {
})(); })();
const modifiedFtlFileContent = ftlFileContent.replace( const modifiedFtlFileContent = ftlFileContent.replace(
`out.pageId = "\${pageId}";`, `kcContext.pageId = "\${pageId}";`,
`out.pageId = "${pageId}"; out.realPageId = "${realPageId}";` `kcContext.pageId = "${pageId}"; kcContext.realPageId = "${realPageId}";`
); );
assert(modifiedFtlFileContent !== ftlFileContent); assert(modifiedFtlFileContent !== ftlFileContent);

View File

@ -8,7 +8,6 @@ import type { BuildContext } from "../../shared/buildContext";
import { assert } from "tsafe/assert"; import { assert } from "tsafe/assert";
import { import {
type ThemeType, type ThemeType,
nameOfTheGlobal,
basenameOfTheKeycloakifyResourcesDir, basenameOfTheKeycloakifyResourcesDir,
resources_common, resources_common,
nameOfTheLocalizationRealmOverridesUserProfileProperty nameOfTheLocalizationRealmOverridesUserProfileProperty
@ -116,7 +115,7 @@ export function generateFtlFilesCodeFactory(params: {
} }
//FTL is no valid html, we can't insert with cheerio, we put placeholder for injecting later. //FTL is no valid html, we can't insert with cheerio, we put placeholder for injecting later.
const ftlObjectToJsCodeDeclaringAnObject = fs const kcContextDeclarationTemplateFtl = fs
.readFileSync( .readFileSync(
pathJoin( pathJoin(
getThisCodebaseRootDirPath(), getThisCodebaseRootDirPath(),
@ -124,11 +123,10 @@ export function generateFtlFilesCodeFactory(params: {
"bin", "bin",
"keycloakify", "keycloakify",
"generateFtl", "generateFtl",
"ftl_object_to_js_code_declaring_an_object.ftl" "kcContextDeclarationTemplate.ftl"
) )
) )
.toString("utf8") .toString("utf8")
.match(/^<script>const _=((?:.|\n)+)<\/script>[\n]?$/)![1]
.replace( .replace(
"FIELD_NAMES_eKsIY4ZsZ4xeM", "FIELD_NAMES_eKsIY4ZsZ4xeM",
fieldNames.map(name => `"${name}"`).join(", ") fieldNames.map(name => `"${name}"`).join(", ")
@ -150,7 +148,7 @@ export function generateFtlFilesCodeFactory(params: {
'{ "x": "vIdLqMeOed9sdLdIdOxdK0d" }'; '{ "x": "vIdLqMeOed9sdLdIdOxdK0d" }';
$("head").prepend( $("head").prepend(
`<script>\nwindow.${nameOfTheGlobal}=${ftlObjectToJsCodeDeclaringAnObjectPlaceholder}</script>` `<script>\n${ftlObjectToJsCodeDeclaringAnObjectPlaceholder}\n</script>`
); );
// Remove part of the document marked as ignored. // Remove part of the document marked as ignored.
@ -189,7 +187,7 @@ export function generateFtlFilesCodeFactory(params: {
Object.entries({ Object.entries({
[ftlObjectToJsCodeDeclaringAnObjectPlaceholder]: [ftlObjectToJsCodeDeclaringAnObjectPlaceholder]:
ftlObjectToJsCodeDeclaringAnObject, kcContextDeclarationTemplateFtl,
PAGE_ID_xIgLsPgGId9D8e: pageId PAGE_ID_xIgLsPgGId9D8e: pageId
}).map( }).map(
([searchValue, replaceValue]) => ([searchValue, replaceValue]) =>

View File

@ -1,10 +1,8 @@
<script>const _=
(()=>{
<#assign pageId="PAGE_ID_xIgLsPgGId9D8e"> <#assign pageId="PAGE_ID_xIgLsPgGId9D8e">
const out = ${ftl_object_to_js_code_declaring_an_object(.data_model, [])?no_esc}; const kcContext = ${ftl_object_to_js_code_declaring_an_object(.data_model, [])?no_esc};
if( out.messagesPerField ){ if( kcContext.messagesPerField ){
var existsError_singleFieldName = out.messagesPerField.existsError; var existsError_singleFieldName = kcContext.messagesPerField.existsError;
out.messagesPerField.existsError = function (){ kcContext.messagesPerField.existsError = function (){
for( let i = 0; i < arguments.length; i++ ){ for( let i = 0; i < arguments.length; i++ ){
if( existsError_singleFieldName(arguments[i]) ){ if( existsError_singleFieldName(arguments[i]) ){
return true; return true;
@ -12,31 +10,31 @@ if( out.messagesPerField ){
} }
return false; return false;
}; };
out.messagesPerField.exists = function (fieldName) { kcContext.messagesPerField.exists = function (fieldName) {
return out.messagesPerField.get(fieldName) !== ""; return kcContext.messagesPerField.get(fieldName) !== "";
}; };
out.messagesPerField.printIfExists = function (fieldName, text) { kcContext.messagesPerField.printIfExists = function (fieldName, text) {
return out.messagesPerField.exists(fieldName) ? text : undefined; return kcContext.messagesPerField.exists(fieldName) ? text : undefined;
}; };
out.messagesPerField.getFirstError = function () { kcContext.messagesPerField.getFirstError = function () {
for( let i = 0; i < arguments.length; i++ ){ for( let i = 0; i < arguments.length; i++ ){
const fieldName = arguments[i]; const fieldName = arguments[i];
if( out.messagesPerField.existsError(fieldName) ){ if( kcContext.messagesPerField.existsError(fieldName) ){
return out.messagesPerField.get(fieldName); return kcContext.messagesPerField.get(fieldName);
} }
} }
}; };
} }
out.keycloakifyVersion = "KEYCLOAKIFY_VERSION_xEdKd3xEdr"; kcContext.keycloakifyVersion = "KEYCLOAKIFY_VERSION_xEdKd3xEdr";
out.themeVersion = "KEYCLOAKIFY_THEME_VERSION_sIgKd3xEdr3dx"; kcContext.themeVersion = "KEYCLOAKIFY_THEME_VERSION_sIgKd3xEdr3dx";
out.themeType = "KEYCLOAKIFY_THEME_TYPE_dExKd3xEdr"; kcContext.themeType = "KEYCLOAKIFY_THEME_TYPE_dExKd3xEdr";
out.themeName = "KEYCLOAKIFY_THEME_NAME_cXxKd3xEer"; kcContext.themeName = "KEYCLOAKIFY_THEME_NAME_cXxKd3xEer";
out.pageId = "${pageId}"; kcContext.pageId = "${pageId}";
if( out.url && out.url.resourcesPath ){ if( kcContext.url && kcContext.url.resourcesPath ){
out.url.resourcesCommonPath = out.url.resourcesPath + "/" + "RESOURCES_COMMON_cLsLsMrtDkpVv"; kcContext.url.resourcesCommonPath = kcContext.url.resourcesPath + "/" + "RESOURCES_COMMON_cLsLsMrtDkpVv";
} }
<#if profile?? && profile.attributes??> <#if profile?? && profile.attributes??>
out.lOCALIZATION_REALM_OVERRIDES_USER_PROFILE_PROPERTY_KEY_aaGLsPgGIdeeX = { kcContext.lOCALIZATION_REALM_OVERRIDES_USER_PROFILE_PROPERTY_KEY_aaGLsPgGIdeeX = {
<#list profile.attributes as attribute> <#list profile.attributes as attribute>
<#if attribute.annotations?? && attribute.displayName??> <#if attribute.annotations?? && attribute.displayName??>
"${attribute.displayName}": decodeHtmlEntities("${advancedMsg(attribute.displayName)?js_string}"), "${attribute.displayName}": decodeHtmlEntities("${advancedMsg(attribute.displayName)?js_string}"),
@ -64,21 +62,20 @@ if( out.url && out.url.resourcesPath ){
}; };
</#if> </#if>
attributes_to_attributesByName: { attributes_to_attributesByName: {
if( !out.profile ){ if( !kcContext.profile ){
break attributes_to_attributesByName; break attributes_to_attributesByName;
} }
if( !out.profile.attributes ){ if( !kcContext.profile.attributes ){
break attributes_to_attributesByName; break attributes_to_attributesByName;
} }
var attributes = out.profile.attributes; var attributes = kcContext.profile.attributes;
delete out.profile.attributes; delete kcContext.profile.attributes;
out.profile.attributesByName = {}; kcContext.profile.attributesByName = {};
attributes.forEach(function(attribute){ attributes.forEach(function(attribute){
out.profile.attributesByName[attribute.name] = attribute; kcContext.profile.attributesByName[attribute.name] = attribute;
}); });
} }
return out; window.kcContext = kcContext;
function decodeHtmlEntities(htmlStr){ function decodeHtmlEntities(htmlStr){
var element = decodeHtmlEntities.element; var element = decodeHtmlEntities.element;
if (!element) { if (!element) {
@ -88,7 +85,7 @@ function decodeHtmlEntities(htmlStr){
element.innerHTML = htmlStr; element.innerHTML = htmlStr;
return element.value; return element.value;
} }
})();
<#function ftl_object_to_js_code_declaring_an_object object path> <#function ftl_object_to_js_code_declaring_an_object object path>
<#local isHash = ""> <#local isHash = "">
@ -341,7 +338,7 @@ function decodeHtmlEntities(htmlStr){
<#local jsFunctionCode += "if(fieldName === 'username' || fieldName === 'password' ){ "> <#local jsFunctionCode += "if(fieldName === 'username' || fieldName === 'password' ){ ">
<#if messagesPerField.exists('username') || messagesPerField.exists('password')> <#if messagesPerField.exists('username') || messagesPerField.exists('password')>
<#local jsFunctionCode += "return out.message && out.message.summary ? out.message.summary : 'error'; "> <#local jsFunctionCode += "return kcContext.message && kcContext.message.summary ? kcContext.message.summary : 'error'; ">
<#else> <#else>
<#local jsFunctionCode += "return ''; "> <#local jsFunctionCode += "return ''; ">
</#if> </#if>
@ -552,4 +549,3 @@ function decodeHtmlEntities(htmlStr){
<#function are_same_path path searchedPath> <#function are_same_path path searchedPath>
<#return path?size == searchedPath?size && is_subpath(path, searchedPath)> <#return path?size == searchedPath?size && is_subpath(path, searchedPath)>
</#function> </#function>
</script>

View File

@ -1,7 +1,4 @@
import { import { basenameOfTheKeycloakifyResourcesDir } from "../../../shared/constants";
nameOfTheGlobal,
basenameOfTheKeycloakifyResourcesDir
} from "../../../shared/constants";
import { assert } from "tsafe/assert"; import { assert } from "tsafe/assert";
import type { BuildContext } from "../../../shared/buildContext"; import type { BuildContext } from "../../../shared/buildContext";
import * as nodePath from "path"; import * as nodePath from "path";
@ -88,13 +85,13 @@ export function replaceImportsInJsCode_vite(params: {
fixedJsCode = replaceAll( fixedJsCode = replaceAll(
fixedJsCode, fixedJsCode,
`"${relativePathOfAssetFile}"`, `"${relativePathOfAssetFile}"`,
`(window.${nameOfTheGlobal}.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/${relativePathOfAssetFile}")` `(window.kcContext.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/${relativePathOfAssetFile}")`
); );
fixedJsCode = replaceAll( fixedJsCode = replaceAll(
fixedJsCode, fixedJsCode,
`"${buildContext.urlPathname ?? "/"}${relativePathOfAssetFile}"`, `"${buildContext.urlPathname ?? "/"}${relativePathOfAssetFile}"`,
`(window.${nameOfTheGlobal}.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/${relativePathOfAssetFile}")` `(window.kcContext.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/${relativePathOfAssetFile}")`
); );
}); });
} }

View File

@ -1,7 +1,4 @@
import { import { basenameOfTheKeycloakifyResourcesDir } from "../../../shared/constants";
nameOfTheGlobal,
basenameOfTheKeycloakifyResourcesDir
} from "../../../shared/constants";
import { assert } from "tsafe/assert"; import { assert } from "tsafe/assert";
import type { BuildContext } from "../../../shared/buildContext"; import type { BuildContext } from "../../../shared/buildContext";
import * as nodePath from "path"; import * as nodePath from "path";
@ -86,7 +83,7 @@ export function replaceImportsInJsCode_webpack(params: {
var pd = Object.getOwnPropertyDescriptor(${n}, "p"); var pd = Object.getOwnPropertyDescriptor(${n}, "p");
if( pd === undefined || pd.configurable ){ if( pd === undefined || pd.configurable ){
Object.defineProperty(${n}, "p", { Object.defineProperty(${n}, "p", {
get: function() { return window.${nameOfTheGlobal}.url.resourcesPath; }, get: function() { return window.kcContext.url.resourcesPath; },
set: function() {} set: function() {}
}); });
} }
@ -107,7 +104,7 @@ export function replaceImportsInJsCode_webpack(params: {
`[a-zA-Z]+\\.[a-zA-Z]+\\+"${staticDir.replace(/\//g, "\\/")}`, `[a-zA-Z]+\\.[a-zA-Z]+\\+"${staticDir.replace(/\//g, "\\/")}`,
"g" "g"
), ),
`window.${nameOfTheGlobal}.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/${staticDir}` `window.kcContext.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/${staticDir}`
); );
return { fixedJsCode }; return { fixedJsCode };

View File

@ -1,4 +1,3 @@
export const nameOfTheGlobal = "kcContext";
export const nameOfTheLocalizationRealmOverridesUserProfileProperty = export const nameOfTheLocalizationRealmOverridesUserProfileProperty =
"__localizationRealmOverridesUserProfile"; "__localizationRealmOverridesUserProfile";
export const keycloak_resources = "keycloak-resources"; export const keycloak_resources = "keycloak-resources";

View File

@ -1,7 +1,6 @@
import { join as pathJoin, relative as pathRelative, sep as pathSep } from "path"; import { join as pathJoin, relative as pathRelative, sep as pathSep } from "path";
import type { Plugin } from "vite"; import type { Plugin } from "vite";
import { import {
nameOfTheGlobal,
basenameOfTheKeycloakifyResourcesDir, basenameOfTheKeycloakifyResourcesDir,
keycloak_resources, keycloak_resources,
vitePluginSubScriptEnvNames vitePluginSubScriptEnvNames
@ -170,9 +169,9 @@ export function keycloakify(params?: Params) {
/import\.meta\.env(?:(?:\.BASE_URL)|(?:\["BASE_URL"\]))/g, /import\.meta\.env(?:(?:\.BASE_URL)|(?:\["BASE_URL"\]))/g,
[ [
`(`, `(`,
`(window.${nameOfTheGlobal} === undefined || import.meta.env.MODE === "development")?`, `(window.kcContext === undefined || import.meta.env.MODE === "development")?`,
`"${urlPathname ?? "/"}":`, `"${urlPathname ?? "/"}":`,
`(window.${nameOfTheGlobal}.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/")`, `(window.kcContext.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/")`,
`)` `)`
].join("") ].join("")
); );

View File

@ -7,10 +7,7 @@ import {
import { replaceImportsInInlineCssCode } from "keycloakify/bin/keycloakify/replacers/replaceImportsInInlineCssCode"; import { replaceImportsInInlineCssCode } from "keycloakify/bin/keycloakify/replacers/replaceImportsInInlineCssCode";
import { same } from "evt/tools/inDepth/same"; import { same } from "evt/tools/inDepth/same";
import { expect, it, describe } from "vitest"; import { expect, it, describe } from "vitest";
import { import { basenameOfTheKeycloakifyResourcesDir } from "keycloakify/bin/shared/constants";
basenameOfTheKeycloakifyResourcesDir,
nameOfTheGlobal
} from "keycloakify/bin/shared/constants";
describe("js replacer - vite", () => { describe("js replacer - vite", () => {
it("replaceImportsInJsCode_vite - 1", () => { it("replaceImportsInJsCode_vite - 1", () => {
@ -95,13 +92,13 @@ describe("js replacer - vite", () => {
}); });
const fixedJsCodeExpected = ` const fixedJsCodeExpected = `
S=(window.${nameOfTheGlobal}.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/assets/keycloakify-logo-mqjydaoZ.png"),H=(()=>{ S=(window.kcContext.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/assets/keycloakify-logo-mqjydaoZ.png"),H=(()=>{
function __vite__mapDeps(indexes) { function __vite__mapDeps(indexes) {
if (!__vite__mapDeps.viteFileDeps) { if (!__vite__mapDeps.viteFileDeps) {
__vite__mapDeps.viteFileDeps = [ __vite__mapDeps.viteFileDeps = [
(window.${nameOfTheGlobal}.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/assets/Login-dJpPRzM4.js"), (window.kcContext.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/assets/Login-dJpPRzM4.js"),
(window.${nameOfTheGlobal}.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/assets/index-XwzrZ5Gu.js") (window.kcContext.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/assets/index-XwzrZ5Gu.js")
] ]
} }
return indexes.map((i) => __vite__mapDeps.viteFileDeps[i]) return indexes.map((i) => __vite__mapDeps.viteFileDeps[i])
@ -154,13 +151,13 @@ describe("js replacer - vite", () => {
}); });
const fixedJsCodeExpected = ` const fixedJsCodeExpected = `
S=(window.${nameOfTheGlobal}.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/foo/bar/keycloakify-logo-mqjydaoZ.png"),H=(()=>{ S=(window.kcContext.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/foo/bar/keycloakify-logo-mqjydaoZ.png"),H=(()=>{
function __vite__mapDeps(indexes) { function __vite__mapDeps(indexes) {
if (!__vite__mapDeps.viteFileDeps) { if (!__vite__mapDeps.viteFileDeps) {
__vite__mapDeps.viteFileDeps = [ __vite__mapDeps.viteFileDeps = [
(window.${nameOfTheGlobal}.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/foo/bar/Login-dJpPRzM4.js"), (window.kcContext.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/foo/bar/Login-dJpPRzM4.js"),
(window.${nameOfTheGlobal}.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/foo/bar/index-XwzrZ5Gu.js") (window.kcContext.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/foo/bar/index-XwzrZ5Gu.js")
] ]
} }
return indexes.map((i) => __vite__mapDeps.viteFileDeps[i]) return indexes.map((i) => __vite__mapDeps.viteFileDeps[i])
@ -213,13 +210,13 @@ describe("js replacer - vite", () => {
}); });
const fixedJsCodeExpected = ` const fixedJsCodeExpected = `
S=(window.${nameOfTheGlobal}.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/assets/keycloakify-logo-mqjydaoZ.png"),H=(()=>{ S=(window.kcContext.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/assets/keycloakify-logo-mqjydaoZ.png"),H=(()=>{
function __vite__mapDeps(indexes) { function __vite__mapDeps(indexes) {
if (!__vite__mapDeps.viteFileDeps) { if (!__vite__mapDeps.viteFileDeps) {
__vite__mapDeps.viteFileDeps = [ __vite__mapDeps.viteFileDeps = [
(window.${nameOfTheGlobal}.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/assets/Login-dJpPRzM4.js"), (window.kcContext.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/assets/Login-dJpPRzM4.js"),
(window.${nameOfTheGlobal}.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/assets/index-XwzrZ5Gu.js") (window.kcContext.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/assets/index-XwzrZ5Gu.js")
] ]
} }
return indexes.map((i) => __vite__mapDeps.viteFileDeps[i]) return indexes.map((i) => __vite__mapDeps.viteFileDeps[i])