keycloak_theme/src/bin/postinstall/getUiModuleFileSourceCodeReadyToBeCopied.ts

82 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-11-02 22:39:03 +01:00
import { getIsPrettierAvailable, runPrettier } from "../tools/runPrettier";
import * as fsPr from "fs/promises";
import { join as pathJoin, sep as pathSep } from "path";
import { assert } from "tsafe/assert";
import type { BuildContext } from "../shared/buildContext";
2024-11-09 14:02:19 +01:00
import { KEYCLOAK_THEME } from "../shared/constants";
2024-11-02 22:39:03 +01:00
export type BuildContextLike = {
themeSrcDirPath: string;
};
assert<BuildContext extends BuildContextLike ? true : false>();
2024-11-09 14:02:19 +01:00
export async function getUiModuleFileSourceCodeReadyToBeCopied(params: {
2024-11-02 22:39:03 +01:00
buildContext: BuildContextLike;
fileRelativePath: string;
2024-11-09 14:02:19 +01:00
isForEjection: boolean;
uiModuleDirPath: string;
uiModuleName: string;
uiModuleVersion: string;
}): Promise<Buffer> {
const {
buildContext,
uiModuleDirPath,
fileRelativePath,
isForEjection,
uiModuleName,
uiModuleVersion
} = params;
2024-11-02 22:39:03 +01:00
let sourceCode = (
2024-11-09 14:02:19 +01:00
await fsPr.readFile(pathJoin(uiModuleDirPath, KEYCLOAK_THEME, fileRelativePath))
2024-11-02 22:39:03 +01:00
).toString("utf8");
const toComment = (lines: string[]) => {
for (const ext of [".ts", ".tsx", ".css", ".less", ".sass", ".js", ".jsx"]) {
if (!fileRelativePath.endsWith(ext)) {
continue;
}
return [`/**`, ...lines.map(line => ` * ${line}`), ` */`].join("\n");
}
if (fileRelativePath.endsWith(".html")) {
return [`<!--`, ...lines.map(line => ` ${line}`), `-->`].join("\n");
2024-11-02 22:39:03 +01:00
}
return undefined;
};
const comment = toComment(
isForEjection
? [`This file was ejected from ${uiModuleName} version ${uiModuleVersion}.`]
: [
`WARNING: Before modifying this file run the following command:`,
``,
`$ npx keycloakify eject-file --file ${fileRelativePath.split(pathSep).join("/")}`,
``,
`This file comes from ${uiModuleName} version ${uiModuleVersion}.`
]
);
if (comment !== undefined) {
sourceCode = [comment, ``, sourceCode].join("\n");
}
2024-11-02 22:39:03 +01:00
2024-11-09 14:02:19 +01:00
const destFilePath = pathJoin(buildContext.themeSrcDirPath, fileRelativePath);
2024-11-02 22:39:03 +01:00
format: {
if (!(await getIsPrettierAvailable())) {
break format;
}
sourceCode = await runPrettier({
2024-11-09 14:02:19 +01:00
filePath: destFilePath,
2024-11-02 22:39:03 +01:00
sourceCode
});
}
2024-11-09 14:02:19 +01:00
return Buffer.from(sourceCode, "utf8");
2024-11-02 22:39:03 +01:00
}