keycloak_theme/src/bin/keycloakify/replacers/replaceImportsInCssCode.ts

77 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-08-16 14:41:06 +07:00
import * as crypto from "crypto";
import type { BuildOptions } from "../../shared/buildOptions";
2022-08-16 14:41:06 +07:00
import { assert } from "tsafe/assert";
import { basenameOfTheKeycloakifyResourcesDir } from "../../shared/constants";
2022-08-16 14:41:06 +07:00
export type BuildOptionsLike = {
urlPathname: string | undefined;
};
2023-08-21 05:54:17 +02:00
assert<BuildOptions extends BuildOptionsLike ? true : false>();
2022-08-16 14:41:06 +07:00
export function replaceImportsInCssCode(params: { cssCode: string }): {
fixedCssCode: string;
cssGlobalsToDefine: Record<string, string>;
} {
const { cssCode } = params;
const cssGlobalsToDefine: Record<string, string> = {};
2023-12-12 14:51:09 +00:00
new Set(cssCode.match(/url\(["']?\/[^/][^)"']+["']?\)[^;}]*?/g) ?? []).forEach(
2024-05-20 15:48:51 +02:00
match =>
(cssGlobalsToDefine[
"url" +
crypto
.createHash("sha256")
.update(match)
.digest("hex")
.substring(0, 15)
] = match)
2022-08-16 14:41:06 +07:00
);
let fixedCssCode = cssCode;
Object.keys(cssGlobalsToDefine).forEach(
cssVariableName =>
//NOTE: split/join pattern ~ replace all
2024-05-20 15:48:51 +02:00
(fixedCssCode = fixedCssCode
.split(cssGlobalsToDefine[cssVariableName])
.join(`var(--${cssVariableName})`))
2022-08-16 14:41:06 +07:00
);
return { fixedCssCode, cssGlobalsToDefine };
}
2024-05-20 15:48:51 +02:00
export function generateCssCodeToDefineGlobals(params: {
cssGlobalsToDefine: Record<string, string>;
buildOptions: BuildOptionsLike;
}): {
2022-08-16 14:41:06 +07:00
cssCodeToPrependInHead: string;
} {
const { cssGlobalsToDefine, buildOptions } = params;
return {
2024-05-20 15:48:51 +02:00
cssCodeToPrependInHead: [
2022-08-16 14:41:06 +07:00
":root {",
...Object.keys(cssGlobalsToDefine)
.map(cssVariableName =>
[
`--${cssVariableName}:`,
cssGlobalsToDefine[cssVariableName].replace(
2024-05-20 15:48:51 +02:00
new RegExp(
`url\\(${(buildOptions.urlPathname ?? "/").replace(
/\//g,
"\\/"
)}`,
"g"
),
2024-01-30 00:06:17 +01:00
`url(\${url.resourcesPath}/${basenameOfTheKeycloakifyResourcesDir}/`
)
].join(" ")
2022-08-16 14:41:06 +07:00
)
.map(line => ` ${line};`),
"}"
].join("\n")
2022-08-16 14:41:06 +07:00
};
}