Make sure the update-kc-gen command is delegated when building with vite

This commit is contained in:
Joseph Garrone 2024-10-06 09:03:15 +02:00
parent 63775b2866
commit a04f07d149
7 changed files with 239 additions and 312 deletions

View File

@ -5,7 +5,7 @@ import chalk from "chalk";
import { join as pathJoin, relative as pathRelative } from "path"; import { join as pathJoin, relative as pathRelative } from "path";
import * as fs from "fs"; import * as fs from "fs";
import { updateAccountThemeImplementationInConfig } from "./updateAccountThemeImplementationInConfig"; import { updateAccountThemeImplementationInConfig } from "./updateAccountThemeImplementationInConfig";
import { generateKcGenTs } from "../shared/generateKcGenTs"; import { command as updateKcGenCommand } from "../update-kc-gen";
export async function command(params: { buildContext: BuildContext }) { export async function command(params: { buildContext: BuildContext }) {
const { buildContext } = params; const { buildContext } = params;
@ -94,7 +94,7 @@ export async function command(params: { buildContext: BuildContext }) {
updateAccountThemeImplementationInConfig({ buildContext, accountThemeType }); updateAccountThemeImplementationInConfig({ buildContext, accountThemeType });
await generateKcGenTs({ await updateKcGenCommand({
buildContext: { buildContext: {
...buildContext, ...buildContext,
implementedThemeTypes: { implementedThemeTypes: {

View File

@ -4,7 +4,6 @@ import { termost } from "termost";
import { readThisNpmPackageVersion } from "./tools/readThisNpmPackageVersion"; import { readThisNpmPackageVersion } from "./tools/readThisNpmPackageVersion";
import * as child_process from "child_process"; import * as child_process from "child_process";
import { assertNoPnpmDlx } from "./tools/assertNoPnpmDlx"; import { assertNoPnpmDlx } from "./tools/assertNoPnpmDlx";
import { callHandlerIfAny } from "./shared/customHandler_caller";
import { getBuildContext } from "./shared/buildContext"; import { getBuildContext } from "./shared/buildContext";
type CliCommandOptions = { type CliCommandOptions = {
@ -72,24 +71,19 @@ program
.task({ .task({
skip, skip,
handler: async ({ projectDirPath }) => { handler: async ({ projectDirPath }) => {
const buildContext = getBuildContext({ projectDirPath });
const { command } = await import("./keycloakify"); const { command } = await import("./keycloakify");
await command({ buildContext }); await command({ buildContext: getBuildContext({ projectDirPath }) });
} }
}); });
{ program
const commandName = "start-keycloak";
program
.command<{ .command<{
port: number | undefined; port: number | undefined;
keycloakVersion: string | undefined; keycloakVersion: string | undefined;
realmJsonFilePath: string | undefined; realmJsonFilePath: string | undefined;
}>({ }>({
name: commandName, name: "start-keycloak",
description: description:
"Spin up a pre configured Docker image of Keycloak to test your theme." "Spin up a pre configured Docker image of Keycloak to test your theme."
}) })
@ -137,88 +131,57 @@ program
}) })
.task({ .task({
skip, skip,
handler: async ({ handler: async ({ projectDirPath, keycloakVersion, port, realmJsonFilePath }) => {
projectDirPath,
keycloakVersion,
port,
realmJsonFilePath
}) => {
const buildContext = getBuildContext({ projectDirPath });
const { command } = await import("./start-keycloak"); const { command } = await import("./start-keycloak");
await command({ await command({
buildContext, buildContext: getBuildContext({ projectDirPath }),
cliCommandOptions: { keycloakVersion, port, realmJsonFilePath } cliCommandOptions: { keycloakVersion, port, realmJsonFilePath }
}); });
} }
}); });
}
{ program
const commandName = "eject-page";
program
.command({ .command({
name: commandName, name: "eject-page",
description: "Eject a Keycloak page." description: "Eject a Keycloak page."
}) })
.task({ .task({
skip, skip,
handler: async ({ projectDirPath }) => { handler: async ({ projectDirPath }) => {
const buildContext = getBuildContext({ projectDirPath });
callHandlerIfAny({ buildContext, commandName });
const { command } = await import("./eject-page"); const { command } = await import("./eject-page");
await command({ buildContext }); await command({ buildContext: getBuildContext({ projectDirPath }) });
} }
}); });
}
{ program
const commandName = "add-story";
program
.command({ .command({
name: commandName, name: "add-story",
description: description: "Add *.stories.tsx file for a specific page to in your Storybook."
"Add *.stories.tsx file for a specific page to in your Storybook."
}) })
.task({ .task({
skip, skip,
handler: async ({ projectDirPath }) => { handler: async ({ projectDirPath }) => {
const buildContext = getBuildContext({ projectDirPath });
callHandlerIfAny({ buildContext, commandName });
const { command } = await import("./add-story"); const { command } = await import("./add-story");
await command({ buildContext }); await command({ buildContext: getBuildContext({ projectDirPath }) });
} }
}); });
}
{ program
const comandName = "initialize-login-theme";
program
.command({ .command({
name: comandName, name: "initialize-login-theme",
description: "Initialize an email theme." description: "Initialize an email theme."
}) })
.task({ .task({
skip, skip,
handler: async ({ projectDirPath }) => { handler: async ({ projectDirPath }) => {
const buildContext = getBuildContext({ projectDirPath });
const { command } = await import("./initialize-email-theme"); const { command } = await import("./initialize-email-theme");
await command({ buildContext }); await command({ buildContext: getBuildContext({ projectDirPath }) });
} }
}); });
}
program program
.command({ .command({
@ -228,57 +191,41 @@ program
.task({ .task({
skip, skip,
handler: async ({ projectDirPath }) => { handler: async ({ projectDirPath }) => {
const buildContext = getBuildContext({ projectDirPath });
const { command } = await import("./initialize-account-theme"); const { command } = await import("./initialize-account-theme");
await command({ buildContext }); await command({ buildContext: getBuildContext({ projectDirPath }) });
} }
}); });
{ program
const commandName = "copy-keycloak-resources-to-public";
program
.command({ .command({
name: commandName, name: "copy-keycloak-resources-to-public",
description: description:
"(Webpack/Create-React-App only) Copy Keycloak default theme resources to the public directory." "(Webpack/Create-React-App only) Copy Keycloak default theme resources to the public directory."
}) })
.task({ .task({
skip, skip,
handler: async ({ projectDirPath }) => { handler: async ({ projectDirPath }) => {
const buildContext = getBuildContext({ projectDirPath });
const { command } = await import("./copy-keycloak-resources-to-public"); const { command } = await import("./copy-keycloak-resources-to-public");
await command({ buildContext }); await command({ buildContext: getBuildContext({ projectDirPath }) });
} }
}); });
}
{ program
const commandName = "update-kc-gen";
program
.command({ .command({
name: commandName, name: "update-kc-gen",
description: description:
"(Webpack/Create-React-App only) Create/update the kc.gen.ts file in your project." "(Webpack/Create-React-App only) Create/update the kc.gen.ts file in your project."
}) })
.task({ .task({
skip, skip,
handler: async ({ projectDirPath }) => { handler: async ({ projectDirPath }) => {
const buildContext = getBuildContext({ projectDirPath });
callHandlerIfAny({ buildContext, commandName });
const { command } = await import("./update-kc-gen"); const { command } = await import("./update-kc-gen");
await command({ buildContext }); await command({ buildContext: getBuildContext({ projectDirPath }) });
} }
}); });
}
// Fallback to build command if no command is provided // Fallback to build command if no command is provided
{ {

View File

@ -13,7 +13,7 @@ import * as fs from "fs";
assert<Equals<ApiVersion, "v1">>(); assert<Equals<ApiVersion, "v1">>();
export function callHandlerIfAny(params: { export function maybeDelegateCommandToCustomHandler(params: {
commandName: CommandName; commandName: CommandName;
buildContext: BuildContext; buildContext: BuildContext;
}) { }) {

View File

@ -1,127 +0,0 @@
import { assert } from "tsafe/assert";
import type { BuildContext } from "./buildContext";
import * as fs from "fs/promises";
import { join as pathJoin } from "path";
import { existsAsync } from "../tools/fs.existsAsync";
export type BuildContextLike = {
projectDirPath: string;
themeNames: string[];
environmentVariables: { name: string; default: string }[];
themeSrcDirPath: string;
implementedThemeTypes: Pick<
BuildContext["implementedThemeTypes"],
"login" | "account"
>;
packageJsonFilePath: string;
};
assert<BuildContext extends BuildContextLike ? true : false>();
export async function generateKcGenTs(params: {
buildContext: BuildContextLike;
}): Promise<void> {
const { buildContext } = params;
const filePath = pathJoin(buildContext.themeSrcDirPath, `kc.gen.tsx`);
const currentContent = (await existsAsync(filePath))
? await fs.readFile(filePath)
: undefined;
const hasLoginTheme = buildContext.implementedThemeTypes.login.isImplemented;
const hasAccountTheme = buildContext.implementedThemeTypes.account.isImplemented;
const newContent = Buffer.from(
[
`/* prettier-ignore-start */`,
``,
`/* eslint-disable */`,
``,
`// @ts-nocheck`,
``,
`// noinspection JSUnusedGlobalSymbols`,
``,
`// This file is auto-generated by Keycloakify`,
``,
`import { lazy, Suspense, type ReactNode } from "react";`,
``,
`export type ThemeName = ${buildContext.themeNames.map(themeName => `"${themeName}"`).join(" | ")};`,
``,
`export const themeNames: ThemeName[] = [${buildContext.themeNames.map(themeName => `"${themeName}"`).join(", ")}];`,
``,
`export type KcEnvName = ${buildContext.environmentVariables.length === 0 ? "never" : buildContext.environmentVariables.map(({ name }) => `"${name}"`).join(" | ")};`,
``,
`export const kcEnvNames: KcEnvName[] = [${buildContext.environmentVariables.map(({ name }) => `"${name}"`).join(", ")}];`,
``,
`export const kcEnvDefaults: Record<KcEnvName, string> = ${JSON.stringify(
Object.fromEntries(
buildContext.environmentVariables.map(
({ name, default: defaultValue }) => [name, defaultValue]
)
),
null,
2
)};`,
``,
`export type KcContext =`,
hasLoginTheme && ` | import("./login/KcContext").KcContext`,
hasAccountTheme && ` | import("./account/KcContext").KcContext`,
` ;`,
``,
`declare global {`,
` interface Window {`,
` kcContext?: KcContext;`,
` }`,
`}`,
``,
hasLoginTheme &&
`export const KcLoginPage = lazy(() => import("./login/KcPage"));`,
hasAccountTheme &&
`export const KcAccountPage = lazy(() => import("./account/KcPage"));`,
``,
`export function KcPage(`,
` props: {`,
` kcContext: KcContext;`,
` fallback?: ReactNode;`,
` }`,
`) {`,
` const { kcContext, fallback } = props;`,
` return (`,
` <Suspense fallback={fallback}>`,
` {(() => {`,
` switch (kcContext.themeType) {`,
hasLoginTheme &&
` case "login": return <KcLoginPage kcContext={kcContext} />;`,
hasAccountTheme &&
` case "account": return <KcAccountPage kcContext={kcContext} />;`,
` }`,
` })()}`,
` </Suspense>`,
` );`,
`}`,
``,
`/* prettier-ignore-end */`,
``
]
.filter(item => typeof item === "string")
.join("\n"),
"utf8"
);
if (currentContent !== undefined && currentContent.equals(newContent)) {
return;
}
await fs.writeFile(filePath, newContent);
delete_legacy_file: {
const legacyFilePath = filePath.replace(/tsx$/, "ts");
if (!(await existsAsync(legacyFilePath))) {
break delete_legacy_file;
}
await fs.unlink(legacyFilePath);
}
}

View File

@ -1,8 +1,116 @@
import type { BuildContext } from "./shared/buildContext"; import type { BuildContext } from "./shared/buildContext";
import { generateKcGenTs } from "./shared/generateKcGenTs"; import * as fs from "fs/promises";
import { join as pathJoin } from "path";
import { existsAsync } from "./tools/fs.existsAsync";
import { maybeDelegateCommandToCustomHandler } from "./shared/customHandler_delegate";
export async function command(params: { buildContext: BuildContext }) { export async function command(params: { buildContext: BuildContext }) {
const { buildContext } = params; const { buildContext } = params;
await generateKcGenTs({ buildContext }); maybeDelegateCommandToCustomHandler({
commandName: "update-kc-gen",
buildContext
});
const filePath = pathJoin(buildContext.themeSrcDirPath, `kc.gen.tsx`);
const currentContent = (await existsAsync(filePath))
? await fs.readFile(filePath)
: undefined;
const hasLoginTheme = buildContext.implementedThemeTypes.login.isImplemented;
const hasAccountTheme = buildContext.implementedThemeTypes.account.isImplemented;
const newContent = Buffer.from(
[
`/* prettier-ignore-start */`,
``,
`/* eslint-disable */`,
``,
`// @ts-nocheck`,
``,
`// noinspection JSUnusedGlobalSymbols`,
``,
`// This file is auto-generated by Keycloakify`,
``,
`import { lazy, Suspense, type ReactNode } from "react";`,
``,
`export type ThemeName = ${buildContext.themeNames.map(themeName => `"${themeName}"`).join(" | ")};`,
``,
`export const themeNames: ThemeName[] = [${buildContext.themeNames.map(themeName => `"${themeName}"`).join(", ")}];`,
``,
`export type KcEnvName = ${buildContext.environmentVariables.length === 0 ? "never" : buildContext.environmentVariables.map(({ name }) => `"${name}"`).join(" | ")};`,
``,
`export const kcEnvNames: KcEnvName[] = [${buildContext.environmentVariables.map(({ name }) => `"${name}"`).join(", ")}];`,
``,
`export const kcEnvDefaults: Record<KcEnvName, string> = ${JSON.stringify(
Object.fromEntries(
buildContext.environmentVariables.map(
({ name, default: defaultValue }) => [name, defaultValue]
)
),
null,
2
)};`,
``,
`export type KcContext =`,
hasLoginTheme && ` | import("./login/KcContext").KcContext`,
hasAccountTheme && ` | import("./account/KcContext").KcContext`,
` ;`,
``,
`declare global {`,
` interface Window {`,
` kcContext?: KcContext;`,
` }`,
`}`,
``,
hasLoginTheme &&
`export const KcLoginPage = lazy(() => import("./login/KcPage"));`,
hasAccountTheme &&
`export const KcAccountPage = lazy(() => import("./account/KcPage"));`,
``,
`export function KcPage(`,
` props: {`,
` kcContext: KcContext;`,
` fallback?: ReactNode;`,
` }`,
`) {`,
` const { kcContext, fallback } = props;`,
` return (`,
` <Suspense fallback={fallback}>`,
` {(() => {`,
` switch (kcContext.themeType) {`,
hasLoginTheme &&
` case "login": return <KcLoginPage kcContext={kcContext} />;`,
hasAccountTheme &&
` case "account": return <KcAccountPage kcContext={kcContext} />;`,
` }`,
` })()}`,
` </Suspense>`,
` );`,
`}`,
``,
`/* prettier-ignore-end */`,
``
]
.filter(item => typeof item === "string")
.join("\n"),
"utf8"
);
if (currentContent !== undefined && currentContent.equals(newContent)) {
return;
}
await fs.writeFile(filePath, newContent);
delete_legacy_file: {
const legacyFilePath = filePath.replace(/tsx$/, "ts");
if (!(await existsAsync(legacyFilePath))) {
break delete_legacy_file;
}
await fs.unlink(legacyFilePath);
}
} }

View File

@ -15,7 +15,7 @@ import {
type ResolvedViteConfig type ResolvedViteConfig
} from "../bin/shared/buildContext"; } from "../bin/shared/buildContext";
import MagicString from "magic-string"; import MagicString from "magic-string";
import { generateKcGenTs } from "../bin/shared/generateKcGenTs"; import { command as updateKcGenCommand } from "../bin/update-kc-gen";
export namespace keycloakify { export namespace keycloakify {
export type Params = BuildOptions & { export type Params = BuildOptions & {
@ -125,8 +125,9 @@ export function keycloakify(params: keycloakify.Params) {
projectDirPath projectDirPath
}); });
copyKeycloakResourcesToPublic({ buildContext }), copyKeycloakResourcesToPublic({ buildContext });
await generateKcGenTs({ buildContext });
await updateKcGenCommand({ buildContext });
}, },
transform: (code, id) => { transform: (code, id) => {
assert(command !== undefined); assert(command !== undefined);

View File

@ -115,7 +115,6 @@ export const WithFavoritePet: Story = {
) )
}; };
export const WithNewsletter: Story = { export const WithNewsletter: Story = {
render: () => ( render: () => (
<KcPageStory <KcPageStory
@ -132,7 +131,7 @@ export const WithNewsletter: Story = {
}, },
annotations: { annotations: {
inputOptionLabels: { inputOptionLabels: {
"yes": "I want my email inbox filled with spam" yes: "I want my email inbox filled with spam"
}, },
inputType: "multiselect-checkboxes" inputType: "multiselect-checkboxes"
}, },
@ -140,13 +139,12 @@ export const WithNewsletter: Story = {
readOnly: false readOnly: false
} satisfies Attribute } satisfies Attribute
} }
}, }
}} }}
/> />
) )
}; };
export const WithEmailAsUsername: Story = { export const WithEmailAsUsername: Story = {
render: () => ( render: () => (
<KcPageStory <KcPageStory