keycloak_theme/src/bin/start-keycloak/start-keycloak.ts

452 lines
15 KiB
TypeScript
Raw Normal View History

2024-06-09 09:15:16 +02:00
import { getBuildContext } from "../shared/buildContext";
import { exclude } from "tsafe/exclude";
2024-05-20 15:34:07 +02:00
import type { CliCommandOptions as CliCommandOptions_common } from "../main";
import { promptKeycloakVersion } from "../shared/promptKeycloakVersion";
2024-07-13 19:33:59 +02:00
import { ACCOUNT_V1_THEME_NAME, CONTAINER_NAME } from "../shared/constants";
2024-05-20 15:34:07 +02:00
import { SemVer } from "../tools/SemVer";
import { assert } from "tsafe/assert";
2024-05-17 05:13:41 +02:00
import * as fs from "fs";
import {
join as pathJoin,
relative as pathRelative,
sep as pathSep,
basename as pathBasename
} from "path";
2024-05-17 05:13:41 +02:00
import * as child_process from "child_process";
2024-05-18 10:02:14 +02:00
import chalk from "chalk";
2024-05-20 02:27:40 +02:00
import chokidar from "chokidar";
import { waitForDebounceFactory } from "powerhooks/tools/waitForDebounce";
2024-05-20 15:34:07 +02:00
import { getThisCodebaseRootDirPath } from "../tools/getThisCodebaseRootDirPath";
import { getAbsoluteAndInOsFormatPath } from "../tools/getAbsoluteAndInOsFormatPath";
import cliSelect from "cli-select";
2024-05-20 19:30:04 +02:00
import * as runExclusive from "run-exclusive";
import { extractArchive } from "../tools/extractArchive";
import { appBuild } from "./appBuild";
import { keycloakifyBuild } from "./keycloakifyBuild";
2024-06-10 07:57:12 +02:00
import { isInside } from "../tools/isInside";
import { existsAsync } from "../tools/fs.existsAsync";
import { rm } from "../tools/fs.rm";
2024-05-18 11:40:09 +02:00
export type CliCommandOptions = CliCommandOptions_common & {
port: number;
keycloakVersion: string | undefined;
2024-05-20 15:34:07 +02:00
realmJsonFilePath: string | undefined;
2024-05-18 11:40:09 +02:00
};
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
2024-05-18 11:40:09 +02:00
exit_if_docker_not_installed: {
2024-05-18 11:09:04 +02:00
let commandOutput: Buffer | undefined = undefined;
try {
2024-05-20 15:48:51 +02:00
commandOutput = child_process.execSync("docker --version", {
stdio: ["ignore", "pipe", "ignore"]
});
2024-05-18 11:09:04 +02:00
} catch {}
2024-05-18 11:40:09 +02:00
if (commandOutput?.toString("utf8").includes("Docker")) {
break exit_if_docker_not_installed;
2024-05-18 11:09:04 +02:00
}
console.log(
[
`${chalk.red("Docker required.")}`,
2024-05-20 15:48:51 +02:00
`Install it with Docker Desktop: ${chalk.bold.underline(
"https://www.docker.com/products/docker-desktop/"
)}`,
2024-05-18 11:09:04 +02:00
`(or any other way)`
].join(" ")
);
process.exit(1);
}
2024-05-18 11:40:09 +02:00
exit_if_docker_not_running: {
2024-05-18 11:09:04 +02:00
let isDockerRunning: boolean;
try {
2024-05-20 15:48:51 +02:00
child_process.execSync("docker info", { stdio: "ignore" });
2024-05-18 11:09:04 +02:00
isDockerRunning = true;
} catch {
isDockerRunning = false;
}
if (isDockerRunning) {
2024-05-18 11:40:09 +02:00
break exit_if_docker_not_running;
2024-05-18 11:09:04 +02:00
}
2024-05-20 15:48:51 +02:00
console.log(
[
`${chalk.red("Docker daemon is not running.")}`,
`Please start Docker Desktop and try again.`
].join(" ")
);
2024-05-18 11:40:09 +02:00
process.exit(1);
2024-05-18 11:09:04 +02:00
}
const { cliCommandOptions } = params;
2024-06-09 09:15:16 +02:00
const buildContext = getBuildContext({ cliCommandOptions });
const { keycloakVersion } = await (async () => {
if (cliCommandOptions.keycloakVersion !== undefined) {
return {
keycloakVersion: cliCommandOptions.keycloakVersion,
keycloakMajorNumber: SemVer.parse(cliCommandOptions.keycloakVersion).major
};
}
2024-05-17 05:13:41 +02:00
console.log(
chalk.cyan("On which version of Keycloak do you want to test your theme?")
);
2024-05-17 05:13:41 +02:00
const { keycloakVersion } = await promptKeycloakVersion({
startingFromMajor: 18,
excludeMajorVersions: [22],
2024-08-13 00:10:34 +02:00
buildContext
});
2024-05-17 05:13:41 +02:00
console.log(`${keycloakVersion}`);
2024-05-17 05:13:41 +02:00
return { keycloakVersion };
2024-05-17 05:13:41 +02:00
})();
const keycloakMajorVersionNumber = SemVer.parse(keycloakVersion).major;
2024-05-17 05:13:41 +02:00
{
const { isAppBuildSuccess } = await appBuild({
buildContext
});
if (!isAppBuildSuccess) {
console.log(
chalk.red(
`App build failed, exiting. Try building your app (e.g 'npm run build') and see what's wrong.`
)
);
process.exit(1);
}
const { isKeycloakifyBuildSuccess } = await keycloakifyBuild({
buildForKeycloakMajorVersionNumber: keycloakMajorVersionNumber,
buildContext
});
if (!isKeycloakifyBuildSuccess) {
console.log(
chalk.red(
`Keycloakify build failed, exiting. Try running 'npx keycloakify build' and see what's wrong.`
)
);
process.exit(1);
}
}
const jarFilePath = fs
.readdirSync(buildContext.keycloakifyBuildDirPath)
.filter(fileBasename => fileBasename.endsWith(".jar"))
.map(fileBasename => pathJoin(buildContext.keycloakifyBuildDirPath, fileBasename))
.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)[0];
assert(jarFilePath !== undefined);
console.log(`Using ${chalk.bold(pathBasename(jarFilePath))}`);
2024-05-20 02:42:57 +02:00
2024-05-20 15:34:07 +02:00
const realmJsonFilePath = await (async () => {
if (cliCommandOptions.realmJsonFilePath !== undefined) {
if (cliCommandOptions.realmJsonFilePath === "none") {
return undefined;
}
2024-05-20 15:48:51 +02:00
console.log(
chalk.green(
`Using realm json file: ${cliCommandOptions.realmJsonFilePath}`
)
);
2024-05-20 15:34:07 +02:00
return getAbsoluteAndInOsFormatPath({
2024-05-20 15:48:51 +02:00
pathIsh: cliCommandOptions.realmJsonFilePath,
cwd: process.cwd()
2024-05-20 15:34:07 +02:00
});
}
const internalFilePath = await (async () => {
const dirPath = pathJoin(
getThisCodebaseRootDirPath(),
"src",
"bin",
"start-keycloak"
);
2024-05-20 15:34:07 +02:00
const filePath = pathJoin(
dirPath,
`myrealm-realm-${keycloakMajorVersionNumber}.json`
);
2024-05-20 15:34:07 +02:00
if (fs.existsSync(filePath)) {
return filePath;
}
2024-05-20 15:34:07 +02:00
console.log(
`${chalk.yellow(
`Keycloakify do not have a realm configuration for Keycloak ${keycloakMajorVersionNumber} yet.`
)}`
);
2024-05-20 15:34:07 +02:00
console.log(chalk.cyan("Select what configuration to use:"));
const { value } = await cliSelect<string>({
values: [
...fs
.readdirSync(dirPath)
.filter(fileBasename => fileBasename.endsWith(".json")),
"none"
]
}).catch(() => {
process.exit(-1);
});
if (value === "none") {
return undefined;
}
return pathJoin(dirPath, value);
})();
2024-05-20 15:34:07 +02:00
if (internalFilePath === undefined) {
2024-05-20 15:34:07 +02:00
return undefined;
}
const filePath = pathJoin(
buildContext.cacheDirPath,
pathBasename(internalFilePath)
);
fs.writeFileSync(
filePath,
Buffer.from(
fs
.readFileSync(internalFilePath)
.toString("utf8")
.replace(/keycloakify\-starter/g, buildContext.themeNames[0])
),
"utf8"
);
return filePath;
2024-05-20 15:34:07 +02:00
})();
2024-06-10 07:57:12 +02:00
async function extractThemeResourcesFromJar() {
await extractArchive({
archiveFilePath: jarFilePath,
2024-06-10 07:57:12 +02:00
onArchiveFile: async ({ relativeFilePathInArchive, writeFile }) => {
if (isInside({ dirPath: "theme", filePath: relativeFilePathInArchive })) {
await writeFile({
filePath: pathJoin(
buildContext.keycloakifyBuildDirPath,
relativeFilePathInArchive
)
});
}
}
});
2024-06-10 07:57:12 +02:00
}
2024-06-10 07:57:12 +02:00
{
const destDirPath = pathJoin(buildContext.keycloakifyBuildDirPath, "theme");
if (await existsAsync(destDirPath)) {
await rm(destDirPath, { recursive: true });
}
}
2024-06-10 07:57:12 +02:00
await extractThemeResourcesFromJar();
const jarFilePath_cacheDir = pathJoin(
buildContext.cacheDirPath,
pathBasename(jarFilePath)
);
fs.copyFileSync(jarFilePath, jarFilePath_cacheDir);
2024-05-26 19:40:13 +02:00
try {
2024-07-13 19:33:59 +02:00
child_process.execSync(`docker rm --force ${CONTAINER_NAME}`, {
2024-05-26 19:40:13 +02:00
stdio: "ignore"
});
} catch {}
2024-05-20 15:34:07 +02:00
const spawnArgs = [
2024-05-17 05:13:41 +02:00
"docker",
[
"run",
2024-05-18 11:40:09 +02:00
...["-p", `${cliCommandOptions.port}:8080`],
2024-07-13 19:33:59 +02:00
...["--name", CONTAINER_NAME],
2024-05-17 05:13:41 +02:00
...["-e", "KEYCLOAK_ADMIN=admin"],
...["-e", "KEYCLOAK_ADMIN_PASSWORD=admin"],
2024-05-20 15:48:51 +02:00
...(realmJsonFilePath === undefined
? []
: [
"-v",
2024-08-02 14:09:09 +02:00
`"${realmJsonFilePath}":/opt/keycloak/data/import/myrealm-realm.json`
2024-05-20 15:48:51 +02:00
]),
...[
"-v",
2024-08-02 14:09:09 +02:00
`"${jarFilePath_cacheDir}":/opt/keycloak/providers/keycloak-theme.jar`
],
2024-05-20 15:48:51 +02:00
...(keycloakMajorVersionNumber <= 20
? ["-e", "JAVA_OPTS=-Dkeycloak.profile=preview"]
: []),
...[
2024-06-09 09:15:16 +02:00
...buildContext.themeNames,
2024-06-10 07:57:12 +02:00
...(fs.existsSync(
pathJoin(
buildContext.keycloakifyBuildDirPath,
"theme",
2024-07-13 19:33:59 +02:00
ACCOUNT_V1_THEME_NAME
2024-06-10 07:57:12 +02:00
)
)
2024-07-13 19:33:59 +02:00
? [ACCOUNT_V1_THEME_NAME]
2024-06-10 07:57:12 +02:00
: [])
]
.map(themeName => ({
localDirPath: pathJoin(
2024-06-09 09:15:16 +02:00
buildContext.keycloakifyBuildDirPath,
"theme",
themeName
),
containerDirPath: `/opt/keycloak/themes/${themeName}`
}))
.map(({ localDirPath, containerDirPath }) => [
2024-05-20 15:48:51 +02:00
"-v",
2024-08-02 14:09:09 +02:00
`"${localDirPath}":${containerDirPath}:rw`
2024-05-20 15:48:51 +02:00
])
.flat(),
2024-06-09 09:15:16 +02:00
...buildContext.environmentVariables
.map(({ name }) => ({ name, envValue: process.env[name] }))
.map(({ name, envValue }) =>
envValue === undefined ? undefined : { name, envValue }
)
.filter(exclude(undefined))
.map(({ name, envValue }) => [
"--env",
`${name}='${envValue.replace(/'/g, "'\\''")}'`
])
.flat(),
2024-05-18 07:53:06 +02:00
`quay.io/keycloak/keycloak:${keycloakVersion}`,
2024-05-17 05:13:41 +02:00
"start-dev",
2024-05-20 15:48:51 +02:00
...(21 <= keycloakMajorVersionNumber && keycloakMajorVersionNumber < 24
? ["--features=declarative-user-profile"]
: []),
2024-05-20 15:34:07 +02:00
...(realmJsonFilePath === undefined ? [] : ["--import-realm"])
2024-05-17 05:13:41 +02:00
],
{
cwd: buildContext.keycloakifyBuildDirPath,
shell: true
2024-05-17 05:13:41 +02:00
}
2024-05-20 02:27:40 +02:00
] as const;
2024-05-20 15:34:07 +02:00
const child = child_process.spawn(...spawnArgs);
2024-05-17 05:13:41 +02:00
2024-05-18 07:53:06 +02:00
child.stdout.on("data", data => process.stdout.write(data));
child.stderr.on("data", data => process.stderr.write(data));
2024-05-17 05:13:41 +02:00
2024-05-20 02:27:40 +02:00
child.on("exit", process.exit);
2024-06-09 09:15:16 +02:00
const srcDirPath = pathJoin(buildContext.projectDirPath, "src");
2024-05-20 02:27:40 +02:00
2024-05-18 10:02:14 +02:00
{
const handler = async (data: Buffer) => {
if (!data.toString("utf8").includes("Listening on: http://0.0.0.0:8080")) {
return;
}
child.stdout.off("data", handler);
await new Promise(resolve => setTimeout(resolve, 1_000));
console.log(
[
"",
`The ftl files from ${chalk.bold(
`.${pathSep}${pathRelative(process.cwd(), pathJoin(buildContext.keycloakifyBuildDirPath, "theme"))}`
)} are mounted in the Keycloak container.`,
2024-05-26 19:55:59 +02:00
"",
`Keycloak Admin console: ${chalk.cyan.bold(
`http://localhost:${cliCommandOptions.port}`
)}`,
`- user: ${chalk.cyan.bold("admin")}`,
`- password: ${chalk.cyan.bold("admin")}`,
"",
2024-05-18 10:02:14 +02:00
"",
`${chalk.green("Your theme is accessible at:")}`,
2024-05-20 15:48:51 +02:00
`${chalk.green("➜")} ${chalk.cyan.bold(
2024-05-26 19:55:59 +02:00
`https://my-theme.keycloakify.dev${cliCommandOptions.port === 8080 ? "" : `?port=${cliCommandOptions.port}`}`
2024-05-20 15:48:51 +02:00
)}`,
"",
"You can login with the following credentials:",
`- username: ${chalk.cyan.bold("testuser")}`,
`- password: ${chalk.cyan.bold("password123")}`,
2024-05-20 02:27:40 +02:00
"",
2024-05-20 15:48:51 +02:00
`Watching for changes in ${chalk.bold(
2024-06-09 09:15:16 +02:00
`.${pathSep}${pathRelative(process.cwd(), buildContext.projectDirPath)}`
2024-05-20 15:48:51 +02:00
)}`
2024-05-18 10:02:14 +02:00
].join("\n")
);
};
child.stdout.on("data", handler);
}
2024-05-20 02:27:40 +02:00
{
const runFullBuild = runExclusive.build(async () => {
2024-05-20 19:30:04 +02:00
console.log(chalk.cyan("Detected changes in the theme. Rebuilding ..."));
2024-05-20 15:34:07 +02:00
const { isAppBuildSuccess } = await appBuild({
2024-06-09 09:15:16 +02:00
buildContext
});
2024-05-20 02:27:40 +02:00
if (!isAppBuildSuccess) {
return;
2024-05-20 19:30:04 +02:00
}
2024-05-20 02:27:40 +02:00
const { isKeycloakifyBuildSuccess } = await keycloakifyBuild({
buildForKeycloakMajorVersionNumber: keycloakMajorVersionNumber,
2024-06-09 09:15:16 +02:00
buildContext
});
2024-05-20 02:42:57 +02:00
if (!isKeycloakifyBuildSuccess) {
return;
}
2024-05-20 19:30:04 +02:00
2024-06-10 07:57:12 +02:00
await extractThemeResourcesFromJar();
2024-05-20 19:30:04 +02:00
console.log(chalk.green("Theme rebuilt and updated in Keycloak."));
2024-05-20 19:30:04 +02:00
});
const { waitForDebounce } = waitForDebounceFactory({ delay: 400 });
2024-05-20 19:30:04 +02:00
chokidar
.watch(
[
srcDirPath,
2024-06-09 09:15:16 +02:00
buildContext.publicDirPath,
pathJoin(buildContext.projectDirPath, "package.json"),
pathJoin(buildContext.projectDirPath, "vite.config.ts"),
pathJoin(buildContext.projectDirPath, "vite.config.js"),
pathJoin(buildContext.projectDirPath, "index.html"),
pathJoin(getThisCodebaseRootDirPath(), "src")
],
{
ignoreInitial: true
}
)
.on("all", async (...[, filePath]) => {
console.log(`Detected changes in ${filePath}`);
2024-05-20 19:30:04 +02:00
await waitForDebounce();
runFullBuild();
2024-05-20 15:48:51 +02:00
});
2024-05-20 02:27:40 +02:00
}
}