Compare commits
362 Commits
v10.0.0-rc
...
bundle_jar
Author | SHA1 | Date | |
---|---|---|---|
7d8ae040fd | |||
c6cf564842 | |||
380b739017 | |||
c3f3c55303 | |||
2c01018529 | |||
dd2edf3013 | |||
7f3cdf9fac | |||
f75a91fbc1 | |||
f151086bb1 | |||
7c833e6f10 | |||
885e8314e8 | |||
3bdd955ab6 | |||
9499587bad | |||
0879ddba7c | |||
106a1dd4c7 | |||
5580248bcd | |||
c9c10b8fba | |||
ed254922e9 | |||
4b7d1e2cec | |||
775ae57258 | |||
96e4cd79ee | |||
bb70f7df4f | |||
602de2e407 | |||
225ced989c | |||
ab53698f34 | |||
02f2124126 | |||
66623e3324 | |||
4cc886fd04 | |||
a10b490245 | |||
b947b8a00d | |||
60fa240a4d | |||
e05cd87b7c | |||
8e41c905ed | |||
e21f607ab0 | |||
34af5abb82 | |||
fc1cdb5dc9 | |||
069a0cc980 | |||
78363727e1 | |||
23b16746f6 | |||
6edf9c3d15 | |||
2e371d2078 | |||
b70b478e25 | |||
97ad132086 | |||
2c5c54bf46 | |||
c0ca078b43 | |||
53e94d04f6 | |||
dd198f9f06 | |||
43f455f4d0 | |||
d9132ea5a5 | |||
d5c7e2547b | |||
13b87de06c | |||
83bdbb7a7e | |||
89320b8d51 | |||
5fa9c3879c | |||
c0cd76d40e | |||
01f60f8013 | |||
91ad0712af | |||
2cb1b36725 | |||
67ce66765f | |||
c8cc453942 | |||
3f835f152f | |||
35e8a853e0 | |||
d084a4bf4a | |||
2a6b79e097 | |||
5d786c922f | |||
26bd5dd534 | |||
b4df0ce52c | |||
386a8d7cd7 | |||
5221fb3479 | |||
2871f63f25 | |||
4c282d0559 | |||
4ac14dc074 | |||
fcdbb04ea6 | |||
14f283cf49 | |||
efc459663a | |||
d459aaf943 | |||
921c7d5441 | |||
7d7e648968 | |||
96fc779ec8 | |||
9605e17e96 | |||
111c1675f9 | |||
d547ec3126 | |||
0ce6a7be7f | |||
1e5eae69e9 | |||
89d9208f44 | |||
3e80aaf242 | |||
86c3159ded | |||
230e05abc0 | |||
ff2e6e6432 | |||
dc00be9be6 | |||
77249d8a58 | |||
b9ee0afe7f | |||
db23ab0bc2 | |||
13dc47533c | |||
0091a888bc | |||
724b585004 | |||
c0d127e4f4 | |||
1638577d98 | |||
951c202fd0 | |||
a578b86715 | |||
b6b384854e | |||
dac937060d | |||
c628183773 | |||
eaacaa6966 | |||
9a09e280c9 | |||
70ac07d861 | |||
dabe372360 | |||
d8e3fdeb14 | |||
a147084458 | |||
b25e171412 | |||
60aaa03202 | |||
3392ab8385 | |||
f172b94467 | |||
ca549fe8d8 | |||
0b6f56a774 | |||
e5bcff12cb | |||
2754900f7a | |||
54f43d3331 | |||
4900200c06 | |||
6d82a74db4 | |||
2d7f21b021 | |||
4292c0c642 | |||
9dca515a42 | |||
b577cd9829 | |||
704682cbbe | |||
858f0d77c0 | |||
31ef6063f2 | |||
f3bd81c55b | |||
24bb4902c2 | |||
ca7821cfad | |||
a73b25580e | |||
82e179730e | |||
b5d5002061 | |||
2ab2c9e05e | |||
b1e9ba3ac6 | |||
5822ed0185 | |||
17b295788d | |||
6cd5b958c7 | |||
df92cc5f73 | |||
03106cdee3 | |||
c4638daf1b | |||
e2f5eb79ad | |||
b6c8e9bca0 | |||
573839019e | |||
815bf10ae0 | |||
7c257d97a7 | |||
59f8814660 | |||
1a6993099f | |||
f62ded3c8e | |||
4eca6366cc | |||
51a45b355d | |||
e5765cb902 | |||
6e922d2033 | |||
5d1695ada8 | |||
6e3ce29067 | |||
2b9bbc4cef | |||
9557145f72 | |||
249877b9c5 | |||
ff2321fde5 | |||
1edd6e4193 | |||
c7d47f128e | |||
14cb07efb2 | |||
a51724208c | |||
050e2b2b99 | |||
3706f15f7e | |||
bdde9162d9 | |||
99b4933536 | |||
c5caf7e0da | |||
bcc5308cfb | |||
9fb902db5c | |||
7461e38034 | |||
dccd85a151 | |||
910604fdad | |||
508cb9158e | |||
915c500d32 | |||
60bd6621c8 | |||
b5f6262763 | |||
2b8c4422de | |||
a686432c65 | |||
449e625877 | |||
1ac07dafde | |||
3878e28b56 | |||
cf6bc8666b | |||
f76063eb40 | |||
ed52c5824d | |||
9333400322 | |||
3689cfcc0d | |||
b73eceb535 | |||
5dc3453fc9 | |||
cef1139a4b | |||
ac96959947 | |||
4d73d877ba | |||
9f1186302e | |||
319dcc0d15 | |||
e99fdb8561 | |||
f37a342a63 | |||
09a039894d | |||
3efbb1a9fd | |||
920ee62ee3 | |||
1ace44fe31 | |||
a60f05415b | |||
42c9d39e02 | |||
a8186f1ed9 | |||
c2ff515a17 | |||
960c3ba558 | |||
454a9cd01c | |||
7d42ce1c87 | |||
57f6f980cf | |||
8cba3aae2c | |||
01b32f78ed | |||
b6066dfd5f | |||
3ad554ed59 | |||
6aacc6361b | |||
638e4e6410 | |||
aa9b7cccc7 | |||
41739c8528 | |||
89b32dc7fc | |||
44aec23251 | |||
12fd6160c5 | |||
8819abc418 | |||
96b627095c | |||
239f98aa9c | |||
f5d0511662 | |||
75582d2a26 | |||
dba004f924 | |||
5423a07c47 | |||
aba725372e | |||
a61aa9dd5d | |||
74349b20ce | |||
09ab9a1c8f | |||
abfe5789a3 | |||
67ebac496d | |||
60a2bf173b | |||
4e03f07864 | |||
aef1709d7f | |||
2f590f7be2 | |||
d5fa6ca89a | |||
8eaaffb25a | |||
28c5e2bab2 | |||
e212039f2c | |||
99b0b67f77 | |||
6ec9ba3c01 | |||
d7960a7dcf | |||
2a6e9af9c9 | |||
327e4d1f90 | |||
fffadd7b9e | |||
aaaf0d2e77 | |||
9f9a9b8c90 | |||
1f6edb3c0c | |||
142efb4f99 | |||
532655d2d5 | |||
287edabd90 | |||
7aaedbe2ce | |||
4cae1c673c | |||
8e01d836a9 | |||
f6dc8f0741 | |||
3a976d08d2 | |||
50e83b1eb5 | |||
61fbbb0b09 | |||
9e70e5c12e | |||
69d9b64468 | |||
0620d29880 | |||
b52dc74d9b | |||
a46aef2e7e | |||
736806a53d | |||
f1475e5cdf | |||
d04724c70a | |||
bacaadc16d | |||
c51dd235f0 | |||
92f2c9857e | |||
3998cc7f8b | |||
c126d080bc | |||
bc05f1714d | |||
e98becb94b | |||
250b94c8b5 | |||
47f03f6833 | |||
6e7ae48f78 | |||
526dbcc0e7 | |||
1abc5a5643 | |||
c81c350136 | |||
f90dc8bc7e | |||
072e22d072 | |||
59807c1bb0 | |||
7c19e1f1f7 | |||
3b9f915f57 | |||
d85cc530d4 | |||
2bb27c7642 | |||
e90e003204 | |||
b1e58e1add | |||
0fd836314a | |||
0bc3f08cc1 | |||
a78af5080a | |||
074e465284 | |||
bc8165d0ae | |||
ba8561d75a | |||
b2d381ba4b | |||
d39353d332 | |||
ee916af48e | |||
da1dc0309b | |||
30f4e7d833 | |||
cf3a86fb9b | |||
e1633f43f4 | |||
5b64cfc23c | |||
19709cf085 | |||
b8bb6c4f02 | |||
b7a543f8cb | |||
04b4e19563 | |||
ffb27fc66d | |||
8b5f7eefda | |||
c750bf4ee8 | |||
aa74019ef6 | |||
9be6d9f75f | |||
81ebb9b552 | |||
5e13b8c41f | |||
dd1ed948ec | |||
8b93f701cf | |||
2f0084de5b | |||
2ef9828625 | |||
89db8983a7 | |||
287dd9bd31 | |||
9a92054c1a | |||
4189036213 | |||
2c0a427ba5 | |||
77b488d624 | |||
5249e05746 | |||
1e7a0dd7a6 | |||
fd67f2402a | |||
60a65ede2f | |||
1fa659ce61 | |||
0ab903dbc7 | |||
70b0a04793 | |||
c0df9aa939 | |||
60a1886942 | |||
1ebf97871b | |||
72e321aa32 | |||
b0f602b565 | |||
84c774503d | |||
9bbc7cc651 | |||
458083fb6d | |||
8dcfc840b4 | |||
9d06a3a6ad | |||
86cd08b954 | |||
144c3cc082 | |||
802cef41a6 | |||
e128e8f0a9 | |||
8a25b93ab2 | |||
7a040935e9 | |||
2015882688 | |||
379301eb9d | |||
5d86b05cdb | |||
73c99d3157 | |||
acba197c94 | |||
2441d8ed8a | |||
9c123f37c8 | |||
b48dbd99cf | |||
25c8599d8f | |||
3453a17c15 | |||
6e95dacd3a | |||
a286e252e9 | |||
a8997e92c3 | |||
89137153a0 | |||
e3382de8e0 |
@ -231,6 +231,24 @@
|
|||||||
"contributions": [
|
"contributions": [
|
||||||
"code"
|
"code"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"login": "madmadson",
|
||||||
|
"name": "Tobias Matt",
|
||||||
|
"avatar_url": "https://avatars.githubusercontent.com/u/798831?v=4",
|
||||||
|
"profile": "https://github.com/madmadson",
|
||||||
|
"contributions": [
|
||||||
|
"code"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"login": "oliviergoulet5",
|
||||||
|
"name": "Olivier Goulet",
|
||||||
|
"avatar_url": "https://avatars.githubusercontent.com/u/17685861?v=4",
|
||||||
|
"profile": "https://github.com/oliviergoulet5",
|
||||||
|
"contributions": [
|
||||||
|
"code"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"contributorsPerLine": 7,
|
"contributorsPerLine": 7,
|
||||||
|
15
.github/workflows/ci.yaml
vendored
15
.github/workflows/ci.yaml
vendored
@ -16,8 +16,8 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
- uses: bahmutov/npm-install@v1
|
- uses: bahmutov/npm-install@v1
|
||||||
- name: If this step fails run 'yarn format' then commit again.
|
- name: If this step fails run 'npm run format' then commit again.
|
||||||
run: yarn format:check
|
run: npm run _format --list-different
|
||||||
test:
|
test:
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
needs: test_lint
|
needs: test_lint
|
||||||
@ -32,9 +32,8 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: ${{ matrix.node }}
|
node-version: ${{ matrix.node }}
|
||||||
- uses: bahmutov/npm-install@v1
|
- uses: bahmutov/npm-install@v1
|
||||||
- run: yarn build
|
- run: npm run build
|
||||||
- run: yarn test
|
- run: npm run test
|
||||||
#- run: yarn test:keycloakify-starter
|
|
||||||
|
|
||||||
storybook:
|
storybook:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@ -46,11 +45,11 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: '18'
|
node-version: '18'
|
||||||
- uses: bahmutov/npm-install@v1
|
- uses: bahmutov/npm-install@v1
|
||||||
- run: yarn build-storybook -o ./build_storybook
|
- run: npm run build-storybook
|
||||||
- run: git remote set-url origin https://git:${GITHUB_TOKEN}@github.com/${{github.repository}}.git
|
- run: git remote set-url origin https://git:${GITHUB_TOKEN}@github.com/${{github.repository}}.git
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
- run: npx -y -p gh-pages@3.1.0 gh-pages -d ./build_storybook -u "github-actions-bot <actions@github.com>"
|
- run: npx -y -p gh-pages@3.1.0 gh-pages -d ./storybook-static -u "github-actions-bot <actions@github.com>"
|
||||||
|
|
||||||
check_if_version_upgraded:
|
check_if_version_upgraded:
|
||||||
name: Check if version upgrade
|
name: Check if version upgrade
|
||||||
@ -112,7 +111,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
registry-url: https://registry.npmjs.org/
|
registry-url: https://registry.npmjs.org/
|
||||||
- uses: bahmutov/npm-install@v1
|
- uses: bahmutov/npm-install@v1
|
||||||
- run: yarn build
|
- run: npm run build
|
||||||
- run: npx -y -p denoify@1.6.12 enable_short_npm_import_path
|
- run: npx -y -p denoify@1.6.12 enable_short_npm_import_path
|
||||||
env:
|
env:
|
||||||
DRY_RUN: "0"
|
DRY_RUN: "0"
|
||||||
|
4
.gitignore
vendored
4
.gitignore
vendored
@ -48,8 +48,8 @@ jspm_packages
|
|||||||
|
|
||||||
.idea
|
.idea
|
||||||
|
|
||||||
/src/login/i18n/baseMessages/
|
/src/login/i18n/messages_defaultSet/
|
||||||
/src/account/i18n/baseMessages/
|
/src/account/i18n/messages_defaultSet/
|
||||||
|
|
||||||
# VS Code devcontainers
|
# VS Code devcontainers
|
||||||
.devcontainer
|
.devcontainer
|
||||||
|
@ -6,8 +6,8 @@ node_modules/
|
|||||||
/src/tools/types/
|
/src/tools/types/
|
||||||
/build_keycloak/
|
/build_keycloak/
|
||||||
/.vscode/
|
/.vscode/
|
||||||
/src/login/i18n/baseMessages/
|
/src/login/i18n/messages_defaultSet/
|
||||||
/src/account/i18n/baseMessages/
|
/src/account/i18n/messages_defaultSet/
|
||||||
/dist_test
|
/dist_test
|
||||||
/sample_react_project/
|
/sample_react_project/
|
||||||
/sample_custom_react_project/
|
/sample_custom_react_project/
|
||||||
|
@ -1,70 +0,0 @@
|
|||||||
|
|
||||||
import React from "react";
|
|
||||||
import { DocsContainer as BaseContainer } from "@storybook/addon-docs";
|
|
||||||
import { useDarkMode } from "storybook-dark-mode";
|
|
||||||
import { darkTheme, lightTheme } from "./customTheme";
|
|
||||||
import "./static/fonts/WorkSans/font.css";
|
|
||||||
|
|
||||||
export function DocsContainer({ children, context }) {
|
|
||||||
const isStorybookUiDark = useDarkMode();
|
|
||||||
|
|
||||||
const theme = isStorybookUiDark ? darkTheme : lightTheme;
|
|
||||||
|
|
||||||
const backgroundColor = theme.appBg;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<style>{`
|
|
||||||
body {
|
|
||||||
padding: 0 !important;
|
|
||||||
background-color: ${backgroundColor};
|
|
||||||
}
|
|
||||||
|
|
||||||
.docs-story {
|
|
||||||
background-color: ${backgroundColor};
|
|
||||||
}
|
|
||||||
[id^=story--] .container {
|
|
||||||
border: 1px dashed #e8e8e8;
|
|
||||||
}
|
|
||||||
|
|
||||||
.docblock-argstable-head th:nth-child(3), .docblock-argstable-body tr > td:nth-child(3) {
|
|
||||||
visibility: collapse;
|
|
||||||
}
|
|
||||||
|
|
||||||
.docblock-argstable-head th:nth-child(3), .docblock-argstable-body tr > td:nth-child(2) p {
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
`}</style>
|
|
||||||
<BaseContainer
|
|
||||||
context={{
|
|
||||||
...context,
|
|
||||||
"storyById": id => {
|
|
||||||
const storyContext = context.storyById(id);
|
|
||||||
return {
|
|
||||||
...storyContext,
|
|
||||||
"parameters": {
|
|
||||||
...storyContext?.parameters,
|
|
||||||
"docs": {
|
|
||||||
...storyContext?.parameters?.docs,
|
|
||||||
"theme": isStorybookUiDark ? darkTheme : lightTheme
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</BaseContainer>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function CanvasContainer({ children }) {
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{children}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
|
|
||||||
}
|
|
@ -1,35 +0,0 @@
|
|||||||
import { create } from "@storybook/theming";
|
|
||||||
|
|
||||||
const brandImage = "logo.png";
|
|
||||||
const brandTitle = "Keycloakify";
|
|
||||||
const brandUrl = "https://github.com/keycloakify/keycloakify";
|
|
||||||
const fontBase = '"Work Sans", sans-serif';
|
|
||||||
const fontCode = "monospace";
|
|
||||||
|
|
||||||
export const darkTheme = create({
|
|
||||||
"base": "dark",
|
|
||||||
"appBg": "#1E1E1E",
|
|
||||||
"appContentBg": "#161616",
|
|
||||||
"barBg": "#161616",
|
|
||||||
"colorSecondary": "#8585F6",
|
|
||||||
"textColor": "#FFFFFF",
|
|
||||||
brandImage,
|
|
||||||
brandTitle,
|
|
||||||
brandUrl,
|
|
||||||
fontBase,
|
|
||||||
fontCode
|
|
||||||
});
|
|
||||||
|
|
||||||
export const lightTheme = create({
|
|
||||||
"base": "light",
|
|
||||||
"appBg": "#F6F6F6",
|
|
||||||
"appContentBg": "#FFFFFF",
|
|
||||||
"barBg": "#FFFFFF",
|
|
||||||
"colorSecondary": "#000091",
|
|
||||||
"textColor": "#212121",
|
|
||||||
brandImage,
|
|
||||||
brandTitle,
|
|
||||||
brandUrl,
|
|
||||||
fontBase,
|
|
||||||
fontCode
|
|
||||||
});
|
|
33
.storybook/customTheme.ts
Normal file
33
.storybook/customTheme.ts
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
const brandImage = "logo.png";
|
||||||
|
const brandTitle = "Keycloakify";
|
||||||
|
const brandUrl = "https://github.com/keycloakify/keycloakify";
|
||||||
|
const fontBase = '"Work Sans", sans-serif';
|
||||||
|
const fontCode = "monospace";
|
||||||
|
|
||||||
|
export const darkTheme = {
|
||||||
|
base: "dark",
|
||||||
|
appBg: "#1E1E1E",
|
||||||
|
appContentBg: "#161616",
|
||||||
|
barBg: "#161616",
|
||||||
|
colorSecondary: "#8585F6",
|
||||||
|
textColor: "#FFFFFF",
|
||||||
|
brandImage,
|
||||||
|
brandTitle,
|
||||||
|
brandUrl,
|
||||||
|
fontBase,
|
||||||
|
fontCode
|
||||||
|
};
|
||||||
|
|
||||||
|
export const lightTheme: typeof darkTheme = {
|
||||||
|
base: "light",
|
||||||
|
appBg: "#F6F6F6",
|
||||||
|
appContentBg: "#FFFFFF",
|
||||||
|
barBg: "#FFFFFF",
|
||||||
|
colorSecondary: "#000091",
|
||||||
|
textColor: "#212121",
|
||||||
|
brandImage,
|
||||||
|
brandTitle,
|
||||||
|
brandUrl,
|
||||||
|
fontBase,
|
||||||
|
fontCode
|
||||||
|
};
|
@ -1,15 +1,13 @@
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
"stories": [
|
stories: [
|
||||||
"../stories/**/*.stories.@(ts|tsx|mdx)"
|
"../stories/**/*.stories.tsx"
|
||||||
],
|
],
|
||||||
"addons": [
|
addons: [
|
||||||
"@storybook/addon-links",
|
|
||||||
"@storybook/addon-essentials",
|
|
||||||
"storybook-dark-mode",
|
"storybook-dark-mode",
|
||||||
"@storybook/addon-a11y"
|
"@storybook/addon-a11y"
|
||||||
],
|
],
|
||||||
"core": {
|
core: {
|
||||||
"builder": "webpack5"
|
builder: "webpack5"
|
||||||
},
|
},
|
||||||
"staticDirs": ["./static"]
|
staticDirs: ["./static"]
|
||||||
};
|
};
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import { addons } from '@storybook/addons';
|
import { addons } from '@storybook/addons';
|
||||||
|
|
||||||
addons.setConfig({
|
addons.setConfig({
|
||||||
"selectedPanel": 'storybook/a11y/panel',
|
selectedPanel: 'storybook/a11y/panel',
|
||||||
"showPanel": false,
|
showPanel: false
|
||||||
});
|
});
|
||||||
|
@ -1,3 +1,9 @@
|
|||||||
|
<link rel="preload" href="/fonts/WorkSans/worksans-bold-webfont.woff2" as="font" crossorigin="anonymous">
|
||||||
|
<link rel="preload" href="/fonts/WorkSans/worksans-medium-webfont.woff2" as="font" crossorigin="anonymous">
|
||||||
|
<link rel="preload" href="/fonts/WorkSans/worksans-regular-webfont.woff2" as="font" crossorigin="anonymous">
|
||||||
|
<link rel="preload" href="/fonts/WorkSans/worksans-semibold-webfont.woff2" as="font" crossorigin="anonymous">
|
||||||
|
<link rel="stylesheet" type="text/css" href="/fonts/WorkSans/font.css">
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
body.sb-show-main.sb-main-padded {
|
body.sb-show-main.sb-main-padded {
|
||||||
padding: 0;
|
padding: 0;
|
||||||
|
@ -1,116 +1,105 @@
|
|||||||
import { darkTheme, lightTheme } from "./customTheme";
|
import { darkTheme, lightTheme } from "./customTheme";
|
||||||
import { DocsContainer, CanvasContainer } from "./Containers";
|
import { create as createTheme } from "@storybook/theming";
|
||||||
|
|
||||||
export const parameters = {
|
export const parameters = {
|
||||||
"actions": { "argTypesRegex": "^on[A-Z].*" },
|
actions: { argTypesRegex: "^on[A-Z].*" },
|
||||||
"controls": {
|
controls: {
|
||||||
"matchers": {
|
matchers: {
|
||||||
"color": /(background|color)$/i,
|
color: /(background|color)$/i,
|
||||||
"date": /Date$/,
|
date: /Date$/,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"backgrounds": { "disable": true },
|
backgrounds: { disable: true },
|
||||||
"darkMode": {
|
darkMode: {
|
||||||
"light": lightTheme,
|
light: createTheme(lightTheme),
|
||||||
"dark": darkTheme,
|
dark: createTheme(darkTheme),
|
||||||
},
|
},
|
||||||
"docs": {
|
controls: {
|
||||||
"container": DocsContainer
|
disable: true,
|
||||||
},
|
},
|
||||||
"controls": {
|
actions: {
|
||||||
"disable": true,
|
disable: true
|
||||||
},
|
},
|
||||||
"actions": {
|
viewport: {
|
||||||
"disable": true
|
viewports: {
|
||||||
},
|
|
||||||
"viewport": {
|
|
||||||
"viewports": {
|
|
||||||
"1440p": {
|
"1440p": {
|
||||||
"name": "1440p",
|
name: "1440p",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "2560px",
|
width: "2560px",
|
||||||
"height": "1440px",
|
height: "1440px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"fullHD": {
|
fullHD: {
|
||||||
"name": "Full HD",
|
name: "Full HD",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "1920px",
|
width: "1920px",
|
||||||
"height": "1080px",
|
height: "1080px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"macBookProBig": {
|
macBookProBig: {
|
||||||
"name": "MacBook Pro Big",
|
name: "MacBook Pro Big",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "1024px",
|
width: "1024px",
|
||||||
"height": "640px",
|
height: "640px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"macBookProMedium": {
|
macBookProMedium: {
|
||||||
"name": "MacBook Pro Medium",
|
name: "MacBook Pro Medium",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "1440px",
|
width: "1440px",
|
||||||
"height": "900px",
|
height: "900px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"macBookProSmall": {
|
macBookProSmall: {
|
||||||
"name": "MacBook Pro Small",
|
name: "MacBook Pro Small",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "1680px",
|
width: "1680px",
|
||||||
"height": "1050px",
|
height: "1050px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"pcAgent": {
|
pcAgent: {
|
||||||
"name": "PC Agent",
|
name: "PC Agent",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "960px",
|
width: "960px",
|
||||||
"height": "540px",
|
height: "540px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"iphone12Pro": {
|
iphone12Pro: {
|
||||||
"name": "Iphone 12 pro",
|
name: "Iphone 12 pro",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "390px",
|
width: "390px",
|
||||||
"height": "844px",
|
height: "844px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"iphone5se": {
|
iphone5se: {
|
||||||
"name": "Iphone 5/SE",
|
name: "Iphone 5/SE",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "320px",
|
width: "320px",
|
||||||
"height": "568px",
|
height: "568px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"ipadPro": {
|
ipadPro: {
|
||||||
"name": "Ipad pro",
|
name: "Ipad pro",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "1240px",
|
width: "1240px",
|
||||||
"height": "1366px",
|
height: "1366px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"Galaxy s9+": {
|
"Galaxy s9+": {
|
||||||
"name": "Galaxy S9+",
|
name: "Galaxy S9+",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "320px",
|
width: "320px",
|
||||||
"height": "658px",
|
height: "658px",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"options": {
|
options: {
|
||||||
"storySort": (a, b) =>
|
storySort: (a, b) =>
|
||||||
getHardCodedWeight(b[1].kind) - getHardCodedWeight(a[1].kind),
|
getHardCodedWeight(b[1].kind) - getHardCodedWeight(a[1].kind),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export const decorators = [
|
|
||||||
(Story) => (
|
|
||||||
<CanvasContainer>
|
|
||||||
<Story />
|
|
||||||
</CanvasContainer>
|
|
||||||
),
|
|
||||||
];
|
|
||||||
|
|
||||||
const { getHardCodedWeight } = (() => {
|
const { getHardCodedWeight } = (() => {
|
||||||
|
|
||||||
const orderedPagesPrefix = [
|
const orderedPagesPrefix = [
|
||||||
|
285
README.md
285
README.md
@ -2,7 +2,7 @@
|
|||||||
<img src="https://user-images.githubusercontent.com/6702424/109387840-eba11f80-7903-11eb-9050-db1dad883f78.png">
|
<img src="https://user-images.githubusercontent.com/6702424/109387840-eba11f80-7903-11eb-9050-db1dad883f78.png">
|
||||||
</p>
|
</p>
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<i>🔏 Create Keycloak themes using React 🔏</i>
|
<i>🔏 Keycloak Theming for the Modern Web 🔏</i>
|
||||||
<br>
|
<br>
|
||||||
<br>
|
<br>
|
||||||
<a href="https://github.com/garronej/keycloakify/actions">
|
<a href="https://github.com/garronej/keycloakify/actions">
|
||||||
@ -17,9 +17,12 @@
|
|||||||
<a href="https://github.com/thomasdarimont/awesome-keycloak">
|
<a href="https://github.com/thomasdarimont/awesome-keycloak">
|
||||||
<img src="https://awesome.re/mentioned-badge.svg"/>
|
<img src="https://awesome.re/mentioned-badge.svg"/>
|
||||||
</a>
|
</a>
|
||||||
<a href="https://discord.gg/kYFZG7fQmn">
|
<p align="center">
|
||||||
<img src="https://img.shields.io/discord/1097708346976505977"/>
|
Check out our discord server!<br/>
|
||||||
</a>
|
<a href="https://discord.gg/mJdYJSdcm4">
|
||||||
|
<img src="https://dcbadge.limes.pink/api/server/kYFZG7fQmn"/>
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://www.keycloakify.dev">Home</a>
|
<a href="https://www.keycloakify.dev">Home</a>
|
||||||
-
|
-
|
||||||
@ -35,23 +38,39 @@
|
|||||||
<i>This build tool generates a Keycloak theme <a href="https://www.keycloakify.dev">Learn more</a></i>
|
<i>This build tool generates a Keycloak theme <a href="https://www.keycloakify.dev">Learn more</a></i>
|
||||||
<br/>
|
<br/>
|
||||||
<br/>
|
<br/>
|
||||||
<img width="400" src="https://github.com/keycloakify/keycloakify/assets/6702424/e66d105c-c06f-47d1-8a31-a6ab09da4e80">
|
<img width="400" src="https://github.com/user-attachments/assets/6bf3bef9-00b0-4460-97b9-0d2da8500798">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
Keycloakify is fully compatible with Keycloak 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, [~~22~~](https://github.com/keycloakify/keycloakify/issues/389#issuecomment-1822509763), **23** [and up](https://github.com/keycloakify/keycloakify/discussions/346#discussioncomment-5889791)!
|
Keycloakify is fully compatible with Keycloak 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, [~~22~~](https://github.com/keycloakify/keycloakify/issues/389#issuecomment-1822509763), 23, 24, 25...[and beyond](https://github.com/keycloakify/keycloakify/discussions/346#discussioncomment-5889791)
|
||||||
|
|
||||||
> NOTE: Keycloak 24 introduces [important changes](https://www.keycloak.org/docs/latest/upgrading/index.html#changes-to-freemarker-templates-to-render-pages-based-on-the-user-profile-and-realm).
|
> NOTE: Keycloakify 10, while still being tagged as release candidate is the version you should use if you are starting today.
|
||||||
> We're actively working on incorporating them into Keycloakify. [Follow progress](https://github.com/keycloakify/keycloakify/pull/538).
|
> Use `yarn add keycloakify@next` or pin [the latest version candidate](https://www.npmjs.com/package/keycloakify?activeTab=versions).
|
||||||
|
|
||||||
## Sponsor
|
## Sponsors
|
||||||
|
|
||||||
We are exclusively sponsored by [Cloud IAM](https://cloud-iam.com/?mtm_campaign=keycloakify-deal&mtm_source=keycloakify-github), a French company offering Keycloak as a service.
|
Friends for the project, we trust and recommend their services.
|
||||||
Their dedicated support helps us continue the development and maintenance of this project.
|
|
||||||
|
|
||||||
[Cloud IAM](https://cloud-iam.com/?mtm_campaign=keycloakify-deal&mtm_source=keycloakify-github) provides the following services:
|
<br/>
|
||||||
|
|
||||||
- Simplify and secure your Keycloak Identity and Access Management. Keycloak as a Service.
|
<div align="center">
|
||||||
- Custom theme building for your brand using Keycloakify.
|
|
||||||
|

|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<br/>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.zone2.tech/services/keycloak-consulting">
|
||||||
|
<i><strong>Keycloak Consulting Services</strong> - Your partner in Keycloak deployment, configuration, and extension development for optimized identity management solutions.</i>
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
@ -66,13 +85,11 @@ Their dedicated support helps us continue the development and maintenance of thi
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<i>Checkout <a href="https://cloud-iam.com/?mtm_campaign=keycloakify-deal&mtm_source=keycloakify-github">Cloud-IAM</a> and use promo code <code>keycloakify5</code></i>
|
<a href="https://cloud-iam.com/?mtm_campaign=keycloakify-deal&mtm_source=keycloakify-github"><strong>Managed Keycloak Provider</strong> - With Cloud-IAM powering your Keycloak clusters, you can sleep easy knowing you've got the software and the experts you need for operational excellence. </a>
|
||||||
<br/>
|
<br/>
|
||||||
<i>5% of your annual subscription will be donated to us, and you'll get 5% off too.</i>
|
Use code <code>keycloakify5</code> at checkout for a 5% discount.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
Thank you, [Cloud-IAM](https://cloud-iam.com/?mtm_campaign=keycloakify-deal&mtm_source=keycloakify-github), for your support!
|
|
||||||
|
|
||||||
## Contributors ✨
|
## Contributors ✨
|
||||||
|
|
||||||
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
|
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
|
||||||
@ -114,7 +131,8 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
|
|||||||
<td align="center" valign="top" width="14.28%"><a href="https://m-siemens.de/"><img src="https://avatars.githubusercontent.com/u/1873922?v=4?s=100" width="100px;" alt="Markus Siemens"/><br /><sub><b>Markus Siemens</b></sub></a><br /><a href="https://github.com/keycloakify/keycloakify/commits?author=msiemens" title="Code">💻</a></td>
|
<td align="center" valign="top" width="14.28%"><a href="https://m-siemens.de/"><img src="https://avatars.githubusercontent.com/u/1873922?v=4?s=100" width="100px;" alt="Markus Siemens"/><br /><sub><b>Markus Siemens</b></sub></a><br /><a href="https://github.com/keycloakify/keycloakify/commits?author=msiemens" title="Code">💻</a></td>
|
||||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/law108000"><img src="https://avatars.githubusercontent.com/u/8112024?v=4?s=100" width="100px;" alt="Rlok"/><br /><sub><b>Rlok</b></sub></a><br /><a href="https://github.com/keycloakify/keycloakify/commits?author=law108000" title="Code">💻</a></td>
|
<td align="center" valign="top" width="14.28%"><a href="https://github.com/law108000"><img src="https://avatars.githubusercontent.com/u/8112024?v=4?s=100" width="100px;" alt="Rlok"/><br /><sub><b>Rlok</b></sub></a><br /><a href="https://github.com/keycloakify/keycloakify/commits?author=law108000" title="Code">💻</a></td>
|
||||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/Moulyy"><img src="https://avatars.githubusercontent.com/u/115405804?v=4?s=100" width="100px;" alt="Moulyy"/><br /><sub><b>Moulyy</b></sub></a><br /><a href="https://github.com/keycloakify/keycloakify/commits?author=Moulyy" title="Code">💻</a></td>
|
<td align="center" valign="top" width="14.28%"><a href="https://github.com/Moulyy"><img src="https://avatars.githubusercontent.com/u/115405804?v=4?s=100" width="100px;" alt="Moulyy"/><br /><sub><b>Moulyy</b></sub></a><br /><a href="https://github.com/keycloakify/keycloakify/commits?author=Moulyy" title="Code">💻</a></td>
|
||||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/giorgoslytos"><img src="https://avatars.githubusercontent.com/u/50946162?v=4?s=100" width="100px;" alt="giorgoslytos"/><br /><sub><b>giorgoslytos</b></sub></a><br /><a href="https://github.com/keycloakify/keycloakify/commits?author=giorgoslytos" title="Code">💻</a></td>
|
<td align="center" valign="top" width="14.28%"><a href="https://github.com/madmadson"><img src="https://avatars.githubusercontent.com/u/798831?v=4?s=100" width="100px;" alt="Tobias Matt"/><br /><sub><b>Tobias Matt</b></sub></a><br /><a href="https://github.com/keycloakify/keycloakify/commits?author=madmadson" title="Code">💻</a></td>
|
||||||
|
<td align="center" valign="top" width="14.28%"><a href="https://github.com/oliviergoulet5"><img src="https://avatars.githubusercontent.com/u/17685861?v=4?s=100" width="100px;" alt="Olivier Goulet"/><br /><sub><b>Olivier Goulet</b></sub></a><br /><a href="https://github.com/keycloakify/keycloakify/commits?author=oliviergoulet5" title="Code">💻</a></td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@ -123,230 +141,3 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
|
|||||||
<!-- prettier-ignore-end -->
|
<!-- prettier-ignore-end -->
|
||||||
|
|
||||||
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
||||||
|
|
||||||
# Changelog highlights
|
|
||||||
|
|
||||||
## 9.5
|
|
||||||
|
|
||||||
- Post build hook: You can now apply custom transformation to your theme files. [Learn more](https://docs.keycloakify.dev/build-options#postbuild-hook).
|
|
||||||
- You can now specify your option in the Keycloakify's Vite plugin instead in the package.json. [See example](https://docs.keycloakify.dev/build-options#themename).
|
|
||||||
|
|
||||||
## 9.4
|
|
||||||
|
|
||||||
**Vite Support! 🎉**
|
|
||||||
|
|
||||||
- [The starter is now a Vite project](https://github.com/keycloakify/keycloakify-starter).
|
|
||||||
The Webpack based starter is accessible [here](https://github.com/keycloakify/keycloakify-starter-cra).
|
|
||||||
- CRA (Webpack) remains supported for the forseable future.
|
|
||||||
- If you have a CRA Keycloakify theme that you wish to migrate to Vite checkout [this migration guide](https://docs.keycloakify.dev/migration-guides/cra-greater-than-vite).
|
|
||||||
|
|
||||||
## 9.0
|
|
||||||
|
|
||||||
Bring back support for account themes in Keycloak v23 and up! [See issue](https://github.com/keycloakify/keycloakify/issues/389).
|
|
||||||
|
|
||||||
### Breaking changes
|
|
||||||
|
|
||||||
Very few. Check them out [here](https://docs.keycloakify.dev/migration-guides/v8-greater-than-v9).
|
|
||||||
|
|
||||||
## 8.0
|
|
||||||
|
|
||||||
- Much smaller .jar size. 70.2 MB -> 7.8 MB.
|
|
||||||
Keycloakify now detects which of the static resources from the default theme are actually used by your theme and only include those in the .jar.
|
|
||||||
- Build time: The first build is slowed but the subsequent build are faster. [Update your CI so that the cache is persisted across CI build](https://github.com/keycloakify/keycloakify-starter/commit/bc378d5afb67e796f520afbc348185f3e319d9d0).
|
|
||||||
|
|
||||||
### Breaking changes
|
|
||||||
|
|
||||||
There are very few breaking changes in this major version. [Check them out](https://docs.keycloakify.dev/migration-guides/v7-greater-than-v8).
|
|
||||||
|
|
||||||
## 7.15
|
|
||||||
|
|
||||||
- The i18n messages you defines in your theme are now also maid available to Keycloak.
|
|
||||||
In practice this mean that you can now customize the `kcContext.message.summary` that
|
|
||||||
display a general alert and the values returned by `kcContext.messagesPerField.get()` that
|
|
||||||
are used to display specific error on some field of the form.
|
|
||||||
[See video](https://youtu.be/D6tZcemReTI)
|
|
||||||
|
|
||||||
## 7.14
|
|
||||||
|
|
||||||
- Deprecate the `extraPages` build option. Keycloakify is now able to analyze your code to detect extra pages.
|
|
||||||
|
|
||||||
## 7.13
|
|
||||||
|
|
||||||
- Deprecate `customUserAttribute`, Keycloakify now analyze your code to predict field name usage. [See doc](https://docs.keycloakify.dev/build-options#customuserattributes).
|
|
||||||
It's now mandatory to [adopt the new directory structure](https://docs.keycloakify.dev/migration-guides/v6-greater-than-v7).
|
|
||||||
|
|
||||||
## 7.12
|
|
||||||
|
|
||||||
- You can now pack multiple themes variant in a single `.jar` bundle. In vanilla Keycloak themes you have the ability to extend a base theme.
|
|
||||||
There is now an idiomatic way of achieving the same result. [Learn more](https://docs.keycloakify.dev/build-options#keycloakify.themeVariantNames).
|
|
||||||
|
|
||||||
## 7.9
|
|
||||||
|
|
||||||
- Separate script for copying the default theme static assets to the public directory.
|
|
||||||
Theses assets are only needed for testing your theme locally in Storybook or with a `mockPageId`.
|
|
||||||
You are now expected to have a `"prepare": "copy-keycloak-resources-to-public",` in your package.json scripts.
|
|
||||||
This script will create `public/keycloak-assets` when you run `yarn install` (If you are using another package manager
|
|
||||||
like `pnpm` makes sure that `"prepare"` is actually ran.)
|
|
||||||
[See the updated starter](https://github.com/keycloakify/keycloakify-starter/blob/94532fcf10bf8b19e0873be8575fd28a8958a806/package.json#L11). `public/keycloak-assets` shouldn't be tracked by GIT and is automatically ignored.
|
|
||||||
|
|
||||||
## 7.7
|
|
||||||
|
|
||||||
- Better storybook support, see [the starter project](https://github.com/keycloakify/keycloakify-starter).
|
|
||||||
|
|
||||||
## 7.0 🍾
|
|
||||||
|
|
||||||
- Account theme support 🚀
|
|
||||||
- It's much easier to customize pages at the CSS level, you can now see in the browser dev tool the customizable classes.
|
|
||||||
- New interactive CLI tool `npx eject-keycloak-page`, that enables to select the page you want to customize at the component level.
|
|
||||||
- There is [a Storybook](https://storybook.keycloakify.dev)
|
|
||||||
- [Remember me is fixed](https://github.com/keycloakify/keycloakify/pull/272)
|
|
||||||
|
|
||||||
## 6.13
|
|
||||||
|
|
||||||
- Build work behind corporate proxies, [see issue](https://github.com/keycloakify/keycloakify/issues/257).
|
|
||||||
|
|
||||||
## 6.12
|
|
||||||
|
|
||||||
Massive improvement in the developer experience:
|
|
||||||
|
|
||||||
- There is now only one starter repo: https://github.com/codegouvfr/keycloakify-starter
|
|
||||||
- A lot of comments have been added in the code of the starter to make it easier to get started.
|
|
||||||
- The doc has been updated: https://docs.keycloakify.dev
|
|
||||||
- A lot of improvements in the type system.
|
|
||||||
|
|
||||||
## 6.11.4
|
|
||||||
|
|
||||||
- You no longer need to have Maven installed to build the theme. Thanks to @lordvlad, [see PR](https://github.com/keycloakify/keycloakify/pull/239).
|
|
||||||
- Feature new build options: [`bundler`](https://docs.keycloakify.dev/build-options#keycloakify.bundler), [`groupId`](https://docs.keycloakify.dev/build-options#keycloakify.groupid), [`artifactId`](https://docs.keycloakify.dev/build-options#keycloakify.artifactid), [`version`](https://docs.keycloakify.dev/build-options#version).
|
|
||||||
Theses options can be user to customize the output name of the .jar. You can use environnement variables to overrides the values read in the package.json. Thanks to @lordvlad.
|
|
||||||
|
|
||||||
## 6.10.0
|
|
||||||
|
|
||||||
- Widows compat (thanks to @lordvlad, [see PR](https://github.com/keycloakify/keycloakify/pull/226)). WSL is no longer required 🎉
|
|
||||||
|
|
||||||
## 6.8.4
|
|
||||||
|
|
||||||
- `@emotion/react` is no longer a peer dependency of Keycloakify.
|
|
||||||
|
|
||||||
## 6.8.0
|
|
||||||
|
|
||||||
- It is now possible to pass a custom `<Template />` component as a prop to `<KcApp />` and every
|
|
||||||
individual page (`<Login />`, `<RegisterUserProfile />`, ...) it enables to customize only the header and footer for
|
|
||||||
example without having to switch to a full-component level customization. [See issue](https://github.com/keycloakify/keycloakify/issues/191).
|
|
||||||
|
|
||||||
## 6.7.0
|
|
||||||
|
|
||||||
- Add support for `webauthn-authenticate.ftl` thanks to [@mstrodl](https://github.com/Mstrodl)'s hacktoberfest [PR](https://github.com/keycloakify/keycloakify/pull/185).
|
|
||||||
|
|
||||||
## 6.6.0
|
|
||||||
|
|
||||||
- Add support for `login-password.ftl` thanks to [@mstrodl](https://github.com/Mstrodl)'s hacktoberfest [PR](https://github.com/keycloakify/keycloakify/pull/184).
|
|
||||||
|
|
||||||
## 6.5.0
|
|
||||||
|
|
||||||
- Add support for `login-username.ftl` thanks to [@mstrodl](https://github.com/Mstrodl)'s hacktoberfest [PR](https://github.com/keycloakify/keycloakify/pull/183).
|
|
||||||
|
|
||||||
## 6.4.0
|
|
||||||
|
|
||||||
- You can now optionally pass a `doFetchDefaultThemeResources: boolean` prop to every page component and the default `<KcApp />`
|
|
||||||
This enables you to prevent the default CSS and JS that comes with the builtin Keycloak theme to be downloaded.
|
|
||||||
You'll get [a black slate](https://user-images.githubusercontent.com/6702424/192619083-4baa5df4-4a21-4ec7-8e28-d200d1208299.png).
|
|
||||||
|
|
||||||
## 6.0.0
|
|
||||||
|
|
||||||
- Bundle size drastically reduced, locals and component dynamically loaded.
|
|
||||||
- First print much quicker, use of React.lazy() everywhere.
|
|
||||||
- Real i18n API.
|
|
||||||
- Actual documentation for build options.
|
|
||||||
|
|
||||||
Checkout [the migration guide](https://docs.keycloakify.dev/v5-to-v6)
|
|
||||||
|
|
||||||
## 5.8.0
|
|
||||||
|
|
||||||
- [React.lazy()](https://reactjs.org/docs/code-splitting.html#reactlazy) support 🎉. [#141](https://github.com/keycloakify/keycloakify/issues/141)
|
|
||||||
|
|
||||||
## 5.7.0
|
|
||||||
|
|
||||||
- Feat `logout-confirm.ftl`. [PR](https://github.com/keycloakify/keycloakify/pull/120)
|
|
||||||
|
|
||||||
## 5.6.4
|
|
||||||
|
|
||||||
Fix `login-verify-email.ftl` page. [Before](https://user-images.githubusercontent.com/6702424/177436014-0bad22c4-5bfb-45bb-8fc9-dad65143cd0c.png) - [After](https://user-images.githubusercontent.com/6702424/177435797-ec5d7db3-84cf-49cb-8efc-3427a81f744e.png)
|
|
||||||
|
|
||||||
## 5.6.0
|
|
||||||
|
|
||||||
Add support for `login-config-totp.ftl` page [#127](https://github.com/keycloakify/keycloakify/pull/127).
|
|
||||||
|
|
||||||
## 5.3.0
|
|
||||||
|
|
||||||
Rename `keycloak_theme_email` to `keycloak_email`.
|
|
||||||
If you already had a `keycloak_theme_email` you should rename it `keycloak_email`.
|
|
||||||
|
|
||||||
## 5.0.0
|
|
||||||
|
|
||||||
[Migration guide](https://github.com/garronej/keycloakify-demo-app/blob/a5b6a50f24bc25e082931f5ad9ebf47492acd12a/src/index.tsx#L46-L63)
|
|
||||||
New i18n system.
|
|
||||||
Import of terms and services have changed. [See example](https://github.com/garronej/keycloakify-demo-app/blob/a5b6a50f24bc25e082931f5ad9ebf47492acd12a/src/index.tsx#L46-L63).
|
|
||||||
|
|
||||||
## 4.10.0
|
|
||||||
|
|
||||||
Add `login-idp-link-email.ftl` page [See PR](https://github.com/keycloakify/keycloakify/pull/92).
|
|
||||||
|
|
||||||
## 4.8.0
|
|
||||||
|
|
||||||
[Email template customization.](#email-template-customization)
|
|
||||||
|
|
||||||
## 4.7.4
|
|
||||||
|
|
||||||
**M1 Mac** support (for testing locally with a dockerized Keycloak).
|
|
||||||
|
|
||||||
## 4.7.2
|
|
||||||
|
|
||||||
> WARNING: This is broken.
|
|
||||||
> Testing with local Keycloak container working with M1 Mac. Thanks to [@eduardosanzb](https://github.com/keycloakify/keycloakify/issues/43#issuecomment-975699658).
|
|
||||||
> Be aware: When running M1s you are testing with Keycloak v15 else the local container spun will be a Keycloak v16.1.0.
|
|
||||||
|
|
||||||
## 4.7.0
|
|
||||||
|
|
||||||
Register with user profile enabled: Out of the box `options` validator support.
|
|
||||||
[Example](https://user-images.githubusercontent.com/6702424/158911163-81e6bbe8-feb0-4dc8-abff-de199d7a678e.mov)
|
|
||||||
|
|
||||||
## 4.6.0
|
|
||||||
|
|
||||||
`tss-react` and `powerhooks` are no longer peer dependencies of `keycloakify`.
|
|
||||||
After updating Keycloakify you can remove `tss-react` and `powerhooks` from your dependencies if you don't use them explicitly.
|
|
||||||
|
|
||||||
## 4.5.3
|
|
||||||
|
|
||||||
There is a new recommended way to setup highly customized theme. See [here](https://github.com/garronej/keycloakify-demo-app/blob/look_and_feel/src/KcApp/KcApp.tsx).
|
|
||||||
Unlike with [the previous recommended method](https://github.com/garronej/keycloakify-demo-app/blob/a51660578bea15fb3e506b8a2b78e1056c6d68bb/src/KcApp/KcApp.tsx),
|
|
||||||
with this new method your theme wont break on minor Keycloakify update.
|
|
||||||
|
|
||||||
## 4.3.0
|
|
||||||
|
|
||||||
Feature [`login-update-password.ftl`](https://user-images.githubusercontent.com/6702424/147517600-6191cf72-93dd-437b-a35c-47180142063e.png).
|
|
||||||
Every time a page is added it's a breaking change for non CSS-only theme.
|
|
||||||
Change [this](https://github.com/garronej/keycloakify-demo-app/blob/df664c13c77ce3c53ac7df0622d94d04e76d3f9f/src/KcApp/KcApp.tsx#L17) and [this](https://github.com/garronej/keycloakify-demo-app/blob/df664c13c77ce3c53ac7df0622d94d04e76d3f9f/src/KcApp/KcApp.tsx#L37) to update.
|
|
||||||
|
|
||||||
## 4
|
|
||||||
|
|
||||||
- Out of the box [frontend form validation](#user-profile-and-frontend-form-validation) 🥳
|
|
||||||
- Improvements (and breaking changes in `import { useKcMessage } from "keycloakify"`.
|
|
||||||
|
|
||||||
## 3
|
|
||||||
|
|
||||||
No breaking changes except that `@emotion/react`, [`tss-react`](https://www.npmjs.com/package/tss-react) and [`powerhooks`](https://www.npmjs.com/package/powerhooks) are now `peerDependencies` instead of being just dependencies.
|
|
||||||
It's important to avoid problem when using `keycloakify` alongside [`mui`](https://mui.com) and
|
|
||||||
[when passing params from the app to the login page](https://github.com/keycloakify/keycloakify#implement-context-persistence-optional).
|
|
||||||
|
|
||||||
## 2.5
|
|
||||||
|
|
||||||
- Feature [Use advanced message](https://github.com/keycloakify/keycloakify/blob/59f106bf9e210b63b190826da2bf5f75fc8b7644/src/lib/i18n/useKcMessage.tsx#L53-L66)
|
|
||||||
and [`messagesPerFields`](https://github.com/keycloakify/keycloakify/blob/59f106bf9e210b63b190826da2bf5f75fc8b7644/src/lib/getKcContext/KcContextBase.ts#L70-L75) (implementation [here](https://github.com/keycloakify/keycloakify/blob/59f106bf9e210b63b190826da2bf5f75fc8b7644/src/bin/build-keycloak-theme/generateFtl/common.ftl#L130-L189))
|
|
||||||
- Test container now uses Keycloak version `15.0.2`.
|
|
||||||
|
|
||||||
## 2
|
|
||||||
|
|
||||||
- It's now possible to implement custom `.ftl` pages.
|
|
||||||
- Support for Keycloak plugins that introduce non standard ftl values.
|
|
||||||
(Like for example [this plugin](https://github.com/micedre/keycloak-mail-whitelisting) that define `authorizedMailDomains` in `register.ftl`).
|
|
||||||
|
49
package.json
49
package.json
@ -1,24 +1,23 @@
|
|||||||
{
|
{
|
||||||
"name": "keycloakify",
|
"name": "keycloakify",
|
||||||
"version": "10.0.0-rc.38",
|
"version": "10.0.0-rc.147",
|
||||||
"description": "Create Keycloak themes using React",
|
"description": "Create Keycloak themes using React",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git://github.com/keycloakify/keycloakify.git"
|
"url": "git://github.com/keycloakify/keycloakify.git"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepare": "patch-package && ts-node --skipProject scripts/generate-i18n-messages.ts",
|
"prepare": "tsx scripts/generate-i18n-messages.ts",
|
||||||
"build": "ts-node --skipProject scripts/build.ts",
|
"build": "tsx scripts/build.ts",
|
||||||
"storybook": "ts-node --skipProject scripts/start-storybook.ts",
|
"storybook": "tsx scripts/start-storybook.ts",
|
||||||
"link-in-starter": "ts-node --skipProject scripts/link-in-starter.ts",
|
"link-in-starter": "tsx scripts/link-in-starter.ts",
|
||||||
"test": "yarn test:types && vitest run",
|
"test": "yarn test:types && vitest run",
|
||||||
"test:types": "tsc -p test/tsconfig.json --noEmit",
|
"test:types": "tsc -p test/tsconfig.json --noEmit",
|
||||||
"_format": "prettier '**/*.{ts,tsx,json,md}'",
|
"_format": "prettier '**/*.{ts,tsx,json,md}'",
|
||||||
"format": "yarn _format --write",
|
"format": "yarn _format --write",
|
||||||
"format:check": "yarn _format --list-different",
|
"link-in-app": "tsx scripts/link-in-app.ts",
|
||||||
"link-in-app": "ts-node --skipProject scripts/link-in-app.ts",
|
"build-storybook": "tsx scripts/build-storybook.ts",
|
||||||
"build-storybook": "ts-node --skipProject scripts/build-storybook.ts",
|
"dump-keycloak-realm": "tsx scripts/dump-keycloak-realm.ts"
|
||||||
"dump-keycloak-realm": "ts-node --skipProject scripts/dump-keycloak-realm.ts"
|
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"keycloakify": "dist/bin/main.js"
|
"keycloakify": "dist/bin/main.js"
|
||||||
@ -41,13 +40,14 @@
|
|||||||
"!dist/bin/",
|
"!dist/bin/",
|
||||||
"dist/bin/main.js",
|
"dist/bin/main.js",
|
||||||
"dist/bin/*.index.js",
|
"dist/bin/*.index.js",
|
||||||
|
"dist/bin/*.node",
|
||||||
"dist/bin/shared/constants.js",
|
"dist/bin/shared/constants.js",
|
||||||
"dist/bin/shared/constants.d.ts",
|
"dist/bin/shared/*.d.ts",
|
||||||
"dist/bin/shared/constants.js.map",
|
"dist/bin/shared/*.js.map",
|
||||||
"!dist/vite-plugin/",
|
"!dist/vite-plugin/",
|
||||||
|
"dist/vite-plugin/index.js",
|
||||||
"dist/vite-plugin/index.d.ts",
|
"dist/vite-plugin/index.d.ts",
|
||||||
"dist/vite-plugin/vite-plugin.d.ts",
|
"dist/vite-plugin/vite-plugin.d.ts"
|
||||||
"dist/vite-plugin/index.js"
|
|
||||||
],
|
],
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"keycloak",
|
"keycloak",
|
||||||
@ -61,11 +61,7 @@
|
|||||||
"bluehats"
|
"bluehats"
|
||||||
],
|
],
|
||||||
"homepage": "https://www.keycloakify.dev",
|
"homepage": "https://www.keycloakify.dev",
|
||||||
"peerDependencies": {
|
|
||||||
"react": "*"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"react-markdown": "^5.0.3",
|
|
||||||
"tsafe": "^1.6.6"
|
"tsafe": "^1.6.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@ -76,14 +72,10 @@
|
|||||||
"@emotion/react": "^11.11.4",
|
"@emotion/react": "^11.11.4",
|
||||||
"@octokit/rest": "^20.1.1",
|
"@octokit/rest": "^20.1.1",
|
||||||
"@storybook/addon-a11y": "^6.5.16",
|
"@storybook/addon-a11y": "^6.5.16",
|
||||||
"@storybook/addon-actions": "^6.5.13",
|
|
||||||
"@storybook/addon-essentials": "^6.5.13",
|
|
||||||
"@storybook/addon-interactions": "^6.5.13",
|
|
||||||
"@storybook/addon-links": "^6.5.13",
|
|
||||||
"@storybook/builder-webpack5": "^6.5.13",
|
"@storybook/builder-webpack5": "^6.5.13",
|
||||||
"@storybook/manager-webpack5": "^6.5.13",
|
"@storybook/manager-webpack5": "^6.5.13",
|
||||||
"@storybook/react": "^6.5.13",
|
"@storybook/react": "^6.5.13",
|
||||||
"@storybook/testing-library": "^0.0.13",
|
"eslint-plugin-storybook": "^0.6.7",
|
||||||
"@types/babel__generator": "^7.6.4",
|
"@types/babel__generator": "^7.6.4",
|
||||||
"@types/make-fetch-happen": "^10.0.1",
|
"@types/make-fetch-happen": "^10.0.1",
|
||||||
"@types/minimist": "^1.2.2",
|
"@types/minimist": "^1.2.2",
|
||||||
@ -93,15 +85,13 @@
|
|||||||
"@types/yauzl": "^2.10.3",
|
"@types/yauzl": "^2.10.3",
|
||||||
"@vercel/ncc": "^0.38.1",
|
"@vercel/ncc": "^0.38.1",
|
||||||
"chalk": "^4.1.2",
|
"chalk": "^4.1.2",
|
||||||
"cheerio": "^1.0.0-rc.12",
|
"cheerio": "1.0.0-rc.12",
|
||||||
"chokidar-cli": "^3.0.0",
|
"chokidar-cli": "^3.0.0",
|
||||||
"cli-select": "^1.1.2",
|
"cli-select": "^1.1.2",
|
||||||
"eslint-plugin-storybook": "^0.6.7",
|
|
||||||
"husky": "^4.3.8",
|
"husky": "^4.3.8",
|
||||||
"lint-staged": "^11.0.0",
|
"lint-staged": "^11.0.0",
|
||||||
"magic-string": "^0.30.7",
|
"magic-string": "^0.30.7",
|
||||||
"make-fetch-happen": "^11.0.3",
|
"make-fetch-happen": "^11.0.3",
|
||||||
"patch-package": "^8.0.0",
|
|
||||||
"powerhooks": "^1.0.10",
|
"powerhooks": "^1.0.10",
|
||||||
"prettier": "^3.2.5",
|
"prettier": "^3.2.5",
|
||||||
"properties-parser": "^0.3.1",
|
"properties-parser": "^0.3.1",
|
||||||
@ -109,17 +99,16 @@
|
|||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
"recast": "^0.23.3",
|
"recast": "^0.23.3",
|
||||||
"run-exclusive": "^2.2.19",
|
"run-exclusive": "^2.2.19",
|
||||||
"scripting-tools": "^0.19.13",
|
|
||||||
"storybook-dark-mode": "^1.1.2",
|
"storybook-dark-mode": "^1.1.2",
|
||||||
"termost": "^0.12.0",
|
"termost": "^v0.12.1",
|
||||||
"ts-node": "^10.9.2",
|
|
||||||
"tsc-alias": "^1.8.10",
|
"tsc-alias": "^1.8.10",
|
||||||
"tss-react": "^4.9.10",
|
"tss-react": "^4.9.10",
|
||||||
"typescript": "^4.9.1-beta",
|
"typescript": "^4.9.4",
|
||||||
"vite": "^5.2.11",
|
"vite": "^5.2.11",
|
||||||
"vitest": "^1.6.0",
|
"vitest": "^1.6.0",
|
||||||
"yauzl": "^2.10.0",
|
"yauzl": "^2.10.0",
|
||||||
"zod": "^3.17.10",
|
"zod": "^3.17.10",
|
||||||
"evt": "^2.5.7"
|
"evt": "^2.5.7",
|
||||||
|
"tsx": "^4.15.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
File diff suppressed because one or more lines are too long
@ -1,16 +1,13 @@
|
|||||||
import * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import { join } from "path";
|
import { copyKeycloakResourcesToStorybookStaticDir } from "./copyKeycloakResourcesToStorybookStaticDir";
|
||||||
|
|
||||||
run("yarn build");
|
(async () => {
|
||||||
|
run("yarn build");
|
||||||
|
|
||||||
run(`node ${join("dist", "bin", "main.js")} copy-keycloak-resources-to-public`, {
|
await copyKeycloakResourcesToStorybookStaticDir();
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
PUBLIC_DIR_PATH: join(".storybook", "static")
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
run("npx build-storybook");
|
run("npx build-storybook");
|
||||||
|
})();
|
||||||
|
|
||||||
function run(command: string, options?: { env?: NodeJS.ProcessEnv }) {
|
function run(command: string, options?: { env?: NodeJS.ProcessEnv }) {
|
||||||
console.log(`$ ${command}`);
|
console.log(`$ ${command}`);
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { join, relative } from "path";
|
import { join } from "path";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import { transformCodebase } from "../src/bin/tools/transformCodebase";
|
import { transformCodebase } from "../src/bin/tools/transformCodebase";
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
@ -16,7 +16,7 @@ if (fs.existsSync(join("dist", "bin", "main.original.js"))) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
fs.readdirSync(join("dist", "bin")).forEach(fileBasename => {
|
fs.readdirSync(join("dist", "bin")).forEach(fileBasename => {
|
||||||
if (/[0-9]\.index.js/.test(fileBasename)) {
|
if (/[0-9]\.index.js/.test(fileBasename) || fileBasename.endsWith(".node")) {
|
||||||
fs.rmSync(join("dist", "bin", fileBasename));
|
fs.rmSync(join("dist", "bin", fileBasename));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -111,9 +111,10 @@ run(
|
|||||||
)}`
|
)}`
|
||||||
);
|
);
|
||||||
|
|
||||||
fs.readdirSync(join("dist", "ncc_out")).forEach(fileBasename =>
|
fs.readdirSync(join("dist", "ncc_out")).forEach(fileBasename => {
|
||||||
assert(!fileBasename.endsWith(".index.js"))
|
assert(!fileBasename.endsWith(".index.js"));
|
||||||
);
|
assert(!fileBasename.endsWith(".node"));
|
||||||
|
});
|
||||||
|
|
||||||
transformCodebase({
|
transformCodebase({
|
||||||
srcDirPath: join("dist", "ncc_out"),
|
srcDirPath: join("dist", "ncc_out"),
|
||||||
|
18
scripts/copyKeycloakResourcesToStorybookStaticDir.ts
Normal file
18
scripts/copyKeycloakResourcesToStorybookStaticDir.ts
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import { join as pathJoin } from "path";
|
||||||
|
import { copyKeycloakResourcesToPublic } from "../src/bin/shared/copyKeycloakResourcesToPublic";
|
||||||
|
import { getProxyFetchOptions } from "../src/bin/tools/fetchProxyOptions";
|
||||||
|
import { LOGIN_THEME_RESOURCES_FROMkEYCLOAK_VERSION_DEFAULT } from "../src/bin/shared/constants";
|
||||||
|
|
||||||
|
export async function copyKeycloakResourcesToStorybookStaticDir() {
|
||||||
|
await copyKeycloakResourcesToPublic({
|
||||||
|
buildContext: {
|
||||||
|
cacheDirPath: pathJoin(__dirname, "..", "node_modules", ".cache", "scripts"),
|
||||||
|
fetchOptions: getProxyFetchOptions({
|
||||||
|
npmConfigGetCwd: pathJoin(__dirname, "..")
|
||||||
|
}),
|
||||||
|
loginThemeResourcesFromKeycloakVersion:
|
||||||
|
LOGIN_THEME_RESOURCES_FROMkEYCLOAK_VERSION_DEFAULT,
|
||||||
|
publicDirPath: pathJoin(__dirname, "..", ".storybook", "static")
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
@ -1,42 +1,89 @@
|
|||||||
import { containerName } from "../src/bin/shared/constants";
|
import { CONTAINER_NAME } from "../src/bin/shared/constants";
|
||||||
import child_process from "child_process";
|
import child_process from "child_process";
|
||||||
import { SemVer } from "../src/bin/tools/SemVer";
|
import { SemVer } from "../src/bin/tools/SemVer";
|
||||||
import { join as pathJoin, relative as pathRelative } from "path";
|
import { join as pathJoin, relative as pathRelative } from "path";
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
|
import { Deferred } from "evt/tools/Deferred";
|
||||||
|
import { assert } from "tsafe/assert";
|
||||||
|
import { is } from "tsafe/is";
|
||||||
|
|
||||||
run(
|
(async () => {
|
||||||
[
|
{
|
||||||
`docker exec -it ${containerName}`,
|
const dCompleted = new Deferred<void>();
|
||||||
`/opt/keycloak/bin/kc.sh export`,
|
|
||||||
`--dir /tmp`,
|
|
||||||
`--realm myrealm`,
|
|
||||||
`--users realm_file`
|
|
||||||
].join(" ")
|
|
||||||
);
|
|
||||||
|
|
||||||
const keycloakMajorVersionNumber = SemVer.parse(
|
const child = child_process.spawn(
|
||||||
child_process
|
"docker",
|
||||||
.execSync(`docker inspect --format '{{.Config.Image}}' ${containerName}`)
|
[
|
||||||
.toString("utf8")
|
...["exec", CONTAINER_NAME],
|
||||||
.trim()
|
...["/opt/keycloak/bin/kc.sh", "export"],
|
||||||
.split(":")[1]
|
...["--dir", "/tmp"],
|
||||||
).major;
|
...["--realm", "myrealm"],
|
||||||
|
...["--users", "realm_file"]
|
||||||
|
],
|
||||||
|
{ shell: true }
|
||||||
|
);
|
||||||
|
|
||||||
const targetFilePath = pathRelative(
|
let output = "";
|
||||||
process.cwd(),
|
|
||||||
pathJoin(
|
|
||||||
__dirname,
|
|
||||||
"..",
|
|
||||||
"src",
|
|
||||||
"bin",
|
|
||||||
"start-keycloak",
|
|
||||||
`myrealm-realm-${keycloakMajorVersionNumber}.json`
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
run(`docker cp ${containerName}:/tmp/myrealm-realm.json ${targetFilePath}`);
|
const onExit = (code: number | null) => {
|
||||||
|
dCompleted.reject(new Error(`Exited with code ${code}`));
|
||||||
|
};
|
||||||
|
|
||||||
console.log(`${chalk.green(`✓ Exported realm to`)} ${chalk.bold(targetFilePath)}`);
|
child.on("exit", onExit);
|
||||||
|
|
||||||
|
child.stdout.on("data", data => {
|
||||||
|
const outputStr = data.toString("utf8");
|
||||||
|
|
||||||
|
if (outputStr.includes("Export finished successfully")) {
|
||||||
|
child.removeListener("exit", onExit);
|
||||||
|
|
||||||
|
child.kill();
|
||||||
|
|
||||||
|
dCompleted.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
output += outputStr;
|
||||||
|
});
|
||||||
|
|
||||||
|
child.stderr.on("data", data => (output += chalk.red(data.toString("utf8"))));
|
||||||
|
|
||||||
|
try {
|
||||||
|
await dCompleted.pr;
|
||||||
|
} catch (error) {
|
||||||
|
assert(is<Error>(error));
|
||||||
|
|
||||||
|
console.log(chalk.red(error.message));
|
||||||
|
|
||||||
|
console.log(output);
|
||||||
|
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const keycloakMajorVersionNumber = SemVer.parse(
|
||||||
|
child_process
|
||||||
|
.execSync(`docker inspect --format '{{.Config.Image}}' ${CONTAINER_NAME}`)
|
||||||
|
.toString("utf8")
|
||||||
|
.trim()
|
||||||
|
.split(":")[1]
|
||||||
|
).major;
|
||||||
|
|
||||||
|
const targetFilePath = pathRelative(
|
||||||
|
process.cwd(),
|
||||||
|
pathJoin(
|
||||||
|
__dirname,
|
||||||
|
"..",
|
||||||
|
"src",
|
||||||
|
"bin",
|
||||||
|
"start-keycloak",
|
||||||
|
`myrealm-realm-${keycloakMajorVersionNumber}.json`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
run(`docker cp ${CONTAINER_NAME}:/tmp/myrealm-realm.json ${targetFilePath}`);
|
||||||
|
|
||||||
|
console.log(`${chalk.green(`✓ Exported realm to`)} ${chalk.bold(targetFilePath)}`);
|
||||||
|
})();
|
||||||
|
|
||||||
function run(command: string) {
|
function run(command: string) {
|
||||||
console.log(chalk.grey(`$ ${command}`));
|
console.log(chalk.grey(`$ ${command}`));
|
||||||
|
@ -12,6 +12,7 @@ import { crawl } from "../src/bin/tools/crawl";
|
|||||||
import { downloadKeycloakDefaultTheme } from "../src/bin/shared/downloadKeycloakDefaultTheme";
|
import { downloadKeycloakDefaultTheme } from "../src/bin/shared/downloadKeycloakDefaultTheme";
|
||||||
import { getThisCodebaseRootDirPath } from "../src/bin/tools/getThisCodebaseRootDirPath";
|
import { getThisCodebaseRootDirPath } from "../src/bin/tools/getThisCodebaseRootDirPath";
|
||||||
import { deepAssign } from "../src/tools/deepAssign";
|
import { deepAssign } from "../src/tools/deepAssign";
|
||||||
|
import { getProxyFetchOptions } from "../src/bin/tools/fetchProxyOptions";
|
||||||
|
|
||||||
// NOTE: To run without argument when we want to generate src/i18n/generated_kcMessages files,
|
// NOTE: To run without argument when we want to generate src/i18n/generated_kcMessages files,
|
||||||
// update the version array for generating for newer version.
|
// update the version array for generating for newer version.
|
||||||
@ -26,14 +27,16 @@ async function main() {
|
|||||||
|
|
||||||
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
||||||
keycloakVersion,
|
keycloakVersion,
|
||||||
buildOptions: {
|
buildContext: {
|
||||||
cacheDirPath: pathJoin(
|
cacheDirPath: pathJoin(
|
||||||
thisCodebaseRootDirPath,
|
thisCodebaseRootDirPath,
|
||||||
"node_modules",
|
"node_modules",
|
||||||
".cache",
|
".cache",
|
||||||
"keycloakify"
|
"keycloakify"
|
||||||
),
|
),
|
||||||
npmWorkspaceRootDirPath: thisCodebaseRootDirPath
|
fetchOptions: getProxyFetchOptions({
|
||||||
|
npmConfigGetCwd: thisCodebaseRootDirPath
|
||||||
|
})
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -65,11 +68,14 @@ async function main() {
|
|||||||
fs
|
fs
|
||||||
.readFileSync(pathJoin(baseThemeDirPath, filePath))
|
.readFileSync(pathJoin(baseThemeDirPath, filePath))
|
||||||
.toString("utf8")
|
.toString("utf8")
|
||||||
)
|
) as Record<string, string>
|
||||||
).map(([key, value]: any) => [
|
)
|
||||||
key === "locale_pt_BR" ? "locale_pt-BR" : key,
|
.map(([key, value]) => [key, value.replace(/''/g, "'")])
|
||||||
value.replace(/''/g, "'")
|
.map(([key, value]) => [
|
||||||
])
|
key === "locale_pt_BR" ? "locale_pt-BR" : key,
|
||||||
|
value
|
||||||
|
])
|
||||||
|
.map(([key, value]) => [key, key === "termsText" ? "" : value])
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -104,12 +110,12 @@ async function main() {
|
|||||||
source: keycloakifyExtraMessages
|
source: keycloakifyExtraMessages
|
||||||
});
|
});
|
||||||
|
|
||||||
const baseMessagesDirPath = pathJoin(
|
const messagesDirPath = pathJoin(
|
||||||
thisCodebaseRootDirPath,
|
thisCodebaseRootDirPath,
|
||||||
"src",
|
"src",
|
||||||
themeType,
|
themeType,
|
||||||
"i18n",
|
"i18n",
|
||||||
"baseMessages"
|
"messages_defaultSet"
|
||||||
);
|
);
|
||||||
|
|
||||||
const generatedFileHeader = [
|
const generatedFileHeader = [
|
||||||
@ -121,7 +127,7 @@ async function main() {
|
|||||||
].join("\n");
|
].join("\n");
|
||||||
|
|
||||||
languages.forEach(language => {
|
languages.forEach(language => {
|
||||||
const filePath = pathJoin(baseMessagesDirPath, `${language}.ts`);
|
const filePath = pathJoin(messagesDirPath, `${language}.ts`);
|
||||||
|
|
||||||
fs.mkdirSync(pathDirname(filePath), { recursive: true });
|
fs.mkdirSync(pathDirname(filePath), { recursive: true });
|
||||||
|
|
||||||
@ -149,14 +155,14 @@ async function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
pathJoin(baseMessagesDirPath, "index.ts"),
|
pathJoin(messagesDirPath, "index.ts"),
|
||||||
Buffer.from(
|
Buffer.from(
|
||||||
[
|
[
|
||||||
generatedFileHeader,
|
generatedFileHeader,
|
||||||
`import * as en from "./en";`,
|
`import * as en from "./en";`,
|
||||||
"",
|
"",
|
||||||
"export async function getMessages(currentLanguageTag: string) {",
|
"export async function fetchMessages_defaultSet(currentLanguageTag: string) {",
|
||||||
" const { default: messages } = await (() => {",
|
" const { default: messages_defaultSet } = await (() => {",
|
||||||
" switch (currentLanguageTag) {",
|
" switch (currentLanguageTag) {",
|
||||||
` case "en": return en;`,
|
` case "en": return en;`,
|
||||||
...languages
|
...languages
|
||||||
@ -168,7 +174,7 @@ async function main() {
|
|||||||
' default: return { "default": {} };',
|
' default: return { "default": {} };',
|
||||||
" }",
|
" }",
|
||||||
" })();",
|
" })();",
|
||||||
" return messages;",
|
" return messages_defaultSet;",
|
||||||
"}"
|
"}"
|
||||||
].join("\n"),
|
].join("\n"),
|
||||||
"utf8"
|
"utf8"
|
||||||
|
@ -2,66 +2,59 @@ import { execSync } from "child_process";
|
|||||||
import { join as pathJoin, relative as pathRelative } from "path";
|
import { join as pathJoin, relative as pathRelative } from "path";
|
||||||
import { getThisCodebaseRootDirPath } from "../src/bin/tools/getThisCodebaseRootDirPath";
|
import { getThisCodebaseRootDirPath } from "../src/bin/tools/getThisCodebaseRootDirPath";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
|
import * as os from "os";
|
||||||
|
|
||||||
const singletonDependencies: string[] = ["react", "@types/react"];
|
const singletonDependencies: string[] = ["react", "@types/react"];
|
||||||
|
|
||||||
|
// For example [ "@emotion" ] it's more convenient than
|
||||||
|
// having to list every sub emotion packages (@emotion/css @emotion/utils ...)
|
||||||
|
// in singletonDependencies
|
||||||
|
const namespaceSingletonDependencies: string[] = [];
|
||||||
|
|
||||||
const rootDirPath = getThisCodebaseRootDirPath();
|
const rootDirPath = getThisCodebaseRootDirPath();
|
||||||
|
|
||||||
|
const commonThirdPartyDeps = [
|
||||||
|
...namespaceSingletonDependencies
|
||||||
|
.map(namespaceModuleName =>
|
||||||
|
fs
|
||||||
|
.readdirSync(pathJoin(rootDirPath, "node_modules", namespaceModuleName))
|
||||||
|
.map(submoduleName => `${namespaceModuleName}/${submoduleName}`)
|
||||||
|
)
|
||||||
|
.reduce((prev, curr) => [...prev, ...curr], []),
|
||||||
|
...singletonDependencies
|
||||||
|
];
|
||||||
|
|
||||||
//NOTE: This is only required because of: https://github.com/garronej/ts-ci/blob/c0e207b9677523d4ec97fe672ddd72ccbb3c1cc4/README.md?plain=1#L54-L58
|
//NOTE: This is only required because of: https://github.com/garronej/ts-ci/blob/c0e207b9677523d4ec97fe672ddd72ccbb3c1cc4/README.md?plain=1#L54-L58
|
||||||
fs.writeFileSync(
|
{
|
||||||
pathJoin(rootDirPath, "dist", "package.json"),
|
let modifiedPackageJsonContent = fs
|
||||||
Buffer.from(
|
.readFileSync(pathJoin(rootDirPath, "package.json"))
|
||||||
JSON.stringify(
|
.toString("utf8");
|
||||||
(() => {
|
|
||||||
const packageJsonParsed = JSON.parse(
|
|
||||||
fs
|
|
||||||
.readFileSync(pathJoin(rootDirPath, "package.json"))
|
|
||||||
.toString("utf8")
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
modifiedPackageJsonContent = (() => {
|
||||||
...packageJsonParsed,
|
const o = JSON.parse(modifiedPackageJsonContent);
|
||||||
main: packageJsonParsed["main"]?.replace(/^dist\//, ""),
|
|
||||||
types: packageJsonParsed["types"]?.replace(/^dist\//, ""),
|
|
||||||
module: packageJsonParsed["module"]?.replace(/^dist\//, ""),
|
|
||||||
exports: !("exports" in packageJsonParsed)
|
|
||||||
? undefined
|
|
||||||
: Object.fromEntries(
|
|
||||||
Object.entries(packageJsonParsed["exports"]).map(
|
|
||||||
([key, value]) => [
|
|
||||||
key,
|
|
||||||
(value as string).replace(/^\.\/dist\//, "./")
|
|
||||||
]
|
|
||||||
)
|
|
||||||
)
|
|
||||||
};
|
|
||||||
})(),
|
|
||||||
null,
|
|
||||||
2
|
|
||||||
),
|
|
||||||
"utf8"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
const commonThirdPartyDeps = (() => {
|
delete o.files;
|
||||||
// For example [ "@emotion" ] it's more convenient than
|
|
||||||
// having to list every sub emotion packages (@emotion/css @emotion/utils ...)
|
|
||||||
// in singletonDependencies
|
|
||||||
const namespaceSingletonDependencies: string[] = [];
|
|
||||||
|
|
||||||
return [
|
return JSON.stringify(o, null, 2);
|
||||||
...namespaceSingletonDependencies
|
})();
|
||||||
.map(namespaceModuleName =>
|
|
||||||
fs
|
modifiedPackageJsonContent = modifiedPackageJsonContent
|
||||||
.readdirSync(
|
.replace(/"dist\//g, '"')
|
||||||
pathJoin(rootDirPath, "node_modules", namespaceModuleName)
|
.replace(/"\.\/dist\//g, '"./')
|
||||||
)
|
.replace(/"!dist\//g, '"!')
|
||||||
.map(submoduleName => `${namespaceModuleName}/${submoduleName}`)
|
.replace(/"!\.\/dist\//g, '"!./');
|
||||||
)
|
|
||||||
.reduce((prev, curr) => [...prev, ...curr], []),
|
modifiedPackageJsonContent = JSON.stringify(
|
||||||
...singletonDependencies
|
{ ...JSON.parse(modifiedPackageJsonContent), version: "0.0.0" },
|
||||||
];
|
null,
|
||||||
})();
|
4
|
||||||
|
);
|
||||||
|
|
||||||
|
fs.writeFileSync(
|
||||||
|
pathJoin(rootDirPath, "dist", "package.json"),
|
||||||
|
Buffer.from(modifiedPackageJsonContent, "utf8")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const yarnGlobalDirPath = pathJoin(rootDirPath, ".yarn_home");
|
const yarnGlobalDirPath = pathJoin(rootDirPath, ".yarn_home");
|
||||||
|
|
||||||
@ -83,7 +76,9 @@ const execYarnLink = (params: { targetModuleName?: string; cwd: string }) => {
|
|||||||
cwd,
|
cwd,
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
HOME: yarnGlobalDirPath
|
...(os.platform() === "win32"
|
||||||
|
? { USERPROFILE: yarnGlobalDirPath }
|
||||||
|
: { HOME: yarnGlobalDirPath })
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
@ -2,22 +2,49 @@ import * as child_process from "child_process";
|
|||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { join } from "path";
|
import { join } from "path";
|
||||||
import { startRebuildOnSrcChange } from "./startRebuildOnSrcChange";
|
import { startRebuildOnSrcChange } from "./startRebuildOnSrcChange";
|
||||||
|
import { crawl } from "../src/bin/tools/crawl";
|
||||||
|
|
||||||
|
{
|
||||||
|
const dirPath = "node_modules";
|
||||||
|
|
||||||
|
try {
|
||||||
|
fs.rmSync(dirPath, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// NOTE: This is a workaround for windows
|
||||||
|
// we can't remove locked executables.
|
||||||
|
|
||||||
|
crawl({
|
||||||
|
dirPath,
|
||||||
|
returnedPathsType: "absolute"
|
||||||
|
}).forEach(filePath => {
|
||||||
|
try {
|
||||||
|
fs.rmSync(filePath, { force: true });
|
||||||
|
} catch (error) {
|
||||||
|
if (filePath.endsWith(".exe")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fs.rmSync("node_modules", { recursive: true, force: true });
|
|
||||||
fs.rmSync("dist", { recursive: true, force: true });
|
fs.rmSync("dist", { recursive: true, force: true });
|
||||||
fs.rmSync(".yarn_home", { recursive: true, force: true });
|
fs.rmSync(".yarn_home", { recursive: true, force: true });
|
||||||
|
|
||||||
run("yarn install");
|
run("yarn install");
|
||||||
run("yarn build");
|
run("yarn build");
|
||||||
|
|
||||||
fs.rmSync(join("..", "keycloakify-starter", "node_modules"), {
|
const starterName = "keycloakify-starter";
|
||||||
|
|
||||||
|
fs.rmSync(join("..", starterName, "node_modules"), {
|
||||||
recursive: true,
|
recursive: true,
|
||||||
force: true
|
force: true
|
||||||
});
|
});
|
||||||
|
|
||||||
run("yarn install", { cwd: join("..", "keycloakify-starter") });
|
run("yarn install", { cwd: join("..", starterName) });
|
||||||
|
|
||||||
run(`npx ts-node --skipProject ${join("scripts", "link-in-app.ts")} keycloakify-starter`);
|
run(`npx tsx ${join("scripts", "link-in-app.ts")} ${starterName}`);
|
||||||
|
|
||||||
startRebuildOnSrcChange();
|
startRebuildOnSrcChange();
|
||||||
|
|
||||||
|
@ -1,28 +1,26 @@
|
|||||||
import * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import * as fs from "fs";
|
|
||||||
import { join } from "path";
|
|
||||||
import { startRebuildOnSrcChange } from "./startRebuildOnSrcChange";
|
import { startRebuildOnSrcChange } from "./startRebuildOnSrcChange";
|
||||||
|
import { copyKeycloakResourcesToStorybookStaticDir } from "./copyKeycloakResourcesToStorybookStaticDir";
|
||||||
|
|
||||||
run("yarn build");
|
(async () => {
|
||||||
|
run("yarn build");
|
||||||
|
|
||||||
run(`node ${join("dist", "bin", "main.js")} copy-keycloak-resources-to-public`, {
|
await copyKeycloakResourcesToStorybookStaticDir();
|
||||||
env: {
|
|
||||||
...process.env,
|
{
|
||||||
PUBLIC_DIR_PATH: join(".storybook", "static")
|
const child = child_process.spawn("npx", ["start-storybook", "-p", "6006"], {
|
||||||
|
shell: true
|
||||||
|
});
|
||||||
|
|
||||||
|
child.stdout.on("data", data => process.stdout.write(data));
|
||||||
|
|
||||||
|
child.stderr.on("data", data => process.stderr.write(data));
|
||||||
|
|
||||||
|
child.on("exit", process.exit.bind(process));
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
{
|
startRebuildOnSrcChange();
|
||||||
const child = child_process.spawn("npx", ["start-storybook", "-p", "6006"]);
|
})();
|
||||||
|
|
||||||
child.stdout.on("data", data => process.stdout.write(data));
|
|
||||||
|
|
||||||
child.stderr.on("data", data => process.stderr.write(data));
|
|
||||||
|
|
||||||
child.on("exit", process.exit.bind(process));
|
|
||||||
}
|
|
||||||
|
|
||||||
startRebuildOnSrcChange();
|
|
||||||
|
|
||||||
function run(command: string, options?: { env?: NodeJS.ProcessEnv }) {
|
function run(command: string, options?: { env?: NodeJS.ProcessEnv }) {
|
||||||
console.log(`$ ${command}`);
|
console.log(`$ ${command}`);
|
||||||
|
@ -13,7 +13,7 @@ export function startRebuildOnSrcChange() {
|
|||||||
|
|
||||||
const dCompleted = new Deferred<void>();
|
const dCompleted = new Deferred<void>();
|
||||||
|
|
||||||
const child = child_process.spawn("yarn", ["build"]);
|
const child = child_process.spawn("yarn", ["build"], { shell: true });
|
||||||
|
|
||||||
child.stdout.on("data", data => process.stdout.write(data));
|
child.stdout.on("data", data => process.stdout.write(data));
|
||||||
|
|
||||||
@ -28,9 +28,13 @@ export function startRebuildOnSrcChange() {
|
|||||||
|
|
||||||
console.log(chalk.green("Watching for changes in src/"));
|
console.log(chalk.green("Watching for changes in src/"));
|
||||||
|
|
||||||
chokidar.watch(["src", "stories"], { ignoreInitial: true }).on("all", async () => {
|
chokidar
|
||||||
await waitForDebounce();
|
.watch(["src", "stories"], { ignoreInitial: true })
|
||||||
|
.on("all", async (event, path) => {
|
||||||
|
console.log(chalk.bold(`${event}: ${path}`));
|
||||||
|
|
||||||
runYarnBuild();
|
await waitForDebounce();
|
||||||
});
|
|
||||||
|
runYarnBuild();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,4 @@
|
|||||||
import {
|
import { BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR } 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(
|
||||||
@ -20,5 +17,5 @@ export const PUBLIC_URL = (() => {
|
|||||||
return process.env.PUBLIC_URL;
|
return process.env.PUBLIC_URL;
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${kcContext.url.resourcesPath}/${basenameOfTheKeycloakifyResourcesDir}`;
|
return `${kcContext.url.resourcesPath}/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}`;
|
||||||
})();
|
})();
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
import { lazy, Suspense } from "react";
|
import { lazy, Suspense } from "react";
|
||||||
import { assert, type Equals } from "tsafe/assert";
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
||||||
import type { KcContext } from "./KcContext";
|
import type { KcContext } from "keycloakify/account/KcContext";
|
||||||
|
import { I18n } from "keycloakify/account/i18n";
|
||||||
|
|
||||||
const Password = lazy(() => import("keycloakify/account/pages/Password"));
|
const Password = lazy(() => import("keycloakify/account/pages/Password"));
|
||||||
const Account = lazy(() => import("keycloakify/account/pages/Account"));
|
const Account = lazy(() => import("keycloakify/account/pages/Account"));
|
||||||
@ -11,7 +12,7 @@ const Applications = lazy(() => import("keycloakify/account/pages/Applications")
|
|||||||
const Log = lazy(() => import("keycloakify/account/pages/Log"));
|
const Log = lazy(() => import("keycloakify/account/pages/Log"));
|
||||||
const FederatedIdentity = lazy(() => import("keycloakify/account/pages/FederatedIdentity"));
|
const FederatedIdentity = lazy(() => import("keycloakify/account/pages/FederatedIdentity"));
|
||||||
|
|
||||||
export default function Fallback(props: PageProps<KcContext>) {
|
export default function DefaultPage(props: PageProps<KcContext, I18n>) {
|
||||||
const { kcContext, ...rest } = props;
|
const { kcContext, ...rest } = props;
|
||||||
|
|
||||||
return (
|
return (
|
@ -118,7 +118,10 @@ export declare namespace KcContext {
|
|||||||
lastName?: string;
|
lastName?: string;
|
||||||
username?: string;
|
username?: string;
|
||||||
};
|
};
|
||||||
properties: Record<string, string | undefined>;
|
properties: {};
|
||||||
|
"x-keycloakify": {
|
||||||
|
messages: Record<string, string>;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Password = Common & {
|
export type Password = Common & {
|
||||||
@ -166,6 +169,7 @@ export declare namespace KcContext {
|
|||||||
algorithm: "HmacSHA1" | "HmacSHA256" | "HmacSHA512";
|
algorithm: "HmacSHA1" | "HmacSHA256" | "HmacSHA512";
|
||||||
digits: number;
|
digits: number;
|
||||||
lookAheadWindow: number;
|
lookAheadWindow: number;
|
||||||
|
getAlgorithmKey: () => string;
|
||||||
} & (
|
} & (
|
||||||
| {
|
| {
|
||||||
type: "totp";
|
type: "totp";
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import "keycloakify/tools/Object.fromEntries";
|
import "keycloakify/tools/Object.fromEntries";
|
||||||
import { resources_common, keycloak_resources } from "keycloakify/bin/shared/constants";
|
import { RESOURCES_COMMON, KEYCLOAK_RESOURCES } from "keycloakify/bin/shared/constants";
|
||||||
import { id } from "tsafe/id";
|
import { id } from "tsafe/id";
|
||||||
import type { KcContext } from "./KcContext";
|
import type { KcContext } from "./KcContext";
|
||||||
import { BASE_URL } from "keycloakify/lib/BASE_URL";
|
import { BASE_URL } from "keycloakify/lib/BASE_URL";
|
||||||
|
|
||||||
const resourcesPath = `${BASE_URL}${keycloak_resources}/account/resources`;
|
const resourcesPath = `${BASE_URL}${KEYCLOAK_RESOURCES}/account/resources`;
|
||||||
|
|
||||||
export const kcContextCommonMock: KcContext.Common = {
|
export const kcContextCommonMock: KcContext.Common = {
|
||||||
themeVersion: "0.0.0",
|
themeVersion: "0.0.0",
|
||||||
@ -13,7 +13,7 @@ export const kcContextCommonMock: KcContext.Common = {
|
|||||||
themeName: "my-theme-name",
|
themeName: "my-theme-name",
|
||||||
url: {
|
url: {
|
||||||
resourcesPath,
|
resourcesPath,
|
||||||
resourcesCommonPath: `${resourcesPath}/${resources_common}`,
|
resourcesCommonPath: `${resourcesPath}/${RESOURCES_COMMON}`,
|
||||||
resourceUrl: "#",
|
resourceUrl: "#",
|
||||||
accountUrl: "#",
|
accountUrl: "#",
|
||||||
applicationsUrl: "#",
|
applicationsUrl: "#",
|
||||||
@ -82,16 +82,9 @@ export const kcContextCommonMock: KcContext.Common = {
|
|||||||
email: "john.doe@code.gouv.fr",
|
email: "john.doe@code.gouv.fr",
|
||||||
username: "doe_j"
|
username: "doe_j"
|
||||||
},
|
},
|
||||||
properties: {
|
properties: {},
|
||||||
parent: "account-v1",
|
"x-keycloakify": {
|
||||||
kcButtonLargeClass: "btn-lg",
|
messages: {}
|
||||||
locales:
|
|
||||||
"ar,ca,cs,da,de,en,es,fr,fi,hu,it,ja,lt,nl,no,pl,pt-BR,ru,sk,sv,tr,zh-CN",
|
|
||||||
kcButtonPrimaryClass: "btn-primary",
|
|
||||||
accountResourceProvider: "account-v1",
|
|
||||||
styles: "css/account.css img/icon-sidebar-active.png img/logo.png resources-common/node_modules/patternfly/dist/css/patternfly.min.css resources-common/node_modules/patternfly/dist/css/patternfly-additions.min.css resources-common/node_modules/patternfly/dist/css/patternfly-additions.min.css",
|
|
||||||
kcButtonClass: "btn",
|
|
||||||
kcButtonDefaultClass: "btn-default"
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -158,7 +151,8 @@ export const kcContextMocks: KcContext[] = [
|
|||||||
digits: 6,
|
digits: 6,
|
||||||
lookAheadWindow: 1,
|
lookAheadWindow: 1,
|
||||||
type: "totp",
|
type: "totp",
|
||||||
period: 30
|
period: 30,
|
||||||
|
getAlgorithmKey: () => "SHA1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
mode: "qr",
|
mode: "qr",
|
||||||
|
@ -5,15 +5,15 @@ import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
|||||||
import { useInsertLinkTags } from "keycloakify/tools/useInsertLinkTags";
|
import { useInsertLinkTags } from "keycloakify/tools/useInsertLinkTags";
|
||||||
import { useSetClassName } from "keycloakify/tools/useSetClassName";
|
import { useSetClassName } from "keycloakify/tools/useSetClassName";
|
||||||
import type { TemplateProps } from "keycloakify/account/TemplateProps";
|
import type { TemplateProps } from "keycloakify/account/TemplateProps";
|
||||||
|
import type { I18n } from "./i18n";
|
||||||
import type { KcContext } from "./KcContext";
|
import type { KcContext } from "./KcContext";
|
||||||
import { useI18n } from "./i18n";
|
|
||||||
|
|
||||||
export default function Template(props: TemplateProps<KcContext>) {
|
export default function Template(props: TemplateProps<KcContext, I18n>) {
|
||||||
const { kcContext, doUseDefaultCss, active, classes, children } = props;
|
const { kcContext, i18n, doUseDefaultCss, active, classes, children } = props;
|
||||||
|
|
||||||
const { kcClsx } = getKcClsx({ doUseDefaultCss, classes });
|
const { kcClsx } = getKcClsx({ doUseDefaultCss, classes });
|
||||||
|
|
||||||
const { msg, msgStr, getChangeLocalUrl, labelBySupportedLanguageTag, currentLanguageTag } = useI18n({ kcContext });
|
const { msg, msgStr, getChangeLocaleUrl, labelBySupportedLanguageTag, currentLanguageTag } = i18n;
|
||||||
|
|
||||||
const { locale, url, features, realm, message, referrer } = kcContext;
|
const { locale, url, features, realm, message, referrer } = kcContext;
|
||||||
|
|
||||||
@ -79,7 +79,7 @@ export default function Template(props: TemplateProps<KcContext>) {
|
|||||||
<ul>
|
<ul>
|
||||||
{locale.supported.map(({ languageTag }) => (
|
{locale.supported.map(({ languageTag }) => (
|
||||||
<li key={languageTag} className="kc-dropdown-item">
|
<li key={languageTag} className="kc-dropdown-item">
|
||||||
<a href={getChangeLocalUrl(languageTag)}>{labelBySupportedLanguageTag[languageTag]}</a>
|
<a href={getChangeLocaleUrl(languageTag)}>{labelBySupportedLanguageTag[languageTag]}</a>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
@ -145,7 +145,12 @@ export default function Template(props: TemplateProps<KcContext>) {
|
|||||||
<div className={clsx("alert", `alert-${message.type}`)}>
|
<div className={clsx("alert", `alert-${message.type}`)}>
|
||||||
{message.type === "success" && <span className="pficon pficon-ok"></span>}
|
{message.type === "success" && <span className="pficon pficon-ok"></span>}
|
||||||
{message.type === "error" && <span className="pficon pficon-error-circle-o"></span>}
|
{message.type === "error" && <span className="pficon pficon-error-circle-o"></span>}
|
||||||
<span className="kc-feedback-text">{message.summary}</span>
|
<span
|
||||||
|
className="kc-feedback-text"
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: message.summary
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
@ -1,12 +1,13 @@
|
|||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import type { KcContext } from "./KcContext";
|
|
||||||
|
|
||||||
export type TemplateProps<KcContext extends KcContext.Common> = {
|
export type TemplateProps<KcContext, I18n> = {
|
||||||
kcContext: KcContext;
|
kcContext: KcContext;
|
||||||
|
i18n: I18n;
|
||||||
doUseDefaultCss: boolean;
|
doUseDefaultCss: boolean;
|
||||||
active: string;
|
|
||||||
classes?: Partial<Record<ClassKey, string>>;
|
classes?: Partial<Record<ClassKey, string>>;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
|
|
||||||
|
active: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ClassKey =
|
export type ClassKey =
|
||||||
|
6
src/account/i18n/GenericI18n.tsx
Normal file
6
src/account/i18n/GenericI18n.tsx
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
import type { GenericI18n_noJsx } from "./i18n";
|
||||||
|
|
||||||
|
export type GenericI18n<MessageKey extends string> = GenericI18n_noJsx<MessageKey> & {
|
||||||
|
msg: (key: MessageKey, ...args: (string | undefined)[]) => JSX.Element;
|
||||||
|
advancedMsg: (key: string, ...args: (string | undefined)[]) => JSX.Element;
|
||||||
|
};
|
@ -1,25 +1,24 @@
|
|||||||
import "keycloakify/tools/Object.fromEntries";
|
import "keycloakify/tools/Object.fromEntries";
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import messages_fallbackLanguage from "./baseMessages/en";
|
import messages_defaultSet_fallbackLanguage from "./messages_defaultSet/en";
|
||||||
import { getMessages } from "./baseMessages";
|
import { fetchMessages_defaultSet } from "./messages_defaultSet";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import { Reflect } from "tsafe/Reflect";
|
import { FALLBACK_LANGUAGE_TAG } from "keycloakify/bin/shared/constants";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
export const fallbackLanguageTag = "en";
|
|
||||||
|
|
||||||
export type KcContextLike = {
|
export type KcContextLike = {
|
||||||
locale?: {
|
locale?: {
|
||||||
currentLanguageTag: string;
|
currentLanguageTag: string;
|
||||||
supported: { languageTag: string; url: string; label: string }[];
|
supported: { languageTag: string; url: string; label: string }[];
|
||||||
};
|
};
|
||||||
|
"x-keycloakify": {
|
||||||
|
messages: Record<string, string>;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<KcContext extends KcContextLike ? true : false>();
|
assert<KcContext extends KcContextLike ? true : false>();
|
||||||
|
|
||||||
export type MessageKey = keyof typeof messages_fallbackLanguage;
|
export type GenericI18n_noJsx<MessageKey extends string> = {
|
||||||
|
|
||||||
export type GenericI18n<MessageKey extends string> = {
|
|
||||||
/**
|
/**
|
||||||
* e.g: "en", "fr", "zh-CN"
|
* e.g: "en", "fr", "zh-CN"
|
||||||
*
|
*
|
||||||
@ -30,7 +29,7 @@ export type GenericI18n<MessageKey extends string> = {
|
|||||||
* Redirect to this url to change the language.
|
* Redirect to this url to change the language.
|
||||||
* After reload currentLanguageTag === newLanguageTag
|
* After reload currentLanguageTag === newLanguageTag
|
||||||
*/
|
*/
|
||||||
getChangeLocalUrl: (newLanguageTag: string) => string;
|
getChangeLocaleUrl: (newLanguageTag: string) => string;
|
||||||
/**
|
/**
|
||||||
* e.g. "en" => "English", "fr" => "Français", ...
|
* e.g. "en" => "English", "fr" => "Français", ...
|
||||||
*
|
*
|
||||||
@ -39,16 +38,21 @@ export type GenericI18n<MessageKey extends string> = {
|
|||||||
* */
|
* */
|
||||||
labelBySupportedLanguageTag: Record<string, string>;
|
labelBySupportedLanguageTag: Record<string, string>;
|
||||||
/**
|
/**
|
||||||
* Examples assuming currentLanguageTag === "en"
|
|
||||||
*
|
*
|
||||||
* msg("access-denied") === <span>Access denied</span>
|
* Examples assuming currentLanguageTag === "en"
|
||||||
* msg("impersonateTitleHtml", "Foo") === <span><strong>Foo</strong> Impersonate User</span>
|
* {
|
||||||
*/
|
* en: {
|
||||||
msg: (key: MessageKey, ...args: (string | undefined)[]) => JSX.Element;
|
* "access-denied": "Access denied",
|
||||||
/**
|
* "impersonateTitleHtml": "<strong>{0}</strong> Impersonate User",
|
||||||
* It's the same thing as msg() but instead of returning a JSX.Element it returns a string.
|
* "bar": "Bar {0}"
|
||||||
* It can be more convenient to manipulate strings but if there are HTML tags it wont render.
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* msgStr("access-denied") === "Access denied"
|
||||||
|
* msgStr("not-a-message-key") Throws an error
|
||||||
* msgStr("impersonateTitleHtml", "Foo") === "<strong>Foo</strong> Impersonate User"
|
* msgStr("impersonateTitleHtml", "Foo") === "<strong>Foo</strong> Impersonate User"
|
||||||
|
* msgStr("${bar}", "<strong>c</strong>") === "Bar <strong>XXX</strong>"
|
||||||
|
* The html in the arg is partially escaped for security reasons, it might come from an untrusted source, it's not safe to render it as html.
|
||||||
*/
|
*/
|
||||||
msgStr: (key: MessageKey, ...args: (string | undefined)[]) => string;
|
msgStr: (key: MessageKey, ...args: (string | undefined)[]) => string;
|
||||||
/**
|
/**
|
||||||
@ -59,24 +63,11 @@ export type GenericI18n<MessageKey extends string> = {
|
|||||||
* {
|
* {
|
||||||
* en: {
|
* en: {
|
||||||
* "access-denied": "Access denied",
|
* "access-denied": "Access denied",
|
||||||
* "foo": "Foo {0} {1}",
|
|
||||||
* "bar": "Bar {0}"
|
|
||||||
* }
|
* }
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* advancedMsg("${access-denied} foo bar") === <span>{msgStr("access-denied")} foo bar<span> === <span>Access denied foo bar</span>
|
* advancedMsgStr("${access-denied}") === advancedMsgStr("access-denied") === msgStr("access-denied") === "Access denied"
|
||||||
* advancedMsg("${access-denied}") === advancedMsg("access-denied") === msg("access-denied") === <span>Access denied</span>
|
* advancedMsgStr("${not-a-message-key}") === advancedMsgStr("not-a-message-key") === "not-a-message-key"
|
||||||
* advancedMsg("${not-a-message-key}") === advancedMsg(not-a-message-key") === <span>not-a-message-key</span>
|
|
||||||
* advancedMsg("${bar}", "<strong>c</strong>")
|
|
||||||
* === <span>{msgStr("bar", "<strong>XXX</strong>")}<span>
|
|
||||||
* === <span>Bar <strong>XXX</strong></span> (The html in the arg is partially escaped for security reasons, it might be untrusted)
|
|
||||||
* advancedMsg("${foo} xx ${bar}", "a", "b", "c")
|
|
||||||
* === <span>{msgStr("foo", "a", "b")} xx {msgStr("bar")}<span>
|
|
||||||
* === <span>Foo a b xx Bar {0}</span> (The substitution are only applied in the first message)
|
|
||||||
*/
|
|
||||||
advancedMsg: (key: string, ...args: (string | undefined)[]) => JSX.Element;
|
|
||||||
/**
|
|
||||||
* See advancedMsg() but instead of returning a JSX.Element it returns a string.
|
|
||||||
*/
|
*/
|
||||||
advancedMsgStr: (key: string, ...args: (string | undefined)[]) => string;
|
advancedMsgStr: (key: string, ...args: (string | undefined)[]) => string;
|
||||||
|
|
||||||
@ -88,8 +79,12 @@ export type GenericI18n<MessageKey extends string> = {
|
|||||||
isFetchingTranslations: boolean;
|
isFetchingTranslations: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
function createGetI18n<ExtraMessageKey extends string = never>(extraMessages: { [languageTag: string]: { [key in ExtraMessageKey]: string } }) {
|
export type MessageKey_defaultSet = keyof typeof messages_defaultSet_fallbackLanguage;
|
||||||
type I18n = GenericI18n<MessageKey | ExtraMessageKey>;
|
|
||||||
|
export function createGetI18n<MessageKey_themeDefined extends string = never>(messagesByLanguageTag_themeDefined: {
|
||||||
|
[languageTag: string]: { [key in MessageKey_themeDefined]: string };
|
||||||
|
}) {
|
||||||
|
type I18n = GenericI18n_noJsx<MessageKey_defaultSet | MessageKey_themeDefined>;
|
||||||
|
|
||||||
type Result = { i18n: I18n; prI18n_currentLanguage: Promise<I18n> | undefined };
|
type Result = { i18n: I18n; prI18n_currentLanguage: Promise<I18n> | undefined };
|
||||||
|
|
||||||
@ -108,9 +103,9 @@ function createGetI18n<ExtraMessageKey extends string = never>(extraMessages: {
|
|||||||
return cachedResult;
|
return cachedResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
const partialI18n: Pick<I18n, "currentLanguageTag" | "getChangeLocalUrl" | "labelBySupportedLanguageTag"> = {
|
const partialI18n: Pick<I18n, "currentLanguageTag" | "getChangeLocaleUrl" | "labelBySupportedLanguageTag"> = {
|
||||||
currentLanguageTag: kcContext.locale?.currentLanguageTag ?? fallbackLanguageTag,
|
currentLanguageTag: kcContext.locale?.currentLanguageTag ?? FALLBACK_LANGUAGE_TAG,
|
||||||
getChangeLocalUrl: newLanguageTag => {
|
getChangeLocaleUrl: newLanguageTag => {
|
||||||
const { locale } = kcContext;
|
const { locale } = kcContext;
|
||||||
|
|
||||||
assert(locale !== undefined, "Internationalization not enabled");
|
assert(locale !== undefined, "Internationalization not enabled");
|
||||||
@ -124,28 +119,38 @@ function createGetI18n<ExtraMessageKey extends string = never>(extraMessages: {
|
|||||||
labelBySupportedLanguageTag: Object.fromEntries((kcContext.locale?.supported ?? []).map(({ languageTag, label }) => [languageTag, label]))
|
labelBySupportedLanguageTag: Object.fromEntries((kcContext.locale?.supported ?? []).map(({ languageTag, label }) => [languageTag, label]))
|
||||||
};
|
};
|
||||||
|
|
||||||
const { createI18nTranslationFunctions } = createI18nTranslationFunctionsFactory<MessageKey, ExtraMessageKey>({
|
const { createI18nTranslationFunctions } = createI18nTranslationFunctionsFactory<MessageKey_themeDefined>({
|
||||||
messages_fallbackLanguage,
|
messages_themeDefined:
|
||||||
extraMessages_fallbackLanguage: extraMessages[fallbackLanguageTag],
|
messagesByLanguageTag_themeDefined[partialI18n.currentLanguageTag] ??
|
||||||
extraMessages: extraMessages[partialI18n.currentLanguageTag]
|
messagesByLanguageTag_themeDefined[FALLBACK_LANGUAGE_TAG] ??
|
||||||
|
(() => {
|
||||||
|
const firstLanguageTag = Object.keys(messagesByLanguageTag_themeDefined)[0];
|
||||||
|
if (firstLanguageTag === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return messagesByLanguageTag_themeDefined[firstLanguageTag];
|
||||||
|
})(),
|
||||||
|
messages_fromKcServer: kcContext["x-keycloakify"].messages
|
||||||
});
|
});
|
||||||
|
|
||||||
const isCurrentLanguageFallbackLanguage = partialI18n.currentLanguageTag !== fallbackLanguageTag;
|
const isCurrentLanguageFallbackLanguage = partialI18n.currentLanguageTag === FALLBACK_LANGUAGE_TAG;
|
||||||
|
|
||||||
const result: Result = {
|
const result: Result = {
|
||||||
i18n: {
|
i18n: {
|
||||||
...partialI18n,
|
...partialI18n,
|
||||||
...createI18nTranslationFunctions({ messages: undefined }),
|
...createI18nTranslationFunctions({
|
||||||
|
messages_defaultSet_currentLanguage: isCurrentLanguageFallbackLanguage ? messages_defaultSet_fallbackLanguage : undefined
|
||||||
|
}),
|
||||||
isFetchingTranslations: !isCurrentLanguageFallbackLanguage
|
isFetchingTranslations: !isCurrentLanguageFallbackLanguage
|
||||||
},
|
},
|
||||||
prI18n_currentLanguage: isCurrentLanguageFallbackLanguage
|
prI18n_currentLanguage: isCurrentLanguageFallbackLanguage
|
||||||
? undefined
|
? undefined
|
||||||
: (async () => {
|
: (async () => {
|
||||||
const messages = await getMessages(partialI18n.currentLanguageTag);
|
const messages_defaultSet_currentLanguage = await fetchMessages_defaultSet(partialI18n.currentLanguageTag);
|
||||||
|
|
||||||
const i18n_currentLanguage: I18n = {
|
const i18n_currentLanguage: I18n = {
|
||||||
...partialI18n,
|
...partialI18n,
|
||||||
...createI18nTranslationFunctions({ messages }),
|
...createI18nTranslationFunctions({ messages_defaultSet_currentLanguage }),
|
||||||
isFetchingTranslations: false
|
isFetchingTranslations: false
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -168,154 +173,76 @@ function createGetI18n<ExtraMessageKey extends string = never>(extraMessages: {
|
|||||||
return { getI18n };
|
return { getI18n };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createUseI18n<ExtraMessageKey extends string = never>(extraMessages: {
|
function createI18nTranslationFunctionsFactory<MessageKey_themeDefined extends string>(params: {
|
||||||
[languageTag: string]: { [key in ExtraMessageKey]: string };
|
messages_themeDefined: Record<MessageKey_themeDefined, string> | undefined;
|
||||||
|
messages_fromKcServer: Record<string, string>;
|
||||||
}) {
|
}) {
|
||||||
type I18n = GenericI18n<MessageKey | ExtraMessageKey>;
|
const { messages_themeDefined, messages_fromKcServer } = params;
|
||||||
|
|
||||||
const { getI18n } = createGetI18n(extraMessages);
|
|
||||||
|
|
||||||
function useI18n(params: { kcContext: KcContextLike }): I18n {
|
|
||||||
const { kcContext } = params;
|
|
||||||
|
|
||||||
const { i18n, prI18n_currentLanguage } = getI18n({ kcContext });
|
|
||||||
|
|
||||||
const [i18n_toReturn, setI18n_toReturn] = useState<I18n>(i18n);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let isActive = true;
|
|
||||||
|
|
||||||
prI18n_currentLanguage?.then(i18n => {
|
|
||||||
if (!isActive) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setI18n_toReturn(i18n);
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
isActive = false;
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return i18n_toReturn;
|
|
||||||
}
|
|
||||||
|
|
||||||
return { useI18n, ofTypeI18n: Reflect<I18n>() };
|
|
||||||
}
|
|
||||||
|
|
||||||
function createI18nTranslationFunctionsFactory<MessageKey extends string, ExtraMessageKey extends string>(params: {
|
|
||||||
messages_fallbackLanguage: Record<MessageKey, string>;
|
|
||||||
extraMessages_fallbackLanguage: Record<ExtraMessageKey, string> | undefined;
|
|
||||||
extraMessages: Partial<Record<ExtraMessageKey, string>> | undefined;
|
|
||||||
}) {
|
|
||||||
const { extraMessages } = params;
|
|
||||||
|
|
||||||
const messages_fallbackLanguage = {
|
|
||||||
...params.messages_fallbackLanguage,
|
|
||||||
...params.extraMessages_fallbackLanguage
|
|
||||||
};
|
|
||||||
|
|
||||||
function createI18nTranslationFunctions(params: {
|
function createI18nTranslationFunctions(params: {
|
||||||
messages: Partial<Record<MessageKey, string>> | undefined;
|
messages_defaultSet_currentLanguage: Partial<Record<MessageKey_defaultSet, string>> | undefined;
|
||||||
}): Pick<GenericI18n<MessageKey | ExtraMessageKey>, "msg" | "msgStr" | "advancedMsg" | "advancedMsgStr"> {
|
}): Pick<GenericI18n_noJsx<MessageKey_defaultSet | MessageKey_themeDefined>, "msgStr" | "advancedMsgStr"> {
|
||||||
const messages = {
|
const { messages_defaultSet_currentLanguage } = params;
|
||||||
...params.messages,
|
|
||||||
...extraMessages
|
|
||||||
};
|
|
||||||
|
|
||||||
function resolveMsg(props: { key: string; args: (string | undefined)[]; doRenderAsHtml: boolean }): string | JSX.Element | undefined {
|
function resolveMsg(props: { key: string; args: (string | undefined)[] }): string | undefined {
|
||||||
const { key, args, doRenderAsHtml } = props;
|
const { key, args } = props;
|
||||||
|
|
||||||
const messageOrUndefined: string | undefined = (messages as any)[key] ?? (messages_fallbackLanguage as any)[key];
|
const message =
|
||||||
|
id<Record<string, string | undefined>>(messages_fromKcServer)[key] ??
|
||||||
|
id<Record<string, string | undefined> | undefined>(messages_themeDefined)?.[key] ??
|
||||||
|
id<Record<string, string | undefined> | undefined>(messages_defaultSet_currentLanguage)?.[key] ??
|
||||||
|
id<Record<string, string | undefined>>(messages_defaultSet_fallbackLanguage)[key];
|
||||||
|
|
||||||
if (messageOrUndefined === undefined) {
|
if (message === undefined) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = messageOrUndefined;
|
const startIndex = message
|
||||||
|
.match(/{[0-9]+}/g)
|
||||||
|
?.map(g => g.match(/{([0-9]+)}/)![1])
|
||||||
|
.map(indexStr => parseInt(indexStr))
|
||||||
|
.sort((a, b) => a - b)[0];
|
||||||
|
|
||||||
const messageWithArgsInjectedIfAny = (() => {
|
if (startIndex === undefined) {
|
||||||
const startIndex = message
|
// No {0} in message (no arguments expected)
|
||||||
.match(/{[0-9]+}/g)
|
return message;
|
||||||
?.map(g => g.match(/{([0-9]+)}/)![1])
|
|
||||||
.map(indexStr => parseInt(indexStr))
|
|
||||||
.sort((a, b) => a - b)[0];
|
|
||||||
|
|
||||||
if (startIndex === undefined) {
|
|
||||||
// No {0} in message (no arguments expected)
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
let messageWithArgsInjected = message;
|
|
||||||
|
|
||||||
args.forEach((arg, i) => {
|
|
||||||
if (arg === undefined) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
messageWithArgsInjected = messageWithArgsInjected.replace(
|
|
||||||
new RegExp(`\\{${i + startIndex}\\}`, "g"),
|
|
||||||
arg.replace(/</g, "<").replace(/>/g, ">")
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
return messageWithArgsInjected;
|
|
||||||
})();
|
|
||||||
|
|
||||||
return doRenderAsHtml ? (
|
|
||||||
<span
|
|
||||||
// NOTE: The message is trusted. The arguments are not but are escaped.
|
|
||||||
dangerouslySetInnerHTML={{
|
|
||||||
__html: messageWithArgsInjectedIfAny
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
messageWithArgsInjectedIfAny
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveMsgAdvanced(props: { key: string; args: (string | undefined)[]; doRenderAsHtml: boolean }): JSX.Element | string {
|
|
||||||
const { key, args, doRenderAsHtml } = props;
|
|
||||||
|
|
||||||
if (!/\$\{[^}]+\}/.test(key)) {
|
|
||||||
const resolvedMessage = resolveMsg({ key, args, doRenderAsHtml });
|
|
||||||
|
|
||||||
if (resolvedMessage === undefined) {
|
|
||||||
return doRenderAsHtml ? <span dangerouslySetInnerHTML={{ __html: key }} /> : key;
|
|
||||||
}
|
|
||||||
|
|
||||||
return resolvedMessage;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let isFirstMatch = true;
|
let messageWithArgsInjected = message;
|
||||||
|
|
||||||
const resolvedComplexMessage = key.replace(/\$\{([^}]+)\}/g, (...[, key_i]) => {
|
args.forEach((arg, i) => {
|
||||||
const replaceBy = resolveMsg({ key: key_i, args: isFirstMatch ? args : [], doRenderAsHtml: false }) ?? key_i;
|
if (arg === undefined) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
isFirstMatch = false;
|
messageWithArgsInjected = messageWithArgsInjected.replace(
|
||||||
|
new RegExp(`\\{${i + startIndex}\\}`, "g"),
|
||||||
return replaceBy;
|
arg.replace(/</g, "<").replace(/>/g, ">")
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
return doRenderAsHtml ? <span dangerouslySetInnerHTML={{ __html: resolvedComplexMessage }} /> : resolvedComplexMessage;
|
return messageWithArgsInjected;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveMsgAdvanced(props: { key: string; args: (string | undefined)[] }): string {
|
||||||
|
const { key, args } = props;
|
||||||
|
|
||||||
|
const match = key.match(/^\$\{(.+)\}$/);
|
||||||
|
|
||||||
|
if (match === null) {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolveMsg({ key: match[1], args }) ?? key;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
msgStr: (key, ...args) => resolveMsg({ key, args, doRenderAsHtml: false }) as string,
|
msgStr: (key, ...args) => {
|
||||||
msg: (key, ...args) => resolveMsg({ key, args, doRenderAsHtml: true }) as JSX.Element,
|
const resolvedMessage = resolveMsg({ key, args });
|
||||||
advancedMsg: (key, ...args) =>
|
assert(resolvedMessage !== undefined, `Message with key "${key}" not found`);
|
||||||
resolveMsgAdvanced({
|
return resolvedMessage;
|
||||||
key,
|
},
|
||||||
args,
|
advancedMsgStr: (key, ...args) => resolveMsgAdvanced({ key, args })
|
||||||
doRenderAsHtml: true
|
|
||||||
}) as JSX.Element,
|
|
||||||
advancedMsgStr: (key, ...args) =>
|
|
||||||
resolveMsgAdvanced({
|
|
||||||
key,
|
|
||||||
args,
|
|
||||||
doRenderAsHtml: false
|
|
||||||
}) as string
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,10 +1,5 @@
|
|||||||
export type { MessageKey } from "./i18n";
|
import type { GenericI18n } from "./GenericI18n";
|
||||||
import { createUseI18n } from "./i18n";
|
import type { MessageKey_defaultSet, KcContextLike } from "./i18n";
|
||||||
export { createUseI18n };
|
export type { MessageKey_defaultSet, KcContextLike };
|
||||||
export { fallbackLanguageTag } from "./i18n";
|
export type I18n = GenericI18n<MessageKey_defaultSet>;
|
||||||
|
export { createUseI18n } from "./useI18n";
|
||||||
const { useI18n, ofTypeI18n } = createUseI18n({});
|
|
||||||
|
|
||||||
export type I18n = typeof ofTypeI18n;
|
|
||||||
|
|
||||||
export { useI18n };
|
|
||||||
|
95
src/account/i18n/useI18n.tsx
Normal file
95
src/account/i18n/useI18n.tsx
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { createGetI18n, type GenericI18n_noJsx, type KcContextLike, type MessageKey_defaultSet } from "./i18n";
|
||||||
|
import { GenericI18n } from "./GenericI18n";
|
||||||
|
import { Reflect } from "tsafe/Reflect";
|
||||||
|
|
||||||
|
export function createUseI18n<MessageKey_themeDefined extends string = never>(messagesByLanguageTag: {
|
||||||
|
[languageTag: string]: { [key in MessageKey_themeDefined]: string };
|
||||||
|
}) {
|
||||||
|
type MessageKey = MessageKey_defaultSet | MessageKey_themeDefined;
|
||||||
|
|
||||||
|
type I18n = GenericI18n<MessageKey>;
|
||||||
|
|
||||||
|
const { withJsx } = (() => {
|
||||||
|
const cache = new WeakMap<GenericI18n_noJsx<MessageKey>, GenericI18n<MessageKey>>();
|
||||||
|
|
||||||
|
function renderHtmlString(params: { htmlString: string; msgKey: string }): JSX.Element {
|
||||||
|
const { htmlString, msgKey } = params;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-kc-msg={msgKey}
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: htmlString
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function withJsx(i18n_noJsx: GenericI18n_noJsx<MessageKey>): I18n {
|
||||||
|
use_cache: {
|
||||||
|
const i18n = cache.get(i18n_noJsx);
|
||||||
|
|
||||||
|
if (i18n === undefined) {
|
||||||
|
break use_cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
return i18n;
|
||||||
|
}
|
||||||
|
|
||||||
|
const i18n: I18n = {
|
||||||
|
...i18n_noJsx,
|
||||||
|
msg: (msgKey, ...args) => renderHtmlString({ htmlString: i18n_noJsx.msgStr(msgKey, ...args), msgKey }),
|
||||||
|
advancedMsg: (msgKey, ...args) => renderHtmlString({ htmlString: i18n_noJsx.advancedMsgStr(msgKey, ...args), msgKey })
|
||||||
|
};
|
||||||
|
|
||||||
|
cache.set(i18n_noJsx, i18n);
|
||||||
|
|
||||||
|
return i18n;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { withJsx };
|
||||||
|
})();
|
||||||
|
|
||||||
|
add_style: {
|
||||||
|
const attributeName = "data-kc-i18n";
|
||||||
|
|
||||||
|
// Check if already exists in head
|
||||||
|
if (document.querySelector(`style[${attributeName}]`) !== null) {
|
||||||
|
break add_style;
|
||||||
|
}
|
||||||
|
|
||||||
|
const styleElement = document.createElement("style");
|
||||||
|
styleElement.attributes.setNamedItem(document.createAttribute(attributeName));
|
||||||
|
(styleElement.textContent = `[data-kc-msg] { display: inline-block; }`), document.head.prepend(styleElement);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { getI18n } = createGetI18n(messagesByLanguageTag);
|
||||||
|
|
||||||
|
function useI18n(params: { kcContext: KcContextLike }): { i18n: I18n } {
|
||||||
|
const { kcContext } = params;
|
||||||
|
|
||||||
|
const { i18n, prI18n_currentLanguage } = getI18n({ kcContext });
|
||||||
|
|
||||||
|
const [i18n_toReturn, setI18n_toReturn] = useState<I18n>(withJsx(i18n));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let isActive = true;
|
||||||
|
|
||||||
|
prI18n_currentLanguage?.then(i18n => {
|
||||||
|
if (!isActive) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setI18n_toReturn(withJsx(i18n));
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
isActive = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { i18n: i18n_toReturn };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { useI18n, ofTypeI18n: Reflect<I18n>() };
|
||||||
|
}
|
@ -2,10 +2,10 @@ import { clsx } from "keycloakify/tools/clsx";
|
|||||||
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
||||||
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import { useI18n } from "../i18n";
|
import type { I18n } from "../i18n";
|
||||||
|
|
||||||
export default function Account(props: PageProps<Extract<KcContext, { pageId: "account.ftl" }>>) {
|
export default function Account(props: PageProps<Extract<KcContext, { pageId: "account.ftl" }>, I18n>) {
|
||||||
const { kcContext, doUseDefaultCss, Template } = props;
|
const { kcContext, i18n, doUseDefaultCss, Template } = props;
|
||||||
|
|
||||||
const classes = {
|
const classes = {
|
||||||
...props.classes,
|
...props.classes,
|
||||||
@ -19,10 +19,10 @@ export default function Account(props: PageProps<Extract<KcContext, { pageId: "a
|
|||||||
|
|
||||||
const { url, realm, messagesPerField, stateChecker, account, referrer } = kcContext;
|
const { url, realm, messagesPerField, stateChecker, account, referrer } = kcContext;
|
||||||
|
|
||||||
const { msg } = useI18n({ kcContext });
|
const { msg } = i18n;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Template {...{ kcContext, doUseDefaultCss, classes }} active="account">
|
<Template {...{ kcContext, i18n, doUseDefaultCss, classes }} active="account">
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<div className="col-md-10">
|
<div className="col-md-10">
|
||||||
<h2>{msg("editAccountHtmlTitle")}</h2>
|
<h2>{msg("editAccountHtmlTitle")}</h2>
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
||||||
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import { useI18n } from "../i18n";
|
import type { I18n } from "../i18n";
|
||||||
|
|
||||||
export default function Applications(props: PageProps<Extract<KcContext, { pageId: "applications.ftl" }>>) {
|
export default function Applications(props: PageProps<Extract<KcContext, { pageId: "applications.ftl" }>, I18n>) {
|
||||||
const { kcContext, doUseDefaultCss, classes, Template } = props;
|
const { kcContext, i18n, doUseDefaultCss, classes, Template } = props;
|
||||||
|
|
||||||
const { kcClsx } = getKcClsx({
|
const { kcClsx } = getKcClsx({
|
||||||
doUseDefaultCss,
|
doUseDefaultCss,
|
||||||
@ -17,10 +17,10 @@ export default function Applications(props: PageProps<Extract<KcContext, { pageI
|
|||||||
stateChecker
|
stateChecker
|
||||||
} = kcContext;
|
} = kcContext;
|
||||||
|
|
||||||
const { msg, advancedMsg } = useI18n({ kcContext });
|
const { msg, advancedMsg } = i18n;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Template {...{ kcContext, doUseDefaultCss, classes }} active="applications">
|
<Template {...{ kcContext, i18n, doUseDefaultCss, classes }} active="applications">
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<div className="col-md-10">
|
<div className="col-md-10">
|
||||||
<h2>{msg("applicationsHtmlTitle")}</h2>
|
<h2>{msg("applicationsHtmlTitle")}</h2>
|
||||||
@ -62,7 +62,6 @@ export default function Applications(props: PageProps<Extract<KcContext, { pageI
|
|||||||
{index < application.realmRolesAvailable.length - 1 && ", "}
|
{index < application.realmRolesAvailable.length - 1 && ", "}
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
{!isArrayWithEmptyObject(application.realmRolesAvailable) && application.resourceRolesAvailable && ", "}
|
|
||||||
{application.resourceRolesAvailable &&
|
{application.resourceRolesAvailable &&
|
||||||
Object.keys(application.resourceRolesAvailable).map(resource => (
|
Object.keys(application.resourceRolesAvailable).map(resource => (
|
||||||
<span key={resource}>
|
<span key={resource}>
|
||||||
|
@ -1,14 +1,14 @@
|
|||||||
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import { useI18n } from "../i18n";
|
import type { I18n } from "../i18n";
|
||||||
|
|
||||||
export default function FederatedIdentity(props: PageProps<Extract<KcContext, { pageId: "federatedIdentity.ftl" }>>) {
|
export default function FederatedIdentity(props: PageProps<Extract<KcContext, { pageId: "federatedIdentity.ftl" }>, I18n>) {
|
||||||
const { kcContext, doUseDefaultCss, classes, Template } = props;
|
const { kcContext, i18n, doUseDefaultCss, classes, Template } = props;
|
||||||
|
|
||||||
const { url, federatedIdentity, stateChecker } = kcContext;
|
const { url, federatedIdentity, stateChecker } = kcContext;
|
||||||
const { msg } = useI18n({ kcContext });
|
const { msg } = i18n;
|
||||||
return (
|
return (
|
||||||
<Template {...{ kcContext, doUseDefaultCss, classes }} active="federatedIdentity">
|
<Template {...{ kcContext, i18n, doUseDefaultCss, classes }} active="social">
|
||||||
<div className="main-layout social">
|
<div className="main-layout social">
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<div className="col-md-10">
|
<div className="col-md-10">
|
||||||
|
@ -2,10 +2,10 @@ import type { Key } from "react";
|
|||||||
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
||||||
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import { useI18n } from "../i18n";
|
import type { I18n } from "../i18n";
|
||||||
|
|
||||||
export default function Log(props: PageProps<Extract<KcContext, { pageId: "log.ftl" }>>) {
|
export default function Log(props: PageProps<Extract<KcContext, { pageId: "log.ftl" }>, I18n>) {
|
||||||
const { kcContext, doUseDefaultCss, classes, Template } = props;
|
const { kcContext, i18n, doUseDefaultCss, classes, Template } = props;
|
||||||
|
|
||||||
const { kcClsx } = getKcClsx({
|
const { kcClsx } = getKcClsx({
|
||||||
doUseDefaultCss,
|
doUseDefaultCss,
|
||||||
@ -14,10 +14,10 @@ export default function Log(props: PageProps<Extract<KcContext, { pageId: "log.f
|
|||||||
|
|
||||||
const { log } = kcContext;
|
const { log } = kcContext;
|
||||||
|
|
||||||
const { msg } = useI18n({ kcContext });
|
const { msg } = i18n;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Template {...{ kcContext, doUseDefaultCss, classes }} active="log">
|
<Template {...{ kcContext, i18n, doUseDefaultCss, classes }} active="log">
|
||||||
<div className={kcClsx("kcContentWrapperClass")}>
|
<div className={kcClsx("kcContentWrapperClass")}>
|
||||||
<div className="col-md-10">
|
<div className="col-md-10">
|
||||||
<h2>{msg("accountLogHtmlTitle")}</h2>
|
<h2>{msg("accountLogHtmlTitle")}</h2>
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import type { TemplateProps, ClassKey } from "keycloakify/account/TemplateProps";
|
import { type TemplateProps, type ClassKey } from "keycloakify/account/TemplateProps";
|
||||||
import type { LazyOrNot } from "keycloakify/tools/LazyOrNot";
|
import type { LazyOrNot } from "keycloakify/tools/LazyOrNot";
|
||||||
import type { KcContext } from "../KcContext";
|
|
||||||
|
|
||||||
export type PageProps<NarrowedKcContext = KcContext> = {
|
export type PageProps<NarrowedKcContext, I18n> = {
|
||||||
Template: LazyOrNot<(props: TemplateProps<any>) => JSX.Element | null>;
|
Template: LazyOrNot<(props: TemplateProps<any, any>) => JSX.Element | null>;
|
||||||
kcContext: NarrowedKcContext;
|
kcContext: NarrowedKcContext;
|
||||||
|
i18n: I18n;
|
||||||
doUseDefaultCss: boolean;
|
doUseDefaultCss: boolean;
|
||||||
classes?: Partial<Record<ClassKey, string>>;
|
classes?: Partial<Record<ClassKey, string>>;
|
||||||
};
|
};
|
||||||
|
@ -3,10 +3,10 @@ import { clsx } from "keycloakify/tools/clsx";
|
|||||||
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
||||||
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import { useI18n } from "../i18n";
|
import type { I18n } from "../i18n";
|
||||||
|
|
||||||
export default function Password(props: PageProps<Extract<KcContext, { pageId: "password.ftl" }>>) {
|
export default function Password(props: PageProps<Extract<KcContext, { pageId: "password.ftl" }>, I18n>) {
|
||||||
const { kcContext, doUseDefaultCss, Template } = props;
|
const { kcContext, i18n, doUseDefaultCss, Template } = props;
|
||||||
|
|
||||||
const classes = {
|
const classes = {
|
||||||
...props.classes,
|
...props.classes,
|
||||||
@ -20,7 +20,7 @@ export default function Password(props: PageProps<Extract<KcContext, { pageId: "
|
|||||||
|
|
||||||
const { url, password, account, stateChecker } = kcContext;
|
const { url, password, account, stateChecker } = kcContext;
|
||||||
|
|
||||||
const { msgStr, msg } = useI18n({ kcContext });
|
const { msgStr, msg } = i18n;
|
||||||
|
|
||||||
const [currentPassword, setCurrentPassword] = useState("");
|
const [currentPassword, setCurrentPassword] = useState("");
|
||||||
const [newPassword, setNewPassword] = useState("");
|
const [newPassword, setNewPassword] = useState("");
|
||||||
@ -77,6 +77,7 @@ export default function Password(props: PageProps<Extract<KcContext, { pageId: "
|
|||||||
return kcContext.message;
|
return kcContext.message;
|
||||||
})()
|
})()
|
||||||
},
|
},
|
||||||
|
i18n,
|
||||||
doUseDefaultCss,
|
doUseDefaultCss,
|
||||||
classes
|
classes
|
||||||
}}
|
}}
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
||||||
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import { useI18n } from "../i18n";
|
import type { I18n } from "../i18n";
|
||||||
|
|
||||||
export default function Sessions(props: PageProps<Extract<KcContext, { pageId: "sessions.ftl" }>>) {
|
export default function Sessions(props: PageProps<Extract<KcContext, { pageId: "sessions.ftl" }>, I18n>) {
|
||||||
const { kcContext, doUseDefaultCss, Template, classes } = props;
|
const { kcContext, i18n, doUseDefaultCss, Template, classes } = props;
|
||||||
|
|
||||||
const { kcClsx } = getKcClsx({
|
const { kcClsx } = getKcClsx({
|
||||||
doUseDefaultCss,
|
doUseDefaultCss,
|
||||||
@ -13,9 +13,9 @@ export default function Sessions(props: PageProps<Extract<KcContext, { pageId: "
|
|||||||
|
|
||||||
const { url, stateChecker, sessions } = kcContext;
|
const { url, stateChecker, sessions } = kcContext;
|
||||||
|
|
||||||
const { msg } = useI18n({ kcContext });
|
const { msg } = i18n;
|
||||||
return (
|
return (
|
||||||
<Template {...{ kcContext, doUseDefaultCss, classes }} active="sessions">
|
<Template {...{ kcContext, i18n, doUseDefaultCss, classes }} active="sessions">
|
||||||
<div className={kcClsx("kcContentWrapperClass")}>
|
<div className={kcClsx("kcContentWrapperClass")}>
|
||||||
<div className="col-md-10">
|
<div className="col-md-10">
|
||||||
<h2>{msg("sessionsHtmlTitle")}</h2>
|
<h2>{msg("sessionsHtmlTitle")}</h2>
|
||||||
|
@ -2,10 +2,10 @@ import { clsx } from "keycloakify/tools/clsx";
|
|||||||
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
import { getKcClsx } from "keycloakify/account/lib/kcClsx";
|
||||||
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
import type { PageProps } from "keycloakify/account/pages/PageProps";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import { useI18n } from "../i18n";
|
import type { I18n } from "../i18n";
|
||||||
|
|
||||||
export default function Totp(props: PageProps<Extract<KcContext, { pageId: "totp.ftl" }>>) {
|
export default function Totp(props: PageProps<Extract<KcContext, { pageId: "totp.ftl" }>, I18n>) {
|
||||||
const { kcContext, doUseDefaultCss, Template, classes } = props;
|
const { kcContext, i18n, doUseDefaultCss, Template, classes } = props;
|
||||||
|
|
||||||
const { kcClsx } = getKcClsx({
|
const { kcClsx } = getKcClsx({
|
||||||
doUseDefaultCss,
|
doUseDefaultCss,
|
||||||
@ -14,16 +14,10 @@ export default function Totp(props: PageProps<Extract<KcContext, { pageId: "totp
|
|||||||
|
|
||||||
const { totp, mode, url, messagesPerField, stateChecker } = kcContext;
|
const { totp, mode, url, messagesPerField, stateChecker } = kcContext;
|
||||||
|
|
||||||
const { msg, msgStr, advancedMsg } = useI18n({ kcContext });
|
const { msg, msgStr, advancedMsg } = i18n;
|
||||||
|
|
||||||
const algToKeyUriAlg: Record<(typeof kcContext)["totp"]["policy"]["algorithm"], string> = {
|
|
||||||
HmacSHA1: "SHA1",
|
|
||||||
HmacSHA256: "SHA256",
|
|
||||||
HmacSHA512: "SHA512"
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Template {...{ kcContext, doUseDefaultCss, classes }} active="totp">
|
<Template {...{ kcContext, i18n, doUseDefaultCss, classes }} active="totp">
|
||||||
<>
|
<>
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<div className="col-md-10">
|
<div className="col-md-10">
|
||||||
@ -100,7 +94,7 @@ export default function Totp(props: PageProps<Extract<KcContext, { pageId: "totp
|
|||||||
{msg("totpType")}: {msg(`totp.${totp.policy.type}`)}
|
{msg("totpType")}: {msg(`totp.${totp.policy.type}`)}
|
||||||
</li>
|
</li>
|
||||||
<li id="kc-totp-algorithm">
|
<li id="kc-totp-algorithm">
|
||||||
{msg("totpAlgorithm")}: {algToKeyUriAlg?.[totp.policy.algorithm] ?? totp.policy.algorithm}
|
{msg("totpAlgorithm")}: {totp.policy.getAlgorithmKey()}
|
||||||
</li>
|
</li>
|
||||||
<li id="kc-totp-digits">
|
<li id="kc-totp-digits">
|
||||||
{msg("totpDigits")}: {totp.policy.digits}
|
{msg("totpDigits")}: {totp.policy.digits}
|
||||||
@ -160,9 +154,14 @@ export default function Totp(props: PageProps<Extract<KcContext, { pageId: "totp
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
{messagesPerField.existsError("totp") && (
|
{messagesPerField.existsError("totp") && (
|
||||||
<span id="input-error-otp-code" className={kcClsx("kcInputErrorMessageClass")} aria-live="polite">
|
<span
|
||||||
{messagesPerField.get("totp")}
|
id="input-error-otp-code"
|
||||||
</span>
|
className={kcClsx("kcInputErrorMessageClass")}
|
||||||
|
aria-live="polite"
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: messagesPerField.get("totp")
|
||||||
|
}}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<input type="hidden" id="totpSecret" name="totpSecret" value={totp.totpSecret} />
|
<input type="hidden" id="totpSecret" name="totpSecret" value={totp.totpSecret} />
|
||||||
@ -186,9 +185,14 @@ export default function Totp(props: PageProps<Extract<KcContext, { pageId: "totp
|
|||||||
aria-invalid={messagesPerField.existsError("userLabel")}
|
aria-invalid={messagesPerField.existsError("userLabel")}
|
||||||
/>
|
/>
|
||||||
{messagesPerField.existsError("userLabel") && (
|
{messagesPerField.existsError("userLabel") && (
|
||||||
<span id="input-error-otp-label" className={kcClsx("kcInputErrorMessageClass")} aria-live="polite">
|
<span
|
||||||
{messagesPerField.get("userLabel")}
|
id="input-error-otp-label"
|
||||||
</span>
|
className={kcClsx("kcInputErrorMessageClass")}
|
||||||
|
aria-live="polite"
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: messagesPerField.get("userLabel")
|
||||||
|
}}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
import { getThisCodebaseRootDirPath } from "./tools/getThisCodebaseRootDirPath";
|
import { getThisCodebaseRootDirPath } from "./tools/getThisCodebaseRootDirPath";
|
||||||
import cliSelect from "cli-select";
|
import cliSelect from "cli-select";
|
||||||
import {
|
import {
|
||||||
loginThemePageIds,
|
LOGIN_THEME_PAGE_IDS,
|
||||||
accountThemePageIds,
|
ACCOUNT_THEME_PAGE_IDS,
|
||||||
type LoginThemePageId,
|
type LoginThemePageId,
|
||||||
type AccountThemePageId,
|
type AccountThemePageId,
|
||||||
themeTypes,
|
THEME_TYPES,
|
||||||
type ThemeType
|
type ThemeType
|
||||||
} from "./shared/constants";
|
} from "./shared/constants";
|
||||||
import { capitalize } from "tsafe/capitalize";
|
import { capitalize } from "tsafe/capitalize";
|
||||||
@ -13,25 +13,56 @@ import * as fs from "fs";
|
|||||||
import { join as pathJoin, relative as pathRelative, dirname as pathDirname } from "path";
|
import { join as pathJoin, relative as pathRelative, dirname as pathDirname } from "path";
|
||||||
import { kebabCaseToCamelCase } from "./tools/kebabCaseToSnakeCase";
|
import { kebabCaseToCamelCase } from "./tools/kebabCaseToSnakeCase";
|
||||||
import { assert, Equals } from "tsafe/assert";
|
import { assert, Equals } from "tsafe/assert";
|
||||||
import { getThemeSrcDirPath } from "./shared/getThemeSrcDirPath";
|
|
||||||
import type { CliCommandOptions } from "./main";
|
import type { CliCommandOptions } from "./main";
|
||||||
import { readBuildOptions } from "./shared/buildOptions";
|
import { getBuildContext } from "./shared/buildContext";
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
|
|
||||||
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
||||||
const { cliCommandOptions } = params;
|
const { cliCommandOptions } = params;
|
||||||
|
|
||||||
const buildOptions = readBuildOptions({
|
const buildContext = getBuildContext({
|
||||||
cliCommandOptions
|
cliCommandOptions
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(chalk.cyan("Theme type:"));
|
console.log(chalk.cyan("Theme type:"));
|
||||||
|
|
||||||
const { value: themeType } = await cliSelect<ThemeType>({
|
const themeType = await (async () => {
|
||||||
values: [...themeTypes]
|
const values = THEME_TYPES.filter(themeType => {
|
||||||
}).catch(() => {
|
switch (themeType) {
|
||||||
process.exit(-1);
|
case "account":
|
||||||
});
|
return buildContext.implementedThemeTypes.account.isImplemented;
|
||||||
|
case "login":
|
||||||
|
return buildContext.implementedThemeTypes.login.isImplemented;
|
||||||
|
}
|
||||||
|
assert<Equals<typeof themeType, never>>(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
assert(values.length > 0, "No theme is implemented in this project");
|
||||||
|
|
||||||
|
if (values.length === 1) {
|
||||||
|
return values[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { value } = await cliSelect<ThemeType>({
|
||||||
|
values
|
||||||
|
}).catch(() => {
|
||||||
|
process.exit(-1);
|
||||||
|
});
|
||||||
|
|
||||||
|
return value;
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (
|
||||||
|
themeType === "account" &&
|
||||||
|
(assert(buildContext.implementedThemeTypes.account.isImplemented),
|
||||||
|
buildContext.implementedThemeTypes.account.type === "Single-Page")
|
||||||
|
) {
|
||||||
|
console.log(
|
||||||
|
`${chalk.red("✗")} Sorry, there is no Storybook support for Single-Page Account themes.`
|
||||||
|
);
|
||||||
|
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
console.log(`→ ${themeType}`);
|
console.log(`→ ${themeType}`);
|
||||||
|
|
||||||
@ -41,9 +72,9 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
values: (() => {
|
values: (() => {
|
||||||
switch (themeType) {
|
switch (themeType) {
|
||||||
case "login":
|
case "login":
|
||||||
return [...loginThemePageIds];
|
return [...LOGIN_THEME_PAGE_IDS];
|
||||||
case "account":
|
case "account":
|
||||||
return [...accountThemePageIds];
|
return [...ACCOUNT_THEME_PAGE_IDS];
|
||||||
}
|
}
|
||||||
assert<Equals<typeof themeType, never>>(false);
|
assert<Equals<typeof themeType, never>>(false);
|
||||||
})()
|
})()
|
||||||
@ -53,17 +84,13 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
|
|
||||||
console.log(`→ ${pageId}`);
|
console.log(`→ ${pageId}`);
|
||||||
|
|
||||||
const { themeSrcDirPath } = getThemeSrcDirPath({
|
|
||||||
reactAppRootDirPath: buildOptions.reactAppRootDirPath
|
|
||||||
});
|
|
||||||
|
|
||||||
const componentBasename = capitalize(kebabCaseToCamelCase(pageId)).replace(
|
const componentBasename = capitalize(kebabCaseToCamelCase(pageId)).replace(
|
||||||
/ftl$/,
|
/ftl$/,
|
||||||
"stories.tsx"
|
"stories.tsx"
|
||||||
);
|
);
|
||||||
|
|
||||||
const targetFilePath = pathJoin(
|
const targetFilePath = pathJoin(
|
||||||
themeSrcDirPath,
|
buildContext.themeSrcDirPath,
|
||||||
themeType,
|
themeType,
|
||||||
"pages",
|
"pages",
|
||||||
componentBasename
|
componentBasename
|
||||||
@ -86,7 +113,8 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
.toString("utf8")
|
.toString("utf8")
|
||||||
.replace('import React from "react";\n', "");
|
.replace('import React from "react";\n', "")
|
||||||
|
.replace(/from "[./]+dist\//, 'from "keycloakify/');
|
||||||
|
|
||||||
{
|
{
|
||||||
const targetDirPath = pathDirname(targetFilePath);
|
const targetDirPath = pathDirname(targetFilePath);
|
||||||
@ -103,7 +131,7 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
`${chalk.green("✓")} ${chalk.bold(
|
`${chalk.green("✓")} ${chalk.bold(
|
||||||
pathJoin(".", pathRelative(process.cwd(), targetFilePath))
|
pathJoin(".", pathRelative(process.cwd(), targetFilePath))
|
||||||
)} copy pasted from the Keycloakify source code into your project`,
|
)} copy pasted from the Keycloakify source code into your project`,
|
||||||
`You can start storybook with ${chalk.bold("yarn storybook")}`
|
`You can start storybook with ${chalk.bold("npm run storybook")}`
|
||||||
].join("\n")
|
].join("\n")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
import { copyKeycloakResourcesToPublic } from "./shared/copyKeycloakResourcesToPublic";
|
import { copyKeycloakResourcesToPublic } from "./shared/copyKeycloakResourcesToPublic";
|
||||||
import { readBuildOptions } from "./shared/buildOptions";
|
import { getBuildContext } from "./shared/buildContext";
|
||||||
import type { CliCommandOptions } from "./main";
|
import type { CliCommandOptions } from "./main";
|
||||||
|
|
||||||
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
||||||
const { cliCommandOptions } = params;
|
const { cliCommandOptions } = params;
|
||||||
|
|
||||||
const buildOptions = readBuildOptions({ cliCommandOptions });
|
const buildContext = getBuildContext({ cliCommandOptions });
|
||||||
|
|
||||||
await copyKeycloakResourcesToPublic({
|
await copyKeycloakResourcesToPublic({
|
||||||
buildOptions
|
buildContext
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,63 +0,0 @@
|
|||||||
import { join as pathJoin, relative as pathRelative, sep as pathSep } from "path";
|
|
||||||
import { promptKeycloakVersion } from "./shared/promptKeycloakVersion";
|
|
||||||
import { readBuildOptions } from "./shared/buildOptions";
|
|
||||||
import { downloadKeycloakDefaultTheme } from "./shared/downloadKeycloakDefaultTheme";
|
|
||||||
import { transformCodebase } from "./tools/transformCodebase";
|
|
||||||
import type { CliCommandOptions } from "./main";
|
|
||||||
import chalk from "chalk";
|
|
||||||
|
|
||||||
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
|
||||||
const { cliCommandOptions } = params;
|
|
||||||
|
|
||||||
const buildOptions = readBuildOptions({
|
|
||||||
cliCommandOptions
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
chalk.cyan(
|
|
||||||
"Select the Keycloak version from which you want to download the builtins theme:"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
const { keycloakVersion } = await promptKeycloakVersion({
|
|
||||||
startingFromMajor: undefined,
|
|
||||||
cacheDirPath: buildOptions.cacheDirPath
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(`→ ${keycloakVersion}`);
|
|
||||||
|
|
||||||
const destDirPath = pathJoin(
|
|
||||||
buildOptions.keycloakifyBuildDirPath,
|
|
||||||
"src",
|
|
||||||
"main",
|
|
||||||
"resources",
|
|
||||||
"theme"
|
|
||||||
);
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
[
|
|
||||||
`Downloading builtins theme of Keycloak ${keycloakVersion} here:`,
|
|
||||||
`- ${chalk.bold(
|
|
||||||
`.${pathSep}${pathJoin(pathRelative(process.cwd(), destDirPath), "base")}`
|
|
||||||
)}`,
|
|
||||||
`- ${chalk.bold(
|
|
||||||
`.${pathSep}${pathJoin(
|
|
||||||
pathRelative(process.cwd(), destDirPath),
|
|
||||||
"keycloak"
|
|
||||||
)}`
|
|
||||||
)}`
|
|
||||||
].join("\n")
|
|
||||||
);
|
|
||||||
|
|
||||||
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
|
||||||
keycloakVersion,
|
|
||||||
buildOptions
|
|
||||||
});
|
|
||||||
|
|
||||||
transformCodebase({
|
|
||||||
srcDirPath: defaultThemeDirPath,
|
|
||||||
destDirPath
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(chalk.green(`✓ done`));
|
|
||||||
}
|
|
@ -3,37 +3,144 @@
|
|||||||
import { getThisCodebaseRootDirPath } from "./tools/getThisCodebaseRootDirPath";
|
import { getThisCodebaseRootDirPath } from "./tools/getThisCodebaseRootDirPath";
|
||||||
import cliSelect from "cli-select";
|
import cliSelect from "cli-select";
|
||||||
import {
|
import {
|
||||||
loginThemePageIds,
|
LOGIN_THEME_PAGE_IDS,
|
||||||
accountThemePageIds,
|
ACCOUNT_THEME_PAGE_IDS,
|
||||||
type LoginThemePageId,
|
type LoginThemePageId,
|
||||||
type AccountThemePageId,
|
type AccountThemePageId,
|
||||||
themeTypes,
|
THEME_TYPES,
|
||||||
type ThemeType
|
type ThemeType
|
||||||
} from "./shared/constants";
|
} from "./shared/constants";
|
||||||
import { capitalize } from "tsafe/capitalize";
|
import { capitalize } from "tsafe/capitalize";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { join as pathJoin, relative as pathRelative, dirname as pathDirname } from "path";
|
import {
|
||||||
|
join as pathJoin,
|
||||||
|
relative as pathRelative,
|
||||||
|
dirname as pathDirname,
|
||||||
|
basename as pathBasename
|
||||||
|
} from "path";
|
||||||
import { kebabCaseToCamelCase } from "./tools/kebabCaseToSnakeCase";
|
import { kebabCaseToCamelCase } from "./tools/kebabCaseToSnakeCase";
|
||||||
import { assert, Equals } from "tsafe/assert";
|
import { assert, Equals } from "tsafe/assert";
|
||||||
import { getThemeSrcDirPath } from "./shared/getThemeSrcDirPath";
|
|
||||||
import type { CliCommandOptions } from "./main";
|
import type { CliCommandOptions } from "./main";
|
||||||
import { readBuildOptions } from "./shared/buildOptions";
|
import { getBuildContext } from "./shared/buildContext";
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
|
|
||||||
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
||||||
const { cliCommandOptions } = params;
|
const { cliCommandOptions } = params;
|
||||||
|
|
||||||
const buildOptions = readBuildOptions({
|
const buildContext = getBuildContext({
|
||||||
cliCommandOptions
|
cliCommandOptions
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(chalk.cyan("Theme type:"));
|
console.log(chalk.cyan("Theme type:"));
|
||||||
|
|
||||||
const { value: themeType } = await cliSelect<ThemeType>({
|
const themeType = await (async () => {
|
||||||
values: [...themeTypes]
|
const values = THEME_TYPES.filter(themeType => {
|
||||||
}).catch(() => {
|
switch (themeType) {
|
||||||
process.exit(-1);
|
case "account":
|
||||||
});
|
return buildContext.implementedThemeTypes.account.isImplemented;
|
||||||
|
case "login":
|
||||||
|
return buildContext.implementedThemeTypes.login.isImplemented;
|
||||||
|
}
|
||||||
|
assert<Equals<typeof themeType, never>>(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
assert(values.length > 0, "No theme is implemented in this project");
|
||||||
|
|
||||||
|
if (values.length === 1) {
|
||||||
|
return values[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { value } = await cliSelect<ThemeType>({
|
||||||
|
values
|
||||||
|
}).catch(() => {
|
||||||
|
process.exit(-1);
|
||||||
|
});
|
||||||
|
|
||||||
|
return value;
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (
|
||||||
|
themeType === "account" &&
|
||||||
|
(assert(buildContext.implementedThemeTypes.account.isImplemented),
|
||||||
|
buildContext.implementedThemeTypes.account.type === "Single-Page")
|
||||||
|
) {
|
||||||
|
const srcDirPath = pathJoin(
|
||||||
|
pathDirname(buildContext.packageJsonFilePath),
|
||||||
|
"node_modules",
|
||||||
|
"@keycloakify",
|
||||||
|
"keycloak-account-ui",
|
||||||
|
"src"
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
[
|
||||||
|
`There isn't an interactive CLI to eject components of the Single-Page Account theme.`,
|
||||||
|
`You can however copy paste into your codebase the any file or directory from the following source directory:`,
|
||||||
|
``,
|
||||||
|
`${chalk.bold(pathJoin(pathRelative(process.cwd(), srcDirPath)))}`,
|
||||||
|
``
|
||||||
|
].join("\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
eject_entrypoint: {
|
||||||
|
const kcAccountUiTsxFileRelativePath = "KcAccountUi.tsx";
|
||||||
|
|
||||||
|
const accountThemeSrcDirPath = pathJoin(
|
||||||
|
buildContext.themeSrcDirPath,
|
||||||
|
"account"
|
||||||
|
);
|
||||||
|
|
||||||
|
const targetFilePath = pathJoin(
|
||||||
|
accountThemeSrcDirPath,
|
||||||
|
kcAccountUiTsxFileRelativePath
|
||||||
|
);
|
||||||
|
|
||||||
|
if (fs.existsSync(targetFilePath)) {
|
||||||
|
break eject_entrypoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.cpSync(
|
||||||
|
pathJoin(srcDirPath, kcAccountUiTsxFileRelativePath),
|
||||||
|
targetFilePath
|
||||||
|
);
|
||||||
|
|
||||||
|
{
|
||||||
|
const kcPageTsxFilePath = pathJoin(accountThemeSrcDirPath, "KcPage.tsx");
|
||||||
|
|
||||||
|
const kcPageTsxCode = fs.readFileSync(kcPageTsxFilePath).toString("utf8");
|
||||||
|
|
||||||
|
const componentName = pathBasename(
|
||||||
|
kcAccountUiTsxFileRelativePath
|
||||||
|
).replace(/.tsx$/, "");
|
||||||
|
|
||||||
|
const modifiedKcPageTsxCode = kcPageTsxCode.replace(
|
||||||
|
`@keycloakify/keycloak-account-ui/${componentName}`,
|
||||||
|
`./${componentName}`
|
||||||
|
);
|
||||||
|
|
||||||
|
fs.writeFileSync(
|
||||||
|
kcPageTsxFilePath,
|
||||||
|
Buffer.from(modifiedKcPageTsxCode, "utf8")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const routesTsxFilePath = pathRelative(
|
||||||
|
process.cwd(),
|
||||||
|
pathJoin(srcDirPath, "routes.tsx")
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
[
|
||||||
|
`To help you get started ${chalk.bold(pathRelative(process.cwd(), targetFilePath))} has been copied into your project.`,
|
||||||
|
`The next step is usually to eject ${chalk.bold(routesTsxFilePath)}`,
|
||||||
|
`with \`cp ${routesTsxFilePath} ${pathRelative(process.cwd(), accountThemeSrcDirPath)}\``,
|
||||||
|
`then update the import of routes in ${kcAccountUiTsxFileRelativePath}.`
|
||||||
|
].join("\n")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
console.log(`→ ${themeType}`);
|
console.log(`→ ${themeType}`);
|
||||||
|
|
||||||
@ -55,10 +162,10 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
return [
|
return [
|
||||||
templateValue,
|
templateValue,
|
||||||
userProfileFormFieldsValue,
|
userProfileFormFieldsValue,
|
||||||
...loginThemePageIds
|
...LOGIN_THEME_PAGE_IDS
|
||||||
];
|
];
|
||||||
case "account":
|
case "account":
|
||||||
return [templateValue, ...accountThemePageIds];
|
return [templateValue, ...ACCOUNT_THEME_PAGE_IDS];
|
||||||
}
|
}
|
||||||
assert<Equals<typeof themeType, never>>(false);
|
assert<Equals<typeof themeType, never>>(false);
|
||||||
})()
|
})()
|
||||||
@ -68,10 +175,6 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
|
|
||||||
console.log(`→ ${pageIdOrComponent}`);
|
console.log(`→ ${pageIdOrComponent}`);
|
||||||
|
|
||||||
const { themeSrcDirPath } = getThemeSrcDirPath({
|
|
||||||
reactAppRootDirPath: buildOptions.reactAppRootDirPath
|
|
||||||
});
|
|
||||||
|
|
||||||
const componentBasename = (() => {
|
const componentBasename = (() => {
|
||||||
if (pageIdOrComponent === templateValue) {
|
if (pageIdOrComponent === templateValue) {
|
||||||
return "Template.tsx";
|
return "Template.tsx";
|
||||||
@ -96,7 +199,7 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
const targetFilePath = pathJoin(
|
const targetFilePath = pathJoin(
|
||||||
themeSrcDirPath,
|
buildContext.themeSrcDirPath,
|
||||||
themeType,
|
themeType,
|
||||||
pagesOrDot,
|
pagesOrDot,
|
||||||
componentBasename
|
componentBasename
|
||||||
@ -149,7 +252,11 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
break edit_KcApp;
|
break edit_KcApp;
|
||||||
}
|
}
|
||||||
|
|
||||||
const kcAppTsxPath = pathJoin(themeSrcDirPath, themeType, "KcApp.tsx");
|
const kcAppTsxPath = pathJoin(
|
||||||
|
buildContext.themeSrcDirPath,
|
||||||
|
themeType,
|
||||||
|
"KcPage.tsx"
|
||||||
|
);
|
||||||
|
|
||||||
const kcAppTsxCode = fs.readFileSync(kcAppTsxPath).toString("utf8");
|
const kcAppTsxCode = fs.readFileSync(kcAppTsxPath).toString("utf8");
|
||||||
|
|
||||||
@ -172,7 +279,7 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
if (kcAppTsxCode === modifiedKcAppTsxCode) {
|
if (kcAppTsxCode === modifiedKcAppTsxCode) {
|
||||||
console.log(
|
console.log(
|
||||||
chalk.red(
|
chalk.red(
|
||||||
"Unable to automatically update KcApp.tsx, please update it manually"
|
"Unable to automatically update KcPage.tsx, please update it manually"
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
@ -191,6 +298,8 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
|
|
||||||
const userProfileFormFieldComponentName = "UserProfileFormFields";
|
const userProfileFormFieldComponentName = "UserProfileFormFields";
|
||||||
|
|
||||||
|
const componentName = componentBasename.replace(/.tsx$/, "");
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
[
|
[
|
||||||
``,
|
``,
|
||||||
@ -199,23 +308,20 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
`${chalk.bold(
|
`${chalk.bold(
|
||||||
pathJoin(
|
pathJoin(
|
||||||
".",
|
".",
|
||||||
pathRelative(process.cwd(), themeSrcDirPath),
|
pathRelative(process.cwd(), buildContext.themeSrcDirPath),
|
||||||
themeType,
|
themeType,
|
||||||
"KcApp.tsx"
|
"KcPage.tsx"
|
||||||
)
|
)
|
||||||
)}:`,
|
)}:`,
|
||||||
chalk.grey("```"),
|
chalk.grey("```"),
|
||||||
`// ...`,
|
`// ...`,
|
||||||
``,
|
``,
|
||||||
chalk.green(
|
chalk.green(
|
||||||
`+const ${componentBasename.replace(
|
`+const ${componentName} = lazy(() => import("./pages/${componentName}"));`
|
||||||
/.tsx$/,
|
|
||||||
""
|
|
||||||
)} = lazy(() => import("./pages/${componentBasename}"));`
|
|
||||||
),
|
),
|
||||||
...[
|
...[
|
||||||
``,
|
``,
|
||||||
` export default function KcApp(props: { kcContext: KcContext; }) {`,
|
` export default function KcPage(props: { kcContext: KcContext; }) {`,
|
||||||
``,
|
``,
|
||||||
` // ...`,
|
` // ...`,
|
||||||
``,
|
``,
|
||||||
@ -225,15 +331,16 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
` switch (kcContext.pageId) {`,
|
` switch (kcContext.pageId) {`,
|
||||||
` // ...`,
|
` // ...`,
|
||||||
`+ case "${pageIdOrComponent}": return (`,
|
`+ case "${pageIdOrComponent}": return (`,
|
||||||
`+ <Login`,
|
`+ <${componentName}`,
|
||||||
`+ {...{ kcContext, i18n, classes }}`,
|
`+ {...{ kcContext, i18n, classes }}`,
|
||||||
`+ Template={Template}`,
|
`+ Template={Template}`,
|
||||||
|
`+ doUseDefaultCss={true}`,
|
||||||
...(!componentCode.includes(userProfileFormFieldComponentName)
|
...(!componentCode.includes(userProfileFormFieldComponentName)
|
||||||
? []
|
? []
|
||||||
: [
|
: [
|
||||||
`+ ${userProfileFormFieldComponentName}={${userProfileFormFieldComponentName}}`
|
`+ ${userProfileFormFieldComponentName}={${userProfileFormFieldComponentName}}`,
|
||||||
|
`+ doMakeUserConfirmPassword={doMakeUserConfirmPassword}`
|
||||||
]),
|
]),
|
||||||
`+ doUseDefaultCss={true}`,
|
|
||||||
`+ />`,
|
`+ />`,
|
||||||
`+ );`,
|
`+ );`,
|
||||||
` default: return <Fallback /* .. */ />;`,
|
` default: return <Fallback /* .. */ />;`,
|
||||||
|
32
src/bin/initialize-account-theme/copyBoilerplate.ts
Normal file
32
src/bin/initialize-account-theme/copyBoilerplate.ts
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
import * as fs from "fs";
|
||||||
|
import { join as pathJoin } from "path";
|
||||||
|
import { getThisCodebaseRootDirPath } from "../tools/getThisCodebaseRootDirPath";
|
||||||
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
|
||||||
|
export function copyBoilerplate(params: {
|
||||||
|
accountThemeType: "Single-Page" | "Multi-Page";
|
||||||
|
accountThemeSrcDirPath: string;
|
||||||
|
}) {
|
||||||
|
const { accountThemeType, accountThemeSrcDirPath } = params;
|
||||||
|
|
||||||
|
fs.cpSync(
|
||||||
|
pathJoin(
|
||||||
|
getThisCodebaseRootDirPath(),
|
||||||
|
"src",
|
||||||
|
"bin",
|
||||||
|
"initialize-account-theme",
|
||||||
|
"src",
|
||||||
|
(() => {
|
||||||
|
switch (accountThemeType) {
|
||||||
|
case "Single-Page":
|
||||||
|
return "single-page";
|
||||||
|
case "Multi-Page":
|
||||||
|
return "multi-page";
|
||||||
|
}
|
||||||
|
assert<Equals<typeof accountThemeType, never>>(false);
|
||||||
|
})()
|
||||||
|
),
|
||||||
|
accountThemeSrcDirPath,
|
||||||
|
{ recursive: true }
|
||||||
|
);
|
||||||
|
}
|
1
src/bin/initialize-account-theme/index.ts
Normal file
1
src/bin/initialize-account-theme/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from "./initialize-account-theme";
|
112
src/bin/initialize-account-theme/initialize-account-theme.ts
Normal file
112
src/bin/initialize-account-theme/initialize-account-theme.ts
Normal file
@ -0,0 +1,112 @@
|
|||||||
|
import { getBuildContext } from "../shared/buildContext";
|
||||||
|
import type { CliCommandOptions } from "../main";
|
||||||
|
import cliSelect from "cli-select";
|
||||||
|
import child_process from "child_process";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import { join as pathJoin, relative as pathRelative } from "path";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { updateAccountThemeImplementationInConfig } from "./updateAccountThemeImplementationInConfig";
|
||||||
|
import { generateKcGenTs } from "../shared/generateKcGenTs";
|
||||||
|
|
||||||
|
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
||||||
|
const { cliCommandOptions } = params;
|
||||||
|
|
||||||
|
const buildContext = getBuildContext({ cliCommandOptions });
|
||||||
|
|
||||||
|
const accountThemeSrcDirPath = pathJoin(buildContext.themeSrcDirPath, "account");
|
||||||
|
|
||||||
|
if (
|
||||||
|
fs.existsSync(accountThemeSrcDirPath) &&
|
||||||
|
fs.readdirSync(accountThemeSrcDirPath).length > 0
|
||||||
|
) {
|
||||||
|
console.warn(
|
||||||
|
chalk.red(
|
||||||
|
`There is already a ${pathRelative(
|
||||||
|
process.cwd(),
|
||||||
|
accountThemeSrcDirPath
|
||||||
|
)} directory in your project. Aborting.`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
process.exit(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
exit_if_uncommitted_changes: {
|
||||||
|
let hasUncommittedChanges: boolean | undefined = undefined;
|
||||||
|
|
||||||
|
try {
|
||||||
|
hasUncommittedChanges =
|
||||||
|
child_process
|
||||||
|
.execSync(`git status --porcelain`, {
|
||||||
|
cwd: buildContext.projectDirPath
|
||||||
|
})
|
||||||
|
.toString()
|
||||||
|
.trim() !== "";
|
||||||
|
} catch {
|
||||||
|
// Probably not a git repository
|
||||||
|
break exit_if_uncommitted_changes;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasUncommittedChanges) {
|
||||||
|
break exit_if_uncommitted_changes;
|
||||||
|
}
|
||||||
|
console.warn(
|
||||||
|
[
|
||||||
|
chalk.red(
|
||||||
|
"Please commit or stash your changes before running this command.\n"
|
||||||
|
),
|
||||||
|
"This command will modify your project's files so it's better to have a clean working directory",
|
||||||
|
"so that you can easily see what has been changed and revert if needed."
|
||||||
|
].join(" ")
|
||||||
|
);
|
||||||
|
|
||||||
|
process.exit(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { value: accountThemeType } = await cliSelect({
|
||||||
|
values: ["Single-Page" as const, "Multi-Page" as const]
|
||||||
|
}).catch(() => {
|
||||||
|
process.exit(-1);
|
||||||
|
});
|
||||||
|
|
||||||
|
switch (accountThemeType) {
|
||||||
|
case "Multi-Page":
|
||||||
|
{
|
||||||
|
const { initializeAccountTheme_multiPage } = await import(
|
||||||
|
"./initializeAccountTheme_multiPage"
|
||||||
|
);
|
||||||
|
|
||||||
|
await initializeAccountTheme_multiPage({
|
||||||
|
accountThemeSrcDirPath
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "Single-Page":
|
||||||
|
{
|
||||||
|
const { initializeAccountTheme_singlePage } = await import(
|
||||||
|
"./initializeAccountTheme_singlePage"
|
||||||
|
);
|
||||||
|
|
||||||
|
await initializeAccountTheme_singlePage({
|
||||||
|
accountThemeSrcDirPath,
|
||||||
|
buildContext
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateAccountThemeImplementationInConfig({ buildContext, accountThemeType });
|
||||||
|
|
||||||
|
await generateKcGenTs({
|
||||||
|
buildContext: {
|
||||||
|
...buildContext,
|
||||||
|
implementedThemeTypes: {
|
||||||
|
...buildContext.implementedThemeTypes,
|
||||||
|
account: {
|
||||||
|
isImplemented: true,
|
||||||
|
type: accountThemeType
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
import { relative as pathRelative } from "path";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import { copyBoilerplate } from "./copyBoilerplate";
|
||||||
|
|
||||||
|
export async function initializeAccountTheme_multiPage(params: {
|
||||||
|
accountThemeSrcDirPath: string;
|
||||||
|
}) {
|
||||||
|
const { accountThemeSrcDirPath } = params;
|
||||||
|
|
||||||
|
copyBoilerplate({
|
||||||
|
accountThemeType: "Multi-Page",
|
||||||
|
accountThemeSrcDirPath
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
[
|
||||||
|
chalk.green("The Multi-Page account theme has been initialized."),
|
||||||
|
`Directory created: ${chalk.bold(pathRelative(process.cwd(), accountThemeSrcDirPath))}`
|
||||||
|
].join("\n")
|
||||||
|
);
|
||||||
|
}
|
@ -0,0 +1,152 @@
|
|||||||
|
import { join as pathJoin, relative as pathRelative, dirname as pathDirname } from "path";
|
||||||
|
import type { BuildContext } from "../shared/buildContext";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import {
|
||||||
|
getLatestsSemVersionedTag,
|
||||||
|
type BuildContextLike as BuildContextLike_getLatestsSemVersionedTag
|
||||||
|
} from "../shared/getLatestsSemVersionedTag";
|
||||||
|
import fetch from "make-fetch-happen";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
import { is } from "tsafe/is";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
|
import { npmInstall } from "../tools/npmInstall";
|
||||||
|
import { copyBoilerplate } from "./copyBoilerplate";
|
||||||
|
import { getThisCodebaseRootDirPath } from "../tools/getThisCodebaseRootDirPath";
|
||||||
|
|
||||||
|
type BuildContextLike = BuildContextLike_getLatestsSemVersionedTag & {
|
||||||
|
fetchOptions: BuildContext["fetchOptions"];
|
||||||
|
packageJsonFilePath: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
|
export async function initializeAccountTheme_singlePage(params: {
|
||||||
|
accountThemeSrcDirPath: string;
|
||||||
|
buildContext: BuildContextLike;
|
||||||
|
}) {
|
||||||
|
const { accountThemeSrcDirPath, buildContext } = params;
|
||||||
|
|
||||||
|
const OWNER = "keycloakify";
|
||||||
|
const REPO = "keycloak-account-ui";
|
||||||
|
|
||||||
|
const [semVersionedTag] = await getLatestsSemVersionedTag({
|
||||||
|
owner: OWNER,
|
||||||
|
repo: REPO,
|
||||||
|
count: 1,
|
||||||
|
doIgnoreReleaseCandidates: false,
|
||||||
|
buildContext
|
||||||
|
});
|
||||||
|
|
||||||
|
const dependencies = await fetch(
|
||||||
|
`https://raw.githubusercontent.com/${OWNER}/${REPO}/${semVersionedTag.tag}/dependencies.gen.json`,
|
||||||
|
buildContext.fetchOptions
|
||||||
|
)
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(
|
||||||
|
(() => {
|
||||||
|
type Dependencies = {
|
||||||
|
dependencies: Record<string, string>;
|
||||||
|
devDependencies?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const zDependencies = (() => {
|
||||||
|
type TargetType = Dependencies;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
dependencies: z.record(z.string()),
|
||||||
|
devDependencies: z.record(z.string()).optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
return o => zDependencies.parse(o);
|
||||||
|
})()
|
||||||
|
);
|
||||||
|
|
||||||
|
dependencies.dependencies["@keycloakify/keycloak-account-ui"] = semVersionedTag.tag;
|
||||||
|
|
||||||
|
const parsedPackageJson = (() => {
|
||||||
|
type ParsedPackageJson = {
|
||||||
|
dependencies?: Record<string, string>;
|
||||||
|
devDependencies?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const zParsedPackageJson = (() => {
|
||||||
|
type TargetType = ParsedPackageJson;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
dependencies: z.record(z.string()).optional(),
|
||||||
|
devDependencies: z.record(z.string()).optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
const parsedPackageJson = JSON.parse(
|
||||||
|
fs.readFileSync(buildContext.packageJsonFilePath).toString("utf8")
|
||||||
|
);
|
||||||
|
|
||||||
|
zParsedPackageJson.parse(parsedPackageJson);
|
||||||
|
|
||||||
|
assert(is<ParsedPackageJson>(parsedPackageJson));
|
||||||
|
|
||||||
|
return parsedPackageJson;
|
||||||
|
})();
|
||||||
|
|
||||||
|
parsedPackageJson.dependencies = {
|
||||||
|
...parsedPackageJson.dependencies,
|
||||||
|
...dependencies.dependencies
|
||||||
|
};
|
||||||
|
|
||||||
|
parsedPackageJson.devDependencies = {
|
||||||
|
...parsedPackageJson.devDependencies,
|
||||||
|
...dependencies.devDependencies
|
||||||
|
};
|
||||||
|
|
||||||
|
if (Object.keys(parsedPackageJson.devDependencies).length === 0) {
|
||||||
|
delete parsedPackageJson.devDependencies;
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(
|
||||||
|
buildContext.packageJsonFilePath,
|
||||||
|
JSON.stringify(parsedPackageJson, undefined, 4)
|
||||||
|
);
|
||||||
|
|
||||||
|
run_npm_install: {
|
||||||
|
if (
|
||||||
|
JSON.parse(
|
||||||
|
fs
|
||||||
|
.readFileSync(pathJoin(getThisCodebaseRootDirPath(), "package.json"))
|
||||||
|
.toString("utf8")
|
||||||
|
)["version"] === "0.0.0"
|
||||||
|
) {
|
||||||
|
//NOTE: Linked version
|
||||||
|
break run_npm_install;
|
||||||
|
}
|
||||||
|
|
||||||
|
npmInstall({ packageJsonDirPath: pathDirname(buildContext.packageJsonFilePath) });
|
||||||
|
}
|
||||||
|
|
||||||
|
copyBoilerplate({
|
||||||
|
accountThemeType: "Single-Page",
|
||||||
|
accountThemeSrcDirPath
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
[
|
||||||
|
chalk.green(
|
||||||
|
"The Single-Page account theme has been successfully initialized."
|
||||||
|
),
|
||||||
|
`Using Account UI of Keycloak version: ${chalk.bold(semVersionedTag.tag.split("-")[0])}`,
|
||||||
|
`Directory created: ${chalk.bold(pathRelative(process.cwd(), accountThemeSrcDirPath))}`,
|
||||||
|
`Dependencies added to your project's package.json: `,
|
||||||
|
chalk.bold(JSON.stringify(dependencies, null, 2))
|
||||||
|
].join("\n")
|
||||||
|
);
|
||||||
|
}
|
12
src/bin/initialize-account-theme/src/multi-page/KcContext.ts
Normal file
12
src/bin/initialize-account-theme/src/multi-page/KcContext.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/ban-types */
|
||||||
|
import type { ExtendKcContext } from "keycloakify/account";
|
||||||
|
import type { KcEnvName, ThemeName } from "../kc.gen";
|
||||||
|
|
||||||
|
export type KcContextExtension = {
|
||||||
|
themeName: ThemeName;
|
||||||
|
properties: Record<KcEnvName, string> & {};
|
||||||
|
};
|
||||||
|
|
||||||
|
export type KcContextExtensionPerPage = {};
|
||||||
|
|
||||||
|
export type KcContext = ExtendKcContext<KcContextExtension, KcContextExtensionPerPage>;
|
25
src/bin/initialize-account-theme/src/multi-page/KcPage.tsx
Normal file
25
src/bin/initialize-account-theme/src/multi-page/KcPage.tsx
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import { Suspense } from "react";
|
||||||
|
import type { ClassKey } from "keycloakify/account";
|
||||||
|
import type { KcContext } from "./KcContext";
|
||||||
|
import { useI18n } from "./i18n";
|
||||||
|
import DefaultPage from "keycloakify/account/DefaultPage";
|
||||||
|
import Template from "keycloakify/account/Template";
|
||||||
|
|
||||||
|
export default function KcPage(props: { kcContext: KcContext }) {
|
||||||
|
const { kcContext } = props;
|
||||||
|
|
||||||
|
const { i18n } = useI18n({ kcContext });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Suspense>
|
||||||
|
{(() => {
|
||||||
|
switch (kcContext.pageId) {
|
||||||
|
default:
|
||||||
|
return <DefaultPage kcContext={kcContext} i18n={i18n} classes={classes} Template={Template} doUseDefaultCss={true} />;
|
||||||
|
}
|
||||||
|
})()}
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const classes = {} satisfies { [key in ClassKey]?: string };
|
@ -0,0 +1,38 @@
|
|||||||
|
import type { DeepPartial } from "keycloakify/tools/DeepPartial";
|
||||||
|
import type { KcContext } from "./KcContext";
|
||||||
|
import { createGetKcContextMock } from "keycloakify/account/KcContext";
|
||||||
|
import type { KcContextExtension, KcContextExtensionPerPage } from "./KcContext";
|
||||||
|
import KcPage from "./KcPage";
|
||||||
|
import { themeNames, kcEnvDefaults } from "../kc.gen";
|
||||||
|
|
||||||
|
const kcContextExtension: KcContextExtension = {
|
||||||
|
themeName: themeNames[0],
|
||||||
|
properties: {
|
||||||
|
...kcEnvDefaults
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const kcContextExtensionPerPage: KcContextExtensionPerPage = {};
|
||||||
|
|
||||||
|
export const { getKcContextMock } = createGetKcContextMock({
|
||||||
|
kcContextExtension,
|
||||||
|
kcContextExtensionPerPage,
|
||||||
|
overrides: {},
|
||||||
|
overridesPerPage: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
export function createKcPageStory<PageId extends KcContext["pageId"]>(params: { pageId: PageId }) {
|
||||||
|
const { pageId } = params;
|
||||||
|
|
||||||
|
function KcPageStory(props: { kcContext?: DeepPartial<Extract<KcContext, { pageId: PageId }>> }) {
|
||||||
|
const { kcContext: overrides } = props;
|
||||||
|
|
||||||
|
const kcContextMock = getKcContextMock({
|
||||||
|
pageId,
|
||||||
|
overrides
|
||||||
|
});
|
||||||
|
|
||||||
|
return <KcPage kcContext={kcContextMock} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { KcPageStory };
|
||||||
|
}
|
5
src/bin/initialize-account-theme/src/multi-page/i18n.ts
Normal file
5
src/bin/initialize-account-theme/src/multi-page/i18n.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { createUseI18n } from "keycloakify/account";
|
||||||
|
|
||||||
|
export const { useI18n, ofTypeI18n } = createUseI18n({});
|
||||||
|
|
||||||
|
export type I18n = typeof ofTypeI18n;
|
@ -0,0 +1,7 @@
|
|||||||
|
import type { KcContextLike } from "@keycloakify/keycloak-account-ui";
|
||||||
|
import type { KcEnvName } from "../kc.gen";
|
||||||
|
|
||||||
|
export type KcContext = KcContextLike & {
|
||||||
|
themeType: "account";
|
||||||
|
properties: Record<KcEnvName, string>;
|
||||||
|
};
|
11
src/bin/initialize-account-theme/src/single-page/KcPage.tsx
Normal file
11
src/bin/initialize-account-theme/src/single-page/KcPage.tsx
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import { lazy } from "react";
|
||||||
|
import { KcAccountUiLoader } from "@keycloakify/keycloak-account-ui";
|
||||||
|
import type { KcContext } from "./KcContext";
|
||||||
|
|
||||||
|
const KcAccountUi = lazy(() => import("@keycloakify/keycloak-account-ui/KcAccountUi"));
|
||||||
|
|
||||||
|
export default function KcPage(props: { kcContext: KcContext }) {
|
||||||
|
const { kcContext } = props;
|
||||||
|
|
||||||
|
return <KcAccountUiLoader kcContext={kcContext} KcAccountUi={KcAccountUi} />;
|
||||||
|
}
|
@ -0,0 +1,92 @@
|
|||||||
|
import { join as pathJoin } from "path";
|
||||||
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
import type { BuildContext } from "../shared/buildContext";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
|
|
||||||
|
export type BuildContextLike = {
|
||||||
|
bundler: BuildContext["bundler"];
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
|
export function updateAccountThemeImplementationInConfig(params: {
|
||||||
|
buildContext: BuildContext;
|
||||||
|
accountThemeType: "Single-Page" | "Multi-Page";
|
||||||
|
}) {
|
||||||
|
const { buildContext, accountThemeType } = params;
|
||||||
|
|
||||||
|
switch (buildContext.bundler) {
|
||||||
|
case "vite":
|
||||||
|
{
|
||||||
|
const viteConfigPath = pathJoin(
|
||||||
|
buildContext.projectDirPath,
|
||||||
|
"vite.config.ts"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!fs.existsSync(viteConfigPath)) {
|
||||||
|
console.log(
|
||||||
|
chalk.bold(
|
||||||
|
`You must manually set the accountThemeImplementation to "${accountThemeType}" in your vite config`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const viteConfigContent = fs
|
||||||
|
.readFileSync(viteConfigPath)
|
||||||
|
.toString("utf8");
|
||||||
|
|
||||||
|
const modifiedViteConfigContent = viteConfigContent.replace(
|
||||||
|
/accountThemeImplementation\s*:\s*"none"/,
|
||||||
|
`accountThemeImplementation: "${accountThemeType}"`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (modifiedViteConfigContent === viteConfigContent) {
|
||||||
|
console.log(
|
||||||
|
chalk.bold(
|
||||||
|
`You must manually set the accountThemeImplementation to "${accountThemeType}" in your vite.config.ts`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(viteConfigPath, modifiedViteConfigContent);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "webpack":
|
||||||
|
{
|
||||||
|
const parsedPackageJson = (() => {
|
||||||
|
type ParsedPackageJson = {
|
||||||
|
keycloakify: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const zParsedPackageJson = (() => {
|
||||||
|
type TargetType = ParsedPackageJson;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
keycloakify: z.record(z.string())
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
return zParsedPackageJson.parse(
|
||||||
|
JSON.parse(
|
||||||
|
fs
|
||||||
|
.readFileSync(buildContext.packageJsonFilePath)
|
||||||
|
.toString("utf8")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
})();
|
||||||
|
|
||||||
|
parsedPackageJson.keycloakify.accountThemeImplementation =
|
||||||
|
accountThemeType;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
@ -2,21 +2,16 @@ import { downloadKeycloakDefaultTheme } from "./shared/downloadKeycloakDefaultTh
|
|||||||
import { join as pathJoin, relative as pathRelative } from "path";
|
import { join as pathJoin, relative as pathRelative } from "path";
|
||||||
import { transformCodebase } from "./tools/transformCodebase";
|
import { transformCodebase } from "./tools/transformCodebase";
|
||||||
import { promptKeycloakVersion } from "./shared/promptKeycloakVersion";
|
import { promptKeycloakVersion } from "./shared/promptKeycloakVersion";
|
||||||
import { readBuildOptions } from "./shared/buildOptions";
|
import { getBuildContext } from "./shared/buildContext";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { getThemeSrcDirPath } from "./shared/getThemeSrcDirPath";
|
|
||||||
import type { CliCommandOptions } from "./main";
|
import type { CliCommandOptions } from "./main";
|
||||||
|
|
||||||
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
||||||
const { cliCommandOptions } = params;
|
const { cliCommandOptions } = params;
|
||||||
|
|
||||||
const buildOptions = readBuildOptions({ cliCommandOptions });
|
const buildContext = getBuildContext({ cliCommandOptions });
|
||||||
|
|
||||||
const { themeSrcDirPath } = getThemeSrcDirPath({
|
const emailThemeSrcDirPath = pathJoin(buildContext.themeSrcDirPath, "email");
|
||||||
reactAppRootDirPath: buildOptions.reactAppRootDirPath
|
|
||||||
});
|
|
||||||
|
|
||||||
const emailThemeSrcDirPath = pathJoin(themeSrcDirPath, "email");
|
|
||||||
|
|
||||||
if (fs.existsSync(emailThemeSrcDirPath)) {
|
if (fs.existsSync(emailThemeSrcDirPath)) {
|
||||||
console.warn(
|
console.warn(
|
||||||
@ -34,12 +29,13 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
const { keycloakVersion } = await promptKeycloakVersion({
|
const { keycloakVersion } = await promptKeycloakVersion({
|
||||||
// NOTE: This is arbitrary
|
// NOTE: This is arbitrary
|
||||||
startingFromMajor: 17,
|
startingFromMajor: 17,
|
||||||
cacheDirPath: buildOptions.cacheDirPath
|
excludeMajorVersions: [],
|
||||||
|
buildContext
|
||||||
});
|
});
|
||||||
|
|
||||||
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
||||||
keycloakVersion,
|
keycloakVersion,
|
||||||
buildOptions
|
buildContext
|
||||||
});
|
});
|
||||||
|
|
||||||
transformCodebase({
|
transformCodebase({
|
||||||
|
@ -5,79 +5,72 @@ import type {
|
|||||||
} from "./extensionVersions";
|
} from "./extensionVersions";
|
||||||
import { join as pathJoin, dirname as pathDirname } from "path";
|
import { join as pathJoin, dirname as pathDirname } from "path";
|
||||||
import { transformCodebase } from "../../tools/transformCodebase";
|
import { transformCodebase } from "../../tools/transformCodebase";
|
||||||
import type { BuildOptions } from "../../shared/buildOptions";
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
import * as fs from "fs/promises";
|
import * as fs from "fs/promises";
|
||||||
import { accountV1ThemeName } from "../../shared/constants";
|
import { ACCOUNT_V1_THEME_NAME } from "../../shared/constants";
|
||||||
import {
|
import {
|
||||||
generatePom,
|
generatePom,
|
||||||
BuildOptionsLike as BuildOptionsLike_generatePom
|
BuildContextLike as BuildContextLike_generatePom
|
||||||
} from "./generatePom";
|
} from "./generatePom";
|
||||||
import { readFileSync } from "fs";
|
import { readFileSync } from "fs";
|
||||||
import { isInside } from "../../tools/isInside";
|
import { isInside } from "../../tools/isInside";
|
||||||
import child_process from "child_process";
|
import child_process from "child_process";
|
||||||
import { rmSync } from "../../tools/fs.rmSync";
|
import { rmSync } from "../../tools/fs.rmSync";
|
||||||
import { getMetaInfKeycloakThemesJsonFilePath } from "../../shared/metaInfKeycloakThemes";
|
import { writeMetaInfKeycloakThemes } from "../../shared/metaInfKeycloakThemes";
|
||||||
|
import {
|
||||||
|
bundleExtensionsIntoJar,
|
||||||
|
type BuildContextLike as BuildContextLike_bundleExtensionsIntoJar
|
||||||
|
} from "./bundleExtensionsIntoJar";
|
||||||
|
|
||||||
export type BuildOptionsLike = BuildOptionsLike_generatePom & {
|
export type BuildContextLike = BuildContextLike_generatePom &
|
||||||
keycloakifyBuildDirPath: string;
|
BuildContextLike_bundleExtensionsIntoJar & {
|
||||||
themeNames: string[];
|
keycloakifyBuildDirPath: string;
|
||||||
artifactId: string;
|
themeNames: string[];
|
||||||
themeVersion: string;
|
artifactId: string;
|
||||||
cacheDirPath: string;
|
themeVersion: string;
|
||||||
};
|
cacheDirPath: string;
|
||||||
|
implementedThemeTypes: BuildContext["implementedThemeTypes"];
|
||||||
|
};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export async function buildJar(params: {
|
export async function buildJar(params: {
|
||||||
jarFileBasename: string;
|
jarFileBasename: string;
|
||||||
keycloakAccountV1Version: KeycloakAccountV1Version;
|
keycloakAccountV1Version: KeycloakAccountV1Version;
|
||||||
keycloakThemeAdditionalInfoExtensionVersion: KeycloakThemeAdditionalInfoExtensionVersion;
|
keycloakThemeAdditionalInfoExtensionVersion: KeycloakThemeAdditionalInfoExtensionVersion;
|
||||||
buildOptions: BuildOptionsLike;
|
resourcesDirPath: string;
|
||||||
|
doesImplementAccountV1Theme: boolean;
|
||||||
|
buildContext: BuildContextLike;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
const {
|
const {
|
||||||
jarFileBasename,
|
jarFileBasename,
|
||||||
keycloakAccountV1Version,
|
keycloakAccountV1Version,
|
||||||
keycloakThemeAdditionalInfoExtensionVersion,
|
keycloakThemeAdditionalInfoExtensionVersion,
|
||||||
buildOptions
|
resourcesDirPath,
|
||||||
|
doesImplementAccountV1Theme,
|
||||||
|
buildContext
|
||||||
} = params;
|
} = params;
|
||||||
|
|
||||||
const keycloakifyBuildTmpDirPath = pathJoin(
|
const keycloakifyBuildCacheDirPath = pathJoin(
|
||||||
buildOptions.cacheDirPath,
|
buildContext.cacheDirPath,
|
||||||
|
"maven",
|
||||||
jarFileBasename.replace(".jar", "")
|
jarFileBasename.replace(".jar", "")
|
||||||
);
|
);
|
||||||
|
|
||||||
rmSync(keycloakifyBuildTmpDirPath, { recursive: true, force: true });
|
const tmpResourcesDirPath = pathJoin(
|
||||||
|
keycloakifyBuildCacheDirPath,
|
||||||
|
"src",
|
||||||
|
"main",
|
||||||
|
"resources"
|
||||||
|
);
|
||||||
|
|
||||||
{
|
rmSync(tmpResourcesDirPath, { recursive: true, force: true });
|
||||||
const transformCodebase_common = (params: {
|
|
||||||
fileRelativePath: string;
|
|
||||||
sourceCode: Buffer;
|
|
||||||
}): { modifiedSourceCode: Buffer } | undefined => {
|
|
||||||
const { fileRelativePath, sourceCode } = params;
|
|
||||||
|
|
||||||
if (
|
transformCodebase({
|
||||||
fileRelativePath ===
|
srcDirPath: resourcesDirPath,
|
||||||
getMetaInfKeycloakThemesJsonFilePath({ keycloakifyBuildDirPath: "." })
|
destDirPath: tmpResourcesDirPath,
|
||||||
) {
|
transformSourceCode:
|
||||||
return { modifiedSourceCode: sourceCode };
|
!doesImplementAccountV1Theme || keycloakAccountV1Version !== null
|
||||||
}
|
|
||||||
|
|
||||||
for (const themeName of [...buildOptions.themeNames, accountV1ThemeName]) {
|
|
||||||
if (
|
|
||||||
isInside({
|
|
||||||
dirPath: pathJoin("src", "main", "resources", "theme", themeName),
|
|
||||||
filePath: fileRelativePath
|
|
||||||
})
|
|
||||||
) {
|
|
||||||
return { modifiedSourceCode: sourceCode };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
const transformCodebase_patchForUsingBuiltinAccountV1 =
|
|
||||||
keycloakAccountV1Version !== null
|
|
||||||
? undefined
|
? undefined
|
||||||
: (params: {
|
: (params: {
|
||||||
fileRelativePath: string;
|
fileRelativePath: string;
|
||||||
@ -87,62 +80,23 @@ export async function buildJar(params: {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
isInside({
|
isInside({
|
||||||
dirPath: pathJoin(
|
dirPath: pathJoin("theme", ACCOUNT_V1_THEME_NAME),
|
||||||
"src",
|
|
||||||
"main",
|
|
||||||
"resources",
|
|
||||||
"theme",
|
|
||||||
accountV1ThemeName
|
|
||||||
),
|
|
||||||
filePath: fileRelativePath
|
filePath: fileRelativePath
|
||||||
})
|
})
|
||||||
) {
|
) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
for (const themeName of buildContext.themeNames) {
|
||||||
fileRelativePath ===
|
|
||||||
getMetaInfKeycloakThemesJsonFilePath({
|
|
||||||
keycloakifyBuildDirPath: "."
|
|
||||||
})
|
|
||||||
) {
|
|
||||||
const keycloakThemesJsonParsed = JSON.parse(
|
|
||||||
sourceCode.toString("utf8")
|
|
||||||
) as {
|
|
||||||
themes: { name: string; types: string[] }[];
|
|
||||||
};
|
|
||||||
|
|
||||||
keycloakThemesJsonParsed.themes =
|
|
||||||
keycloakThemesJsonParsed.themes.filter(
|
|
||||||
({ name }) => name !== accountV1ThemeName
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
modifiedSourceCode: Buffer.from(
|
|
||||||
JSON.stringify(keycloakThemesJsonParsed, null, 2),
|
|
||||||
"utf8"
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const themeName of buildOptions.themeNames) {
|
|
||||||
if (
|
if (
|
||||||
fileRelativePath ===
|
fileRelativePath ===
|
||||||
pathJoin(
|
pathJoin("theme", themeName, "account", "theme.properties")
|
||||||
"src",
|
|
||||||
"main",
|
|
||||||
"resources",
|
|
||||||
"theme",
|
|
||||||
themeName,
|
|
||||||
"account",
|
|
||||||
"theme.properties"
|
|
||||||
)
|
|
||||||
) {
|
) {
|
||||||
const modifiedSourceCode = Buffer.from(
|
const modifiedSourceCode = Buffer.from(
|
||||||
sourceCode
|
sourceCode
|
||||||
.toString("utf8")
|
.toString("utf8")
|
||||||
.replace(
|
.replace(
|
||||||
`parent=${accountV1ThemeName}`,
|
`parent=${ACCOUNT_V1_THEME_NAME}`,
|
||||||
"parent=keycloak"
|
"parent=keycloak"
|
||||||
),
|
),
|
||||||
"utf8"
|
"utf8"
|
||||||
@ -157,33 +111,39 @@ export async function buildJar(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return { modifiedSourceCode: sourceCode };
|
return { modifiedSourceCode: sourceCode };
|
||||||
};
|
}
|
||||||
|
});
|
||||||
|
|
||||||
transformCodebase({
|
remove_account_v1_in_meta_inf: {
|
||||||
srcDirPath: buildOptions.keycloakifyBuildDirPath,
|
if (!doesImplementAccountV1Theme) {
|
||||||
destDirPath: keycloakifyBuildTmpDirPath,
|
// NOTE: We do not have account v1 anyway
|
||||||
transformSourceCode: params => {
|
break remove_account_v1_in_meta_inf;
|
||||||
const resultCommon = transformCodebase_common(params);
|
}
|
||||||
|
|
||||||
if (transformCodebase_patchForUsingBuiltinAccountV1 === undefined) {
|
if (keycloakAccountV1Version !== null) {
|
||||||
return resultCommon;
|
// NOTE: No, we need to keep account-v1 in meta-inf
|
||||||
}
|
break remove_account_v1_in_meta_inf;
|
||||||
|
}
|
||||||
|
|
||||||
if (resultCommon === undefined) {
|
writeMetaInfKeycloakThemes({
|
||||||
return undefined;
|
resourcesDirPath: tmpResourcesDirPath,
|
||||||
}
|
getNewMetaInfKeycloakTheme: ({ metaInfKeycloakTheme }) => {
|
||||||
|
assert(metaInfKeycloakTheme !== undefined);
|
||||||
|
|
||||||
const { modifiedSourceCode } = resultCommon;
|
metaInfKeycloakTheme.themes = metaInfKeycloakTheme.themes.filter(
|
||||||
|
({ name }) => name !== ACCOUNT_V1_THEME_NAME
|
||||||
|
);
|
||||||
|
|
||||||
return transformCodebase_patchForUsingBuiltinAccountV1({
|
return metaInfKeycloakTheme;
|
||||||
...params,
|
|
||||||
sourceCode: modifiedSourceCode
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
route_legacy_pages: {
|
route_legacy_pages: {
|
||||||
|
if (!buildContext.implementedThemeTypes.login.isImplemented) {
|
||||||
|
break route_legacy_pages;
|
||||||
|
}
|
||||||
|
|
||||||
// NOTE: If there's no account theme there is no special target for keycloak 24 and up so we create
|
// NOTE: If there's no account theme there is no special target for keycloak 24 and up so we create
|
||||||
// the pages anyway. If there is an account pages, since we know that account-v1 is only support keycloak
|
// the pages anyway. If there is an account pages, since we know that account-v1 is only support keycloak
|
||||||
// 24 in version 0.4 and up, we can safely break the route for legacy pages.
|
// 24 in version 0.4 and up, we can safely break the route for legacy pages.
|
||||||
@ -198,17 +158,15 @@ export async function buildJar(params: {
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// TODO: Remove this optimization, it's a bit hacky.
|
||||||
if (doBreak) {
|
if (doBreak) {
|
||||||
break route_legacy_pages;
|
break route_legacy_pages;
|
||||||
}
|
}
|
||||||
|
|
||||||
(["register.ftl", "login-update-profile.ftl"] as const).forEach(pageId =>
|
(["register.ftl", "login-update-profile.ftl"] as const).forEach(pageId =>
|
||||||
buildOptions.themeNames.map(themeName => {
|
buildContext.themeNames.map(themeName => {
|
||||||
const ftlFilePath = pathJoin(
|
const ftlFilePath = pathJoin(
|
||||||
keycloakifyBuildTmpDirPath,
|
tmpResourcesDirPath,
|
||||||
"src",
|
|
||||||
"main",
|
|
||||||
"resources",
|
|
||||||
"theme",
|
"theme",
|
||||||
themeName,
|
themeName,
|
||||||
"login",
|
"login",
|
||||||
@ -217,7 +175,7 @@ export async function buildJar(params: {
|
|||||||
|
|
||||||
const ftlFileContent = readFileSync(ftlFilePath).toString("utf8");
|
const ftlFileContent = readFileSync(ftlFilePath).toString("utf8");
|
||||||
|
|
||||||
const realPageId = (() => {
|
const ftlFileBasename = (() => {
|
||||||
switch (pageId) {
|
switch (pageId) {
|
||||||
case "register.ftl":
|
case "register.ftl":
|
||||||
return "register-user-profile.ftl";
|
return "register-user-profile.ftl";
|
||||||
@ -228,14 +186,14 @@ export async function buildJar(params: {
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
const modifiedFtlFileContent = ftlFileContent.replace(
|
const modifiedFtlFileContent = ftlFileContent.replace(
|
||||||
`out["pageId"] = "\${pageId}";`,
|
`"ftlTemplateFileName": "${pageId}"`,
|
||||||
`out["pageId"] = "${pageId}"; out["realPageId"] = "${realPageId}";`
|
`"ftlTemplateFileName": "${ftlFileBasename}"`
|
||||||
);
|
);
|
||||||
|
|
||||||
assert(modifiedFtlFileContent !== ftlFileContent);
|
assert(modifiedFtlFileContent !== ftlFileContent);
|
||||||
|
|
||||||
fs.writeFile(
|
fs.writeFile(
|
||||||
pathJoin(pathDirname(ftlFilePath), realPageId),
|
pathJoin(pathDirname(ftlFilePath), ftlFileBasename),
|
||||||
Buffer.from(modifiedFtlFileContent, "utf8")
|
Buffer.from(modifiedFtlFileContent, "utf8")
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
@ -244,21 +202,21 @@ export async function buildJar(params: {
|
|||||||
|
|
||||||
{
|
{
|
||||||
const { pomFileCode } = generatePom({
|
const { pomFileCode } = generatePom({
|
||||||
buildOptions,
|
buildContext,
|
||||||
keycloakAccountV1Version,
|
keycloakAccountV1Version,
|
||||||
keycloakThemeAdditionalInfoExtensionVersion
|
keycloakThemeAdditionalInfoExtensionVersion
|
||||||
});
|
});
|
||||||
|
|
||||||
await fs.writeFile(
|
await fs.writeFile(
|
||||||
pathJoin(keycloakifyBuildTmpDirPath, "pom.xml"),
|
pathJoin(keycloakifyBuildCacheDirPath, "pom.xml"),
|
||||||
Buffer.from(pomFileCode, "utf8")
|
Buffer.from(pomFileCode, "utf8")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
await new Promise<void>((resolve, reject) =>
|
await new Promise<void>((resolve, reject) =>
|
||||||
child_process.exec(
|
child_process.exec(
|
||||||
`mvn clean install -Dmaven.repo.local=${pathJoin(keycloakifyBuildTmpDirPath, ".m2")}`,
|
`mvn install -Dmaven.repo.local="${pathJoin(keycloakifyBuildCacheDirPath, ".m2")}"`,
|
||||||
{ cwd: keycloakifyBuildTmpDirPath },
|
{ cwd: keycloakifyBuildCacheDirPath },
|
||||||
error => {
|
error => {
|
||||||
if (error !== null) {
|
if (error !== null) {
|
||||||
console.error(
|
console.error(
|
||||||
@ -281,14 +239,19 @@ export async function buildJar(params: {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
await fs.rename(
|
const jarFilePath_generatedByMaven = pathJoin(
|
||||||
pathJoin(
|
keycloakifyBuildCacheDirPath,
|
||||||
keycloakifyBuildTmpDirPath,
|
"target",
|
||||||
"target",
|
`${buildContext.artifactId}-${buildContext.themeVersion}.jar`
|
||||||
`${buildOptions.artifactId}-${buildOptions.themeVersion}.jar`
|
|
||||||
),
|
|
||||||
pathJoin(buildOptions.keycloakifyBuildDirPath, jarFileBasename)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
rmSync(keycloakifyBuildTmpDirPath, { recursive: true });
|
await bundleExtensionsIntoJar({
|
||||||
|
buildContext,
|
||||||
|
jarFilePath: jarFilePath_generatedByMaven
|
||||||
|
});
|
||||||
|
|
||||||
|
await fs.rename(
|
||||||
|
jarFilePath_generatedByMaven,
|
||||||
|
pathJoin(buildContext.keycloakifyBuildDirPath, jarFileBasename)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,38 +1,38 @@
|
|||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import { exclude } from "tsafe/exclude";
|
|
||||||
import {
|
import {
|
||||||
keycloakAccountV1Versions,
|
keycloakAccountV1Versions,
|
||||||
keycloakThemeAdditionalInfoExtensionVersions
|
keycloakThemeAdditionalInfoExtensionVersions
|
||||||
} from "./extensionVersions";
|
} from "./extensionVersions";
|
||||||
import { getKeycloakVersionRangeForJar } from "./getKeycloakVersionRangeForJar";
|
import { getKeycloakVersionRangeForJar } from "./getKeycloakVersionRangeForJar";
|
||||||
import { buildJar, BuildOptionsLike as BuildOptionsLike_buildJar } from "./buildJar";
|
import { buildJar, BuildContextLike as BuildContextLike_buildJar } from "./buildJar";
|
||||||
import type { BuildOptions } from "../../shared/buildOptions";
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
import { getJarFileBasename } from "../../shared/getJarFileBasename";
|
|
||||||
import { readMetaInfKeycloakThemes } from "../../shared/metaInfKeycloakThemes";
|
|
||||||
import { accountV1ThemeName } from "../../shared/constants";
|
|
||||||
|
|
||||||
export type BuildOptionsLike = BuildOptionsLike_buildJar & {
|
export type BuildContextLike = BuildContextLike_buildJar & {
|
||||||
|
projectDirPath: string;
|
||||||
keycloakifyBuildDirPath: string;
|
keycloakifyBuildDirPath: string;
|
||||||
|
implementedThemeTypes: BuildContext["implementedThemeTypes"];
|
||||||
|
jarTargets: BuildContext["jarTargets"];
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export async function buildJars(params: {
|
export async function buildJars(params: {
|
||||||
buildOptions: BuildOptionsLike;
|
resourcesDirPath: string;
|
||||||
|
buildContext: BuildContextLike;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
const { buildOptions } = params;
|
const { resourcesDirPath, buildContext } = params;
|
||||||
|
|
||||||
const doesImplementAccountTheme = readMetaInfKeycloakThemes({
|
const doesImplementAccountV1Theme =
|
||||||
keycloakifyBuildDirPath: buildOptions.keycloakifyBuildDirPath
|
buildContext.implementedThemeTypes.account.isImplemented &&
|
||||||
}).themes.some(({ name }) => name === accountV1ThemeName);
|
buildContext.implementedThemeTypes.account.type === "Multi-Page";
|
||||||
|
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
keycloakAccountV1Versions
|
keycloakAccountV1Versions
|
||||||
.map(keycloakAccountV1Version =>
|
.map(keycloakAccountV1Version =>
|
||||||
keycloakThemeAdditionalInfoExtensionVersions
|
keycloakThemeAdditionalInfoExtensionVersions.map(
|
||||||
.map(keycloakThemeAdditionalInfoExtensionVersion => {
|
keycloakThemeAdditionalInfoExtensionVersion => {
|
||||||
const keycloakVersionRange = getKeycloakVersionRangeForJar({
|
const keycloakVersionRange = getKeycloakVersionRangeForJar({
|
||||||
doesImplementAccountTheme,
|
doesImplementAccountV1Theme,
|
||||||
keycloakAccountV1Version,
|
keycloakAccountV1Version,
|
||||||
keycloakThemeAdditionalInfoExtensionVersion
|
keycloakThemeAdditionalInfoExtensionVersion
|
||||||
});
|
});
|
||||||
@ -41,39 +41,27 @@ export async function buildJars(params: {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
const jarTarget = buildContext.jarTargets.find(
|
||||||
keycloakThemeAdditionalInfoExtensionVersion,
|
jarTarget =>
|
||||||
keycloakVersionRange
|
jarTarget.keycloakVersionRange === keycloakVersionRange
|
||||||
};
|
);
|
||||||
})
|
|
||||||
.filter(exclude(undefined))
|
|
||||||
.map(
|
|
||||||
({
|
|
||||||
keycloakThemeAdditionalInfoExtensionVersion,
|
|
||||||
keycloakVersionRange
|
|
||||||
}) => {
|
|
||||||
const { jarFileBasename } = getJarFileBasename({
|
|
||||||
keycloakVersionRange
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
if (jarTarget === undefined) {
|
||||||
keycloakThemeAdditionalInfoExtensionVersion,
|
return undefined;
|
||||||
jarFileBasename
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
)
|
|
||||||
.map(
|
const { jarFileBasename } = jarTarget;
|
||||||
({
|
|
||||||
|
return buildJar({
|
||||||
|
jarFileBasename,
|
||||||
|
keycloakAccountV1Version,
|
||||||
keycloakThemeAdditionalInfoExtensionVersion,
|
keycloakThemeAdditionalInfoExtensionVersion,
|
||||||
jarFileBasename
|
resourcesDirPath,
|
||||||
}) =>
|
doesImplementAccountV1Theme,
|
||||||
buildJar({
|
buildContext
|
||||||
jarFileBasename,
|
});
|
||||||
keycloakAccountV1Version,
|
}
|
||||||
keycloakThemeAdditionalInfoExtensionVersion,
|
)
|
||||||
buildOptions
|
|
||||||
})
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
.flat()
|
.flat()
|
||||||
);
|
);
|
||||||
|
137
src/bin/keycloakify/buildJars/bundleExtensionsIntoJar.ts
Normal file
137
src/bin/keycloakify/buildJars/bundleExtensionsIntoJar.ts
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
import { downloadAndExtractArchive } from "../../tools/downloadAndExtractArchive";
|
||||||
|
import { assert } from "tsafe/assert";
|
||||||
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
|
import { transformCodebase } from "../../tools/transformCodebase";
|
||||||
|
import { join as pathJoin, basename as pathBasename, sep as pathSep } from "path";
|
||||||
|
import { rm } from "../../tools/fs.rm";
|
||||||
|
import { extractArchive } from "../../tools/extractArchive";
|
||||||
|
import * as crypto from "crypto";
|
||||||
|
|
||||||
|
export type BuildContextLike = {
|
||||||
|
cacheDirPath: string;
|
||||||
|
fetchOptions: BuildContext["fetchOptions"];
|
||||||
|
extensionJars: BuildContext["extensionJars"];
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
|
export async function bundleExtensionsIntoJar(params: {
|
||||||
|
jarFilePath: string;
|
||||||
|
buildContext: BuildContextLike;
|
||||||
|
}): Promise<void> {
|
||||||
|
const { jarFilePath, buildContext } = params;
|
||||||
|
|
||||||
|
if (buildContext.extensionJars.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mergeDirPath = pathJoin(
|
||||||
|
buildContext.cacheDirPath,
|
||||||
|
`merge_${pathBasename(jarFilePath).replace(/\.jar$/, "")}_${crypto
|
||||||
|
.createHash("sha256")
|
||||||
|
.update(jarFilePath)
|
||||||
|
.digest("hex")
|
||||||
|
.substring(0, 5)}`
|
||||||
|
);
|
||||||
|
|
||||||
|
await extractArchive({
|
||||||
|
archiveFilePath: jarFilePath,
|
||||||
|
onArchiveFile: async ({ relativeFilePathInArchive, writeFile }) =>
|
||||||
|
writeFile({
|
||||||
|
filePath: pathJoin(mergeDirPath, relativeFilePathInArchive)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const extensionJar of buildContext.extensionJars) {
|
||||||
|
const transformSourceCode = (params: {
|
||||||
|
fileRelativePath: string;
|
||||||
|
sourceCode: Buffer;
|
||||||
|
}): { modifiedSourceCode: Buffer } | undefined => {
|
||||||
|
const { fileRelativePath } = params;
|
||||||
|
|
||||||
|
if (!fileRelativePath.startsWith(`META-INF${pathSep}`)) {
|
||||||
|
for (const ext of [".DSA", ".SF", ".RSA"]) {
|
||||||
|
if (fileRelativePath.endsWith(ext)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
switch (extensionJar.type) {
|
||||||
|
case "path":
|
||||||
|
await extractArchive({
|
||||||
|
archiveFilePath: extensionJar.path,
|
||||||
|
onArchiveFile: async ({
|
||||||
|
relativeFilePathInArchive,
|
||||||
|
writeFile,
|
||||||
|
readFile
|
||||||
|
}) => {
|
||||||
|
const transformResult = transformSourceCode({
|
||||||
|
fileRelativePath: relativeFilePathInArchive,
|
||||||
|
sourceCode: await readFile()
|
||||||
|
});
|
||||||
|
|
||||||
|
if (transformResult === undefined) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await writeFile({
|
||||||
|
filePath: pathJoin(mergeDirPath, relativeFilePathInArchive),
|
||||||
|
modifiedData: transformResult.modifiedSourceCode
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "url": {
|
||||||
|
const { extractedDirPath } = await downloadAndExtractArchive({
|
||||||
|
url: extensionJar.url,
|
||||||
|
cacheDirPath: buildContext.cacheDirPath,
|
||||||
|
fetchOptions: buildContext.fetchOptions,
|
||||||
|
uniqueIdOfOnArchiveFile: "noOp",
|
||||||
|
onArchiveFile: async ({ fileRelativePath, writeFile }) =>
|
||||||
|
writeFile({ fileRelativePath })
|
||||||
|
});
|
||||||
|
transformCodebase({
|
||||||
|
srcDirPath: extractedDirPath,
|
||||||
|
destDirPath: mergeDirPath,
|
||||||
|
transformSourceCode
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
transformCodebase({
|
||||||
|
srcDirPath: extractedDirPath,
|
||||||
|
destDirPath: mergeDirPath,
|
||||||
|
transformSourceCode: ({ fileRelativePath, sourceCode }) => {
|
||||||
|
if (fileRelativePath === pathJoin("META-INF", "MANIFEST.MF")) {
|
||||||
|
const sourceCodeStr = sourceCode.toString("utf8");
|
||||||
|
|
||||||
|
const lines = sourceCodeStr.split(/\r?\n/);
|
||||||
|
|
||||||
|
console.log(lines);
|
||||||
|
|
||||||
|
return {
|
||||||
|
modifiedSourceCode: Buffer.concat([
|
||||||
|
sourceCode,
|
||||||
|
Buffer.from(
|
||||||
|
`Class-Path: ${pathBasename(userProvidedJarFilePathOrUrl)}\n`
|
||||||
|
)
|
||||||
|
])
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Acctually build new jar
|
||||||
|
|
||||||
|
await rm(mergeDirPath, { recursive: true, force: true });
|
||||||
|
}
|
@ -1,5 +1,5 @@
|
|||||||
// NOTE: v0.5 is a dummy version.
|
// NOTE: v0.5 is a dummy version.
|
||||||
export const keycloakAccountV1Versions = [null, "0.3", "0.4"] as const;
|
export const keycloakAccountV1Versions = [null, "0.3", "0.4", "0.6"] as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* https://central.sonatype.com/artifact/io.phasetwo.keycloak/keycloak-account-v1
|
* https://central.sonatype.com/artifact/io.phasetwo.keycloak/keycloak-account-v1
|
||||||
|
@ -1,27 +1,27 @@
|
|||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import type { BuildOptions } from "../../shared/buildOptions";
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
import type {
|
import type {
|
||||||
KeycloakAccountV1Version,
|
KeycloakAccountV1Version,
|
||||||
KeycloakThemeAdditionalInfoExtensionVersion
|
KeycloakThemeAdditionalInfoExtensionVersion
|
||||||
} from "./extensionVersions";
|
} from "./extensionVersions";
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
export type BuildContextLike = {
|
||||||
groupId: string;
|
groupId: string;
|
||||||
artifactId: string;
|
artifactId: string;
|
||||||
themeVersion: string;
|
themeVersion: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export function generatePom(params: {
|
export function generatePom(params: {
|
||||||
keycloakAccountV1Version: KeycloakAccountV1Version;
|
keycloakAccountV1Version: KeycloakAccountV1Version;
|
||||||
keycloakThemeAdditionalInfoExtensionVersion: KeycloakThemeAdditionalInfoExtensionVersion;
|
keycloakThemeAdditionalInfoExtensionVersion: KeycloakThemeAdditionalInfoExtensionVersion;
|
||||||
buildOptions: BuildOptionsLike;
|
buildContext: BuildContextLike;
|
||||||
}) {
|
}) {
|
||||||
const {
|
const {
|
||||||
keycloakAccountV1Version,
|
keycloakAccountV1Version,
|
||||||
keycloakThemeAdditionalInfoExtensionVersion,
|
keycloakThemeAdditionalInfoExtensionVersion,
|
||||||
buildOptions
|
buildContext
|
||||||
} = params;
|
} = params;
|
||||||
|
|
||||||
const { pomFileCode } = (function generatePomFileCode(): {
|
const { pomFileCode } = (function generatePomFileCode(): {
|
||||||
@ -33,16 +33,16 @@ export function generatePom(params: {
|
|||||||
` xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"`,
|
` xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"`,
|
||||||
` xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">`,
|
` xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">`,
|
||||||
` <modelVersion>4.0.0</modelVersion>`,
|
` <modelVersion>4.0.0</modelVersion>`,
|
||||||
` <groupId>${buildOptions.groupId}</groupId>`,
|
` <groupId>${buildContext.groupId}</groupId>`,
|
||||||
` <artifactId>${buildOptions.artifactId}</artifactId>`,
|
` <artifactId>${buildContext.artifactId}</artifactId>`,
|
||||||
` <version>${buildOptions.themeVersion}</version>`,
|
` <version>${buildContext.themeVersion}</version>`,
|
||||||
` <name>${buildOptions.artifactId}</name>`,
|
` <name>${buildContext.artifactId}</name>`,
|
||||||
` <description />`,
|
` <description />`,
|
||||||
` <packaging>jar</packaging>`,
|
` <packaging>jar</packaging>`,
|
||||||
` <properties>`,
|
` <properties>`,
|
||||||
` <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>`,
|
` <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>`,
|
||||||
` </properties>`,
|
` </properties>`,
|
||||||
...(keycloakAccountV1Version !== null &&
|
...(keycloakAccountV1Version !== null ||
|
||||||
keycloakThemeAdditionalInfoExtensionVersion !== null
|
keycloakThemeAdditionalInfoExtensionVersion !== null
|
||||||
? [
|
? [
|
||||||
` <build>`,
|
` <build>`,
|
||||||
|
@ -6,17 +6,17 @@ import type {
|
|||||||
import type { KeycloakVersionRange } from "../../shared/KeycloakVersionRange";
|
import type { KeycloakVersionRange } from "../../shared/KeycloakVersionRange";
|
||||||
|
|
||||||
export function getKeycloakVersionRangeForJar(params: {
|
export function getKeycloakVersionRangeForJar(params: {
|
||||||
doesImplementAccountTheme: boolean;
|
doesImplementAccountV1Theme: boolean;
|
||||||
keycloakAccountV1Version: KeycloakAccountV1Version;
|
keycloakAccountV1Version: KeycloakAccountV1Version;
|
||||||
keycloakThemeAdditionalInfoExtensionVersion: KeycloakThemeAdditionalInfoExtensionVersion;
|
keycloakThemeAdditionalInfoExtensionVersion: KeycloakThemeAdditionalInfoExtensionVersion;
|
||||||
}): KeycloakVersionRange | undefined {
|
}): KeycloakVersionRange | undefined {
|
||||||
const {
|
const {
|
||||||
keycloakAccountV1Version,
|
keycloakAccountV1Version,
|
||||||
keycloakThemeAdditionalInfoExtensionVersion,
|
keycloakThemeAdditionalInfoExtensionVersion,
|
||||||
doesImplementAccountTheme
|
doesImplementAccountV1Theme
|
||||||
} = params;
|
} = params;
|
||||||
|
|
||||||
if (doesImplementAccountTheme) {
|
if (doesImplementAccountV1Theme) {
|
||||||
const keycloakVersionRange = (() => {
|
const keycloakVersionRange = (() => {
|
||||||
switch (keycloakAccountV1Version) {
|
switch (keycloakAccountV1Version) {
|
||||||
case null:
|
case null:
|
||||||
@ -44,18 +44,26 @@ export function getKeycloakVersionRangeForJar(params: {
|
|||||||
case null:
|
case null:
|
||||||
return undefined;
|
return undefined;
|
||||||
case "1.1.5":
|
case "1.1.5":
|
||||||
return "24-and-above" as const;
|
return "24" as const;
|
||||||
}
|
}
|
||||||
assert<
|
assert<
|
||||||
Equals<typeof keycloakThemeAdditionalInfoExtensionVersion, never>
|
Equals<typeof keycloakThemeAdditionalInfoExtensionVersion, never>
|
||||||
>(false);
|
>(false);
|
||||||
|
case "0.6":
|
||||||
|
switch (keycloakThemeAdditionalInfoExtensionVersion) {
|
||||||
|
case null:
|
||||||
|
return undefined;
|
||||||
|
case "1.1.5":
|
||||||
|
return "25-and-above" as const;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
assert<Equals<typeof keycloakAccountV1Version, never>>(false);
|
||||||
})();
|
})();
|
||||||
|
|
||||||
assert<
|
assert<
|
||||||
Equals<
|
Equals<
|
||||||
typeof keycloakVersionRange,
|
typeof keycloakVersionRange,
|
||||||
KeycloakVersionRange.WithAccountTheme | undefined
|
KeycloakVersionRange.WithAccountV1Theme | undefined
|
||||||
>
|
>
|
||||||
>();
|
>();
|
||||||
|
|
||||||
@ -65,7 +73,6 @@ export function getKeycloakVersionRangeForJar(params: {
|
|||||||
if (keycloakAccountV1Version !== null) {
|
if (keycloakAccountV1Version !== null) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (keycloakThemeAdditionalInfoExtensionVersion) {
|
switch (keycloakThemeAdditionalInfoExtensionVersion) {
|
||||||
case null:
|
case null:
|
||||||
return "21-and-below";
|
return "21-and-below";
|
||||||
@ -80,7 +87,7 @@ export function getKeycloakVersionRangeForJar(params: {
|
|||||||
assert<
|
assert<
|
||||||
Equals<
|
Equals<
|
||||||
typeof keycloakVersionRange,
|
typeof keycloakVersionRange,
|
||||||
KeycloakVersionRange.WithoutAccountTheme | undefined
|
KeycloakVersionRange.WithoutAccountV1Theme | undefined
|
||||||
>
|
>
|
||||||
>();
|
>();
|
||||||
|
|
||||||
|
@ -1,544 +0,0 @@
|
|||||||
<script>const _=
|
|
||||||
(()=>{
|
|
||||||
<#assign pageId="PAGE_ID_xIgLsPgGId9D8e">
|
|
||||||
const out = ${ftl_object_to_js_code_declaring_an_object(.data_model, [])?no_esc};
|
|
||||||
out["messagesPerField"]= {
|
|
||||||
<#assign fieldNames = [ FIELD_NAMES_eKsIY4ZsZ4xeM ]>
|
|
||||||
<#attempt>
|
|
||||||
<#if profile?? && profile.attributes?? && profile.attributes?is_enumerable>
|
|
||||||
<#list profile.attributes as attribute>
|
|
||||||
<#if fieldNames?seq_contains(attribute.name)>
|
|
||||||
<#continue>
|
|
||||||
</#if>
|
|
||||||
<#assign fieldNames += [attribute.name]>
|
|
||||||
</#list>
|
|
||||||
</#if>
|
|
||||||
<#recover>
|
|
||||||
</#attempt>
|
|
||||||
"printIfExists": function (fieldName, text) {
|
|
||||||
<#if !messagesPerField?? || !(messagesPerField?is_hash)>
|
|
||||||
throw new Error("You're not supposed to use messagesPerField.printIfExists in this page");
|
|
||||||
<#else>
|
|
||||||
<#list fieldNames as fieldName>
|
|
||||||
if(fieldName === "${fieldName}" ){
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/pull/218 -->
|
|
||||||
<#if ('${fieldName}' == 'username' || '${fieldName}' == 'password') && pageId != 'register.ftl' && pageId != 'register-user-profile.ftl'>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = "">
|
|
||||||
<#attempt>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = messagesPerField.existsError('username', 'password')>
|
|
||||||
<#recover>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = true>
|
|
||||||
</#attempt>
|
|
||||||
return <#if doExistErrorOnUsernameOrPassword>text<#else>undefined</#if>
|
|
||||||
<#else>
|
|
||||||
<#assign doExistMessageForField = "">
|
|
||||||
<#attempt>
|
|
||||||
<#assign doExistMessageForField = messagesPerField.exists('${fieldName}')>
|
|
||||||
<#recover>
|
|
||||||
<#assign doExistMessageForField = true>
|
|
||||||
</#attempt>
|
|
||||||
return <#if doExistMessageForField>text<#else>undefined</#if>;
|
|
||||||
</#if>
|
|
||||||
}
|
|
||||||
</#list>
|
|
||||||
throw new Error(fieldName + "is probably runtime generated, see: https://docs.keycloakify.dev/limitations#field-names-cant-be-runtime-generated");
|
|
||||||
</#if>
|
|
||||||
},
|
|
||||||
"existsError": function (){
|
|
||||||
function existsError_singleFieldName(fieldName) {
|
|
||||||
<#if !messagesPerField?? || !(messagesPerField?is_hash)>
|
|
||||||
throw new Error("You're not supposed to use messagesPerField.printIfExists in this page");
|
|
||||||
<#else>
|
|
||||||
<#list fieldNames as fieldName>
|
|
||||||
if(fieldName === "${fieldName}" ){
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/pull/218 -->
|
|
||||||
<#if ('${fieldName}' == 'username' || '${fieldName}' == 'password') && pageId != 'register.ftl' && pageId != 'register-user-profile.ftl'>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = "">
|
|
||||||
<#attempt>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = messagesPerField.existsError('username', 'password')>
|
|
||||||
<#recover>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = true>
|
|
||||||
</#attempt>
|
|
||||||
return <#if doExistErrorOnUsernameOrPassword>true<#else>false</#if>;
|
|
||||||
<#else>
|
|
||||||
<#assign doExistErrorMessageForField = "">
|
|
||||||
<#attempt>
|
|
||||||
<#assign doExistErrorMessageForField = messagesPerField.existsError('${fieldName}')>
|
|
||||||
<#recover>
|
|
||||||
<#assign doExistErrorMessageForField = true>
|
|
||||||
</#attempt>
|
|
||||||
return <#if doExistErrorMessageForField>true<#else>false</#if>;
|
|
||||||
</#if>
|
|
||||||
}
|
|
||||||
</#list>
|
|
||||||
throw new Error(fieldName + "is probably runtime generated, see: https://docs.keycloakify.dev/limitations#field-names-cant-be-runtime-generated");
|
|
||||||
</#if>
|
|
||||||
}
|
|
||||||
for( let i = 0; i < arguments.length; i++ ){
|
|
||||||
if( existsError_singleFieldName(arguments[i]) ){
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
"get": function (fieldName) {
|
|
||||||
<#if !messagesPerField?? || !(messagesPerField?is_hash)>
|
|
||||||
throw new Error("You're not supposed to use messagesPerField.get in this page");
|
|
||||||
<#else>
|
|
||||||
<#list fieldNames as fieldName>
|
|
||||||
if(fieldName === "${fieldName}" ){
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/pull/218 -->
|
|
||||||
<#if ('${fieldName}' == 'username' || '${fieldName}' == 'password') && pageId != 'register.ftl' && pageId != 'register-user-profile.ftl'>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = "">
|
|
||||||
<#attempt>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = messagesPerField.existsError('username', 'password')>
|
|
||||||
<#recover>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = true>
|
|
||||||
</#attempt>
|
|
||||||
<#if doExistErrorOnUsernameOrPassword>
|
|
||||||
<#attempt>
|
|
||||||
return decodeHtmlEntities("${msg('invalidUserMessage')?js_string}");
|
|
||||||
<#recover>
|
|
||||||
return "Invalid username or password.";
|
|
||||||
</#attempt>
|
|
||||||
<#else>
|
|
||||||
return "";
|
|
||||||
</#if>
|
|
||||||
<#else>
|
|
||||||
<#attempt>
|
|
||||||
return decodeHtmlEntities("${messagesPerField.get('${fieldName}')?js_string}");
|
|
||||||
<#recover>
|
|
||||||
return "Invalid field";
|
|
||||||
</#attempt>
|
|
||||||
</#if>
|
|
||||||
}
|
|
||||||
</#list>
|
|
||||||
throw new Error(fieldName + "is probably runtime generated, see: https://docs.keycloakify.dev/limitations#field-names-cant-be-runtime-generated");
|
|
||||||
</#if>
|
|
||||||
},
|
|
||||||
"exists": function (fieldName) {
|
|
||||||
<#if !messagesPerField?? || !(messagesPerField?is_hash)>
|
|
||||||
throw new Error("You're not supposed to use messagesPerField.exists in this page");
|
|
||||||
<#else>
|
|
||||||
<#list fieldNames as fieldName>
|
|
||||||
if(fieldName === "${fieldName}" ){
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/pull/218 -->
|
|
||||||
<#if ('${fieldName}' == 'username' || '${fieldName}' == 'password') && pageId != 'register.ftl' && pageId != 'register-user-profile.ftl'>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = "">
|
|
||||||
<#attempt>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = messagesPerField.existsError('username', 'password')>
|
|
||||||
<#recover>
|
|
||||||
<#assign doExistErrorOnUsernameOrPassword = true>
|
|
||||||
</#attempt>
|
|
||||||
return <#if doExistErrorOnUsernameOrPassword>true<#else>false</#if>;
|
|
||||||
<#else>
|
|
||||||
<#assign doExistErrorMessageForField = "">
|
|
||||||
<#attempt>
|
|
||||||
<#assign doExistErrorMessageForField = messagesPerField.exists('${fieldName}')>
|
|
||||||
<#recover>
|
|
||||||
<#assign doExistErrorMessageForField = true>
|
|
||||||
</#attempt>
|
|
||||||
return <#if doExistErrorMessageForField>true<#else>false</#if>;
|
|
||||||
</#if>
|
|
||||||
}
|
|
||||||
</#list>
|
|
||||||
throw new Error(fieldName + "is probably runtime generated, see: https://docs.keycloakify.dev/limitations#field-names-cant-be-runtime-generated");
|
|
||||||
</#if>
|
|
||||||
},
|
|
||||||
"getFirstError": function () {
|
|
||||||
for( let i = 0; i < arguments.length; i++ ){
|
|
||||||
const fieldName = arguments[i];
|
|
||||||
if( out.messagesPerField.existsError(fieldName) ){
|
|
||||||
return out.messagesPerField.get(fieldName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
out["keycloakifyVersion"] = "KEYCLOAKIFY_VERSION_xEdKd3xEdr";
|
|
||||||
out["themeVersion"] = "KEYCLOAKIFY_THEME_VERSION_sIgKd3xEdr3dx";
|
|
||||||
out["themeType"] = "KEYCLOAKIFY_THEME_TYPE_dExKd3xEdr";
|
|
||||||
out["themeName"] = "KEYCLOAKIFY_THEME_NAME_cXxKd3xEer";
|
|
||||||
out["pageId"] = "${pageId}";
|
|
||||||
|
|
||||||
try {
|
|
||||||
out["url"]["resourcesCommonPath"] = out["url"]["resourcesPath"] + "/" + "RESOURCES_COMMON_cLsLsMrtDkpVv";
|
|
||||||
} catch(error) { }
|
|
||||||
|
|
||||||
<#if profile?? && profile.attributes??>
|
|
||||||
out["lOCALIZATION_REALM_OVERRIDES_USER_PROFILE_PROPERTY_KEY_aaGLsPgGIdeeX"] = {
|
|
||||||
<#list profile.attributes as attribute>
|
|
||||||
<#if attribute.annotations?? && attribute.displayName??>
|
|
||||||
"${attribute.displayName}": decodeHtmlEntities("${advancedMsg(attribute.displayName)?js_string}"),
|
|
||||||
</#if>
|
|
||||||
<#if attribute.annotations.inputHelperTextBefore??>
|
|
||||||
"${attribute.annotations.inputHelperTextBefore}": decodeHtmlEntities("${advancedMsg(attribute.annotations.inputHelperTextBefore)?js_string}"),
|
|
||||||
</#if>
|
|
||||||
<#if attribute.annotations.inputHelperTextAfter??>
|
|
||||||
"${attribute.annotations.inputHelperTextAfter}": decodeHtmlEntities("${advancedMsg(attribute.annotations.inputHelperTextAfter)?js_string}"),
|
|
||||||
</#if>
|
|
||||||
<#if attribute.annotations.inputTypePlaceholder??>
|
|
||||||
"${attribute.annotations.inputTypePlaceholder}": decodeHtmlEntities("${advancedMsg(attribute.annotations.inputTypePlaceholder)?js_string}"),
|
|
||||||
</#if>
|
|
||||||
</#list>
|
|
||||||
};
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
return out;
|
|
||||||
|
|
||||||
function decodeHtmlEntities(htmlStr){
|
|
||||||
var element = decodeHtmlEntities.element;
|
|
||||||
if (!element) {
|
|
||||||
element = document.createElement("textarea");
|
|
||||||
decodeHtmlEntities.element = element;
|
|
||||||
}
|
|
||||||
element.innerHTML = htmlStr;
|
|
||||||
return element.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
})();
|
|
||||||
<#function ftl_object_to_js_code_declaring_an_object object path>
|
|
||||||
|
|
||||||
<#local isHash = "">
|
|
||||||
<#attempt>
|
|
||||||
<#local isHash = object?is_hash || object?is_hash_ex>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Can't evaluate if " + path?join(".") + " is hash">
|
|
||||||
</#attempt>
|
|
||||||
|
|
||||||
<#if isHash>
|
|
||||||
|
|
||||||
<#if path?size gt 10>
|
|
||||||
<#return "ABORT: Too many recursive calls, path: " + path?join(".")>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local keys = "">
|
|
||||||
|
|
||||||
<#attempt>
|
|
||||||
<#local keys = object?keys>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: We can't list keys on this object">
|
|
||||||
</#attempt>
|
|
||||||
|
|
||||||
<#local out_seq = []>
|
|
||||||
|
|
||||||
<#list keys as key>
|
|
||||||
|
|
||||||
<#if ["class","declaredConstructors","superclass","declaringClass" ]?seq_contains(key) >
|
|
||||||
<#continue>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#if
|
|
||||||
(
|
|
||||||
["loginUpdatePasswordUrl", "loginUpdateProfileUrl", "loginUsernameReminderUrl", "loginUpdateTotpUrl"]?seq_contains(key) &&
|
|
||||||
are_same_path(path, ["url"])
|
|
||||||
) || (
|
|
||||||
key == "updateProfileCtx" &&
|
|
||||||
are_same_path(path, [])
|
|
||||||
) || (
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/pull/65#issuecomment-991896344 (reports with saml-post-form.ftl) -->
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/issues/91#issue-1212319466 (reports with error.ftl and Kc18) -->
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/issues/109#issuecomment-1134610163 -->
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/issues/357 -->
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/discussions/406#discussioncomment-7514787 -->
|
|
||||||
key == "loginAction" &&
|
|
||||||
are_same_path(path, ["url"]) &&
|
|
||||||
["saml-post-form.ftl", "error.ftl", "info.ftl", "login-oauth-grant.ftl", "logout-confirm.ftl", "login-oauth2-device-verify-user-code.ftl"]?seq_contains(pageId) &&
|
|
||||||
!(auth?has_content && auth.showTryAnotherWayLink())
|
|
||||||
) || (
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/issues/362 -->
|
|
||||||
["secretData", "value"]?seq_contains(key) &&
|
|
||||||
are_same_path(path, [ "totp", "otpCredentials", "*" ])
|
|
||||||
) || (
|
|
||||||
["contextData", "idpConfig", "idp", "authenticationSession"]?seq_contains(key) &&
|
|
||||||
are_same_path(path, ["brokerContext"]) &&
|
|
||||||
["login-idp-link-confirm.ftl", "login-idp-link-email.ftl" ]?seq_contains(pageId)
|
|
||||||
) || (
|
|
||||||
key == "identityProviderBrokerCtx" &&
|
|
||||||
are_same_path(path, []) &&
|
|
||||||
["login-idp-link-confirm.ftl", "login-idp-link-email.ftl" ]?seq_contains(pageId)
|
|
||||||
) || (
|
|
||||||
["masterAdminClient", "delegateForUpdate", "defaultRole"]?seq_contains(key) &&
|
|
||||||
are_same_path(path, ["realm"])
|
|
||||||
) || (
|
|
||||||
"error.ftl" == pageId &&
|
|
||||||
are_same_path(path, ["realm"]) &&
|
|
||||||
!["name", "displayName", "displayNameHtml", "internationalizationEnabled", "registrationEmailAsUsername" ]?seq_contains(key)
|
|
||||||
) || (
|
|
||||||
"applications.ftl" == pageId &&
|
|
||||||
(
|
|
||||||
key == "realm" ||
|
|
||||||
key == "container"
|
|
||||||
) &&
|
|
||||||
is_subpath(path, ["applications", "applications"])
|
|
||||||
) || (
|
|
||||||
key == "delegateForUpdate" &&
|
|
||||||
are_same_path(path, ["user"])
|
|
||||||
) || (
|
|
||||||
<#-- Security audit forwarded by Garth (Gmail) -->
|
|
||||||
key == "saml.signing.private.key" &&
|
|
||||||
are_same_path(path, ["client", "attributes"])
|
|
||||||
) || (
|
|
||||||
<#-- See: https://github.com/keycloakify/keycloakify/issues/534 -->
|
|
||||||
key == "password" &&
|
|
||||||
are_same_path(path, ["login"])
|
|
||||||
) || (
|
|
||||||
<#-- Remove realmAttributes added by https://github.com/jcputney/keycloak-theme-additional-info-extension for peace of mind. -->
|
|
||||||
key == "realmAttributes" &&
|
|
||||||
are_same_path(path, [])
|
|
||||||
) || (
|
|
||||||
<#-- attributesByName adds a lot of noise to the output and is not needed -->
|
|
||||||
key == "attributes" &&
|
|
||||||
are_same_path(path, ["profile"])
|
|
||||||
) || (
|
|
||||||
<#-- We already have the attributes in profile speedup the rendering by filtering it out from the register object -->
|
|
||||||
(key == "attributes" || key == "attributesByName") &&
|
|
||||||
are_same_path(path, ["register"])
|
|
||||||
)
|
|
||||||
>
|
|
||||||
<#local out_seq += ["/*" + path?join(".") + "." + key + " excluded*/"]>
|
|
||||||
<#continue>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
USER_DEFINED_EXCLUSIONS_eKsaY4ZsZ4eMr2
|
|
||||||
|
|
||||||
<#-- https://github.com/keycloakify/keycloakify/discussions/406 -->
|
|
||||||
<#if (
|
|
||||||
["register.ftl", "register-user-profile.ftl", "info.ftl", "login.ftl", "login-update-password.ftl", "login-oauth2-device-verify-user-code.ftl"]?seq_contains(pageId) &&
|
|
||||||
key == "attemptedUsername" && are_same_path(path, ["auth"])
|
|
||||||
)>
|
|
||||||
<#attempt>
|
|
||||||
<#-- https://github.com/keycloak/keycloak/blob/3a2bf0c04bcde185e497aaa32d0bb7ab7520cf4a/themes/src/main/resources/theme/base/login/template.ftl#L63 -->
|
|
||||||
<#if !(auth?has_content && auth.showUsername() && !auth.showResetCredentials())>
|
|
||||||
<#local out_seq += ["/*" + path?join(".") + "." + key + " excluded*/"]>
|
|
||||||
<#continue>
|
|
||||||
</#if>
|
|
||||||
<#recover>
|
|
||||||
<#local out_seq += ["/*Accessing attemptedUsername throwed an exception */"]>
|
|
||||||
</#attempt>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#attempt>
|
|
||||||
<#if !object[key]??>
|
|
||||||
<#continue>
|
|
||||||
</#if>
|
|
||||||
<#recover>
|
|
||||||
<#local out_seq += ["/*Couldn't test if '" + key + "' is available on this object*/"]>
|
|
||||||
<#continue>
|
|
||||||
</#attempt>
|
|
||||||
|
|
||||||
<#local propertyValue = "">
|
|
||||||
|
|
||||||
<#attempt>
|
|
||||||
<#local propertyValue = object[key]>
|
|
||||||
<#recover>
|
|
||||||
<#local out_seq += ["/*Couldn't dereference '" + key + "' on this object*/"]>
|
|
||||||
<#continue>
|
|
||||||
</#attempt>
|
|
||||||
|
|
||||||
<#local rec_out = ftl_object_to_js_code_declaring_an_object(propertyValue, path + [ key ])>
|
|
||||||
|
|
||||||
<#if rec_out?starts_with("ABORT:")>
|
|
||||||
|
|
||||||
<#local errorMessage = rec_out?remove_beginning("ABORT:")>
|
|
||||||
|
|
||||||
<#if errorMessage != " It's a method" >
|
|
||||||
<#local out_seq += ["/*" + key + ": " + errorMessage + "*/"]>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#continue>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local out_seq += ['"' + key + '": ' + rec_out + ","]>
|
|
||||||
|
|
||||||
</#list>
|
|
||||||
|
|
||||||
<#return (["{"] + out_seq?map(str -> ""?right_pad(4 * (path?size + 1)) + str) + [ ""?right_pad(4 * path?size) + "}"])?join("\n")>
|
|
||||||
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local isMethod = "">
|
|
||||||
<#attempt>
|
|
||||||
<#local isMethod = object?is_method>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Can't test if it'sa method.">
|
|
||||||
</#attempt>
|
|
||||||
|
|
||||||
<#if isMethod>
|
|
||||||
|
|
||||||
<#if are_same_path(path, ["auth", "showUsername"])>
|
|
||||||
<#attempt>
|
|
||||||
<#return auth.showUsername()?c>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Couldn't evaluate auth.showUsername()">
|
|
||||||
</#attempt>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#if are_same_path(path, ["auth", "showResetCredentials"])>
|
|
||||||
<#attempt>
|
|
||||||
<#return auth.showResetCredentials()?c>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Couldn't evaluate auth.showResetCredentials()">
|
|
||||||
</#attempt>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#if are_same_path(path, ["auth", "showTryAnotherWayLink"])>
|
|
||||||
<#attempt>
|
|
||||||
<#return auth.showTryAnotherWayLink()?c>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Couldn't evaluate auth.showTryAnotherWayLink()">
|
|
||||||
</#attempt>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#if are_same_path(path, ["url", "getLogoutUrl"])>
|
|
||||||
<#local returnValue = "">
|
|
||||||
<#attempt>
|
|
||||||
<#local returnValue = url.getLogoutUrl()>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Couldn't evaluate url.getLogoutUrl()">
|
|
||||||
</#attempt>
|
|
||||||
<#return 'function(){ return "' + returnValue + '"; }'>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#if are_same_path(path, ["totp", "policy", "getAlgorithmKey"])>
|
|
||||||
<#local returnValue = "">
|
|
||||||
<#attempt>
|
|
||||||
<#local returnValue = totp.policy.getAlgorithmKey()>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Couldn't evaluate totp.policy.getAlgorithmKey()">
|
|
||||||
</#attempt>
|
|
||||||
<#return 'function(){ return "' + returnValue + '"; }'>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#return "ABORT: It's a method">
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local isBoolean = "">
|
|
||||||
<#attempt>
|
|
||||||
<#local isBoolean = object?is_boolean>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Can't test if it's a boolean">
|
|
||||||
</#attempt>
|
|
||||||
|
|
||||||
<#if isBoolean>
|
|
||||||
<#return object?c>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local isEnumerable = "">
|
|
||||||
<#attempt>
|
|
||||||
<#local isEnumerable = object?is_enumerable>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Can't test if it's an enumerable">
|
|
||||||
</#attempt>
|
|
||||||
|
|
||||||
|
|
||||||
<#if isEnumerable>
|
|
||||||
|
|
||||||
<#local out_seq = []>
|
|
||||||
|
|
||||||
<#local i = 0>
|
|
||||||
|
|
||||||
<#list object as array_item>
|
|
||||||
|
|
||||||
<#if !array_item??>
|
|
||||||
<#local out_seq += ["null,"]>
|
|
||||||
<#continue>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local rec_out = ftl_object_to_js_code_declaring_an_object(array_item, path + [ i ])>
|
|
||||||
|
|
||||||
<#local i = i + 1>
|
|
||||||
|
|
||||||
<#if rec_out?starts_with("ABORT:")>
|
|
||||||
|
|
||||||
<#local errorMessage = rec_out?remove_beginning("ABORT:")>
|
|
||||||
|
|
||||||
<#if errorMessage != " It's a method" >
|
|
||||||
<#local out_seq += ["/*" + i?string + ": " + errorMessage + "*/"]>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#continue>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local out_seq += [rec_out + ","]>
|
|
||||||
|
|
||||||
</#list>
|
|
||||||
|
|
||||||
<#return (["["] + out_seq?map(str -> ""?right_pad(4 * (path?size + 1)) + str) + [ ""?right_pad(4 * path?size) + "]"])?join("\n")>
|
|
||||||
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local isDate = "">
|
|
||||||
<#attempt>
|
|
||||||
<#local isDate = object?is_date_like>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Can't test if it's a date">
|
|
||||||
</#attempt>
|
|
||||||
|
|
||||||
<#if isDate>
|
|
||||||
<#return '"' + object?datetime?iso_utc + '"'>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local isNumber = "">
|
|
||||||
<#attempt>
|
|
||||||
<#local isNumber = object?is_number>
|
|
||||||
<#recover>
|
|
||||||
<#return "ABORT: Can't test if it's a number">
|
|
||||||
</#attempt>
|
|
||||||
|
|
||||||
<#if isNumber>
|
|
||||||
<#return object?c>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#attempt>
|
|
||||||
<#return '"' + object?js_string + '"'>;
|
|
||||||
<#recover>
|
|
||||||
</#attempt>
|
|
||||||
|
|
||||||
<#return "ABORT: Couldn't convert into string non hash, non method, non boolean, non number, non enumerable object">
|
|
||||||
|
|
||||||
</#function>
|
|
||||||
<#function is_subpath path searchedPath>
|
|
||||||
|
|
||||||
<#if path?size < searchedPath?size>
|
|
||||||
<#return false>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local i=0>
|
|
||||||
|
|
||||||
<#list path as property>
|
|
||||||
|
|
||||||
<#if i == searchedPath?size >
|
|
||||||
<#continue>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#local searchedProperty=searchedPath[i]>
|
|
||||||
|
|
||||||
<#local i+= 1>
|
|
||||||
|
|
||||||
<#if searchedProperty?is_string && searchedProperty == "*">
|
|
||||||
<#continue>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#if searchedProperty?is_string && !property?is_string>
|
|
||||||
<#return false>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#if searchedProperty?is_number && !property?is_number>
|
|
||||||
<#return false>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
<#if searchedProperty?string != property?string>
|
|
||||||
<#return false>
|
|
||||||
</#if>
|
|
||||||
|
|
||||||
</#list>
|
|
||||||
|
|
||||||
<#return true>
|
|
||||||
|
|
||||||
</#function>
|
|
||||||
|
|
||||||
<#function are_same_path path searchedPath>
|
|
||||||
<#return path?size == searchedPath?size && is_subpath(path, searchedPath)>
|
|
||||||
</#function>
|
|
||||||
</script>
|
|
@ -1,45 +1,44 @@
|
|||||||
import cheerio from "cheerio";
|
import * as cheerio from "cheerio";
|
||||||
import { replaceImportsInJsCode } from "../replacers/replaceImportsInJsCode";
|
import {
|
||||||
import { generateCssCodeToDefineGlobals } from "../replacers/replaceImportsInCssCode";
|
replaceImportsInJsCode,
|
||||||
import { replaceImportsInInlineCssCode } from "../replacers/replaceImportsInInlineCssCode";
|
BuildContextLike as BuildContextLike_replaceImportsInJsCode
|
||||||
|
} from "../replacers/replaceImportsInJsCode";
|
||||||
|
import {
|
||||||
|
replaceImportsInCssCode,
|
||||||
|
BuildContextLike as BuildContextLike_replaceImportsInCssCode
|
||||||
|
} from "../replacers/replaceImportsInCssCode";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { join as pathJoin } from "path";
|
import { join as pathJoin } from "path";
|
||||||
import type { BuildOptions } from "../../shared/buildOptions";
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import {
|
import {
|
||||||
type ThemeType,
|
type ThemeType,
|
||||||
nameOfTheGlobal,
|
BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR,
|
||||||
basenameOfTheKeycloakifyResourcesDir,
|
RESOURCES_COMMON
|
||||||
resources_common,
|
|
||||||
nameOfTheLocalizationRealmOverridesUserProfileProperty
|
|
||||||
} from "../../shared/constants";
|
} from "../../shared/constants";
|
||||||
import { getThisCodebaseRootDirPath } from "../../tools/getThisCodebaseRootDirPath";
|
import { getThisCodebaseRootDirPath } from "../../tools/getThisCodebaseRootDirPath";
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
export type BuildContextLike = BuildContextLike_replaceImportsInJsCode &
|
||||||
bundler: "vite" | "webpack";
|
BuildContextLike_replaceImportsInCssCode & {
|
||||||
themeVersion: string;
|
urlPathname: string | undefined;
|
||||||
urlPathname: string | undefined;
|
themeVersion: string;
|
||||||
reactAppBuildDirPath: string;
|
kcContextExclusionsFtlCode: string | undefined;
|
||||||
assetsDirPath: string;
|
};
|
||||||
kcContextExclusionsFtlCode: string | undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export function generateFtlFilesCodeFactory(params: {
|
export function generateFtlFilesCodeFactory(params: {
|
||||||
themeName: string;
|
themeName: string;
|
||||||
indexHtmlCode: string;
|
indexHtmlCode: string;
|
||||||
cssGlobalsToDefine: Record<string, string>;
|
buildContext: BuildContextLike;
|
||||||
buildOptions: BuildOptionsLike;
|
|
||||||
keycloakifyVersion: string;
|
keycloakifyVersion: string;
|
||||||
themeType: ThemeType;
|
themeType: ThemeType;
|
||||||
fieldNames: string[];
|
fieldNames: string[];
|
||||||
}) {
|
}) {
|
||||||
const {
|
const {
|
||||||
themeName,
|
themeName,
|
||||||
cssGlobalsToDefine,
|
|
||||||
indexHtmlCode,
|
indexHtmlCode,
|
||||||
buildOptions,
|
buildContext,
|
||||||
keycloakifyVersion,
|
keycloakifyVersion,
|
||||||
themeType,
|
themeType,
|
||||||
fieldNames
|
fieldNames
|
||||||
@ -55,7 +54,7 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
|
|
||||||
const { fixedJsCode } = replaceImportsInJsCode({
|
const { fixedJsCode } = replaceImportsInJsCode({
|
||||||
jsCode,
|
jsCode,
|
||||||
buildOptions
|
buildContext
|
||||||
});
|
});
|
||||||
|
|
||||||
$(element).text(fixedJsCode);
|
$(element).text(fixedJsCode);
|
||||||
@ -66,9 +65,10 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
|
|
||||||
assert(cssCode !== null);
|
assert(cssCode !== null);
|
||||||
|
|
||||||
const { fixedCssCode } = replaceImportsInInlineCssCode({
|
const { fixedCssCode } = replaceImportsInCssCode({
|
||||||
cssCode,
|
cssCode,
|
||||||
buildOptions
|
cssFileRelativeDirPath: undefined,
|
||||||
|
buildContext
|
||||||
});
|
});
|
||||||
|
|
||||||
$(element).text(fixedCssCode);
|
$(element).text(fixedCssCode);
|
||||||
@ -77,7 +77,8 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
(
|
(
|
||||||
[
|
[
|
||||||
["link", "href"],
|
["link", "href"],
|
||||||
["script", "src"]
|
["script", "src"],
|
||||||
|
["script", "data-src"]
|
||||||
] as const
|
] as const
|
||||||
).forEach(([selector, attrName]) =>
|
).forEach(([selector, attrName]) =>
|
||||||
$(selector).each((...[, element]) => {
|
$(selector).each((...[, element]) => {
|
||||||
@ -91,32 +92,17 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
attrName,
|
attrName,
|
||||||
href.replace(
|
href.replace(
|
||||||
new RegExp(
|
new RegExp(
|
||||||
`^${(buildOptions.urlPathname ?? "/").replace(/\//g, "\\/")}`
|
`^${(buildContext.urlPathname ?? "/").replace(/\//g, "\\/")}`
|
||||||
),
|
),
|
||||||
`\${url.resourcesPath}/${basenameOfTheKeycloakifyResourcesDir}/`
|
`\${xKeycloakify.resourcesPath}/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/`
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
if (Object.keys(cssGlobalsToDefine).length !== 0) {
|
|
||||||
$("head").prepend(
|
|
||||||
[
|
|
||||||
"",
|
|
||||||
"<style>",
|
|
||||||
generateCssCodeToDefineGlobals({
|
|
||||||
cssGlobalsToDefine,
|
|
||||||
buildOptions
|
|
||||||
}).cssCodeToPrependInHead,
|
|
||||||
"</style>",
|
|
||||||
""
|
|
||||||
].join("\n")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//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,33 +110,26 @@ 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("{{themeType}}", themeType)
|
||||||
|
.replace("{{themeName}}", themeName)
|
||||||
|
.replace("{{keycloakifyVersion}}", keycloakifyVersion)
|
||||||
|
.replace("{{themeVersion}}", buildContext.themeVersion)
|
||||||
|
.replace("{{fieldNames}}", fieldNames.map(name => `"${name}"`).join(", "))
|
||||||
|
.replace("{{RESOURCES_COMMON}}", RESOURCES_COMMON)
|
||||||
.replace(
|
.replace(
|
||||||
"FIELD_NAMES_eKsIY4ZsZ4xeM",
|
"{{userDefinedExclusions}}",
|
||||||
fieldNames.map(name => `"${name}"`).join(", ")
|
buildContext.kcContextExclusionsFtlCode ?? ""
|
||||||
)
|
|
||||||
.replace("KEYCLOAKIFY_VERSION_xEdKd3xEdr", keycloakifyVersion)
|
|
||||||
.replace("KEYCLOAKIFY_THEME_VERSION_sIgKd3xEdr3dx", buildOptions.themeVersion)
|
|
||||||
.replace("KEYCLOAKIFY_THEME_TYPE_dExKd3xEdr", themeType)
|
|
||||||
.replace("KEYCLOAKIFY_THEME_NAME_cXxKd3xEer", themeName)
|
|
||||||
.replace("RESOURCES_COMMON_cLsLsMrtDkpVv", resources_common)
|
|
||||||
.replace(
|
|
||||||
"lOCALIZATION_REALM_OVERRIDES_USER_PROFILE_PROPERTY_KEY_aaGLsPgGIdeeX",
|
|
||||||
nameOfTheLocalizationRealmOverridesUserProfileProperty
|
|
||||||
)
|
|
||||||
.replace(
|
|
||||||
"USER_DEFINED_EXCLUSIONS_eKsaY4ZsZ4eMr2",
|
|
||||||
buildOptions.kcContextExclusionsFtlCode ?? ""
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const ftlObjectToJsCodeDeclaringAnObjectPlaceholder =
|
const ftlObjectToJsCodeDeclaringAnObjectPlaceholder =
|
||||||
'{ "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,8 +168,9 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
|
|
||||||
Object.entries({
|
Object.entries({
|
||||||
[ftlObjectToJsCodeDeclaringAnObjectPlaceholder]:
|
[ftlObjectToJsCodeDeclaringAnObjectPlaceholder]:
|
||||||
ftlObjectToJsCodeDeclaringAnObject,
|
kcContextDeclarationTemplateFtl,
|
||||||
PAGE_ID_xIgLsPgGId9D8e: pageId
|
"{{pageId}}": pageId,
|
||||||
|
"{{ftlTemplateFileName}}": pageId
|
||||||
}).map(
|
}).map(
|
||||||
([searchValue, replaceValue]) =>
|
([searchValue, replaceValue]) =>
|
||||||
(ftlCode = ftlCode.replace(searchValue, replaceValue))
|
(ftlCode = ftlCode.replace(searchValue, replaceValue))
|
||||||
|
667
src/bin/keycloakify/generateFtl/kcContextDeclarationTemplate.ftl
Normal file
667
src/bin/keycloakify/generateFtl/kcContextDeclarationTemplate.ftl
Normal file
@ -0,0 +1,667 @@
|
|||||||
|
<#assign xKeycloakify={
|
||||||
|
"messages": {},
|
||||||
|
"pageId": "{{pageId}}",
|
||||||
|
"ftlTemplateFileName": "{{ftlTemplateFileName}}",
|
||||||
|
"themeType": "{{themeType}}",
|
||||||
|
"themeName": "{{themeName}}",
|
||||||
|
"keycloakifyVersion": "{{keycloakifyVersion}}",
|
||||||
|
"themeVersion": "{{themeVersion}}",
|
||||||
|
"resourcesPath": ""
|
||||||
|
}>
|
||||||
|
|
||||||
|
<#if url?? && url?is_hash && url.resourcesPath?? && url.resourcesPath?is_string>
|
||||||
|
<#assign xKeycloakify = xKeycloakify + { "resourcesPath": url.resourcesPath }>
|
||||||
|
</#if>
|
||||||
|
<#if resourceUrl?? && resourceUrl?is_string>
|
||||||
|
<#assign xKeycloakify = xKeycloakify + { "resourcesPath": resourceUrl }>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
const kcContext = ${toJsDeclarationString(.data_model, [])?no_esc};
|
||||||
|
kcContext.keycloakifyVersion = "${xKeycloakify.keycloakifyVersion}";
|
||||||
|
kcContext.themeVersion = "${xKeycloakify.themeVersion}";
|
||||||
|
kcContext.themeType = "${xKeycloakify.themeType}";
|
||||||
|
kcContext.themeName = "${xKeycloakify.themeName}";
|
||||||
|
kcContext.pageId = "${xKeycloakify.pageId}";
|
||||||
|
kcContext.ftlTemplateFileName = "${xKeycloakify.ftlTemplateFileName}";
|
||||||
|
|
||||||
|
<@addNonAutomaticallyGatherableMessagesToXKeycloakifyMessages />
|
||||||
|
|
||||||
|
kcContext["x-keycloakify"] = {};
|
||||||
|
|
||||||
|
kcContext["x-keycloakify"].resourcesPath = "${xKeycloakify.resourcesPath}";
|
||||||
|
|
||||||
|
{
|
||||||
|
var messages = {};
|
||||||
|
<#list xKeycloakify.messages as key, resolvedMsg>
|
||||||
|
messages["${key}"] = decodeHtmlEntities("${resolvedMsg?js_string}");
|
||||||
|
</#list>
|
||||||
|
kcContext["x-keycloakify"].messages = messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(
|
||||||
|
kcContext.url instanceof Object &&
|
||||||
|
typeof kcContext.url.resourcesPath === "string"
|
||||||
|
){
|
||||||
|
kcContext.url.resourcesCommonPath = kcContext.url.resourcesPath + "/{{RESOURCES_COMMON}}";
|
||||||
|
}
|
||||||
|
|
||||||
|
if( kcContext.messagesPerField ){
|
||||||
|
var existsError_singleFieldName = kcContext.messagesPerField.existsError;
|
||||||
|
kcContext.messagesPerField.existsError = function (){
|
||||||
|
for( let i = 0; i < arguments.length; i++ ){
|
||||||
|
if( existsError_singleFieldName(arguments[i]) ){
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
kcContext.messagesPerField.exists = function (fieldName) {
|
||||||
|
return kcContext.messagesPerField.get(fieldName) !== "";
|
||||||
|
};
|
||||||
|
kcContext.messagesPerField.printIfExists = function (fieldName, text) {
|
||||||
|
return kcContext.messagesPerField.exists(fieldName) ? text : undefined;
|
||||||
|
};
|
||||||
|
kcContext.messagesPerField.getFirstError = function () {
|
||||||
|
for( let i = 0; i < arguments.length; i++ ){
|
||||||
|
const fieldName = arguments[i];
|
||||||
|
if( kcContext.messagesPerField.existsError(fieldName) ){
|
||||||
|
return kcContext.messagesPerField.get(fieldName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
attributes_to_attributesByName: {
|
||||||
|
if( !kcContext.profile ){
|
||||||
|
break attributes_to_attributesByName;
|
||||||
|
}
|
||||||
|
if( !kcContext.profile.attributes ){
|
||||||
|
break attributes_to_attributesByName;
|
||||||
|
}
|
||||||
|
var attributes = kcContext.profile.attributes;
|
||||||
|
delete kcContext.profile.attributes;
|
||||||
|
kcContext.profile.attributesByName = {};
|
||||||
|
attributes.forEach(function(attribute){
|
||||||
|
kcContext.profile.attributesByName[attribute.name] = attribute;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
window.kcContext = kcContext;
|
||||||
|
function decodeHtmlEntities(htmlStr){
|
||||||
|
var element = decodeHtmlEntities.element;
|
||||||
|
if (!element) {
|
||||||
|
element = document.createElement("textarea");
|
||||||
|
decodeHtmlEntities.element = element;
|
||||||
|
}
|
||||||
|
element.innerHTML = htmlStr;
|
||||||
|
return element.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
<#function toJsDeclarationString object path>
|
||||||
|
<#local isHash = -1>
|
||||||
|
<#attempt>
|
||||||
|
<#local isHash = object?is_hash || object?is_hash_ex>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Can't evaluate if " + path?join(".") + " is a hash">
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
<#if isHash>
|
||||||
|
<#if path?size gt 10>
|
||||||
|
<#return "ABORT: Too many recursive calls, path: " + path?join(".")>
|
||||||
|
</#if>
|
||||||
|
<#local keys = -1>
|
||||||
|
|
||||||
|
<#attempt>
|
||||||
|
<#local keys = object?keys>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: We can't list keys on object">
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
<#local outSeq = []>
|
||||||
|
|
||||||
|
<#list keys as key>
|
||||||
|
<#if ["class","declaredConstructors","superclass","declaringClass" ]?seq_contains(key) >
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if (
|
||||||
|
areSamePath(path, ["url"]) &&
|
||||||
|
["loginUpdatePasswordUrl", "loginUpdateProfileUrl", "loginUsernameReminderUrl", "loginUpdateTotpUrl"]?seq_contains(key)
|
||||||
|
) || (
|
||||||
|
key == "updateProfileCtx" &&
|
||||||
|
areSamePath(path, [])
|
||||||
|
) || (
|
||||||
|
<#-- https://github.com/keycloakify/keycloakify/pull/65#issuecomment-991896344 (reports with saml-post-form.ftl) -->
|
||||||
|
<#-- https://github.com/keycloakify/keycloakify/issues/91#issue-1212319466 (reports with error.ftl and Kc18) -->
|
||||||
|
<#-- https://github.com/keycloakify/keycloakify/issues/109#issuecomment-1134610163 -->
|
||||||
|
<#-- https://github.com/keycloakify/keycloakify/issues/357 -->
|
||||||
|
<#-- https://github.com/keycloakify/keycloakify/discussions/406#discussioncomment-7514787 -->
|
||||||
|
key == "loginAction" &&
|
||||||
|
areSamePath(path, ["url"]) &&
|
||||||
|
["saml-post-form.ftl", "error.ftl", "info.ftl", "login-oauth-grant.ftl", "logout-confirm.ftl", "login-oauth2-device-verify-user-code.ftl"]?seq_contains(xKeycloakify.pageId) &&
|
||||||
|
!(auth?has_content && auth.showTryAnotherWayLink())
|
||||||
|
) || (
|
||||||
|
<#-- https://github.com/keycloakify/keycloakify/issues/362 -->
|
||||||
|
["secretData", "value"]?seq_contains(key) &&
|
||||||
|
areSamePath(path, [ "totp", "otpCredentials", "*" ])
|
||||||
|
) || (
|
||||||
|
["contextData", "idpConfig", "idp", "authenticationSession"]?seq_contains(key) &&
|
||||||
|
areSamePath(path, ["brokerContext"]) &&
|
||||||
|
["login-idp-link-confirm.ftl", "login-idp-link-email.ftl" ]?seq_contains(xKeycloakify.pageId)
|
||||||
|
) || (
|
||||||
|
key == "identityProviderBrokerCtx" &&
|
||||||
|
areSamePath(path, []) &&
|
||||||
|
["login-idp-link-confirm.ftl", "login-idp-link-email.ftl" ]?seq_contains(xKeycloakify.pageId)
|
||||||
|
) || (
|
||||||
|
["masterAdminClient", "delegateForUpdate", "defaultRole"]?seq_contains(key) &&
|
||||||
|
areSamePath(path, ["realm"])
|
||||||
|
) || (
|
||||||
|
xKeycloakify.pageId == "error.ftl" &&
|
||||||
|
areSamePath(path, ["realm"]) &&
|
||||||
|
!["name", "displayName", "displayNameHtml", "internationalizationEnabled", "registrationEmailAsUsername" ]?seq_contains(key)
|
||||||
|
) || (
|
||||||
|
xKeycloakify.pageId == "applications.ftl" &&
|
||||||
|
(
|
||||||
|
key == "realm" ||
|
||||||
|
key == "container"
|
||||||
|
) &&
|
||||||
|
isSubpath(path, ["applications", "applications"])
|
||||||
|
) || (
|
||||||
|
key == "delegateForUpdate" &&
|
||||||
|
areSamePath(path, ["user"])
|
||||||
|
) || (
|
||||||
|
<#-- Security audit forwarded by Garth (Gmail) -->
|
||||||
|
key == "saml.signing.private.key" &&
|
||||||
|
areSamePath(path, ["client", "attributes"])
|
||||||
|
) || (
|
||||||
|
<#-- See: https://github.com/keycloakify/keycloakify/issues/534 -->
|
||||||
|
key == "password" &&
|
||||||
|
areSamePath(path, ["login"])
|
||||||
|
) || (
|
||||||
|
<#-- Remove realmAttributes added by https://github.com/jcputney/keycloak-theme-additional-info-extension for peace of mind. -->
|
||||||
|
key == "realmAttributes" &&
|
||||||
|
areSamePath(path, [])
|
||||||
|
) || (
|
||||||
|
<#-- attributesByName adds a lot of noise to the output and is not needed, we already have profile.attributes -->
|
||||||
|
key == "attributesByName" &&
|
||||||
|
areSamePath(path, ["profile"])
|
||||||
|
) || (
|
||||||
|
<#-- We already have the attributes in profile speedup the rendering by filtering it out from the register object -->
|
||||||
|
(key == "attributes" || key == "attributesByName") &&
|
||||||
|
areSamePath(path, ["register"])
|
||||||
|
) || (
|
||||||
|
areSamePath(path, ["properties"]) &&
|
||||||
|
(
|
||||||
|
key?starts_with("kc") ||
|
||||||
|
key == "locales" ||
|
||||||
|
key == "import" ||
|
||||||
|
key == "parent" ||
|
||||||
|
key == "meta" ||
|
||||||
|
key == "stylesCommon" ||
|
||||||
|
key == "styles" ||
|
||||||
|
key == "accountResourceProvider"
|
||||||
|
)
|
||||||
|
) || (
|
||||||
|
key == "execution" &&
|
||||||
|
areSamePath(path, [])
|
||||||
|
) || (
|
||||||
|
key == "entity" &&
|
||||||
|
areSamePath(path, ["user"])
|
||||||
|
) || (
|
||||||
|
key == "attributes" &&
|
||||||
|
areSamePath(path, ["realm"])
|
||||||
|
) || (
|
||||||
|
xKeycloakify.pageId == "index.ftl" &&
|
||||||
|
xKeycloakify.themeType == "account" &&
|
||||||
|
areSamePath(path, ["realm"]) &&
|
||||||
|
![
|
||||||
|
"name",
|
||||||
|
"registrationEmailAsUsername",
|
||||||
|
"editUsernameAllowed",
|
||||||
|
"isInternationalizationEnabled",
|
||||||
|
"identityFederationEnabled",
|
||||||
|
"userManagedAccessAllowed"
|
||||||
|
]?seq_contains(key)
|
||||||
|
)
|
||||||
|
>
|
||||||
|
<#-- <#local outSeq += ["/*" + path?join(".") + "." + key + " excluded*/"]> -->
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#-- https://github.com/keycloakify/keycloakify/discussions/406 -->
|
||||||
|
<#if (
|
||||||
|
key == "attemptedUsername" &&
|
||||||
|
areSamePath(path, ["auth"]) &&
|
||||||
|
[
|
||||||
|
"register.ftl", "terms.ftl", "info.ftl", "login.ftl",
|
||||||
|
"login-update-password.ftl", "login-oauth2-device-verify-user-code.ftl"
|
||||||
|
]?seq_contains(xKeycloakify.pageId)
|
||||||
|
)>
|
||||||
|
<#attempt>
|
||||||
|
<#-- https://github.com/keycloak/keycloak/blob/3a2bf0c04bcde185e497aaa32d0bb7ab7520cf4a/themes/src/main/resources/theme/base/login/template.ftl#L63 -->
|
||||||
|
<#if !(auth?has_content && auth.showUsername() && !auth.showResetCredentials())>
|
||||||
|
<#local outSeq += ["/*" + path?join(".") + "." + key + " excluded*/"]>
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
<#recover>
|
||||||
|
<#local outSeq += ["/*Accessing attemptedUsername throwed an exception */"]>
|
||||||
|
</#attempt>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
{{userDefinedExclusions}}
|
||||||
|
|
||||||
|
<#attempt>
|
||||||
|
<#if !object[key]??>
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
<#recover>
|
||||||
|
<#local outSeq += ["/*Couldn't test if '" + key + "' is available on this object*/"]>
|
||||||
|
<#continue>
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
<#local propertyValue = -1>
|
||||||
|
|
||||||
|
<#attempt>
|
||||||
|
<#local propertyValue = object[key]>
|
||||||
|
<#recover>
|
||||||
|
<#local outSeq += ["/*Couldn't dereference '" + key + "' on this object*/"]>
|
||||||
|
<#continue>
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
<#local recOut = toJsDeclarationString(propertyValue, path + [ key ])>
|
||||||
|
|
||||||
|
<#if recOut?starts_with("ABORT:")>
|
||||||
|
|
||||||
|
<#local errorMessage = recOut?remove_beginning("ABORT:")>
|
||||||
|
|
||||||
|
<#if errorMessage != " It's a method" >
|
||||||
|
<#local outSeq += ["/*" + key + ": " + errorMessage + "*/"]>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local outSeq += ['"' + key + '": ' + recOut + ","]>
|
||||||
|
|
||||||
|
</#list>
|
||||||
|
|
||||||
|
<#return (["{"] + outSeq?map(str -> ""?right_pad(4 * (path?size + 1)) + str) + [ ""?right_pad(4 * path?size) + "}"])?join("\n")>
|
||||||
|
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local isMethod = -1>
|
||||||
|
<#attempt>
|
||||||
|
<#local isMethod = object?is_method>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Can't test if it'sa method.">
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
<#if isMethod>
|
||||||
|
|
||||||
|
<#if areSamePath(path, ["auth", "showUsername"])>
|
||||||
|
<#attempt>
|
||||||
|
<#return auth.showUsername()?c>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Couldn't evaluate auth.showUsername()">
|
||||||
|
</#attempt>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if areSamePath(path, ["auth", "showResetCredentials"])>
|
||||||
|
<#attempt>
|
||||||
|
<#return auth.showResetCredentials()?c>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Couldn't evaluate auth.showResetCredentials()">
|
||||||
|
</#attempt>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if areSamePath(path, ["auth", "showTryAnotherWayLink"])>
|
||||||
|
<#attempt>
|
||||||
|
<#return auth.showTryAnotherWayLink()?c>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Couldn't evaluate auth.showTryAnotherWayLink()">
|
||||||
|
</#attempt>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if areSamePath(path, ["url", "getLogoutUrl"])>
|
||||||
|
<#local returnValue = -1>
|
||||||
|
<#attempt>
|
||||||
|
<#local returnValue = url.getLogoutUrl()>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Couldn't evaluate url.getLogoutUrl()">
|
||||||
|
</#attempt>
|
||||||
|
<#return 'function(){ return "' + returnValue + '"; }'>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if areSamePath(path, ["totp", "policy", "getAlgorithmKey"])>
|
||||||
|
<#local returnValue = "error">
|
||||||
|
<#if mode?? && mode = "manual">
|
||||||
|
<#attempt>
|
||||||
|
<#local returnValue = totp.policy.getAlgorithmKey()>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Couldn't evaluate totp.policy.getAlgorithmKey()">
|
||||||
|
</#attempt>
|
||||||
|
</#if>
|
||||||
|
<#return 'function(){ return "' + returnValue + '"; }'>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#assign fieldNames = [{{fieldNames}}]>
|
||||||
|
<#if profile?? && profile.attributes??>
|
||||||
|
<#list profile.attributes as attribute>
|
||||||
|
<#if fieldNames?seq_contains(attribute.name)>
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
<#assign fieldNames += [attribute.name]>
|
||||||
|
</#list>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if areSamePath(path, ["messagesPerField", "get"])>
|
||||||
|
|
||||||
|
<#local jsFunctionCode = "function (fieldName) { ">
|
||||||
|
|
||||||
|
<#list fieldNames as fieldName>
|
||||||
|
|
||||||
|
<#-- See: https://github.com/keycloakify/keycloakify/issues/217 -->
|
||||||
|
<#if xKeycloakify.pageId == "login.ftl" >
|
||||||
|
|
||||||
|
<#if fieldName == "username">
|
||||||
|
|
||||||
|
<#local jsFunctionCode += "if(fieldName === 'username' || fieldName === 'password' ){ ">
|
||||||
|
|
||||||
|
<#if messagesPerField.exists('username') || messagesPerField.exists('password')>
|
||||||
|
<#local jsFunctionCode += "return kcContext.message && kcContext.message.summary ? kcContext.message.summary : 'error'; ">
|
||||||
|
<#else>
|
||||||
|
<#local jsFunctionCode += "return ''; ">
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local jsFunctionCode += "} ">
|
||||||
|
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if fieldName == "password">
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local jsFunctionCode += "if(fieldName === '" + fieldName + "'){ ">
|
||||||
|
|
||||||
|
<#if messagesPerField.exists('${fieldName}')>
|
||||||
|
<#local jsFunctionCode += 'return decodeHtmlEntities("' + messagesPerField.get('${fieldName}')?js_string + '"); '>
|
||||||
|
<#else>
|
||||||
|
<#local jsFunctionCode += "return ''; ">
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local jsFunctionCode += "} ">
|
||||||
|
|
||||||
|
</#list>
|
||||||
|
|
||||||
|
<#local jsFunctionCode += "}">
|
||||||
|
|
||||||
|
<#return jsFunctionCode>
|
||||||
|
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if areSamePath(path, ["messagesPerField", "existsError"])>
|
||||||
|
|
||||||
|
<#local jsFunctionCode = "function (fieldName) { ">
|
||||||
|
|
||||||
|
<#list fieldNames as fieldName>
|
||||||
|
|
||||||
|
<#-- See: https://github.com/keycloakify/keycloakify/issues/217 -->
|
||||||
|
<#if xKeycloakify.pageId == "login.ftl" >
|
||||||
|
<#if fieldName == "username">
|
||||||
|
|
||||||
|
<#local jsFunctionCode += "if(fieldName === 'username' || fieldName === 'password' ){ ">
|
||||||
|
|
||||||
|
<#if messagesPerField.existsError('username') || messagesPerField.existsError('password')>
|
||||||
|
<#local jsFunctionCode += "return true; ">
|
||||||
|
<#else>
|
||||||
|
<#local jsFunctionCode += "return false; ">
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local jsFunctionCode += "} ">
|
||||||
|
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if fieldName == "password">
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local jsFunctionCode += "if(fieldName === '" + fieldName + "' ){ ">
|
||||||
|
|
||||||
|
<#if messagesPerField.existsError('${fieldName}')>
|
||||||
|
<#local jsFunctionCode += 'return true; '>
|
||||||
|
<#else>
|
||||||
|
<#local jsFunctionCode += "return false; ">
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local jsFunctionCode += "}">
|
||||||
|
|
||||||
|
</#list>
|
||||||
|
|
||||||
|
<#local jsFunctionCode += "}">
|
||||||
|
|
||||||
|
<#return jsFunctionCode>
|
||||||
|
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if xKeycloakify.themeType == "account" && areSamePath(path, ["realm", "isInternationalizationEnabled"])>
|
||||||
|
<#attempt>
|
||||||
|
<#return realm.isInternationalizationEnabled()?c>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Couldn't evaluate realm.isInternationalizationEnabled()">
|
||||||
|
</#attempt>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#return "ABORT: It's a method">
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local isBoolean = -1>
|
||||||
|
<#attempt>
|
||||||
|
<#local isBoolean = object?is_boolean>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Can't test if it's a boolean">
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
<#if isBoolean>
|
||||||
|
<#return object?c>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local isEnumerable = -1>
|
||||||
|
<#attempt>
|
||||||
|
<#local isEnumerable = object?is_enumerable>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Can't test if it's an enumerable">
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
|
||||||
|
<#if isEnumerable>
|
||||||
|
|
||||||
|
<#local outSeq = []>
|
||||||
|
|
||||||
|
<#local i = 0>
|
||||||
|
|
||||||
|
<#list object as array_item>
|
||||||
|
|
||||||
|
<#if !array_item??>
|
||||||
|
<#local outSeq += ["null,"]>
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local recOut = toJsDeclarationString(array_item, path + [ i ])>
|
||||||
|
|
||||||
|
<#local i = i + 1>
|
||||||
|
|
||||||
|
<#if recOut?starts_with("ABORT:")>
|
||||||
|
|
||||||
|
<#local errorMessage = recOut?remove_beginning("ABORT:")>
|
||||||
|
|
||||||
|
<#if errorMessage != " It's a method" >
|
||||||
|
<#local outSeq += ["/*" + i?string + ": " + errorMessage + "*/"]>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local outSeq += [recOut + ","]>
|
||||||
|
|
||||||
|
</#list>
|
||||||
|
|
||||||
|
<#return (["["] + outSeq?map(str -> ""?right_pad(4 * (path?size + 1)) + str) + [ ""?right_pad(4 * path?size) + "]"])?join("\n")>
|
||||||
|
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local isDate = -1>
|
||||||
|
<#attempt>
|
||||||
|
<#local isDate = object?is_date_like>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Can't test if it's a date">
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
<#if isDate>
|
||||||
|
<#return '"' + object?datetime?iso_utc + '"'>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local isNumber = -1>
|
||||||
|
<#attempt>
|
||||||
|
<#local isNumber = object?is_number>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Can't test if it's a number">
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
<#if isNumber>
|
||||||
|
<#return object?c>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local isString = -1>
|
||||||
|
<#attempt>
|
||||||
|
<#local isString = object?is_string>
|
||||||
|
<#recover>
|
||||||
|
<#return "ABORT: Can't test if it's a string">
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
<#if isString>
|
||||||
|
<@addToXKeycloakifyMessagesIfMessageKey str=object />
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#attempt>
|
||||||
|
<#return '"' + object?js_string + '"'>;
|
||||||
|
<#recover>
|
||||||
|
</#attempt>
|
||||||
|
|
||||||
|
<#return "ABORT: Couldn't convert into string non hash, non method, non boolean, non number, non enumerable object">
|
||||||
|
|
||||||
|
</#function>
|
||||||
|
<#function isSubpath path searchedPath>
|
||||||
|
|
||||||
|
<#if path?size < searchedPath?size>
|
||||||
|
<#return false>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local i=0>
|
||||||
|
|
||||||
|
<#list path as property>
|
||||||
|
|
||||||
|
<#if i == searchedPath?size >
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#local searchedProperty=searchedPath[i]>
|
||||||
|
|
||||||
|
<#local i+= 1>
|
||||||
|
|
||||||
|
<#if searchedProperty?is_string && searchedProperty == "*">
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if searchedProperty?is_string && !property?is_string>
|
||||||
|
<#return false>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if searchedProperty?is_number && !property?is_number>
|
||||||
|
<#return false>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
<#if searchedProperty?string != property?string>
|
||||||
|
<#return false>
|
||||||
|
</#if>
|
||||||
|
|
||||||
|
</#list>
|
||||||
|
|
||||||
|
<#return true>
|
||||||
|
|
||||||
|
</#function>
|
||||||
|
|
||||||
|
<#function areSamePath path searchedPath>
|
||||||
|
<#return path?size == searchedPath?size && isSubpath(path, searchedPath)>
|
||||||
|
</#function>
|
||||||
|
|
||||||
|
<#macro addToXKeycloakifyMessagesIfMessageKey str>
|
||||||
|
<#if !msg?? || !msg?is_method>
|
||||||
|
<#return>
|
||||||
|
</#if>
|
||||||
|
<#if (str?length > 200)>
|
||||||
|
<#return>
|
||||||
|
</#if>
|
||||||
|
<#local key=removeBrackets(str)>
|
||||||
|
<#if key?length==0>
|
||||||
|
<#return>
|
||||||
|
</#if>
|
||||||
|
<#if !(key?matches(r"^[a-zA-Z0-9-_.]*$"))>
|
||||||
|
<#return>
|
||||||
|
</#if>
|
||||||
|
<#local resolvedMsg=msg(key)>
|
||||||
|
<#if resolvedMsg==key>
|
||||||
|
<#return>
|
||||||
|
</#if>
|
||||||
|
<#local messages=xKeycloakify.messages>
|
||||||
|
<#local messages = messages + { key: resolvedMsg }>
|
||||||
|
<#assign xKeycloakify = xKeycloakify + { "messages": messages }>
|
||||||
|
</#macro>
|
||||||
|
|
||||||
|
<#function removeBrackets str>
|
||||||
|
<#if str?starts_with("${") && str?ends_with("}")>
|
||||||
|
<#return str[2..(str?length-2)]>
|
||||||
|
<#else>
|
||||||
|
<#return str>
|
||||||
|
</#if>
|
||||||
|
</#function>
|
||||||
|
|
||||||
|
<#macro addNonAutomaticallyGatherableMessagesToXKeycloakifyMessages>
|
||||||
|
<#if profile?? && profile?is_hash && profile.attributes?? && profile.attributes?is_enumerable>
|
||||||
|
<#list profile.attributes as attribute>
|
||||||
|
<#if !(
|
||||||
|
attribute.annotations?? && attribute.annotations?is_hash &&
|
||||||
|
attribute.annotations.inputOptionLabelsI18nPrefix?? && attribute.annotations.inputOptionLabelsI18nPrefix?is_string
|
||||||
|
)>
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
<#local prefix=attribute.annotations.inputOptionLabelsI18nPrefix>
|
||||||
|
<#if !(
|
||||||
|
attribute.validators?? && attribute.validators?is_hash &&
|
||||||
|
attribute.validators.options?? && attribute.validators.options?is_hash &&
|
||||||
|
attribute.validators.options.options?? && attribute.validators.options.options?is_enumerable
|
||||||
|
)>
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
<#list attribute.validators.options.options as option>
|
||||||
|
<#if !option?is_string>
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
<@addToXKeycloakifyMessagesIfMessageKey str="${prefix}.${option}" />
|
||||||
|
</#list>
|
||||||
|
</#list>
|
||||||
|
</#if>
|
||||||
|
<#if xKeycloakify.pageId == "terms.ftl" || termsAcceptanceRequired?? && termsAcceptanceRequired>
|
||||||
|
<@addToXKeycloakifyMessagesIfMessageKey str="termsText" />
|
||||||
|
</#if>
|
||||||
|
<#if requiredActions?? && requiredActions?is_enumerable>
|
||||||
|
<#list requiredActions as requiredAction>
|
||||||
|
<#if !requiredAction?is_string>
|
||||||
|
<#continue>
|
||||||
|
</#if>
|
||||||
|
<@addToXKeycloakifyMessagesIfMessageKey str="requiredAction.${requiredAction}" />
|
||||||
|
</#list>
|
||||||
|
</#if>
|
||||||
|
</#macro>
|
@ -1,38 +1,37 @@
|
|||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { join as pathJoin } from "path";
|
import { join as pathJoin } from "path";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import type { BuildOptions } from "../../shared/buildOptions";
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
import {
|
import {
|
||||||
resources_common,
|
RESOURCES_COMMON,
|
||||||
lastKeycloakVersionWithAccountV1,
|
LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1,
|
||||||
accountV1ThemeName
|
ACCOUNT_V1_THEME_NAME
|
||||||
} from "../../shared/constants";
|
} from "../../shared/constants";
|
||||||
import { downloadKeycloakDefaultTheme } from "../../shared/downloadKeycloakDefaultTheme";
|
import {
|
||||||
|
downloadKeycloakDefaultTheme,
|
||||||
|
BuildContextLike as BuildContextLike_downloadKeycloakDefaultTheme
|
||||||
|
} from "../../shared/downloadKeycloakDefaultTheme";
|
||||||
import { transformCodebase } from "../../tools/transformCodebase";
|
import { transformCodebase } from "../../tools/transformCodebase";
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
export type BuildContextLike = BuildContextLike_downloadKeycloakDefaultTheme;
|
||||||
cacheDirPath: string;
|
|
||||||
npmWorkspaceRootDirPath: string;
|
|
||||||
keycloakifyBuildDirPath: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export async function bringInAccountV1(params: { buildOptions: BuildOptionsLike }) {
|
export async function bringInAccountV1(params: {
|
||||||
const { buildOptions } = params;
|
resourcesDirPath: string;
|
||||||
|
buildContext: BuildContextLike;
|
||||||
|
}) {
|
||||||
|
const { resourcesDirPath, buildContext } = params;
|
||||||
|
|
||||||
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
||||||
keycloakVersion: lastKeycloakVersionWithAccountV1,
|
keycloakVersion: LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1,
|
||||||
buildOptions
|
buildContext
|
||||||
});
|
});
|
||||||
|
|
||||||
const accountV1DirPath = pathJoin(
|
const accountV1DirPath = pathJoin(
|
||||||
buildOptions.keycloakifyBuildDirPath,
|
resourcesDirPath,
|
||||||
"src",
|
|
||||||
"main",
|
|
||||||
"resources",
|
|
||||||
"theme",
|
"theme",
|
||||||
accountV1ThemeName,
|
ACCOUNT_V1_THEME_NAME,
|
||||||
"account"
|
"account"
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -48,7 +47,7 @@ export async function bringInAccountV1(params: { buildOptions: BuildOptionsLike
|
|||||||
|
|
||||||
transformCodebase({
|
transformCodebase({
|
||||||
srcDirPath: pathJoin(defaultThemeDirPath, "keycloak", "common", "resources"),
|
srcDirPath: pathJoin(defaultThemeDirPath, "keycloak", "common", "resources"),
|
||||||
destDirPath: pathJoin(accountV1DirPath, "resources", resources_common)
|
destDirPath: pathJoin(accountV1DirPath, "resources", RESOURCES_COMMON)
|
||||||
});
|
});
|
||||||
|
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
@ -70,7 +69,7 @@ export async function bringInAccountV1(params: { buildOptions: BuildOptionsLike
|
|||||||
"patternfly-additions.min.css"
|
"patternfly-additions.min.css"
|
||||||
].map(
|
].map(
|
||||||
fileBasename =>
|
fileBasename =>
|
||||||
`${resources_common}/node_modules/patternfly/dist/css/${fileBasename}`
|
`${RESOURCES_COMMON}/node_modules/patternfly/dist/css/${fileBasename}`
|
||||||
)
|
)
|
||||||
].join(" "),
|
].join(" "),
|
||||||
"",
|
"",
|
@ -0,0 +1,192 @@
|
|||||||
|
import { type ThemeType, FALLBACK_LANGUAGE_TAG } from "../../shared/constants";
|
||||||
|
import { crawl } from "../../tools/crawl";
|
||||||
|
import { join as pathJoin } from "path";
|
||||||
|
import { symToStr } from "tsafe/symToStr";
|
||||||
|
import * as recast from "recast";
|
||||||
|
import * as babelParser from "@babel/parser";
|
||||||
|
import babelGenerate from "@babel/generator";
|
||||||
|
import * as babelTypes from "@babel/types";
|
||||||
|
import { escapeStringForPropertiesFile } from "../../tools/escapeStringForPropertiesFile";
|
||||||
|
import { getThisCodebaseRootDirPath } from "../../tools/getThisCodebaseRootDirPath";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { assert } from "tsafe/assert";
|
||||||
|
|
||||||
|
export function generateMessageProperties(params: {
|
||||||
|
themeSrcDirPath: string;
|
||||||
|
themeType: ThemeType;
|
||||||
|
}): { languageTag: string; propertiesFileSource: string }[] {
|
||||||
|
const { themeSrcDirPath, themeType } = params;
|
||||||
|
|
||||||
|
const baseMessagesDirPath = pathJoin(
|
||||||
|
getThisCodebaseRootDirPath(),
|
||||||
|
"src",
|
||||||
|
themeType,
|
||||||
|
"i18n",
|
||||||
|
"messages_defaultSet"
|
||||||
|
);
|
||||||
|
|
||||||
|
const baseMessageBundle: { [languageTag: string]: Record<string, string> } =
|
||||||
|
Object.fromEntries(
|
||||||
|
fs
|
||||||
|
.readdirSync(baseMessagesDirPath)
|
||||||
|
.filter(baseName => baseName !== "index.ts")
|
||||||
|
.map(basename => ({
|
||||||
|
languageTag: basename.replace(/\.ts$/, ""),
|
||||||
|
filePath: pathJoin(baseMessagesDirPath, basename)
|
||||||
|
}))
|
||||||
|
.map(({ languageTag, filePath }) => {
|
||||||
|
const lines = fs
|
||||||
|
.readFileSync(filePath)
|
||||||
|
.toString("utf8")
|
||||||
|
.split(/\r?\n/);
|
||||||
|
|
||||||
|
let messagesJson = "{";
|
||||||
|
|
||||||
|
let isInDeclaration = false;
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
if (!isInDeclaration) {
|
||||||
|
if (line.startsWith("const messages")) {
|
||||||
|
isInDeclaration = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.startsWith("}")) {
|
||||||
|
messagesJson += "}";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
messagesJson += line;
|
||||||
|
}
|
||||||
|
|
||||||
|
const messages = JSON.parse(messagesJson) as Record<string, string>;
|
||||||
|
|
||||||
|
return [languageTag, messages];
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const { i18nTsFilePath } = (() => {
|
||||||
|
let files = crawl({
|
||||||
|
dirPath: pathJoin(themeSrcDirPath, themeType),
|
||||||
|
returnedPathsType: "absolute"
|
||||||
|
});
|
||||||
|
|
||||||
|
files = files.filter(file => {
|
||||||
|
const regex = /\.(js|ts|tsx)$/;
|
||||||
|
return regex.test(file);
|
||||||
|
});
|
||||||
|
|
||||||
|
files = files.sort((a, b) => {
|
||||||
|
const regex = /\.i18n\.(ts|js|tsx)$/;
|
||||||
|
const aIsI18nFile = regex.test(a);
|
||||||
|
const bIsI18nFile = regex.test(b);
|
||||||
|
return aIsI18nFile === bIsI18nFile ? 0 : aIsI18nFile ? -1 : 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
files = files.sort((a, b) => a.length - b.length);
|
||||||
|
|
||||||
|
files = files.filter(file =>
|
||||||
|
fs.readFileSync(file).toString("utf8").includes("createUseI18n(")
|
||||||
|
);
|
||||||
|
|
||||||
|
const i18nTsFilePath: string | undefined = files[0];
|
||||||
|
|
||||||
|
return { i18nTsFilePath };
|
||||||
|
})();
|
||||||
|
|
||||||
|
const messageBundle: { [languageTag: string]: Record<string, string> } | undefined =
|
||||||
|
(() => {
|
||||||
|
if (i18nTsFilePath === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const root = recast.parse(fs.readFileSync(i18nTsFilePath).toString("utf8"), {
|
||||||
|
parser: {
|
||||||
|
parse: (code: string) =>
|
||||||
|
babelParser.parse(code, {
|
||||||
|
sourceType: "module",
|
||||||
|
plugins: ["typescript"]
|
||||||
|
}),
|
||||||
|
generator: babelGenerate,
|
||||||
|
types: babelTypes
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let messageBundleDeclarationTsCode: string | undefined = undefined;
|
||||||
|
|
||||||
|
recast.visit(root, {
|
||||||
|
visitCallExpression: function (path) {
|
||||||
|
if (
|
||||||
|
path.node.callee.type === "Identifier" &&
|
||||||
|
path.node.callee.name === "createUseI18n"
|
||||||
|
) {
|
||||||
|
messageBundleDeclarationTsCode = babelGenerate(
|
||||||
|
path.node.arguments[0] as any
|
||||||
|
).code;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.traverse(path);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
assert(messageBundleDeclarationTsCode !== undefined);
|
||||||
|
|
||||||
|
let messageBundle: {
|
||||||
|
[languageTag: string]: Record<string, string>;
|
||||||
|
} = {};
|
||||||
|
|
||||||
|
try {
|
||||||
|
eval(
|
||||||
|
`${symToStr({ messageBundle })} = ${messageBundleDeclarationTsCode}`
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
console.warn(
|
||||||
|
[
|
||||||
|
"WARNING: Make sure the messageBundle your provided as argument of createUseI18n can be statically evaluated.",
|
||||||
|
"This is important because we need to put your i18n messages in messages_*.properties files",
|
||||||
|
"or they won't be available server side.",
|
||||||
|
"\n",
|
||||||
|
"The following code could not be evaluated:",
|
||||||
|
"\n",
|
||||||
|
messageBundleDeclarationTsCode
|
||||||
|
].join(" ")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return messageBundle;
|
||||||
|
})();
|
||||||
|
|
||||||
|
const mergedMessageBundle: { [languageTag: string]: Record<string, string> } =
|
||||||
|
Object.fromEntries(
|
||||||
|
Object.entries(baseMessageBundle).map(([languageTag, messages]) => [
|
||||||
|
languageTag,
|
||||||
|
{
|
||||||
|
...messages,
|
||||||
|
...(messageBundle === undefined
|
||||||
|
? {}
|
||||||
|
: messageBundle[languageTag] ??
|
||||||
|
messageBundle[FALLBACK_LANGUAGE_TAG] ??
|
||||||
|
messageBundle[Object.keys(messageBundle)[0]] ??
|
||||||
|
{})
|
||||||
|
}
|
||||||
|
])
|
||||||
|
);
|
||||||
|
|
||||||
|
const messageProperties: { languageTag: string; propertiesFileSource: string }[] =
|
||||||
|
Object.entries(mergedMessageBundle).map(([languageTag, messages]) => ({
|
||||||
|
languageTag,
|
||||||
|
propertiesFileSource: [
|
||||||
|
"",
|
||||||
|
...(themeType !== "account" ? ["parent=base"] : []),
|
||||||
|
...Object.entries(messages).map(
|
||||||
|
([key, value]) => `${key}=${escapeStringForPropertiesFile(value)}`
|
||||||
|
),
|
||||||
|
""
|
||||||
|
].join("\n")
|
||||||
|
}));
|
||||||
|
|
||||||
|
return messageProperties;
|
||||||
|
}
|
42
src/bin/keycloakify/generateResources/generateResources.ts
Normal file
42
src/bin/keycloakify/generateResources/generateResources.ts
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
|
import { assert } from "tsafe/assert";
|
||||||
|
import {
|
||||||
|
generateResourcesForMainTheme,
|
||||||
|
type BuildContextLike as BuildContextLike_generateResourcesForMainTheme
|
||||||
|
} from "./generateResourcesForMainTheme";
|
||||||
|
import { generateResourcesForThemeVariant } from "./generateResourcesForThemeVariant";
|
||||||
|
import fs from "fs";
|
||||||
|
import { rmSync } from "../../tools/fs.rmSync";
|
||||||
|
|
||||||
|
export type BuildContextLike = BuildContextLike_generateResourcesForMainTheme & {
|
||||||
|
themeNames: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
|
export async function generateResources(params: {
|
||||||
|
buildContext: BuildContextLike;
|
||||||
|
resourcesDirPath: string;
|
||||||
|
}): Promise<void> {
|
||||||
|
const { resourcesDirPath, buildContext } = params;
|
||||||
|
|
||||||
|
const [themeName, ...themeVariantNames] = buildContext.themeNames;
|
||||||
|
|
||||||
|
if (fs.existsSync(resourcesDirPath)) {
|
||||||
|
rmSync(resourcesDirPath, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
await generateResourcesForMainTheme({
|
||||||
|
resourcesDirPath,
|
||||||
|
themeName,
|
||||||
|
buildContext
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const themeVariantName of themeVariantNames) {
|
||||||
|
generateResourcesForThemeVariant({
|
||||||
|
resourcesDirPath,
|
||||||
|
themeName,
|
||||||
|
themeVariantName
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,366 @@
|
|||||||
|
import { transformCodebase } from "../../tools/transformCodebase";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import {
|
||||||
|
join as pathJoin,
|
||||||
|
resolve as pathResolve,
|
||||||
|
relative as pathRelative,
|
||||||
|
dirname as pathDirname,
|
||||||
|
basename as pathBasename
|
||||||
|
} from "path";
|
||||||
|
import { replaceImportsInJsCode } from "../replacers/replaceImportsInJsCode";
|
||||||
|
import { replaceImportsInCssCode } from "../replacers/replaceImportsInCssCode";
|
||||||
|
import {
|
||||||
|
generateFtlFilesCodeFactory,
|
||||||
|
type BuildContextLike as BuildContextLike_kcContextExclusionsFtlCode
|
||||||
|
} from "../generateFtl";
|
||||||
|
import {
|
||||||
|
type ThemeType,
|
||||||
|
LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1,
|
||||||
|
KEYCLOAK_RESOURCES,
|
||||||
|
ACCOUNT_V1_THEME_NAME,
|
||||||
|
BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR,
|
||||||
|
LOGIN_THEME_PAGE_IDS,
|
||||||
|
ACCOUNT_THEME_PAGE_IDS
|
||||||
|
} from "../../shared/constants";
|
||||||
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
import {
|
||||||
|
downloadKeycloakStaticResources,
|
||||||
|
type BuildContextLike as BuildContextLike_downloadKeycloakStaticResources
|
||||||
|
} from "../../shared/downloadKeycloakStaticResources";
|
||||||
|
import { readFieldNameUsage } from "./readFieldNameUsage";
|
||||||
|
import { readExtraPagesNames } from "./readExtraPageNames";
|
||||||
|
import { generateMessageProperties } from "./generateMessageProperties";
|
||||||
|
import {
|
||||||
|
bringInAccountV1,
|
||||||
|
type BuildContextLike as BuildContextLike_bringInAccountV1
|
||||||
|
} from "./bringInAccountV1";
|
||||||
|
import { rmSync } from "../../tools/fs.rmSync";
|
||||||
|
import { readThisNpmPackageVersion } from "../../tools/readThisNpmPackageVersion";
|
||||||
|
import {
|
||||||
|
writeMetaInfKeycloakThemes,
|
||||||
|
type MetaInfKeycloakTheme
|
||||||
|
} from "../../shared/metaInfKeycloakThemes";
|
||||||
|
import { objectEntries } from "tsafe/objectEntries";
|
||||||
|
import { escapeStringForPropertiesFile } from "../../tools/escapeStringForPropertiesFile";
|
||||||
|
import { downloadAndExtractArchive } from "../../tools/downloadAndExtractArchive";
|
||||||
|
|
||||||
|
export type BuildContextLike = BuildContextLike_kcContextExclusionsFtlCode &
|
||||||
|
BuildContextLike_downloadKeycloakStaticResources &
|
||||||
|
BuildContextLike_bringInAccountV1 & {
|
||||||
|
extraThemeProperties: string[] | undefined;
|
||||||
|
loginThemeResourcesFromKeycloakVersion: string;
|
||||||
|
projectDirPath: string;
|
||||||
|
projectBuildDirPath: string;
|
||||||
|
environmentVariables: { name: string; default: string }[];
|
||||||
|
implementedThemeTypes: BuildContext["implementedThemeTypes"];
|
||||||
|
themeSrcDirPath: string;
|
||||||
|
bundler: "vite" | "webpack";
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
|
export async function generateResourcesForMainTheme(params: {
|
||||||
|
themeName: string;
|
||||||
|
resourcesDirPath: string;
|
||||||
|
buildContext: BuildContextLike;
|
||||||
|
}): Promise<void> {
|
||||||
|
const { themeName, resourcesDirPath, buildContext } = params;
|
||||||
|
|
||||||
|
const getThemeTypeDirPath = (params: { themeType: ThemeType | "email" }) => {
|
||||||
|
const { themeType } = params;
|
||||||
|
return pathJoin(resourcesDirPath, "theme", themeName, themeType);
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const themeType of ["login", "account"] as const) {
|
||||||
|
if (!buildContext.implementedThemeTypes[themeType].isImplemented) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isForAccountSpa =
|
||||||
|
themeType === "account" &&
|
||||||
|
(assert(buildContext.implementedThemeTypes.account.isImplemented),
|
||||||
|
buildContext.implementedThemeTypes.account.type === "Single-Page");
|
||||||
|
|
||||||
|
const themeTypeDirPath = getThemeTypeDirPath({ themeType });
|
||||||
|
|
||||||
|
apply_replacers_and_move_to_theme_resources: {
|
||||||
|
const destDirPath = pathJoin(
|
||||||
|
themeTypeDirPath,
|
||||||
|
"resources",
|
||||||
|
BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR
|
||||||
|
);
|
||||||
|
|
||||||
|
// NOTE: Prevent accumulation of files in the assets dir, as names are hashed they pile up.
|
||||||
|
rmSync(destDirPath, { recursive: true, force: true });
|
||||||
|
|
||||||
|
if (
|
||||||
|
themeType === "account" &&
|
||||||
|
buildContext.implementedThemeTypes.login.isImplemented
|
||||||
|
) {
|
||||||
|
// NOTE: We prevent doing it twice, it has been done for the login theme.
|
||||||
|
|
||||||
|
transformCodebase({
|
||||||
|
srcDirPath: pathJoin(
|
||||||
|
getThemeTypeDirPath({
|
||||||
|
themeType: "login"
|
||||||
|
}),
|
||||||
|
"resources",
|
||||||
|
BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR
|
||||||
|
),
|
||||||
|
destDirPath
|
||||||
|
});
|
||||||
|
|
||||||
|
break apply_replacers_and_move_to_theme_resources;
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
const dirPath = pathJoin(
|
||||||
|
buildContext.projectBuildDirPath,
|
||||||
|
KEYCLOAK_RESOURCES
|
||||||
|
);
|
||||||
|
|
||||||
|
if (fs.existsSync(dirPath)) {
|
||||||
|
assert(buildContext.bundler === "webpack");
|
||||||
|
|
||||||
|
throw new Error(
|
||||||
|
[
|
||||||
|
`Keycloakify build error: The ${KEYCLOAK_RESOURCES} directory shouldn't exist in your build directory.`,
|
||||||
|
`(${pathRelative(process.cwd(), dirPath)}).\n`,
|
||||||
|
`Theses assets are only required for local development with Storybook.",
|
||||||
|
"Please remove this directory as an additional step of your command.\n`,
|
||||||
|
`For example: \`"build": "... && rimraf ${pathRelative(buildContext.projectDirPath, dirPath)}"\``
|
||||||
|
].join(" ")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
transformCodebase({
|
||||||
|
srcDirPath: buildContext.projectBuildDirPath,
|
||||||
|
destDirPath,
|
||||||
|
transformSourceCode: ({ filePath, fileRelativePath, sourceCode }) => {
|
||||||
|
if (filePath.endsWith(".css")) {
|
||||||
|
const { fixedCssCode } = replaceImportsInCssCode({
|
||||||
|
cssCode: sourceCode.toString("utf8"),
|
||||||
|
cssFileRelativeDirPath: pathDirname(fileRelativePath),
|
||||||
|
buildContext
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
modifiedSourceCode: Buffer.from(fixedCssCode, "utf8")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (filePath.endsWith(".js")) {
|
||||||
|
const { fixedJsCode } = replaceImportsInJsCode({
|
||||||
|
jsCode: sourceCode.toString("utf8"),
|
||||||
|
buildContext
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
modifiedSourceCode: Buffer.from(fixedJsCode, "utf8")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { modifiedSourceCode: sourceCode };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const { generateFtlFilesCode } = generateFtlFilesCodeFactory({
|
||||||
|
themeName,
|
||||||
|
indexHtmlCode: fs
|
||||||
|
.readFileSync(pathJoin(buildContext.projectBuildDirPath, "index.html"))
|
||||||
|
.toString("utf8"),
|
||||||
|
buildContext,
|
||||||
|
keycloakifyVersion: readThisNpmPackageVersion(),
|
||||||
|
themeType,
|
||||||
|
fieldNames: readFieldNameUsage({
|
||||||
|
themeSrcDirPath: buildContext.themeSrcDirPath,
|
||||||
|
themeType
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
[
|
||||||
|
...(() => {
|
||||||
|
switch (themeType) {
|
||||||
|
case "login":
|
||||||
|
return LOGIN_THEME_PAGE_IDS;
|
||||||
|
case "account":
|
||||||
|
return isForAccountSpa ? ["index.ftl"] : ACCOUNT_THEME_PAGE_IDS;
|
||||||
|
}
|
||||||
|
})(),
|
||||||
|
...(isForAccountSpa
|
||||||
|
? []
|
||||||
|
: readExtraPagesNames({
|
||||||
|
themeType,
|
||||||
|
themeSrcDirPath: buildContext.themeSrcDirPath
|
||||||
|
}))
|
||||||
|
].forEach(pageId => {
|
||||||
|
const { ftlCode } = generateFtlFilesCode({ pageId });
|
||||||
|
|
||||||
|
fs.writeFileSync(
|
||||||
|
pathJoin(themeTypeDirPath, pageId),
|
||||||
|
Buffer.from(ftlCode, "utf8")
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
i18n_messages_generation: {
|
||||||
|
if (isForAccountSpa) {
|
||||||
|
break i18n_messages_generation;
|
||||||
|
}
|
||||||
|
|
||||||
|
generateMessageProperties({
|
||||||
|
themeSrcDirPath: buildContext.themeSrcDirPath,
|
||||||
|
themeType
|
||||||
|
}).forEach(({ languageTag, propertiesFileSource }) => {
|
||||||
|
const messagesDirPath = pathJoin(themeTypeDirPath, "messages");
|
||||||
|
|
||||||
|
fs.mkdirSync(pathJoin(themeTypeDirPath, "messages"), {
|
||||||
|
recursive: true
|
||||||
|
});
|
||||||
|
|
||||||
|
const propertiesFilePath = pathJoin(
|
||||||
|
messagesDirPath,
|
||||||
|
`messages_${languageTag}.properties`
|
||||||
|
);
|
||||||
|
|
||||||
|
fs.writeFileSync(
|
||||||
|
propertiesFilePath,
|
||||||
|
Buffer.from(propertiesFileSource, "utf8")
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
keycloak_static_resources: {
|
||||||
|
if (isForAccountSpa) {
|
||||||
|
break keycloak_static_resources;
|
||||||
|
}
|
||||||
|
|
||||||
|
await downloadKeycloakStaticResources({
|
||||||
|
keycloakVersion: (() => {
|
||||||
|
switch (themeType) {
|
||||||
|
case "account":
|
||||||
|
return LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1;
|
||||||
|
case "login":
|
||||||
|
return buildContext.loginThemeResourcesFromKeycloakVersion;
|
||||||
|
}
|
||||||
|
})(),
|
||||||
|
themeDirPath: pathResolve(pathJoin(themeTypeDirPath, "..")),
|
||||||
|
themeType,
|
||||||
|
buildContext
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(
|
||||||
|
pathJoin(themeTypeDirPath, "theme.properties"),
|
||||||
|
Buffer.from(
|
||||||
|
[
|
||||||
|
`parent=${(() => {
|
||||||
|
switch (themeType) {
|
||||||
|
case "account":
|
||||||
|
return isForAccountSpa ? "base" : ACCOUNT_V1_THEME_NAME;
|
||||||
|
case "login":
|
||||||
|
return "keycloak";
|
||||||
|
}
|
||||||
|
assert<Equals<typeof themeType, never>>(false);
|
||||||
|
})()}`,
|
||||||
|
...(isForAccountSpa ? ["deprecatedMode=false"] : []),
|
||||||
|
...(buildContext.extraThemeProperties ?? []),
|
||||||
|
...buildContext.environmentVariables.map(
|
||||||
|
({ name, default: defaultValue }) =>
|
||||||
|
`${name}=\${env.${name}:${escapeStringForPropertiesFile(defaultValue)}}`
|
||||||
|
)
|
||||||
|
].join("\n\n"),
|
||||||
|
"utf8"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
email: {
|
||||||
|
if (!buildContext.implementedThemeTypes.email.isImplemented) {
|
||||||
|
break email;
|
||||||
|
}
|
||||||
|
|
||||||
|
const emailThemeSrcDirPath = pathJoin(buildContext.themeSrcDirPath, "email");
|
||||||
|
|
||||||
|
transformCodebase({
|
||||||
|
srcDirPath: emailThemeSrcDirPath,
|
||||||
|
destDirPath: getThemeTypeDirPath({ themeType: "email" })
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bring_in_account_v1: {
|
||||||
|
if (!buildContext.implementedThemeTypes.account.isImplemented) {
|
||||||
|
break bring_in_account_v1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (buildContext.implementedThemeTypes.account.type !== "Multi-Page") {
|
||||||
|
break bring_in_account_v1;
|
||||||
|
}
|
||||||
|
|
||||||
|
await bringInAccountV1({
|
||||||
|
resourcesDirPath,
|
||||||
|
buildContext
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bring_in_account_v3_i18n_messages: {
|
||||||
|
if (!buildContext.implementedThemeTypes.account.isImplemented) {
|
||||||
|
break bring_in_account_v3_i18n_messages;
|
||||||
|
}
|
||||||
|
if (buildContext.implementedThemeTypes.account.type !== "Single-Page") {
|
||||||
|
break bring_in_account_v3_i18n_messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { extractedDirPath } = await downloadAndExtractArchive({
|
||||||
|
url: "https://repo1.maven.org/maven2/org/keycloak/keycloak-account-ui/25.0.1/keycloak-account-ui-25.0.1.jar",
|
||||||
|
cacheDirPath: buildContext.cacheDirPath,
|
||||||
|
fetchOptions: buildContext.fetchOptions,
|
||||||
|
uniqueIdOfOnArchiveFile: "bring_in_account_v3_i18n_messages",
|
||||||
|
onArchiveFile: async ({ fileRelativePath, writeFile }) => {
|
||||||
|
if (
|
||||||
|
!fileRelativePath.startsWith(
|
||||||
|
pathJoin("theme", "keycloak.v3", "account", "messages")
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await writeFile({
|
||||||
|
fileRelativePath: pathBasename(fileRelativePath)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
transformCodebase({
|
||||||
|
srcDirPath: extractedDirPath,
|
||||||
|
destDirPath: pathJoin(
|
||||||
|
getThemeTypeDirPath({ themeType: "account" }),
|
||||||
|
"messages"
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
const metaInfKeycloakThemes: MetaInfKeycloakTheme = { themes: [] };
|
||||||
|
|
||||||
|
metaInfKeycloakThemes.themes.push({
|
||||||
|
name: themeName,
|
||||||
|
types: objectEntries(buildContext.implementedThemeTypes)
|
||||||
|
.filter(([, { isImplemented }]) => isImplemented)
|
||||||
|
.map(([themeType]) => themeType)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (buildContext.implementedThemeTypes.account.isImplemented) {
|
||||||
|
metaInfKeycloakThemes.themes.push({
|
||||||
|
name: ACCOUNT_V1_THEME_NAME,
|
||||||
|
types: ["account"]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
writeMetaInfKeycloakThemes({
|
||||||
|
resourcesDirPath,
|
||||||
|
getNewMetaInfKeycloakTheme: () => metaInfKeycloakThemes
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,70 @@
|
|||||||
|
import { join as pathJoin, extname as pathExtname, sep as pathSep } from "path";
|
||||||
|
import { transformCodebase } from "../../tools/transformCodebase";
|
||||||
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
|
import { writeMetaInfKeycloakThemes } from "../../shared/metaInfKeycloakThemes";
|
||||||
|
import { assert } from "tsafe/assert";
|
||||||
|
|
||||||
|
export type BuildContextLike = {
|
||||||
|
keycloakifyBuildDirPath: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
|
export function generateResourcesForThemeVariant(params: {
|
||||||
|
resourcesDirPath: string;
|
||||||
|
themeName: string;
|
||||||
|
themeVariantName: string;
|
||||||
|
}) {
|
||||||
|
const { resourcesDirPath, themeName, themeVariantName } = params;
|
||||||
|
|
||||||
|
const mainThemeDirPath = pathJoin(resourcesDirPath, "theme", themeName);
|
||||||
|
|
||||||
|
transformCodebase({
|
||||||
|
srcDirPath: mainThemeDirPath,
|
||||||
|
destDirPath: pathJoin(mainThemeDirPath, "..", themeVariantName),
|
||||||
|
transformSourceCode: ({ fileRelativePath, sourceCode }) => {
|
||||||
|
if (
|
||||||
|
pathExtname(fileRelativePath) === ".ftl" &&
|
||||||
|
fileRelativePath.split(pathSep).length === 2
|
||||||
|
) {
|
||||||
|
const modifiedSourceCode = Buffer.from(
|
||||||
|
Buffer.from(sourceCode)
|
||||||
|
.toString("utf-8")
|
||||||
|
.replace(
|
||||||
|
`"themeName": "${themeName}"`,
|
||||||
|
`"themeName": "${themeVariantName}"`
|
||||||
|
),
|
||||||
|
"utf8"
|
||||||
|
);
|
||||||
|
|
||||||
|
assert(Buffer.compare(modifiedSourceCode, sourceCode) !== 0);
|
||||||
|
|
||||||
|
return { modifiedSourceCode };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { modifiedSourceCode: sourceCode };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
writeMetaInfKeycloakThemes({
|
||||||
|
resourcesDirPath,
|
||||||
|
getNewMetaInfKeycloakTheme: ({ metaInfKeycloakTheme }) => {
|
||||||
|
assert(metaInfKeycloakTheme !== undefined);
|
||||||
|
|
||||||
|
const newMetaInfKeycloakTheme = metaInfKeycloakTheme;
|
||||||
|
|
||||||
|
newMetaInfKeycloakTheme.themes.push({
|
||||||
|
name: themeVariantName,
|
||||||
|
types: (() => {
|
||||||
|
const theme = newMetaInfKeycloakTheme.themes.find(
|
||||||
|
({ name }) => name === themeName
|
||||||
|
);
|
||||||
|
assert(theme !== undefined);
|
||||||
|
return theme.types;
|
||||||
|
})()
|
||||||
|
});
|
||||||
|
|
||||||
|
return newMetaInfKeycloakTheme;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
1
src/bin/keycloakify/generateResources/index.ts
Normal file
1
src/bin/keycloakify/generateResources/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from "./generateResources";
|
@ -5,8 +5,8 @@ import * as fs from "fs";
|
|||||||
import { join as pathJoin } from "path";
|
import { join as pathJoin } from "path";
|
||||||
import {
|
import {
|
||||||
type ThemeType,
|
type ThemeType,
|
||||||
accountThemePageIds,
|
ACCOUNT_THEME_PAGE_IDS,
|
||||||
loginThemePageIds
|
LOGIN_THEME_PAGE_IDS
|
||||||
} from "../../shared/constants";
|
} from "../../shared/constants";
|
||||||
|
|
||||||
export function readExtraPagesNames(params: {
|
export function readExtraPagesNames(params: {
|
||||||
@ -34,19 +34,16 @@ export function readExtraPagesNames(params: {
|
|||||||
const rawSourceFile = fs.readFileSync(candidateFilPath).toString("utf8");
|
const rawSourceFile = fs.readFileSync(candidateFilPath).toString("utf8");
|
||||||
|
|
||||||
extraPages.push(
|
extraPages.push(
|
||||||
...Array.from(
|
...Array.from(rawSourceFile.matchAll(/["']([^.\s]+.ftl)["']:/g), m => m[1])
|
||||||
rawSourceFile.matchAll(/["']?pageId["']?\s*:\s*["']([^.]+.ftl)["']/g),
|
|
||||||
m => m[1]
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return extraPages.reduce(...removeDuplicates<string>()).filter(pageId => {
|
return extraPages.reduce(...removeDuplicates<string>()).filter(pageId => {
|
||||||
switch (themeType) {
|
switch (themeType) {
|
||||||
case "account":
|
case "account":
|
||||||
return !id<readonly string[]>(accountThemePageIds).includes(pageId);
|
return !id<readonly string[]>(ACCOUNT_THEME_PAGE_IDS).includes(pageId);
|
||||||
case "login":
|
case "login":
|
||||||
return !id<readonly string[]>(loginThemePageIds).includes(pageId);
|
return !id<readonly string[]>(LOGIN_THEME_PAGE_IDS).includes(pageId);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
@ -11,7 +11,15 @@ export function readFieldNameUsage(params: {
|
|||||||
}): string[] {
|
}): string[] {
|
||||||
const { themeSrcDirPath, themeType } = params;
|
const { themeSrcDirPath, themeType } = params;
|
||||||
|
|
||||||
const fieldNames = new Set<string>();
|
// NOTE: We pre-populate with the synthetic user attributes defined in useUserProfileForm (can't be parsed automatically)
|
||||||
|
const fieldNames = new Set<string>([
|
||||||
|
"firstName",
|
||||||
|
"lastName",
|
||||||
|
"email",
|
||||||
|
"username",
|
||||||
|
"password",
|
||||||
|
"password-confirm"
|
||||||
|
]);
|
||||||
|
|
||||||
for (const srcDirPath of [
|
for (const srcDirPath of [
|
||||||
pathJoin(getThisCodebaseRootDirPath(), "src", themeType),
|
pathJoin(getThisCodebaseRootDirPath(), "src", themeType),
|
@ -1,167 +0,0 @@
|
|||||||
import type { ThemeType } from "../../shared/constants";
|
|
||||||
import { crawl } from "../../tools/crawl";
|
|
||||||
import { join as pathJoin } from "path";
|
|
||||||
import { readFileSync } from "fs";
|
|
||||||
import { symToStr } from "tsafe/symToStr";
|
|
||||||
import { removeDuplicates } from "evt/tools/reducers/removeDuplicates";
|
|
||||||
import * as recast from "recast";
|
|
||||||
import * as babelParser from "@babel/parser";
|
|
||||||
import babelGenerate from "@babel/generator";
|
|
||||||
import * as babelTypes from "@babel/types";
|
|
||||||
import { escapeStringForPropertiesFile } from "../../tools/escapeStringForPropertiesFile";
|
|
||||||
|
|
||||||
export function generateMessageProperties(params: {
|
|
||||||
themeSrcDirPath: string;
|
|
||||||
themeType: ThemeType;
|
|
||||||
}): { languageTag: string; propertiesFileSource: string }[] {
|
|
||||||
const { themeSrcDirPath, themeType } = params;
|
|
||||||
|
|
||||||
let files = crawl({
|
|
||||||
dirPath: pathJoin(themeSrcDirPath, themeType),
|
|
||||||
returnedPathsType: "absolute"
|
|
||||||
});
|
|
||||||
|
|
||||||
files = files.filter(file => {
|
|
||||||
const regex = /\.(js|ts|tsx)$/;
|
|
||||||
return regex.test(file);
|
|
||||||
});
|
|
||||||
|
|
||||||
files = files.sort((a, b) => {
|
|
||||||
const regex = /\.i18n\.(ts|js|tsx)$/;
|
|
||||||
const aIsI18nFile = regex.test(a);
|
|
||||||
const bIsI18nFile = regex.test(b);
|
|
||||||
return aIsI18nFile === bIsI18nFile ? 0 : aIsI18nFile ? -1 : 1;
|
|
||||||
});
|
|
||||||
|
|
||||||
files = files.sort((a, b) => a.length - b.length);
|
|
||||||
|
|
||||||
files = files.filter(file =>
|
|
||||||
readFileSync(file).toString("utf8").includes("createUseI18n")
|
|
||||||
);
|
|
||||||
|
|
||||||
if (files.length === 0) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const extraMessages = files
|
|
||||||
.map(file => {
|
|
||||||
const root = recast.parse(readFileSync(file).toString("utf8"), {
|
|
||||||
parser: {
|
|
||||||
parse: (code: string) =>
|
|
||||||
babelParser.parse(code, {
|
|
||||||
sourceType: "module",
|
|
||||||
plugins: ["typescript"]
|
|
||||||
}),
|
|
||||||
generator: babelGenerate,
|
|
||||||
types: babelTypes
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const codes: string[] = [];
|
|
||||||
|
|
||||||
recast.visit(root, {
|
|
||||||
visitCallExpression: function (path) {
|
|
||||||
if (
|
|
||||||
path.node.callee.type === "Identifier" &&
|
|
||||||
path.node.callee.name === "createUseI18n"
|
|
||||||
) {
|
|
||||||
codes.push(babelGenerate(path.node.arguments[0] as any).code);
|
|
||||||
}
|
|
||||||
this.traverse(path);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return codes;
|
|
||||||
})
|
|
||||||
.flat()
|
|
||||||
.map(code => {
|
|
||||||
let extraMessages: {
|
|
||||||
[languageTag: string]: Record<string, string>;
|
|
||||||
} = {};
|
|
||||||
|
|
||||||
try {
|
|
||||||
eval(`${symToStr({ extraMessages })} = ${code}`);
|
|
||||||
} catch {
|
|
||||||
console.warn(
|
|
||||||
[
|
|
||||||
"WARNING: Make sure that the first argument of createUseI18n can be evaluated in a javascript",
|
|
||||||
"runtime where only the node globals are available.",
|
|
||||||
"This is important because we need to put your i18n messages in messages_*.properties files",
|
|
||||||
"or they won't be available server side.",
|
|
||||||
"\n",
|
|
||||||
"The following code could not be evaluated:",
|
|
||||||
"\n",
|
|
||||||
code
|
|
||||||
].join(" ")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return extraMessages;
|
|
||||||
});
|
|
||||||
|
|
||||||
const languageTags = extraMessages
|
|
||||||
.map(extraMessage => Object.keys(extraMessage))
|
|
||||||
.flat()
|
|
||||||
.reduce(...removeDuplicates<string>());
|
|
||||||
|
|
||||||
const keyValueMapByLanguageTag: Record<string, Record<string, string>> = {};
|
|
||||||
|
|
||||||
for (const languageTag of languageTags) {
|
|
||||||
const keyValueMap: Record<string, string> = {};
|
|
||||||
|
|
||||||
for (const extraMessage of extraMessages) {
|
|
||||||
const keyValueMap_i = extraMessage[languageTag];
|
|
||||||
|
|
||||||
if (keyValueMap_i === undefined) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const [key, value] of Object.entries(keyValueMap_i)) {
|
|
||||||
if (keyValueMap[key] !== undefined) {
|
|
||||||
console.warn(
|
|
||||||
[
|
|
||||||
"WARNING: The following key is defined multiple times:",
|
|
||||||
"\n",
|
|
||||||
key,
|
|
||||||
"\n",
|
|
||||||
"The following value will be ignored:",
|
|
||||||
"\n",
|
|
||||||
value,
|
|
||||||
"\n",
|
|
||||||
"The following value was already defined:",
|
|
||||||
"\n",
|
|
||||||
keyValueMap[key]
|
|
||||||
].join(" ")
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
keyValueMap[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
keyValueMapByLanguageTag[languageTag] = keyValueMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
const out: { languageTag: string; propertiesFileSource: string }[] = [];
|
|
||||||
|
|
||||||
for (const [languageTag, keyValueMap] of Object.entries(keyValueMapByLanguageTag)) {
|
|
||||||
const propertiesFileSource = Object.entries(keyValueMap)
|
|
||||||
.map(([key, value]) => `${key}=${escapeStringForPropertiesFile(value)}`)
|
|
||||||
.join("\n");
|
|
||||||
|
|
||||||
out.push({
|
|
||||||
languageTag,
|
|
||||||
propertiesFileSource: [
|
|
||||||
"# This file was generated by keycloakify",
|
|
||||||
"",
|
|
||||||
"parent=base",
|
|
||||||
"",
|
|
||||||
propertiesFileSource,
|
|
||||||
""
|
|
||||||
].join("\n")
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return out;
|
|
||||||
}
|
|
@ -1,34 +0,0 @@
|
|||||||
import type { BuildOptions } from "../../shared/buildOptions";
|
|
||||||
import { assert } from "tsafe/assert";
|
|
||||||
import {
|
|
||||||
generateSrcMainResourcesForMainTheme,
|
|
||||||
type BuildOptionsLike as BuildOptionsLike_generateSrcMainResourcesForMainTheme
|
|
||||||
} from "./generateSrcMainResourcesForMainTheme";
|
|
||||||
import { generateSrcMainResourcesForThemeVariant } from "./generateSrcMainResourcesForThemeVariant";
|
|
||||||
|
|
||||||
export type BuildOptionsLike = BuildOptionsLike_generateSrcMainResourcesForMainTheme & {
|
|
||||||
themeNames: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
|
||||||
|
|
||||||
export async function generateSrcMainResources(params: {
|
|
||||||
buildOptions: BuildOptionsLike;
|
|
||||||
}): Promise<void> {
|
|
||||||
const { buildOptions } = params;
|
|
||||||
|
|
||||||
const [themeName, ...themeVariantNames] = buildOptions.themeNames;
|
|
||||||
|
|
||||||
await generateSrcMainResourcesForMainTheme({
|
|
||||||
themeName,
|
|
||||||
buildOptions
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const themeVariantName of themeVariantNames) {
|
|
||||||
generateSrcMainResourcesForThemeVariant({
|
|
||||||
themeName,
|
|
||||||
themeVariantName,
|
|
||||||
buildOptions
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,320 +0,0 @@
|
|||||||
import { transformCodebase } from "../../tools/transformCodebase";
|
|
||||||
import * as fs from "fs";
|
|
||||||
import { join as pathJoin, resolve as pathResolve } from "path";
|
|
||||||
import { replaceImportsInJsCode } from "../replacers/replaceImportsInJsCode";
|
|
||||||
import { replaceImportsInCssCode } from "../replacers/replaceImportsInCssCode";
|
|
||||||
import {
|
|
||||||
generateFtlFilesCodeFactory,
|
|
||||||
type BuildOptionsLike as BuildOptionsLike_kcContextExclusionsFtlCode
|
|
||||||
} from "../generateFtl";
|
|
||||||
import {
|
|
||||||
type ThemeType,
|
|
||||||
lastKeycloakVersionWithAccountV1,
|
|
||||||
keycloak_resources,
|
|
||||||
accountV1ThemeName,
|
|
||||||
basenameOfTheKeycloakifyResourcesDir,
|
|
||||||
loginThemePageIds,
|
|
||||||
accountThemePageIds
|
|
||||||
} from "../../shared/constants";
|
|
||||||
import { isInside } from "../../tools/isInside";
|
|
||||||
import type { BuildOptions } from "../../shared/buildOptions";
|
|
||||||
import { assert, type Equals } from "tsafe/assert";
|
|
||||||
import {
|
|
||||||
downloadKeycloakStaticResources,
|
|
||||||
type BuildOptionsLike as BuildOptionsLike_downloadKeycloakStaticResources
|
|
||||||
} from "../../shared/downloadKeycloakStaticResources";
|
|
||||||
import { readFieldNameUsage } from "./readFieldNameUsage";
|
|
||||||
import { readExtraPagesNames } from "./readExtraPageNames";
|
|
||||||
import { generateMessageProperties } from "./generateMessageProperties";
|
|
||||||
import {
|
|
||||||
bringInAccountV1,
|
|
||||||
type BuildOptionsLike as BuildOptionsLike_bringInAccountV1
|
|
||||||
} from "./bringInAccountV1";
|
|
||||||
import { getThemeSrcDirPath } from "../../shared/getThemeSrcDirPath";
|
|
||||||
import { rmSync } from "../../tools/fs.rmSync";
|
|
||||||
import { readThisNpmPackageVersion } from "../../tools/readThisNpmPackageVersion";
|
|
||||||
import {
|
|
||||||
writeMetaInfKeycloakThemes,
|
|
||||||
type MetaInfKeycloakTheme
|
|
||||||
} from "../../shared/metaInfKeycloakThemes";
|
|
||||||
import { objectEntries } from "tsafe/objectEntries";
|
|
||||||
import { escapeStringForPropertiesFile } from "../../tools/escapeStringForPropertiesFile";
|
|
||||||
|
|
||||||
export type BuildOptionsLike = BuildOptionsLike_kcContextExclusionsFtlCode &
|
|
||||||
BuildOptionsLike_downloadKeycloakStaticResources &
|
|
||||||
BuildOptionsLike_bringInAccountV1 & {
|
|
||||||
bundler: "vite" | "webpack";
|
|
||||||
extraThemeProperties: string[] | undefined;
|
|
||||||
loginThemeResourcesFromKeycloakVersion: string;
|
|
||||||
reactAppBuildDirPath: string;
|
|
||||||
assetsDirPath: string;
|
|
||||||
urlPathname: string | undefined;
|
|
||||||
reactAppRootDirPath: string;
|
|
||||||
keycloakifyBuildDirPath: string;
|
|
||||||
environmentVariables: { name: string; default: string }[];
|
|
||||||
};
|
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
|
||||||
|
|
||||||
export async function generateSrcMainResourcesForMainTheme(params: {
|
|
||||||
themeName: string;
|
|
||||||
buildOptions: BuildOptionsLike;
|
|
||||||
}): Promise<void> {
|
|
||||||
const { themeName, buildOptions } = params;
|
|
||||||
|
|
||||||
const { themeSrcDirPath } = getThemeSrcDirPath({
|
|
||||||
reactAppRootDirPath: buildOptions.reactAppRootDirPath
|
|
||||||
});
|
|
||||||
|
|
||||||
const getThemeTypeDirPath = (params: { themeType: ThemeType | "email" }) => {
|
|
||||||
const { themeType } = params;
|
|
||||||
return pathJoin(
|
|
||||||
buildOptions.keycloakifyBuildDirPath,
|
|
||||||
"src",
|
|
||||||
"main",
|
|
||||||
"resources",
|
|
||||||
"theme",
|
|
||||||
themeName,
|
|
||||||
themeType
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const cssGlobalsToDefine: Record<string, string> = {};
|
|
||||||
|
|
||||||
const implementedThemeTypes: Record<ThemeType | "email", boolean> = {
|
|
||||||
login: false,
|
|
||||||
account: false,
|
|
||||||
email: false
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const themeType of ["login", "account"] as const) {
|
|
||||||
if (!fs.existsSync(pathJoin(themeSrcDirPath, themeType))) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
implementedThemeTypes[themeType] = true;
|
|
||||||
|
|
||||||
const themeTypeDirPath = getThemeTypeDirPath({ themeType });
|
|
||||||
|
|
||||||
apply_replacers_and_move_to_theme_resources: {
|
|
||||||
const destDirPath = pathJoin(
|
|
||||||
themeTypeDirPath,
|
|
||||||
"resources",
|
|
||||||
basenameOfTheKeycloakifyResourcesDir
|
|
||||||
);
|
|
||||||
|
|
||||||
// NOTE: Prevent accumulation of files in the assets dir, as names are hashed they pile up.
|
|
||||||
rmSync(destDirPath, { recursive: true, force: true });
|
|
||||||
|
|
||||||
if (themeType === "account" && implementedThemeTypes.login) {
|
|
||||||
// NOTE: We prevent doing it twice, it has been done for the login theme.
|
|
||||||
|
|
||||||
transformCodebase({
|
|
||||||
srcDirPath: pathJoin(
|
|
||||||
getThemeTypeDirPath({
|
|
||||||
themeType: "login"
|
|
||||||
}),
|
|
||||||
"resources",
|
|
||||||
basenameOfTheKeycloakifyResourcesDir
|
|
||||||
),
|
|
||||||
destDirPath
|
|
||||||
});
|
|
||||||
|
|
||||||
break apply_replacers_and_move_to_theme_resources;
|
|
||||||
}
|
|
||||||
|
|
||||||
transformCodebase({
|
|
||||||
srcDirPath: buildOptions.reactAppBuildDirPath,
|
|
||||||
destDirPath,
|
|
||||||
transformSourceCode: ({ filePath, sourceCode }) => {
|
|
||||||
//NOTE: Prevent cycles, excludes the folder we generated for debug in public/
|
|
||||||
// This should not happen if users follow the new instruction setup but we keep it for retrocompatibility.
|
|
||||||
if (
|
|
||||||
isInside({
|
|
||||||
dirPath: pathJoin(
|
|
||||||
buildOptions.reactAppBuildDirPath,
|
|
||||||
keycloak_resources
|
|
||||||
),
|
|
||||||
filePath
|
|
||||||
})
|
|
||||||
) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (/\.css?$/i.test(filePath)) {
|
|
||||||
const {
|
|
||||||
cssGlobalsToDefine: cssGlobalsToDefineForThisFile,
|
|
||||||
fixedCssCode
|
|
||||||
} = replaceImportsInCssCode({
|
|
||||||
cssCode: sourceCode.toString("utf8")
|
|
||||||
});
|
|
||||||
|
|
||||||
Object.entries(cssGlobalsToDefineForThisFile).forEach(
|
|
||||||
([key, value]) => {
|
|
||||||
cssGlobalsToDefine[key] = value;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
modifiedSourceCode: Buffer.from(fixedCssCode, "utf8")
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (/\.js?$/i.test(filePath)) {
|
|
||||||
const { fixedJsCode } = replaceImportsInJsCode({
|
|
||||||
jsCode: sourceCode.toString("utf8"),
|
|
||||||
buildOptions
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
modifiedSourceCode: Buffer.from(fixedJsCode, "utf8")
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return { modifiedSourceCode: sourceCode };
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const { generateFtlFilesCode } = generateFtlFilesCodeFactory({
|
|
||||||
themeName,
|
|
||||||
indexHtmlCode: fs
|
|
||||||
.readFileSync(pathJoin(buildOptions.reactAppBuildDirPath, "index.html"))
|
|
||||||
.toString("utf8"),
|
|
||||||
cssGlobalsToDefine,
|
|
||||||
buildOptions,
|
|
||||||
keycloakifyVersion: readThisNpmPackageVersion(),
|
|
||||||
themeType,
|
|
||||||
fieldNames: readFieldNameUsage({
|
|
||||||
themeSrcDirPath,
|
|
||||||
themeType
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
[
|
|
||||||
...(() => {
|
|
||||||
switch (themeType) {
|
|
||||||
case "login":
|
|
||||||
return loginThemePageIds;
|
|
||||||
case "account":
|
|
||||||
return accountThemePageIds;
|
|
||||||
}
|
|
||||||
})(),
|
|
||||||
...readExtraPagesNames({
|
|
||||||
themeType,
|
|
||||||
themeSrcDirPath
|
|
||||||
})
|
|
||||||
].forEach(pageId => {
|
|
||||||
const { ftlCode } = generateFtlFilesCode({ pageId });
|
|
||||||
|
|
||||||
fs.mkdirSync(themeTypeDirPath, { recursive: true });
|
|
||||||
|
|
||||||
fs.writeFileSync(
|
|
||||||
pathJoin(themeTypeDirPath, pageId),
|
|
||||||
Buffer.from(ftlCode, "utf8")
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
generateMessageProperties({
|
|
||||||
themeSrcDirPath,
|
|
||||||
themeType
|
|
||||||
}).forEach(({ languageTag, propertiesFileSource }) => {
|
|
||||||
const messagesDirPath = pathJoin(themeTypeDirPath, "messages");
|
|
||||||
|
|
||||||
fs.mkdirSync(pathJoin(themeTypeDirPath, "messages"), {
|
|
||||||
recursive: true
|
|
||||||
});
|
|
||||||
|
|
||||||
const propertiesFilePath = pathJoin(
|
|
||||||
messagesDirPath,
|
|
||||||
`messages_${languageTag}.properties`
|
|
||||||
);
|
|
||||||
|
|
||||||
fs.writeFileSync(
|
|
||||||
propertiesFilePath,
|
|
||||||
Buffer.from(propertiesFileSource, "utf8")
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
await downloadKeycloakStaticResources({
|
|
||||||
keycloakVersion: (() => {
|
|
||||||
switch (themeType) {
|
|
||||||
case "account":
|
|
||||||
return lastKeycloakVersionWithAccountV1;
|
|
||||||
case "login":
|
|
||||||
return buildOptions.loginThemeResourcesFromKeycloakVersion;
|
|
||||||
}
|
|
||||||
})(),
|
|
||||||
themeDirPath: pathResolve(pathJoin(themeTypeDirPath, "..")),
|
|
||||||
themeType,
|
|
||||||
buildOptions
|
|
||||||
});
|
|
||||||
|
|
||||||
fs.writeFileSync(
|
|
||||||
pathJoin(themeTypeDirPath, "theme.properties"),
|
|
||||||
Buffer.from(
|
|
||||||
[
|
|
||||||
`parent=${(() => {
|
|
||||||
switch (themeType) {
|
|
||||||
case "account":
|
|
||||||
return accountV1ThemeName;
|
|
||||||
case "login":
|
|
||||||
return "keycloak";
|
|
||||||
}
|
|
||||||
assert<Equals<typeof themeType, never>>(false);
|
|
||||||
})()}`,
|
|
||||||
...(buildOptions.extraThemeProperties ?? []),
|
|
||||||
buildOptions.environmentVariables.map(
|
|
||||||
({ name, default: defaultValue }) =>
|
|
||||||
`${name}=\${env.${name}:${escapeStringForPropertiesFile(defaultValue)}}`
|
|
||||||
)
|
|
||||||
].join("\n\n"),
|
|
||||||
"utf8"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
email: {
|
|
||||||
const emailThemeSrcDirPath = pathJoin(themeSrcDirPath, "email");
|
|
||||||
|
|
||||||
if (!fs.existsSync(emailThemeSrcDirPath)) {
|
|
||||||
break email;
|
|
||||||
}
|
|
||||||
|
|
||||||
implementedThemeTypes.email = true;
|
|
||||||
|
|
||||||
transformCodebase({
|
|
||||||
srcDirPath: emailThemeSrcDirPath,
|
|
||||||
destDirPath: getThemeTypeDirPath({ themeType: "email" })
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (implementedThemeTypes.account) {
|
|
||||||
await bringInAccountV1({
|
|
||||||
buildOptions
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
|
||||||
const metaInfKeycloakThemes: MetaInfKeycloakTheme = { themes: [] };
|
|
||||||
|
|
||||||
metaInfKeycloakThemes.themes.push({
|
|
||||||
name: themeName,
|
|
||||||
types: objectEntries(implementedThemeTypes)
|
|
||||||
.filter(([, isImplemented]) => isImplemented)
|
|
||||||
.map(([themeType]) => themeType)
|
|
||||||
});
|
|
||||||
|
|
||||||
if (implementedThemeTypes.account) {
|
|
||||||
metaInfKeycloakThemes.themes.push({
|
|
||||||
name: accountV1ThemeName,
|
|
||||||
types: ["account"]
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
writeMetaInfKeycloakThemes({
|
|
||||||
keycloakifyBuildDirPath: buildOptions.keycloakifyBuildDirPath,
|
|
||||||
metaInfKeycloakThemes
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,80 +0,0 @@
|
|||||||
import { join as pathJoin, extname as pathExtname, sep as pathSep } from "path";
|
|
||||||
import { transformCodebase } from "../../tools/transformCodebase";
|
|
||||||
import type { BuildOptions } from "../../shared/buildOptions";
|
|
||||||
import {
|
|
||||||
readMetaInfKeycloakThemes,
|
|
||||||
writeMetaInfKeycloakThemes
|
|
||||||
} from "../../shared/metaInfKeycloakThemes";
|
|
||||||
import { assert } from "tsafe/assert";
|
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
|
||||||
keycloakifyBuildDirPath: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
|
||||||
|
|
||||||
export function generateSrcMainResourcesForThemeVariant(params: {
|
|
||||||
themeName: string;
|
|
||||||
themeVariantName: string;
|
|
||||||
buildOptions: BuildOptionsLike;
|
|
||||||
}) {
|
|
||||||
const { themeName, themeVariantName, buildOptions } = params;
|
|
||||||
|
|
||||||
const mainThemeDirPath = pathJoin(
|
|
||||||
buildOptions.keycloakifyBuildDirPath,
|
|
||||||
"src",
|
|
||||||
"main",
|
|
||||||
"resources",
|
|
||||||
"theme",
|
|
||||||
themeName
|
|
||||||
);
|
|
||||||
|
|
||||||
transformCodebase({
|
|
||||||
srcDirPath: mainThemeDirPath,
|
|
||||||
destDirPath: pathJoin(mainThemeDirPath, "..", themeVariantName),
|
|
||||||
transformSourceCode: ({ fileRelativePath, sourceCode }) => {
|
|
||||||
if (
|
|
||||||
pathExtname(fileRelativePath) === ".ftl" &&
|
|
||||||
fileRelativePath.split(pathSep).length === 2
|
|
||||||
) {
|
|
||||||
const modifiedSourceCode = Buffer.from(
|
|
||||||
Buffer.from(sourceCode)
|
|
||||||
.toString("utf-8")
|
|
||||||
.replace(
|
|
||||||
`out["themeName"] = "${themeName}";`,
|
|
||||||
`out["themeName"] = "${themeVariantName}";`
|
|
||||||
),
|
|
||||||
"utf8"
|
|
||||||
);
|
|
||||||
|
|
||||||
assert(Buffer.compare(modifiedSourceCode, sourceCode) !== 0);
|
|
||||||
|
|
||||||
return { modifiedSourceCode };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { modifiedSourceCode: sourceCode };
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
{
|
|
||||||
const updatedMetaInfKeycloakThemes = readMetaInfKeycloakThemes({
|
|
||||||
keycloakifyBuildDirPath: buildOptions.keycloakifyBuildDirPath
|
|
||||||
});
|
|
||||||
|
|
||||||
updatedMetaInfKeycloakThemes.themes.push({
|
|
||||||
name: themeVariantName,
|
|
||||||
types: (() => {
|
|
||||||
const theme = updatedMetaInfKeycloakThemes.themes.find(
|
|
||||||
({ name }) => name === themeName
|
|
||||||
);
|
|
||||||
assert(theme !== undefined);
|
|
||||||
return theme.types;
|
|
||||||
})()
|
|
||||||
});
|
|
||||||
|
|
||||||
writeMetaInfKeycloakThemes({
|
|
||||||
keycloakifyBuildDirPath: buildOptions.keycloakifyBuildDirPath,
|
|
||||||
metaInfKeycloakThemes: updatedMetaInfKeycloakThemes
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from "./generateSrcMainResources";
|
|
@ -1,74 +0,0 @@
|
|||||||
import * as fs from "fs";
|
|
||||||
import {
|
|
||||||
join as pathJoin,
|
|
||||||
relative as pathRelative,
|
|
||||||
basename as pathBasename
|
|
||||||
} from "path";
|
|
||||||
import { assert } from "tsafe/assert";
|
|
||||||
import type { BuildOptions } from "../shared/buildOptions";
|
|
||||||
import { accountV1ThemeName } from "../shared/constants";
|
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
|
||||||
keycloakifyBuildDirPath: string;
|
|
||||||
themeNames: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
|
||||||
|
|
||||||
generateStartKeycloakTestingContainer.basename = "start_keycloak_testing_container.sh";
|
|
||||||
|
|
||||||
const containerName = "keycloak-testing-container";
|
|
||||||
const keycloakVersion = "24.0.4";
|
|
||||||
|
|
||||||
/** Files for being able to run a hot reload keycloak container */
|
|
||||||
export function generateStartKeycloakTestingContainer(params: {
|
|
||||||
jarFilePath: string;
|
|
||||||
doesImplementAccountTheme: boolean;
|
|
||||||
buildOptions: BuildOptionsLike;
|
|
||||||
}) {
|
|
||||||
const { jarFilePath, doesImplementAccountTheme, buildOptions } = params;
|
|
||||||
|
|
||||||
const themeRelativeDirPath = pathJoin("src", "main", "resources", "theme");
|
|
||||||
|
|
||||||
fs.writeFileSync(
|
|
||||||
pathJoin(
|
|
||||||
buildOptions.keycloakifyBuildDirPath,
|
|
||||||
generateStartKeycloakTestingContainer.basename
|
|
||||||
),
|
|
||||||
Buffer.from(
|
|
||||||
[
|
|
||||||
"#!/usr/bin/env bash",
|
|
||||||
"",
|
|
||||||
`docker rm ${containerName} || true`,
|
|
||||||
"",
|
|
||||||
`cd "${buildOptions.keycloakifyBuildDirPath}"`,
|
|
||||||
"",
|
|
||||||
"docker run \\",
|
|
||||||
" -p 8080:8080 \\",
|
|
||||||
` --name ${containerName} \\`,
|
|
||||||
" -e KEYCLOAK_ADMIN=admin \\",
|
|
||||||
" -e KEYCLOAK_ADMIN_PASSWORD=admin \\",
|
|
||||||
` -v "${pathJoin(
|
|
||||||
"$(pwd)",
|
|
||||||
pathRelative(buildOptions.keycloakifyBuildDirPath, jarFilePath)
|
|
||||||
)}":"/opt/keycloak/providers/${pathBasename(jarFilePath)}" \\`,
|
|
||||||
[
|
|
||||||
...(doesImplementAccountTheme ? [accountV1ThemeName] : []),
|
|
||||||
...buildOptions.themeNames
|
|
||||||
].map(
|
|
||||||
themeName =>
|
|
||||||
` -v "${pathJoin(
|
|
||||||
"$(pwd)",
|
|
||||||
themeRelativeDirPath,
|
|
||||||
themeName
|
|
||||||
).replace(/\\/g, "/")}":"/opt/keycloak/themes/${themeName}":rw \\`
|
|
||||||
),
|
|
||||||
` -it quay.io/keycloak/keycloak:${keycloakVersion} \\`,
|
|
||||||
` start-dev`,
|
|
||||||
""
|
|
||||||
].join("\n"),
|
|
||||||
"utf8"
|
|
||||||
),
|
|
||||||
{ mode: 0o755 }
|
|
||||||
);
|
|
||||||
}
|
|
@ -1,14 +1,15 @@
|
|||||||
import { generateSrcMainResources } from "./generateSrcMainResources";
|
import { generateResources } from "./generateResources";
|
||||||
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 * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { readBuildOptions } from "../shared/buildOptions";
|
import { getBuildContext } from "../shared/buildContext";
|
||||||
import { vitePluginSubScriptEnvNames, skipBuildJarsEnvName } from "../shared/constants";
|
import { VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES } from "../shared/constants";
|
||||||
import { buildJars } from "./buildJars";
|
import { buildJars } from "./buildJars";
|
||||||
import type { CliCommandOptions } from "../main";
|
import type { CliCommandOptions } from "../main";
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
import { readThisNpmPackageVersion } from "../tools/readThisNpmPackageVersion";
|
import { readThisNpmPackageVersion } from "../tools/readThisNpmPackageVersion";
|
||||||
import * as os from "os";
|
import * as os from "os";
|
||||||
|
import { rmSync } from "../tools/fs.rmSync";
|
||||||
|
|
||||||
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
||||||
exit_if_maven_not_installed: {
|
exit_if_maven_not_installed: {
|
||||||
@ -47,7 +48,7 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
|
|
||||||
const { cliCommandOptions } = params;
|
const { cliCommandOptions } = params;
|
||||||
|
|
||||||
const buildOptions = readBuildOptions({ cliCommandOptions });
|
const buildContext = getBuildContext({ cliCommandOptions });
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
[
|
[
|
||||||
@ -55,7 +56,7 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
chalk.green(
|
chalk.green(
|
||||||
`Building the keycloak theme in .${pathSep}${pathRelative(
|
`Building the keycloak theme in .${pathSep}${pathRelative(
|
||||||
process.cwd(),
|
process.cwd(),
|
||||||
buildOptions.keycloakifyBuildDirPath
|
buildContext.keycloakifyBuildDirPath
|
||||||
)} ...`
|
)} ...`
|
||||||
)
|
)
|
||||||
].join(" ")
|
].join(" ")
|
||||||
@ -64,44 +65,54 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
const startTime = Date.now();
|
const startTime = Date.now();
|
||||||
|
|
||||||
{
|
{
|
||||||
if (!fs.existsSync(buildOptions.keycloakifyBuildDirPath)) {
|
if (!fs.existsSync(buildContext.keycloakifyBuildDirPath)) {
|
||||||
fs.mkdirSync(buildOptions.keycloakifyBuildDirPath, {
|
fs.mkdirSync(buildContext.keycloakifyBuildDirPath, {
|
||||||
recursive: true
|
recursive: true
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
pathJoin(buildOptions.keycloakifyBuildDirPath, ".gitignore"),
|
pathJoin(buildContext.keycloakifyBuildDirPath, ".gitignore"),
|
||||||
Buffer.from("*", "utf8")
|
Buffer.from("*", "utf8")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
await generateSrcMainResources({ buildOptions });
|
const resourcesDirPath = pathJoin(buildContext.keycloakifyBuildDirPath, "resources");
|
||||||
|
|
||||||
|
await generateResources({
|
||||||
|
resourcesDirPath,
|
||||||
|
buildContext
|
||||||
|
});
|
||||||
|
|
||||||
run_post_build_script: {
|
run_post_build_script: {
|
||||||
if (buildOptions.bundler !== "vite") {
|
if (buildContext.bundler !== "vite") {
|
||||||
break run_post_build_script;
|
break run_post_build_script;
|
||||||
}
|
}
|
||||||
|
|
||||||
child_process.execSync("npx vite", {
|
child_process.execSync("npx vite", {
|
||||||
cwd: buildOptions.reactAppRootDirPath,
|
cwd: buildContext.projectDirPath,
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
[vitePluginSubScriptEnvNames.runPostBuildScript]:
|
[VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RUN_POST_BUILD_SCRIPT]: JSON.stringify(
|
||||||
JSON.stringify(buildOptions)
|
{
|
||||||
|
resourcesDirPath,
|
||||||
|
buildContext
|
||||||
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
build_jars: {
|
await buildJars({
|
||||||
if (process.env[skipBuildJarsEnvName]) {
|
resourcesDirPath,
|
||||||
break build_jars;
|
buildContext
|
||||||
}
|
});
|
||||||
|
|
||||||
await buildJars({ buildOptions });
|
rmSync(resourcesDirPath, { recursive: true });
|
||||||
}
|
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
chalk.green(`✓ built in ${((Date.now() - startTime) / 1000).toFixed(2)}s`)
|
chalk.green(
|
||||||
|
`✓ keycloak theme built in ${((Date.now() - startTime) / 1000).toFixed(2)}s`
|
||||||
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,76 +1,67 @@
|
|||||||
import * as crypto from "crypto";
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
import type { BuildOptions } from "../../shared/buildOptions";
|
import { BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR } from "../../shared/constants";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import { basenameOfTheKeycloakifyResourcesDir } from "../../shared/constants";
|
import { posix } from "path";
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
export type BuildContextLike = {
|
||||||
urlPathname: string | undefined;
|
urlPathname: string | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export function replaceImportsInCssCode(params: { cssCode: string }): {
|
export function replaceImportsInCssCode(params: {
|
||||||
|
cssCode: string;
|
||||||
|
cssFileRelativeDirPath: string | undefined;
|
||||||
|
buildContext: BuildContextLike;
|
||||||
|
}): {
|
||||||
fixedCssCode: string;
|
fixedCssCode: string;
|
||||||
cssGlobalsToDefine: Record<string, string>;
|
|
||||||
} {
|
} {
|
||||||
const { cssCode } = params;
|
const { cssCode, cssFileRelativeDirPath, buildContext } = params;
|
||||||
|
|
||||||
const cssGlobalsToDefine: Record<string, string> = {};
|
|
||||||
|
|
||||||
new Set(cssCode.match(/url\(["']?\/[^/][^)"']+["']?\)[^;}]*?/g) ?? []).forEach(
|
|
||||||
match =>
|
|
||||||
(cssGlobalsToDefine[
|
|
||||||
"url" +
|
|
||||||
crypto
|
|
||||||
.createHash("sha256")
|
|
||||||
.update(match)
|
|
||||||
.digest("hex")
|
|
||||||
.substring(0, 15)
|
|
||||||
] = match)
|
|
||||||
);
|
|
||||||
|
|
||||||
let fixedCssCode = cssCode;
|
let fixedCssCode = cssCode;
|
||||||
|
|
||||||
Object.keys(cssGlobalsToDefine).forEach(
|
[
|
||||||
cssVariableName =>
|
/url\("(\/[^/][^"]+)"\)/g,
|
||||||
//NOTE: split/join pattern ~ replace all
|
/url\('(\/[^/][^']+)'\)/g,
|
||||||
(fixedCssCode = fixedCssCode
|
/url\((\/[^/][^)]+)\)/g
|
||||||
.split(cssGlobalsToDefine[cssVariableName])
|
].forEach(
|
||||||
.join(`var(--${cssVariableName})`))
|
regex =>
|
||||||
|
(fixedCssCode = fixedCssCode.replace(
|
||||||
|
regex,
|
||||||
|
(match, assetFileAbsoluteUrlPathname) => {
|
||||||
|
if (buildContext.urlPathname !== undefined) {
|
||||||
|
if (
|
||||||
|
!assetFileAbsoluteUrlPathname.startsWith(
|
||||||
|
buildContext.urlPathname
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
// NOTE: Should never happen
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
assetFileAbsoluteUrlPathname =
|
||||||
|
assetFileAbsoluteUrlPathname.replace(
|
||||||
|
buildContext.urlPathname,
|
||||||
|
"/"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline_style_in_html: {
|
||||||
|
if (cssFileRelativeDirPath !== undefined) {
|
||||||
|
break inline_style_in_html;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `url("\${xKeycloakify.resourcesPath}/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}${assetFileAbsoluteUrlPathname}")`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const assetFileRelativeUrlPathname = posix.relative(
|
||||||
|
cssFileRelativeDirPath.replace(/\\/g, "/"),
|
||||||
|
assetFileAbsoluteUrlPathname.replace(/^\//, "")
|
||||||
|
);
|
||||||
|
|
||||||
|
return `url("${assetFileRelativeUrlPathname}")`;
|
||||||
|
}
|
||||||
|
))
|
||||||
);
|
);
|
||||||
|
|
||||||
return { fixedCssCode, cssGlobalsToDefine };
|
return { fixedCssCode };
|
||||||
}
|
|
||||||
|
|
||||||
export function generateCssCodeToDefineGlobals(params: {
|
|
||||||
cssGlobalsToDefine: Record<string, string>;
|
|
||||||
buildOptions: BuildOptionsLike;
|
|
||||||
}): {
|
|
||||||
cssCodeToPrependInHead: string;
|
|
||||||
} {
|
|
||||||
const { cssGlobalsToDefine, buildOptions } = params;
|
|
||||||
|
|
||||||
return {
|
|
||||||
cssCodeToPrependInHead: [
|
|
||||||
":root {",
|
|
||||||
...Object.keys(cssGlobalsToDefine)
|
|
||||||
.map(cssVariableName =>
|
|
||||||
[
|
|
||||||
`--${cssVariableName}:`,
|
|
||||||
cssGlobalsToDefine[cssVariableName].replace(
|
|
||||||
new RegExp(
|
|
||||||
`url\\(${(buildOptions.urlPathname ?? "/").replace(
|
|
||||||
/\//g,
|
|
||||||
"\\/"
|
|
||||||
)}`,
|
|
||||||
"g"
|
|
||||||
),
|
|
||||||
`url(\${url.resourcesPath}/${basenameOfTheKeycloakifyResourcesDir}/`
|
|
||||||
)
|
|
||||||
].join(" ")
|
|
||||||
)
|
|
||||||
.map(line => ` ${line};`),
|
|
||||||
"}"
|
|
||||||
].join("\n")
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
@ -1,28 +0,0 @@
|
|||||||
import type { BuildOptions } from "../../shared/buildOptions";
|
|
||||||
import { assert } from "tsafe/assert";
|
|
||||||
import { basenameOfTheKeycloakifyResourcesDir } from "../../shared/constants";
|
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
|
||||||
urlPathname: string | undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
|
||||||
|
|
||||||
export function replaceImportsInInlineCssCode(params: {
|
|
||||||
cssCode: string;
|
|
||||||
buildOptions: BuildOptionsLike;
|
|
||||||
}): {
|
|
||||||
fixedCssCode: string;
|
|
||||||
} {
|
|
||||||
const { cssCode, buildOptions } = params;
|
|
||||||
|
|
||||||
const fixedCssCode = cssCode.replace(
|
|
||||||
buildOptions.urlPathname === undefined
|
|
||||||
? /url\(["']?\/([^/][^)"']+)["']?\)/g
|
|
||||||
: new RegExp(`url\\(["']?${buildOptions.urlPathname}([^)"']+)["']?\\)`, "g"),
|
|
||||||
(...[, group]) =>
|
|
||||||
`url(\${url.resourcesPath}/${basenameOfTheKeycloakifyResourcesDir}/${group})`
|
|
||||||
);
|
|
||||||
|
|
||||||
return { fixedCssCode };
|
|
||||||
}
|
|
@ -1,38 +1,38 @@
|
|||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import type { BuildOptions } from "../../../shared/buildOptions";
|
import type { BuildContext } from "../../../shared/buildContext";
|
||||||
import { replaceImportsInJsCode_vite } from "./vite";
|
import { replaceImportsInJsCode_vite } from "./vite";
|
||||||
import { replaceImportsInJsCode_webpack } from "./webpack";
|
import { replaceImportsInJsCode_webpack } from "./webpack";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
export type BuildContextLike = {
|
||||||
reactAppBuildDirPath: string;
|
projectBuildDirPath: string;
|
||||||
assetsDirPath: string;
|
assetsDirPath: string;
|
||||||
urlPathname: string | undefined;
|
urlPathname: string | undefined;
|
||||||
bundler: "vite" | "webpack";
|
bundler: "vite" | "webpack";
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export function replaceImportsInJsCode(params: {
|
export function replaceImportsInJsCode(params: {
|
||||||
jsCode: string;
|
jsCode: string;
|
||||||
buildOptions: BuildOptionsLike;
|
buildContext: BuildContextLike;
|
||||||
}) {
|
}) {
|
||||||
const { jsCode, buildOptions } = params;
|
const { jsCode, buildContext } = params;
|
||||||
|
|
||||||
const { fixedJsCode } = (() => {
|
const { fixedJsCode } = (() => {
|
||||||
switch (buildOptions.bundler) {
|
switch (buildContext.bundler) {
|
||||||
case "vite":
|
case "vite":
|
||||||
return replaceImportsInJsCode_vite({
|
return replaceImportsInJsCode_vite({
|
||||||
jsCode,
|
jsCode,
|
||||||
buildOptions,
|
buildContext,
|
||||||
basenameOfAssetsFiles: readAssetsDirSync({
|
basenameOfAssetsFiles: readAssetsDirSync({
|
||||||
assetsDirPath: params.buildOptions.assetsDirPath
|
assetsDirPath: params.buildContext.assetsDirPath
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
case "webpack":
|
case "webpack":
|
||||||
return replaceImportsInJsCode_webpack({
|
return replaceImportsInJsCode_webpack({
|
||||||
jsCode,
|
jsCode,
|
||||||
buildOptions
|
buildContext
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
@ -1,23 +1,20 @@
|
|||||||
import {
|
import { BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR } from "../../../shared/constants";
|
||||||
nameOfTheGlobal,
|
|
||||||
basenameOfTheKeycloakifyResourcesDir
|
|
||||||
} from "../../../shared/constants";
|
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import type { BuildOptions } from "../../../shared/buildOptions";
|
import type { BuildContext } from "../../../shared/buildContext";
|
||||||
import * as nodePath from "path";
|
import * as nodePath from "path";
|
||||||
import { replaceAll } from "../../../tools/String.prototype.replaceAll";
|
import { replaceAll } from "../../../tools/String.prototype.replaceAll";
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
export type BuildContextLike = {
|
||||||
reactAppBuildDirPath: string;
|
projectBuildDirPath: string;
|
||||||
assetsDirPath: string;
|
assetsDirPath: string;
|
||||||
urlPathname: string | undefined;
|
urlPathname: string | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export function replaceImportsInJsCode_vite(params: {
|
export function replaceImportsInJsCode_vite(params: {
|
||||||
jsCode: string;
|
jsCode: string;
|
||||||
buildOptions: BuildOptionsLike;
|
buildContext: BuildContextLike;
|
||||||
basenameOfAssetsFiles: string[];
|
basenameOfAssetsFiles: string[];
|
||||||
systemType?: "posix" | "win32";
|
systemType?: "posix" | "win32";
|
||||||
}): {
|
}): {
|
||||||
@ -25,7 +22,7 @@ export function replaceImportsInJsCode_vite(params: {
|
|||||||
} {
|
} {
|
||||||
const {
|
const {
|
||||||
jsCode,
|
jsCode,
|
||||||
buildOptions,
|
buildContext,
|
||||||
basenameOfAssetsFiles,
|
basenameOfAssetsFiles,
|
||||||
systemType = nodePath.sep === "/" ? "posix" : "win32"
|
systemType = nodePath.sep === "/" ? "posix" : "win32"
|
||||||
} = params;
|
} = params;
|
||||||
@ -34,20 +31,20 @@ export function replaceImportsInJsCode_vite(params: {
|
|||||||
|
|
||||||
let fixedJsCode = jsCode;
|
let fixedJsCode = jsCode;
|
||||||
|
|
||||||
replace_base_javacript_import: {
|
replace_base_js_import: {
|
||||||
if (buildOptions.urlPathname === undefined) {
|
if (buildContext.urlPathname === undefined) {
|
||||||
break replace_base_javacript_import;
|
break replace_base_js_import;
|
||||||
}
|
}
|
||||||
// Optimization
|
// Optimization
|
||||||
if (!jsCode.includes(buildOptions.urlPathname)) {
|
if (!jsCode.includes(buildContext.urlPathname)) {
|
||||||
break replace_base_javacript_import;
|
break replace_base_js_import;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Replace `Hv=function(e){return"/abcde12345/"+e}` by `Hv=function(e){return"/"+e}`
|
// Replace `Hv=function(e){return"/abcde12345/"+e}` by `Hv=function(e){return"/"+e}`
|
||||||
fixedJsCode = fixedJsCode.replace(
|
fixedJsCode = fixedJsCode.replace(
|
||||||
new RegExp(
|
new RegExp(
|
||||||
`([\\w\\$][\\w\\d\\$]*)=function\\(([\\w\\$][\\w\\d\\$]*)\\)\\{return"${replaceAll(
|
`([\\w\\$][\\w\\d\\$]*)=function\\(([\\w\\$][\\w\\d\\$]*)\\)\\{return"${replaceAll(
|
||||||
buildOptions.urlPathname,
|
buildContext.urlPathname,
|
||||||
"/",
|
"/",
|
||||||
"\\/"
|
"\\/"
|
||||||
)}"\\+\\2\\}`,
|
)}"\\+\\2\\}`,
|
||||||
@ -62,15 +59,15 @@ export function replaceImportsInJsCode_vite(params: {
|
|||||||
// Example: "assets/ or "foo/bar/"
|
// Example: "assets/ or "foo/bar/"
|
||||||
const staticDir = (() => {
|
const staticDir = (() => {
|
||||||
let out = pathRelative(
|
let out = pathRelative(
|
||||||
buildOptions.reactAppBuildDirPath,
|
buildContext.projectBuildDirPath,
|
||||||
buildOptions.assetsDirPath
|
buildContext.assetsDirPath
|
||||||
);
|
);
|
||||||
|
|
||||||
out = replaceAll(out, pathSep, "/") + "/";
|
out = replaceAll(out, pathSep, "/") + "/";
|
||||||
|
|
||||||
if (out === "/") {
|
if (out === "/") {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`The assetsDirPath must be a subdirectory of reactAppBuildDirPath`
|
`The assetsDirPath must be a subdirectory of projectBuildDirPath`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -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["x-keycloakify"].resourcesPath.substring(1) + "/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/${relativePathOfAssetFile}")`
|
||||||
);
|
);
|
||||||
|
|
||||||
fixedJsCode = replaceAll(
|
fixedJsCode = replaceAll(
|
||||||
fixedJsCode,
|
fixedJsCode,
|
||||||
`"${buildOptions.urlPathname ?? "/"}${relativePathOfAssetFile}"`,
|
`"${buildContext.urlPathname ?? "/"}${relativePathOfAssetFile}"`,
|
||||||
`(window.${nameOfTheGlobal}.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/${relativePathOfAssetFile}")`
|
`(window.kcContext["x-keycloakify"].resourcesPath + "/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/${relativePathOfAssetFile}")`
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,30 +1,27 @@
|
|||||||
import {
|
import { BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR } from "../../../shared/constants";
|
||||||
nameOfTheGlobal,
|
|
||||||
basenameOfTheKeycloakifyResourcesDir
|
|
||||||
} from "../../../shared/constants";
|
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import type { BuildOptions } from "../../../shared/buildOptions";
|
import type { BuildContext } from "../../../shared/buildContext";
|
||||||
import * as nodePath from "path";
|
import * as nodePath from "path";
|
||||||
import { replaceAll } from "../../../tools/String.prototype.replaceAll";
|
import { replaceAll } from "../../../tools/String.prototype.replaceAll";
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
export type BuildContextLike = {
|
||||||
reactAppBuildDirPath: string;
|
projectBuildDirPath: string;
|
||||||
assetsDirPath: string;
|
assetsDirPath: string;
|
||||||
urlPathname: string | undefined;
|
urlPathname: string | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export function replaceImportsInJsCode_webpack(params: {
|
export function replaceImportsInJsCode_webpack(params: {
|
||||||
jsCode: string;
|
jsCode: string;
|
||||||
buildOptions: BuildOptionsLike;
|
buildContext: BuildContextLike;
|
||||||
systemType?: "posix" | "win32";
|
systemType?: "posix" | "win32";
|
||||||
}): {
|
}): {
|
||||||
fixedJsCode: string;
|
fixedJsCode: string;
|
||||||
} {
|
} {
|
||||||
const {
|
const {
|
||||||
jsCode,
|
jsCode,
|
||||||
buildOptions,
|
buildContext,
|
||||||
systemType = nodePath.sep === "/" ? "posix" : "win32"
|
systemType = nodePath.sep === "/" ? "posix" : "win32"
|
||||||
} = params;
|
} = params;
|
||||||
|
|
||||||
@ -32,12 +29,12 @@ export function replaceImportsInJsCode_webpack(params: {
|
|||||||
|
|
||||||
let fixedJsCode = jsCode;
|
let fixedJsCode = jsCode;
|
||||||
|
|
||||||
if (buildOptions.urlPathname !== undefined) {
|
if (buildContext.urlPathname !== undefined) {
|
||||||
// "__esModule",{value:!0})},n.p="/foo-bar/",function(){if("undefined" -> ... n.p="/" ...
|
// "__esModule",{value:!0})},n.p="/foo-bar/",function(){if("undefined" -> ... n.p="/" ...
|
||||||
fixedJsCode = fixedJsCode.replace(
|
fixedJsCode = fixedJsCode.replace(
|
||||||
new RegExp(
|
new RegExp(
|
||||||
`,([a-zA-Z]\\.[a-zA-Z])="${replaceAll(
|
`,([a-zA-Z]\\.[a-zA-Z])="${replaceAll(
|
||||||
buildOptions.urlPathname,
|
buildContext.urlPathname,
|
||||||
"/",
|
"/",
|
||||||
"\\/"
|
"\\/"
|
||||||
)}",`,
|
)}",`,
|
||||||
@ -50,15 +47,15 @@ export function replaceImportsInJsCode_webpack(params: {
|
|||||||
// Example: "static/ or "foo/bar/"
|
// Example: "static/ or "foo/bar/"
|
||||||
const staticDir = (() => {
|
const staticDir = (() => {
|
||||||
let out = pathRelative(
|
let out = pathRelative(
|
||||||
buildOptions.reactAppBuildDirPath,
|
buildContext.projectBuildDirPath,
|
||||||
buildOptions.assetsDirPath
|
buildContext.assetsDirPath
|
||||||
);
|
);
|
||||||
|
|
||||||
out = replaceAll(out, pathSep, "/") + "/";
|
out = replaceAll(out, pathSep, "/") + "/";
|
||||||
|
|
||||||
if (out === "/") {
|
if (out === "/") {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`The assetsDirPath must be a subdirectory of reactAppBuildDirPath`
|
`The assetsDirPath must be a subdirectory of projectBuildDirPath`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -86,14 +83,14 @@ 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["x-keycloakify"].resourcesPath; },
|
||||||
set: function() {}
|
set: function() {}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return "${u}";
|
return "${u}";
|
||||||
})()] = ${
|
})()] = ${
|
||||||
isArrowFunction ? `${e} =>` : `function(${e}) { return `
|
isArrowFunction ? `${e} =>` : `function(${e}) { return `
|
||||||
} "/${basenameOfTheKeycloakifyResourcesDir}/${staticDir}${language}/"`
|
} "/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/${staticDir}${language}/"`
|
||||||
.replace(/\s+/g, " ")
|
.replace(/\s+/g, " ")
|
||||||
.trim();
|
.trim();
|
||||||
}
|
}
|
||||||
@ -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["x-keycloakify"].resourcesPath + "/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/${staticDir}`
|
||||||
);
|
);
|
||||||
|
|
||||||
return { fixedJsCode };
|
return { fixedJsCode };
|
||||||
|
@ -3,11 +3,14 @@
|
|||||||
import { termost } from "termost";
|
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";
|
||||||
|
|
||||||
export type CliCommandOptions = {
|
export type CliCommandOptions = {
|
||||||
reactAppRootDirPath: string | undefined;
|
projectDirPath: string | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
assertNoPnpmDlx();
|
||||||
|
|
||||||
const program = termost<CliCommandOptions>(
|
const program = termost<CliCommandOptions>(
|
||||||
{
|
{
|
||||||
name: "keycloakify",
|
name: "keycloakify",
|
||||||
@ -25,7 +28,7 @@ const program = termost<CliCommandOptions>(
|
|||||||
const optionsKeys: string[] = [];
|
const optionsKeys: string[] = [];
|
||||||
|
|
||||||
program.option({
|
program.option({
|
||||||
key: "reactAppRootDirPath",
|
key: "projectDirPath",
|
||||||
name: (() => {
|
name: (() => {
|
||||||
const long = "project";
|
const long = "project";
|
||||||
const short = "p";
|
const short = "p";
|
||||||
@ -75,7 +78,7 @@ program
|
|||||||
|
|
||||||
program
|
program
|
||||||
.command<{
|
.command<{
|
||||||
port: number;
|
port: number | undefined;
|
||||||
keycloakVersion: string | undefined;
|
keycloakVersion: string | undefined;
|
||||||
realmJsonFilePath: string | undefined;
|
realmJsonFilePath: string | undefined;
|
||||||
}>({
|
}>({
|
||||||
@ -93,7 +96,7 @@ program
|
|||||||
return name;
|
return name;
|
||||||
})(),
|
})(),
|
||||||
description: ["Keycloak server port.", "Example `--port 8085`"].join(" "),
|
description: ["Keycloak server port.", "Example `--port 8085`"].join(" "),
|
||||||
defaultValue: 8080
|
defaultValue: undefined
|
||||||
})
|
})
|
||||||
.option({
|
.option({
|
||||||
key: "keycloakVersion",
|
key: "keycloakVersion",
|
||||||
@ -134,20 +137,6 @@ program
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
program
|
|
||||||
.command({
|
|
||||||
name: "download-keycloak-default-theme",
|
|
||||||
description: "Download the built-in Keycloak theme."
|
|
||||||
})
|
|
||||||
.task({
|
|
||||||
skip,
|
|
||||||
handler: async cliCommandOptions => {
|
|
||||||
const { command } = await import("./download-keycloak-default-theme");
|
|
||||||
|
|
||||||
await command({ cliCommandOptions });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
program
|
program
|
||||||
.command({
|
.command({
|
||||||
name: "eject-page",
|
name: "eject-page",
|
||||||
@ -190,6 +179,20 @@ program
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
program
|
||||||
|
.command({
|
||||||
|
name: "initialize-account-theme",
|
||||||
|
description: "Initialize the account theme."
|
||||||
|
})
|
||||||
|
.task({
|
||||||
|
skip,
|
||||||
|
handler: async cliCommandOptions => {
|
||||||
|
const { command } = await import("./initialize-account-theme");
|
||||||
|
|
||||||
|
await command({ cliCommandOptions });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
program
|
program
|
||||||
.command({
|
.command({
|
||||||
name: "copy-keycloak-resources-to-public",
|
name: "copy-keycloak-resources-to-public",
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
export type KeycloakVersionRange =
|
export type KeycloakVersionRange =
|
||||||
| KeycloakVersionRange.WithAccountTheme
|
| KeycloakVersionRange.WithAccountV1Theme
|
||||||
| KeycloakVersionRange.WithoutAccountTheme;
|
| KeycloakVersionRange.WithoutAccountV1Theme;
|
||||||
|
|
||||||
export namespace KeycloakVersionRange {
|
export namespace KeycloakVersionRange {
|
||||||
export type WithoutAccountTheme = "21-and-below" | "22-and-above";
|
export type WithoutAccountV1Theme = "21-and-below" | "22-and-above";
|
||||||
|
|
||||||
export type WithAccountTheme = "21-and-below" | "23" | "24-and-above";
|
export type WithAccountV1Theme = "21-and-below" | "23" | "24" | "25-and-above";
|
||||||
}
|
}
|
||||||
|
994
src/bin/shared/buildContext.ts
Normal file
994
src/bin/shared/buildContext.ts
Normal file
@ -0,0 +1,994 @@
|
|||||||
|
import { parse as urlParse } from "url";
|
||||||
|
import {
|
||||||
|
join as pathJoin,
|
||||||
|
sep as pathSep,
|
||||||
|
relative as pathRelative,
|
||||||
|
resolve as pathResolve,
|
||||||
|
dirname as pathDirname
|
||||||
|
} from "path";
|
||||||
|
import { getAbsoluteAndInOsFormatPath } from "../tools/getAbsoluteAndInOsFormatPath";
|
||||||
|
import type { CliCommandOptions } from "../main";
|
||||||
|
import { z } from "zod";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
import * as child_process from "child_process";
|
||||||
|
import {
|
||||||
|
VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES,
|
||||||
|
BUILD_FOR_KEYCLOAK_MAJOR_VERSION_ENV_NAME,
|
||||||
|
LOGIN_THEME_RESOURCES_FROMkEYCLOAK_VERSION_DEFAULT
|
||||||
|
} from "./constants";
|
||||||
|
import type { KeycloakVersionRange } from "./KeycloakVersionRange";
|
||||||
|
import { exclude } from "tsafe";
|
||||||
|
import { crawl } from "../tools/crawl";
|
||||||
|
import { THEME_TYPES } from "./constants";
|
||||||
|
import { objectEntries } from "tsafe/objectEntries";
|
||||||
|
import { type ThemeType } from "./constants";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import { getProxyFetchOptions, type ProxyFetchOptions } from "../tools/fetchProxyOptions";
|
||||||
|
import { removeDuplicates } from "evt/tools/reducers/removeDuplicates";
|
||||||
|
import { same } from "evt/tools/inDepth/same";
|
||||||
|
|
||||||
|
export type BuildContext = {
|
||||||
|
themeVersion: string;
|
||||||
|
themeNames: [string, ...string[]];
|
||||||
|
extraThemeProperties: string[] | undefined;
|
||||||
|
groupId: string;
|
||||||
|
artifactId: string;
|
||||||
|
loginThemeResourcesFromKeycloakVersion: string;
|
||||||
|
projectDirPath: string;
|
||||||
|
projectBuildDirPath: string;
|
||||||
|
/** Directory that keycloakify outputs to. Defaults to {cwd}/build_keycloak */
|
||||||
|
keycloakifyBuildDirPath: string;
|
||||||
|
publicDirPath: string;
|
||||||
|
cacheDirPath: string;
|
||||||
|
/** If your app is hosted under a subpath, it's the case in CRA if you have "homepage": "https://example.com/my-app" in your package.json
|
||||||
|
* In this case the urlPathname will be "/my-app/" */
|
||||||
|
urlPathname: string | undefined;
|
||||||
|
assetsDirPath: string;
|
||||||
|
fetchOptions: ProxyFetchOptions;
|
||||||
|
kcContextExclusionsFtlCode: string | undefined;
|
||||||
|
environmentVariables: { name: string; default: string }[];
|
||||||
|
themeSrcDirPath: string;
|
||||||
|
implementedThemeTypes: {
|
||||||
|
login: { isImplemented: boolean };
|
||||||
|
email: { isImplemented: boolean };
|
||||||
|
account:
|
||||||
|
| { isImplemented: false }
|
||||||
|
| { isImplemented: true; type: "Single-Page" | "Multi-Page" };
|
||||||
|
};
|
||||||
|
packageJsonFilePath: string;
|
||||||
|
bundler: "vite" | "webpack";
|
||||||
|
jarTargets: {
|
||||||
|
keycloakVersionRange: KeycloakVersionRange;
|
||||||
|
jarFileBasename: string;
|
||||||
|
}[];
|
||||||
|
extensionJars: ({ type: "path"; path: string } | { type: "url"; url: string })[];
|
||||||
|
startKeycloakOptions: {
|
||||||
|
dockerImage:
|
||||||
|
| {
|
||||||
|
reference: string;
|
||||||
|
tag: string;
|
||||||
|
}
|
||||||
|
| undefined;
|
||||||
|
dockerExtraArgs: string[];
|
||||||
|
keycloakExtraArgs: string[];
|
||||||
|
extensionJars: ({ type: "path"; path: string } | { type: "url"; url: string })[];
|
||||||
|
realmJsonFilePath: string | undefined;
|
||||||
|
port: number | undefined;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<Equals<keyof BuildContext["implementedThemeTypes"], ThemeType | "email">>();
|
||||||
|
|
||||||
|
export type BuildOptions = {
|
||||||
|
themeName?: string | string[];
|
||||||
|
themeVersion?: string;
|
||||||
|
environmentVariables?: { name: string; default: string }[];
|
||||||
|
extraThemeProperties?: string[];
|
||||||
|
artifactId?: string;
|
||||||
|
groupId?: string;
|
||||||
|
loginThemeResourcesFromKeycloakVersion?: string;
|
||||||
|
keycloakifyBuildDirPath?: string;
|
||||||
|
kcContextExclusionsFtl?: string;
|
||||||
|
extensionJars?: string[];
|
||||||
|
startKeycloakOptions?: {
|
||||||
|
dockerImage?: string;
|
||||||
|
dockerExtraArgs?: string[];
|
||||||
|
keycloakExtraArgs?: string[];
|
||||||
|
extensionJars?: string[];
|
||||||
|
realmJsonFilePath?: string;
|
||||||
|
port?: number;
|
||||||
|
};
|
||||||
|
} & BuildOptions.AccountThemeImplAndKeycloakVersionTargets;
|
||||||
|
|
||||||
|
export namespace BuildOptions {
|
||||||
|
export type AccountThemeImplAndKeycloakVersionTargets =
|
||||||
|
| AccountThemeImplAndKeycloakVersionTargets.MultiPageApp
|
||||||
|
| AccountThemeImplAndKeycloakVersionTargets.SinglePageAppOrNone;
|
||||||
|
|
||||||
|
export namespace AccountThemeImplAndKeycloakVersionTargets {
|
||||||
|
export type MultiPageApp = {
|
||||||
|
accountThemeImplementation: "Multi-Page";
|
||||||
|
keycloakVersionTargets?: Record<
|
||||||
|
KeycloakVersionRange.WithAccountV1Theme,
|
||||||
|
string | boolean
|
||||||
|
>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SinglePageAppOrNone = {
|
||||||
|
accountThemeImplementation: "Single-Page" | "none";
|
||||||
|
keycloakVersionTargets?: Record<
|
||||||
|
KeycloakVersionRange.WithoutAccountV1Theme,
|
||||||
|
string | boolean
|
||||||
|
>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ResolvedViteConfig = {
|
||||||
|
buildDir: string;
|
||||||
|
publicDir: string;
|
||||||
|
assetsDir: string;
|
||||||
|
urlPathname: string | undefined;
|
||||||
|
buildOptions: BuildOptions;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function getBuildContext(params: {
|
||||||
|
cliCommandOptions: CliCommandOptions;
|
||||||
|
}): BuildContext {
|
||||||
|
const { cliCommandOptions } = params;
|
||||||
|
|
||||||
|
const projectDirPath =
|
||||||
|
cliCommandOptions.projectDirPath !== undefined
|
||||||
|
? getAbsoluteAndInOsFormatPath({
|
||||||
|
pathIsh: cliCommandOptions.projectDirPath,
|
||||||
|
cwd: process.cwd()
|
||||||
|
})
|
||||||
|
: process.cwd();
|
||||||
|
|
||||||
|
const { themeSrcDirPath } = (() => {
|
||||||
|
const srcDirPath = pathJoin(projectDirPath, "src");
|
||||||
|
|
||||||
|
const themeSrcDirPath: string | undefined = crawl({
|
||||||
|
dirPath: srcDirPath,
|
||||||
|
returnedPathsType: "relative to dirPath"
|
||||||
|
})
|
||||||
|
.map(fileRelativePath => {
|
||||||
|
for (const themeSrcDirBasename of ["keycloak-theme", "keycloak_theme"]) {
|
||||||
|
const split = fileRelativePath.split(themeSrcDirBasename);
|
||||||
|
if (split.length === 2) {
|
||||||
|
return pathJoin(srcDirPath, split[0] + themeSrcDirBasename);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
})
|
||||||
|
.filter(exclude(undefined))[0];
|
||||||
|
|
||||||
|
if (themeSrcDirPath !== undefined) {
|
||||||
|
return { themeSrcDirPath };
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const themeType of [...THEME_TYPES, "email"]) {
|
||||||
|
if (!fs.existsSync(pathJoin(srcDirPath, themeType))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return { themeSrcDirPath: srcDirPath };
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
chalk.red(
|
||||||
|
[
|
||||||
|
`Can't locate your Keycloak theme source directory in .${pathSep}${pathRelative(process.cwd(), srcDirPath)}`,
|
||||||
|
`Make sure to either use the Keycloakify CLI in the root of your Keycloakify project or use the --project CLI option`,
|
||||||
|
`If you are collocating your Keycloak theme with your app you must have a directory named 'keycloak-theme' or 'keycloak_theme' in your 'src' directory`
|
||||||
|
].join("\n")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
process.exit(1);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const { resolvedViteConfig } = (() => {
|
||||||
|
if (
|
||||||
|
fs
|
||||||
|
.readdirSync(projectDirPath)
|
||||||
|
.find(fileBasename => fileBasename.startsWith("vite.config")) ===
|
||||||
|
undefined
|
||||||
|
) {
|
||||||
|
return { resolvedViteConfig: undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = child_process
|
||||||
|
.execSync("npx vite", {
|
||||||
|
cwd: projectDirPath,
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
[VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RESOLVE_VITE_CONFIG]: "true"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.toString("utf8");
|
||||||
|
|
||||||
|
assert(
|
||||||
|
output.includes(VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RESOLVE_VITE_CONFIG),
|
||||||
|
"Seems like the Keycloakify's Vite plugin is not installed."
|
||||||
|
);
|
||||||
|
|
||||||
|
const resolvedViteConfigStr = output
|
||||||
|
.split(VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RESOLVE_VITE_CONFIG)
|
||||||
|
.reverse()[0];
|
||||||
|
|
||||||
|
const resolvedViteConfig: ResolvedViteConfig = JSON.parse(resolvedViteConfigStr);
|
||||||
|
|
||||||
|
return { resolvedViteConfig };
|
||||||
|
})();
|
||||||
|
|
||||||
|
const packageJsonFilePath = (function getPackageJSonDirPath(upCount: number): string {
|
||||||
|
const dirPath = pathResolve(
|
||||||
|
pathJoin(...[projectDirPath, ...Array(upCount).fill("..")])
|
||||||
|
);
|
||||||
|
|
||||||
|
assert(dirPath !== pathSep, "Root package.json not found");
|
||||||
|
|
||||||
|
success: {
|
||||||
|
const packageJsonFilePath = pathJoin(dirPath, "package.json");
|
||||||
|
|
||||||
|
if (!fs.existsSync(packageJsonFilePath)) {
|
||||||
|
break success;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsedPackageJson = z
|
||||||
|
.object({
|
||||||
|
name: z.string().optional(),
|
||||||
|
dependencies: z.record(z.string()).optional(),
|
||||||
|
devDependencies: z.record(z.string()).optional()
|
||||||
|
})
|
||||||
|
.parse(JSON.parse(fs.readFileSync(packageJsonFilePath).toString("utf8")));
|
||||||
|
|
||||||
|
if (
|
||||||
|
parsedPackageJson.dependencies?.keycloakify === undefined &&
|
||||||
|
parsedPackageJson.devDependencies?.keycloakify === undefined &&
|
||||||
|
parsedPackageJson.name !== "keycloakify" // NOTE: For local storybook build
|
||||||
|
) {
|
||||||
|
break success;
|
||||||
|
}
|
||||||
|
|
||||||
|
return packageJsonFilePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
return getPackageJSonDirPath(upCount + 1);
|
||||||
|
})(0);
|
||||||
|
|
||||||
|
const parsedPackageJson = (() => {
|
||||||
|
type BuildOptions_packageJson = BuildOptions & {
|
||||||
|
projectBuildDirPath?: string;
|
||||||
|
staticDirPathInProjectBuildDirPath?: string;
|
||||||
|
publicDirPath?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ParsedPackageJson = {
|
||||||
|
name?: string;
|
||||||
|
version?: string;
|
||||||
|
homepage?: string;
|
||||||
|
keycloakify?: BuildOptions_packageJson;
|
||||||
|
};
|
||||||
|
|
||||||
|
const zMultiPageApp = (() => {
|
||||||
|
type TargetType =
|
||||||
|
BuildOptions.AccountThemeImplAndKeycloakVersionTargets.MultiPageApp;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
accountThemeImplementation: z.literal("Multi-Page"),
|
||||||
|
keycloakVersionTargets: z
|
||||||
|
.object({
|
||||||
|
"21-and-below": z.union([z.boolean(), z.string()]),
|
||||||
|
"23": z.union([z.boolean(), z.string()]),
|
||||||
|
"24": z.union([z.boolean(), z.string()]),
|
||||||
|
"25-and-above": z.union([z.boolean(), z.string()])
|
||||||
|
})
|
||||||
|
.optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zSinglePageApp = (() => {
|
||||||
|
type TargetType =
|
||||||
|
BuildOptions.AccountThemeImplAndKeycloakVersionTargets.SinglePageAppOrNone;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
accountThemeImplementation: z.union([
|
||||||
|
z.literal("Single-Page"),
|
||||||
|
z.literal("none")
|
||||||
|
]),
|
||||||
|
keycloakVersionTargets: z
|
||||||
|
.object({
|
||||||
|
"21-and-below": z.union([z.boolean(), z.string()]),
|
||||||
|
"22-and-above": z.union([z.boolean(), z.string()])
|
||||||
|
})
|
||||||
|
.optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zAccountThemeImplAndKeycloakVersionTargets = (() => {
|
||||||
|
type TargetType = BuildOptions.AccountThemeImplAndKeycloakVersionTargets;
|
||||||
|
|
||||||
|
const zTargetType = z.union([zMultiPageApp, zSinglePageApp]);
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zStartKeycloakOptions = (() => {
|
||||||
|
type TargetType = NonNullable<BuildOptions["startKeycloakOptions"]>;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
dockerImage: z.string().optional(),
|
||||||
|
extensionJars: z.array(z.string()).optional(),
|
||||||
|
realmJsonFilePath: z.string().optional(),
|
||||||
|
dockerExtraArgs: z.array(z.string()).optional(),
|
||||||
|
keycloakExtraArgs: z.array(z.string()).optional(),
|
||||||
|
port: z.number().optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zBuildOptions = (() => {
|
||||||
|
type TargetType = BuildOptions;
|
||||||
|
|
||||||
|
const zTargetType = z.intersection(
|
||||||
|
z.object({
|
||||||
|
themeName: z.union([z.string(), z.array(z.string())]).optional(),
|
||||||
|
themeVersion: z.string().optional(),
|
||||||
|
environmentVariables: z
|
||||||
|
.array(
|
||||||
|
z.object({
|
||||||
|
name: z.string(),
|
||||||
|
default: z.string()
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.optional(),
|
||||||
|
extraThemeProperties: z.array(z.string()).optional(),
|
||||||
|
artifactId: z.string().optional(),
|
||||||
|
groupId: z.string().optional(),
|
||||||
|
loginThemeResourcesFromKeycloakVersion: z.string().optional(),
|
||||||
|
keycloakifyBuildDirPath: z.string().optional(),
|
||||||
|
kcContextExclusionsFtl: z.string().optional(),
|
||||||
|
extensionJars: z.array(z.string()).optional(),
|
||||||
|
startKeycloakOptions: zStartKeycloakOptions.optional()
|
||||||
|
}),
|
||||||
|
zAccountThemeImplAndKeycloakVersionTargets
|
||||||
|
);
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zBuildOptions_packageJson = (() => {
|
||||||
|
type TargetType = BuildOptions_packageJson;
|
||||||
|
|
||||||
|
const zTargetType = z.intersection(
|
||||||
|
zBuildOptions,
|
||||||
|
z.object({
|
||||||
|
projectBuildDirPath: z.string().optional(),
|
||||||
|
staticDirPathInProjectBuildDirPath: z.string().optional(),
|
||||||
|
publicDirPath: z.string().optional()
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zParsedPackageJson = (() => {
|
||||||
|
type TargetType = ParsedPackageJson;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
name: z.string().optional(),
|
||||||
|
version: z.string().optional(),
|
||||||
|
homepage: z.string().optional(),
|
||||||
|
keycloakify: zBuildOptions_packageJson.optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const configurationPackageJsonFilePath = (() => {
|
||||||
|
const rootPackageJsonFilePath = pathJoin(projectDirPath, "package.json");
|
||||||
|
|
||||||
|
return fs.existsSync(rootPackageJsonFilePath)
|
||||||
|
? rootPackageJsonFilePath
|
||||||
|
: packageJsonFilePath;
|
||||||
|
})();
|
||||||
|
|
||||||
|
return zParsedPackageJson.parse(
|
||||||
|
JSON.parse(fs.readFileSync(configurationPackageJsonFilePath).toString("utf8"))
|
||||||
|
);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const bundler = resolvedViteConfig !== undefined ? "vite" : "webpack";
|
||||||
|
|
||||||
|
if (bundler === "vite" && parsedPackageJson.keycloakify !== undefined) {
|
||||||
|
console.error(
|
||||||
|
chalk.red(
|
||||||
|
`In vite projects, provide your Keycloakify options in vite.config.ts, not in package.json`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
process.exit(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildOptions: BuildOptions = (() => {
|
||||||
|
switch (bundler) {
|
||||||
|
case "vite":
|
||||||
|
assert(resolvedViteConfig !== undefined);
|
||||||
|
return resolvedViteConfig.buildOptions;
|
||||||
|
case "webpack":
|
||||||
|
assert(parsedPackageJson.keycloakify !== undefined);
|
||||||
|
return parsedPackageJson.keycloakify;
|
||||||
|
}
|
||||||
|
assert<Equals<typeof bundler, never>>(false);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const implementedThemeTypes: BuildContext["implementedThemeTypes"] = {
|
||||||
|
login: {
|
||||||
|
isImplemented: fs.existsSync(pathJoin(themeSrcDirPath, "login"))
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
isImplemented: fs.existsSync(pathJoin(themeSrcDirPath, "email"))
|
||||||
|
},
|
||||||
|
account: (() => {
|
||||||
|
if (buildOptions.accountThemeImplementation === "none") {
|
||||||
|
return { isImplemented: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
isImplemented: true,
|
||||||
|
type: buildOptions.accountThemeImplementation
|
||||||
|
};
|
||||||
|
})()
|
||||||
|
};
|
||||||
|
|
||||||
|
if (
|
||||||
|
implementedThemeTypes.account.isImplemented &&
|
||||||
|
!fs.existsSync(pathJoin(themeSrcDirPath, "account"))
|
||||||
|
) {
|
||||||
|
console.error(
|
||||||
|
chalk.red(
|
||||||
|
[
|
||||||
|
`You have set 'accountThemeImplementation' to '${implementedThemeTypes.account.type}'`,
|
||||||
|
`but the 'account' directory is missing in your theme source directory`,
|
||||||
|
"Use the `npx keycloakify initialize-account-theme` command to create it"
|
||||||
|
].join(" ")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
process.exit(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const themeNames = ((): [string, ...string[]] => {
|
||||||
|
if (buildOptions.themeName === undefined) {
|
||||||
|
return parsedPackageJson.name === undefined
|
||||||
|
? ["keycloakify"]
|
||||||
|
: [
|
||||||
|
parsedPackageJson.name
|
||||||
|
.replace(/^@(.*)/, "$1")
|
||||||
|
.split("/")
|
||||||
|
.join("-")
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof buildOptions.themeName === "string") {
|
||||||
|
return [buildOptions.themeName];
|
||||||
|
}
|
||||||
|
|
||||||
|
const [mainThemeName, ...themeVariantNames] = buildOptions.themeName;
|
||||||
|
|
||||||
|
assert(mainThemeName !== undefined);
|
||||||
|
|
||||||
|
return [mainThemeName, ...themeVariantNames];
|
||||||
|
})();
|
||||||
|
|
||||||
|
const projectBuildDirPath = (() => {
|
||||||
|
webpack: {
|
||||||
|
if (bundler !== "webpack") {
|
||||||
|
break webpack;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(parsedPackageJson.keycloakify !== undefined);
|
||||||
|
|
||||||
|
if (parsedPackageJson.keycloakify.projectBuildDirPath !== undefined) {
|
||||||
|
return getAbsoluteAndInOsFormatPath({
|
||||||
|
pathIsh: parsedPackageJson.keycloakify.projectBuildDirPath,
|
||||||
|
cwd: projectDirPath
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return pathJoin(projectDirPath, "build");
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(bundler === "vite");
|
||||||
|
assert(resolvedViteConfig !== undefined);
|
||||||
|
|
||||||
|
return pathJoin(projectDirPath, resolvedViteConfig.buildDir);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const buildForKeycloakMajorVersionNumber = (() => {
|
||||||
|
const envValue = process.env[BUILD_FOR_KEYCLOAK_MAJOR_VERSION_ENV_NAME];
|
||||||
|
|
||||||
|
if (envValue === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const major = parseInt(envValue);
|
||||||
|
|
||||||
|
assert(!isNaN(major));
|
||||||
|
|
||||||
|
return major;
|
||||||
|
})();
|
||||||
|
|
||||||
|
function urlOrPathToDiscriminatingWrapper(
|
||||||
|
urlOrPath: string
|
||||||
|
): { type: "url"; url: string } | { type: "path"; path: string } {
|
||||||
|
if (/^https?:\/\//.test(urlOrPath)) {
|
||||||
|
return { type: "url", url: urlOrPath };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "path",
|
||||||
|
path: getAbsoluteAndInOsFormatPath({
|
||||||
|
pathIsh: urlOrPath,
|
||||||
|
cwd: projectDirPath
|
||||||
|
})
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
bundler,
|
||||||
|
packageJsonFilePath,
|
||||||
|
themeVersion: buildOptions.themeVersion ?? parsedPackageJson.version ?? "0.0.0",
|
||||||
|
themeNames,
|
||||||
|
extraThemeProperties: buildOptions.extraThemeProperties,
|
||||||
|
groupId: (() => {
|
||||||
|
const fallbackGroupId = `${themeNames[0]}.keycloak`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
process.env.KEYCLOAKIFY_GROUP_ID ??
|
||||||
|
buildOptions.groupId ??
|
||||||
|
(parsedPackageJson.homepage === undefined
|
||||||
|
? fallbackGroupId
|
||||||
|
: urlParse(parsedPackageJson.homepage)
|
||||||
|
.host?.replace(/:[0-9]+$/, "")
|
||||||
|
?.split(".")
|
||||||
|
.reverse()
|
||||||
|
.join(".") ?? fallbackGroupId) + ".keycloak"
|
||||||
|
);
|
||||||
|
})(),
|
||||||
|
artifactId:
|
||||||
|
process.env.KEYCLOAKIFY_ARTIFACT_ID ??
|
||||||
|
buildOptions.artifactId ??
|
||||||
|
`${themeNames[0]}-keycloak-theme`,
|
||||||
|
loginThemeResourcesFromKeycloakVersion:
|
||||||
|
buildOptions.loginThemeResourcesFromKeycloakVersion ??
|
||||||
|
LOGIN_THEME_RESOURCES_FROMkEYCLOAK_VERSION_DEFAULT,
|
||||||
|
projectDirPath,
|
||||||
|
projectBuildDirPath,
|
||||||
|
keycloakifyBuildDirPath: (() => {
|
||||||
|
if (buildOptions.keycloakifyBuildDirPath !== undefined) {
|
||||||
|
return getAbsoluteAndInOsFormatPath({
|
||||||
|
pathIsh: buildOptions.keycloakifyBuildDirPath,
|
||||||
|
cwd: projectDirPath
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return pathJoin(
|
||||||
|
projectDirPath,
|
||||||
|
resolvedViteConfig?.buildDir === undefined
|
||||||
|
? "build_keycloak"
|
||||||
|
: `${resolvedViteConfig.buildDir}_keycloak`
|
||||||
|
);
|
||||||
|
})(),
|
||||||
|
publicDirPath: (() => {
|
||||||
|
if (process.env.PUBLIC_DIR_PATH !== undefined) {
|
||||||
|
return getAbsoluteAndInOsFormatPath({
|
||||||
|
pathIsh: process.env.PUBLIC_DIR_PATH,
|
||||||
|
cwd: projectDirPath
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
webpack: {
|
||||||
|
if (bundler !== "webpack") {
|
||||||
|
break webpack;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(parsedPackageJson.keycloakify !== undefined);
|
||||||
|
|
||||||
|
if (parsedPackageJson.keycloakify.publicDirPath !== undefined) {
|
||||||
|
return getAbsoluteAndInOsFormatPath({
|
||||||
|
pathIsh: parsedPackageJson.keycloakify.publicDirPath,
|
||||||
|
cwd: projectDirPath
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return pathJoin(projectDirPath, "public");
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(bundler === "vite");
|
||||||
|
assert(resolvedViteConfig !== undefined);
|
||||||
|
|
||||||
|
return pathJoin(projectDirPath, resolvedViteConfig.publicDir);
|
||||||
|
})(),
|
||||||
|
cacheDirPath: pathJoin(
|
||||||
|
(() => {
|
||||||
|
if (process.env.XDG_CACHE_HOME !== undefined) {
|
||||||
|
return getAbsoluteAndInOsFormatPath({
|
||||||
|
pathIsh: process.env.XDG_CACHE_HOME,
|
||||||
|
cwd: process.cwd()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return pathJoin(
|
||||||
|
pathDirname(packageJsonFilePath),
|
||||||
|
"node_modules",
|
||||||
|
".cache"
|
||||||
|
);
|
||||||
|
})(),
|
||||||
|
"keycloakify"
|
||||||
|
),
|
||||||
|
urlPathname: (() => {
|
||||||
|
webpack: {
|
||||||
|
if (bundler !== "webpack") {
|
||||||
|
break webpack;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { homepage } = parsedPackageJson;
|
||||||
|
|
||||||
|
let url: URL | undefined = undefined;
|
||||||
|
|
||||||
|
if (homepage !== undefined) {
|
||||||
|
url = new URL(homepage);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const out = url.pathname.replace(/([^/])$/, "$1/");
|
||||||
|
return out === "/" ? undefined : out;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(bundler === "vite");
|
||||||
|
assert(resolvedViteConfig !== undefined);
|
||||||
|
|
||||||
|
return resolvedViteConfig.urlPathname;
|
||||||
|
})(),
|
||||||
|
assetsDirPath: (() => {
|
||||||
|
webpack: {
|
||||||
|
if (bundler !== "webpack") {
|
||||||
|
break webpack;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(parsedPackageJson.keycloakify !== undefined);
|
||||||
|
|
||||||
|
if (
|
||||||
|
parsedPackageJson.keycloakify.staticDirPathInProjectBuildDirPath !==
|
||||||
|
undefined
|
||||||
|
) {
|
||||||
|
getAbsoluteAndInOsFormatPath({
|
||||||
|
pathIsh:
|
||||||
|
parsedPackageJson.keycloakify
|
||||||
|
.staticDirPathInProjectBuildDirPath,
|
||||||
|
cwd: projectBuildDirPath
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return pathJoin(projectBuildDirPath, "static");
|
||||||
|
}
|
||||||
|
assert(bundler === "vite");
|
||||||
|
assert(resolvedViteConfig !== undefined);
|
||||||
|
|
||||||
|
return pathJoin(projectBuildDirPath, resolvedViteConfig.assetsDir);
|
||||||
|
})(),
|
||||||
|
kcContextExclusionsFtlCode: (() => {
|
||||||
|
if (buildOptions.kcContextExclusionsFtl === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (buildOptions.kcContextExclusionsFtl.endsWith(".ftl")) {
|
||||||
|
const kcContextExclusionsFtlPath = getAbsoluteAndInOsFormatPath({
|
||||||
|
pathIsh: buildOptions.kcContextExclusionsFtl,
|
||||||
|
cwd: projectDirPath
|
||||||
|
});
|
||||||
|
|
||||||
|
return fs.readFileSync(kcContextExclusionsFtlPath).toString("utf8");
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildOptions.kcContextExclusionsFtl;
|
||||||
|
})(),
|
||||||
|
environmentVariables: buildOptions.environmentVariables ?? [],
|
||||||
|
implementedThemeTypes,
|
||||||
|
themeSrcDirPath,
|
||||||
|
fetchOptions: getProxyFetchOptions({
|
||||||
|
npmConfigGetCwd: (function callee(upCount: number): string {
|
||||||
|
const dirPath = pathResolve(
|
||||||
|
pathJoin(...[projectDirPath, ...Array(upCount).fill("..")])
|
||||||
|
);
|
||||||
|
|
||||||
|
assert(
|
||||||
|
dirPath !== pathSep,
|
||||||
|
"Couldn't find a place to run 'npm config get'"
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
child_process.execSync("npm config get", {
|
||||||
|
cwd: dirPath,
|
||||||
|
stdio: "pipe"
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (String(error).includes("ENOWORKSPACES")) {
|
||||||
|
return callee(upCount + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return dirPath;
|
||||||
|
})(0)
|
||||||
|
}),
|
||||||
|
jarTargets: (() => {
|
||||||
|
const getDefaultJarFileBasename = (range: string) =>
|
||||||
|
`keycloak-theme-for-kc-${range}.jar`;
|
||||||
|
|
||||||
|
build_for_specific_keycloak_major_version: {
|
||||||
|
if (buildForKeycloakMajorVersionNumber === undefined) {
|
||||||
|
break build_for_specific_keycloak_major_version;
|
||||||
|
}
|
||||||
|
|
||||||
|
const keycloakVersionRange: KeycloakVersionRange = (() => {
|
||||||
|
if (
|
||||||
|
implementedThemeTypes.account.isImplemented &&
|
||||||
|
implementedThemeTypes.account.type === "Multi-Page"
|
||||||
|
) {
|
||||||
|
const keycloakVersionRange = (() => {
|
||||||
|
if (buildForKeycloakMajorVersionNumber <= 21) {
|
||||||
|
return "21-and-below" as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(buildForKeycloakMajorVersionNumber !== 22);
|
||||||
|
|
||||||
|
if (buildForKeycloakMajorVersionNumber === 23) {
|
||||||
|
return "23" as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (buildForKeycloakMajorVersionNumber === 24) {
|
||||||
|
return "24" as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
return "25-and-above" as const;
|
||||||
|
})();
|
||||||
|
|
||||||
|
assert<
|
||||||
|
Equals<
|
||||||
|
typeof keycloakVersionRange,
|
||||||
|
KeycloakVersionRange.WithAccountV1Theme
|
||||||
|
>
|
||||||
|
>();
|
||||||
|
|
||||||
|
return keycloakVersionRange;
|
||||||
|
} else {
|
||||||
|
const keycloakVersionRange = (() => {
|
||||||
|
if (buildForKeycloakMajorVersionNumber <= 21) {
|
||||||
|
return "21-and-below" as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
return "22-and-above" as const;
|
||||||
|
})();
|
||||||
|
|
||||||
|
assert<
|
||||||
|
Equals<
|
||||||
|
typeof keycloakVersionRange,
|
||||||
|
KeycloakVersionRange.WithoutAccountV1Theme
|
||||||
|
>
|
||||||
|
>();
|
||||||
|
|
||||||
|
return keycloakVersionRange;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
const jarFileBasename = (() => {
|
||||||
|
use_custom_jar_basename: {
|
||||||
|
const { keycloakVersionTargets } = buildOptions;
|
||||||
|
|
||||||
|
if (keycloakVersionTargets === undefined) {
|
||||||
|
break use_custom_jar_basename;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entry = objectEntries(keycloakVersionTargets).find(
|
||||||
|
([keycloakVersionRange_entry]) =>
|
||||||
|
keycloakVersionRange_entry === keycloakVersionRange
|
||||||
|
);
|
||||||
|
|
||||||
|
if (entry === undefined) {
|
||||||
|
break use_custom_jar_basename;
|
||||||
|
}
|
||||||
|
|
||||||
|
const maybeJarFileBasename = entry[1];
|
||||||
|
|
||||||
|
if (typeof maybeJarFileBasename !== "string") {
|
||||||
|
break use_custom_jar_basename;
|
||||||
|
}
|
||||||
|
|
||||||
|
return maybeJarFileBasename;
|
||||||
|
}
|
||||||
|
|
||||||
|
return getDefaultJarFileBasename(keycloakVersionRange);
|
||||||
|
})();
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
keycloakVersionRange,
|
||||||
|
jarFileBasename
|
||||||
|
}
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const jarTargets_default = (() => {
|
||||||
|
const jarTargets: BuildContext["jarTargets"] = [];
|
||||||
|
|
||||||
|
if (
|
||||||
|
implementedThemeTypes.account.isImplemented &&
|
||||||
|
implementedThemeTypes.account.type === "Multi-Page"
|
||||||
|
) {
|
||||||
|
for (const keycloakVersionRange of [
|
||||||
|
"21-and-below",
|
||||||
|
"23",
|
||||||
|
"24",
|
||||||
|
"25-and-above"
|
||||||
|
] as const) {
|
||||||
|
assert<
|
||||||
|
Equals<
|
||||||
|
typeof keycloakVersionRange,
|
||||||
|
KeycloakVersionRange.WithAccountV1Theme
|
||||||
|
>
|
||||||
|
>(true);
|
||||||
|
jarTargets.push({
|
||||||
|
keycloakVersionRange,
|
||||||
|
jarFileBasename:
|
||||||
|
getDefaultJarFileBasename(keycloakVersionRange)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (const keycloakVersionRange of [
|
||||||
|
"21-and-below",
|
||||||
|
"22-and-above"
|
||||||
|
] as const) {
|
||||||
|
assert<
|
||||||
|
Equals<
|
||||||
|
typeof keycloakVersionRange,
|
||||||
|
KeycloakVersionRange.WithoutAccountV1Theme
|
||||||
|
>
|
||||||
|
>(true);
|
||||||
|
jarTargets.push({
|
||||||
|
keycloakVersionRange,
|
||||||
|
jarFileBasename:
|
||||||
|
getDefaultJarFileBasename(keycloakVersionRange)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return jarTargets;
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (buildOptions.keycloakVersionTargets === undefined) {
|
||||||
|
return jarTargets_default;
|
||||||
|
}
|
||||||
|
|
||||||
|
const jarTargets: BuildContext["jarTargets"] = [];
|
||||||
|
|
||||||
|
for (const [keycloakVersionRange, jarNameOrBoolean] of objectEntries(
|
||||||
|
buildOptions.keycloakVersionTargets
|
||||||
|
)) {
|
||||||
|
if (jarNameOrBoolean === false) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (jarNameOrBoolean === true) {
|
||||||
|
jarTargets.push({
|
||||||
|
keycloakVersionRange: keycloakVersionRange,
|
||||||
|
jarFileBasename: getDefaultJarFileBasename(keycloakVersionRange)
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const jarFileBasename = jarNameOrBoolean;
|
||||||
|
|
||||||
|
if (!jarFileBasename.endsWith(".jar")) {
|
||||||
|
console.log(
|
||||||
|
chalk.red(`Bad ${jarFileBasename} should end with '.jar'\n`)
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (jarFileBasename.includes("/") || jarFileBasename.includes("\\")) {
|
||||||
|
console.log(
|
||||||
|
chalk.red(
|
||||||
|
[
|
||||||
|
`Invalid ${jarFileBasename}. It's not supposed to be a path,`,
|
||||||
|
`Only the basename of the jar file is expected.`,
|
||||||
|
`Example: keycloak-theme.jar`
|
||||||
|
].join(" ")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
jarTargets.push({
|
||||||
|
keycloakVersionRange: keycloakVersionRange,
|
||||||
|
jarFileBasename: jarNameOrBoolean
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (jarTargets.length === 0) {
|
||||||
|
console.log(
|
||||||
|
chalk.red(
|
||||||
|
"All jar targets are disabled. Please enable at least one jar target."
|
||||||
|
)
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return jarTargets;
|
||||||
|
})(),
|
||||||
|
extensionJars: (buildForKeycloakMajorVersionNumber !== undefined
|
||||||
|
? []
|
||||||
|
: buildOptions.extensionJars ?? []
|
||||||
|
).map(urlOrPath => urlOrPathToDiscriminatingWrapper(urlOrPath)),
|
||||||
|
startKeycloakOptions: {
|
||||||
|
dockerImage: (() => {
|
||||||
|
if (buildOptions.startKeycloakOptions?.dockerImage === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [reference, tag, ...rest] =
|
||||||
|
buildOptions.startKeycloakOptions.dockerImage.split(":");
|
||||||
|
|
||||||
|
assert(
|
||||||
|
reference !== undefined && tag !== undefined && rest.length === 0,
|
||||||
|
`Invalid docker image: ${buildOptions.startKeycloakOptions.dockerImage}`
|
||||||
|
);
|
||||||
|
|
||||||
|
return { reference, tag };
|
||||||
|
})(),
|
||||||
|
dockerExtraArgs: buildOptions.startKeycloakOptions?.dockerExtraArgs ?? [],
|
||||||
|
keycloakExtraArgs: buildOptions.startKeycloakOptions?.keycloakExtraArgs ?? [],
|
||||||
|
extensionJars: [
|
||||||
|
...(buildForKeycloakMajorVersionNumber !== undefined
|
||||||
|
? buildOptions.extensionJars ?? []
|
||||||
|
: []),
|
||||||
|
...(buildOptions.startKeycloakOptions?.extensionJars ?? [])
|
||||||
|
]
|
||||||
|
.map(urlOrPath => urlOrPathToDiscriminatingWrapper(urlOrPath))
|
||||||
|
.reduce(...removeDuplicates<BuildContext["extensionJars"][number]>(same)),
|
||||||
|
realmJsonFilePath:
|
||||||
|
buildOptions.startKeycloakOptions?.realmJsonFilePath === undefined
|
||||||
|
? undefined
|
||||||
|
: getAbsoluteAndInOsFormatPath({
|
||||||
|
pathIsh: buildOptions.startKeycloakOptions.realmJsonFilePath,
|
||||||
|
cwd: projectDirPath
|
||||||
|
}),
|
||||||
|
port: buildOptions.startKeycloakOptions?.port
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
@ -1,313 +0,0 @@
|
|||||||
import { parse as urlParse } from "url";
|
|
||||||
import { join as pathJoin } from "path";
|
|
||||||
import { getAbsoluteAndInOsFormatPath } from "../tools/getAbsoluteAndInOsFormatPath";
|
|
||||||
import { getNpmWorkspaceRootDirPath } from "../tools/getNpmWorkspaceRootDirPath";
|
|
||||||
import type { CliCommandOptions } from "../main";
|
|
||||||
import { z } from "zod";
|
|
||||||
import * as fs from "fs";
|
|
||||||
import { assert } from "tsafe";
|
|
||||||
import * as child_process from "child_process";
|
|
||||||
import { vitePluginSubScriptEnvNames } from "./constants";
|
|
||||||
|
|
||||||
/** Consolidated build option gathered form CLI arguments and config in package.json */
|
|
||||||
export type BuildOptions = {
|
|
||||||
bundler: "vite" | "webpack";
|
|
||||||
themeVersion: string;
|
|
||||||
themeNames: string[];
|
|
||||||
extraThemeProperties: string[] | undefined;
|
|
||||||
groupId: string;
|
|
||||||
artifactId: string;
|
|
||||||
loginThemeResourcesFromKeycloakVersion: string;
|
|
||||||
reactAppRootDirPath: string;
|
|
||||||
// TODO: Remove from vite type
|
|
||||||
reactAppBuildDirPath: string;
|
|
||||||
/** Directory that keycloakify outputs to. Defaults to {cwd}/build_keycloak */
|
|
||||||
keycloakifyBuildDirPath: string;
|
|
||||||
publicDirPath: string;
|
|
||||||
cacheDirPath: string;
|
|
||||||
/** If your app is hosted under a subpath, it's the case in CRA if you have "homepage": "https://example.com/my-app" in your package.json
|
|
||||||
* In this case the urlPathname will be "/my-app/" */
|
|
||||||
urlPathname: string | undefined;
|
|
||||||
assetsDirPath: string;
|
|
||||||
npmWorkspaceRootDirPath: string;
|
|
||||||
kcContextExclusionsFtlCode: string | undefined;
|
|
||||||
environmentVariables: { name: string; default: string }[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type UserProvidedBuildOptions = {
|
|
||||||
themeName?: string | string[];
|
|
||||||
environmentVariables?: { name: string; default: string }[];
|
|
||||||
extraThemeProperties?: string[];
|
|
||||||
artifactId?: string;
|
|
||||||
groupId?: string;
|
|
||||||
loginThemeResourcesFromKeycloakVersion?: string;
|
|
||||||
keycloakifyBuildDirPath?: string;
|
|
||||||
kcContextExclusionsFtlCode?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ResolvedViteConfig = {
|
|
||||||
buildDir: string;
|
|
||||||
publicDir: string;
|
|
||||||
assetsDir: string;
|
|
||||||
urlPathname: string | undefined;
|
|
||||||
userProvidedBuildOptions: UserProvidedBuildOptions;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function readBuildOptions(params: {
|
|
||||||
cliCommandOptions: CliCommandOptions;
|
|
||||||
}): BuildOptions {
|
|
||||||
const { cliCommandOptions } = params;
|
|
||||||
|
|
||||||
const reactAppRootDirPath = (() => {
|
|
||||||
if (cliCommandOptions.reactAppRootDirPath === undefined) {
|
|
||||||
return process.cwd();
|
|
||||||
}
|
|
||||||
|
|
||||||
return getAbsoluteAndInOsFormatPath({
|
|
||||||
pathIsh: cliCommandOptions.reactAppRootDirPath,
|
|
||||||
cwd: process.cwd()
|
|
||||||
});
|
|
||||||
})();
|
|
||||||
|
|
||||||
const { resolvedViteConfig } = (() => {
|
|
||||||
if (
|
|
||||||
fs
|
|
||||||
.readdirSync(reactAppRootDirPath)
|
|
||||||
.find(fileBasename => fileBasename.startsWith("vite.config")) ===
|
|
||||||
undefined
|
|
||||||
) {
|
|
||||||
return { resolvedViteConfig: undefined };
|
|
||||||
}
|
|
||||||
|
|
||||||
const output = child_process
|
|
||||||
.execSync("npx vite", {
|
|
||||||
cwd: reactAppRootDirPath,
|
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
[vitePluginSubScriptEnvNames.resolveViteConfig]: "true"
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.toString("utf8");
|
|
||||||
|
|
||||||
assert(
|
|
||||||
output.includes(vitePluginSubScriptEnvNames.resolveViteConfig),
|
|
||||||
"Seems like the Keycloakify's Vite plugin is not installed."
|
|
||||||
);
|
|
||||||
|
|
||||||
const resolvedViteConfigStr = output
|
|
||||||
.split(vitePluginSubScriptEnvNames.resolveViteConfig)
|
|
||||||
.reverse()[0];
|
|
||||||
|
|
||||||
const resolvedViteConfig: ResolvedViteConfig = JSON.parse(resolvedViteConfigStr);
|
|
||||||
|
|
||||||
return { resolvedViteConfig };
|
|
||||||
})();
|
|
||||||
|
|
||||||
const parsedPackageJson = (() => {
|
|
||||||
type ParsedPackageJson = {
|
|
||||||
name: string;
|
|
||||||
version?: string;
|
|
||||||
homepage?: string;
|
|
||||||
keycloakify?: UserProvidedBuildOptions & {
|
|
||||||
reactAppBuildDirPath?: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const zParsedPackageJson = z.object({
|
|
||||||
name: z.string(),
|
|
||||||
version: z.string().optional(),
|
|
||||||
homepage: z.string().optional(),
|
|
||||||
keycloakify: z
|
|
||||||
.object({
|
|
||||||
extraThemeProperties: z.array(z.string()).optional(),
|
|
||||||
artifactId: z.string().optional(),
|
|
||||||
groupId: z.string().optional(),
|
|
||||||
loginThemeResourcesFromKeycloakVersion: z.string().optional(),
|
|
||||||
reactAppBuildDirPath: z.string().optional(),
|
|
||||||
keycloakifyBuildDirPath: z.string().optional(),
|
|
||||||
themeName: z.union([z.string(), z.array(z.string())]).optional()
|
|
||||||
})
|
|
||||||
.optional()
|
|
||||||
});
|
|
||||||
|
|
||||||
{
|
|
||||||
type Got = ReturnType<(typeof zParsedPackageJson)["parse"]>;
|
|
||||||
type Expected = ParsedPackageJson;
|
|
||||||
assert<Got extends Expected ? true : false>();
|
|
||||||
assert<Expected extends Got ? true : false>();
|
|
||||||
}
|
|
||||||
|
|
||||||
return zParsedPackageJson.parse(
|
|
||||||
JSON.parse(
|
|
||||||
fs
|
|
||||||
.readFileSync(pathJoin(reactAppRootDirPath, "package.json"))
|
|
||||||
.toString("utf8")
|
|
||||||
)
|
|
||||||
);
|
|
||||||
})();
|
|
||||||
|
|
||||||
const userProvidedBuildOptions: UserProvidedBuildOptions = {
|
|
||||||
...parsedPackageJson.keycloakify,
|
|
||||||
...resolvedViteConfig?.userProvidedBuildOptions
|
|
||||||
};
|
|
||||||
|
|
||||||
const themeNames = (() => {
|
|
||||||
if (userProvidedBuildOptions.themeName === undefined) {
|
|
||||||
return [
|
|
||||||
parsedPackageJson.name
|
|
||||||
.replace(/^@(.*)/, "$1")
|
|
||||||
.split("/")
|
|
||||||
.join("-")
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof userProvidedBuildOptions.themeName === "string") {
|
|
||||||
return [userProvidedBuildOptions.themeName];
|
|
||||||
}
|
|
||||||
|
|
||||||
return userProvidedBuildOptions.themeName;
|
|
||||||
})();
|
|
||||||
|
|
||||||
const reactAppBuildDirPath = (() => {
|
|
||||||
webpack: {
|
|
||||||
if (resolvedViteConfig !== undefined) {
|
|
||||||
break webpack;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (parsedPackageJson.keycloakify?.reactAppBuildDirPath !== undefined) {
|
|
||||||
return getAbsoluteAndInOsFormatPath({
|
|
||||||
pathIsh: parsedPackageJson.keycloakify.reactAppBuildDirPath,
|
|
||||||
cwd: reactAppRootDirPath
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return pathJoin(reactAppRootDirPath, "build");
|
|
||||||
}
|
|
||||||
|
|
||||||
return pathJoin(reactAppRootDirPath, resolvedViteConfig.buildDir);
|
|
||||||
})();
|
|
||||||
|
|
||||||
const { npmWorkspaceRootDirPath } = getNpmWorkspaceRootDirPath({
|
|
||||||
reactAppRootDirPath,
|
|
||||||
dependencyExpected: "keycloakify"
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
bundler: resolvedViteConfig !== undefined ? "vite" : "webpack",
|
|
||||||
themeVersion:
|
|
||||||
process.env.KEYCLOAKIFY_THEME_VERSION ?? parsedPackageJson.version ?? "0.0.0",
|
|
||||||
themeNames,
|
|
||||||
extraThemeProperties: userProvidedBuildOptions.extraThemeProperties,
|
|
||||||
groupId: (() => {
|
|
||||||
const fallbackGroupId = `${themeNames[0]}.keycloak`;
|
|
||||||
|
|
||||||
return (
|
|
||||||
process.env.KEYCLOAKIFY_GROUP_ID ??
|
|
||||||
userProvidedBuildOptions.groupId ??
|
|
||||||
(parsedPackageJson.homepage === undefined
|
|
||||||
? fallbackGroupId
|
|
||||||
: urlParse(parsedPackageJson.homepage)
|
|
||||||
.host?.replace(/:[0-9]+$/, "")
|
|
||||||
?.split(".")
|
|
||||||
.reverse()
|
|
||||||
.join(".") ?? fallbackGroupId) + ".keycloak"
|
|
||||||
);
|
|
||||||
})(),
|
|
||||||
artifactId:
|
|
||||||
process.env.KEYCLOAKIFY_ARTIFACT_ID ??
|
|
||||||
userProvidedBuildOptions.artifactId ??
|
|
||||||
`${themeNames[0]}-keycloak-theme`,
|
|
||||||
loginThemeResourcesFromKeycloakVersion:
|
|
||||||
userProvidedBuildOptions.loginThemeResourcesFromKeycloakVersion ?? "24.0.4",
|
|
||||||
reactAppRootDirPath,
|
|
||||||
reactAppBuildDirPath,
|
|
||||||
keycloakifyBuildDirPath: (() => {
|
|
||||||
if (userProvidedBuildOptions.keycloakifyBuildDirPath !== undefined) {
|
|
||||||
return getAbsoluteAndInOsFormatPath({
|
|
||||||
pathIsh: userProvidedBuildOptions.keycloakifyBuildDirPath,
|
|
||||||
cwd: reactAppRootDirPath
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return pathJoin(
|
|
||||||
reactAppRootDirPath,
|
|
||||||
resolvedViteConfig?.buildDir === undefined
|
|
||||||
? "build_keycloak"
|
|
||||||
: `${resolvedViteConfig.buildDir}_keycloak`
|
|
||||||
);
|
|
||||||
})(),
|
|
||||||
publicDirPath: (() => {
|
|
||||||
webpack: {
|
|
||||||
if (resolvedViteConfig !== undefined) {
|
|
||||||
break webpack;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (process.env.PUBLIC_DIR_PATH !== undefined) {
|
|
||||||
return getAbsoluteAndInOsFormatPath({
|
|
||||||
pathIsh: process.env.PUBLIC_DIR_PATH,
|
|
||||||
cwd: reactAppRootDirPath
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return pathJoin(reactAppRootDirPath, "public");
|
|
||||||
}
|
|
||||||
|
|
||||||
return pathJoin(reactAppRootDirPath, resolvedViteConfig.publicDir);
|
|
||||||
})(),
|
|
||||||
cacheDirPath: (() => {
|
|
||||||
const cacheDirPath = pathJoin(
|
|
||||||
(() => {
|
|
||||||
if (process.env.XDG_CACHE_HOME !== undefined) {
|
|
||||||
return getAbsoluteAndInOsFormatPath({
|
|
||||||
pathIsh: process.env.XDG_CACHE_HOME,
|
|
||||||
cwd: process.cwd()
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return pathJoin(npmWorkspaceRootDirPath, "node_modules", ".cache");
|
|
||||||
})(),
|
|
||||||
"keycloakify"
|
|
||||||
);
|
|
||||||
|
|
||||||
return cacheDirPath;
|
|
||||||
})(),
|
|
||||||
urlPathname: (() => {
|
|
||||||
webpack: {
|
|
||||||
if (resolvedViteConfig !== undefined) {
|
|
||||||
break webpack;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { homepage } = parsedPackageJson;
|
|
||||||
|
|
||||||
let url: URL | undefined = undefined;
|
|
||||||
|
|
||||||
if (homepage !== undefined) {
|
|
||||||
url = new URL(homepage);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url === undefined) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const out = url.pathname.replace(/([^/])$/, "$1/");
|
|
||||||
return out === "/" ? undefined : out;
|
|
||||||
}
|
|
||||||
|
|
||||||
return resolvedViteConfig.urlPathname;
|
|
||||||
})(),
|
|
||||||
assetsDirPath: (() => {
|
|
||||||
webpack: {
|
|
||||||
if (resolvedViteConfig !== undefined) {
|
|
||||||
break webpack;
|
|
||||||
}
|
|
||||||
|
|
||||||
return pathJoin(reactAppBuildDirPath, "static");
|
|
||||||
}
|
|
||||||
|
|
||||||
return pathJoin(reactAppBuildDirPath, resolvedViteConfig.assetsDir);
|
|
||||||
})(),
|
|
||||||
npmWorkspaceRootDirPath,
|
|
||||||
kcContextExclusionsFtlCode: userProvidedBuildOptions.kcContextExclusionsFtlCode,
|
|
||||||
environmentVariables: userProvidedBuildOptions.environmentVariables ?? []
|
|
||||||
};
|
|
||||||
}
|
|
@ -1,24 +1,22 @@
|
|||||||
export const nameOfTheGlobal = "kcContext";
|
export const KEYCLOAK_RESOURCES = "keycloak-resources";
|
||||||
export const nameOfTheLocalizationRealmOverridesUserProfileProperty =
|
export const RESOURCES_COMMON = "resources-common";
|
||||||
"__localizationRealmOverridesUserProfile";
|
export const LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1 = "21.1.2";
|
||||||
export const keycloak_resources = "keycloak-resources";
|
export const BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR = "dist";
|
||||||
export const resources_common = "resources-common";
|
|
||||||
export const lastKeycloakVersionWithAccountV1 = "21.1.2";
|
|
||||||
export const basenameOfTheKeycloakifyResourcesDir = "build";
|
|
||||||
|
|
||||||
export const themeTypes = ["login", "account"] as const;
|
export const THEME_TYPES = ["login", "account"] as const;
|
||||||
export const accountV1ThemeName = "account-v1";
|
export const ACCOUNT_V1_THEME_NAME = "account-v1";
|
||||||
|
|
||||||
export type ThemeType = (typeof themeTypes)[number];
|
export type ThemeType = (typeof THEME_TYPES)[number];
|
||||||
|
|
||||||
export const vitePluginSubScriptEnvNames = {
|
export const VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES = {
|
||||||
runPostBuildScript: "KEYCLOAKIFY_RUN_POST_BUILD_SCRIPT",
|
RUN_POST_BUILD_SCRIPT: "KEYCLOAKIFY_RUN_POST_BUILD_SCRIPT",
|
||||||
resolveViteConfig: "KEYCLOAKIFY_RESOLVE_VITE_CONFIG"
|
RESOLVE_VITE_CONFIG: "KEYCLOAKIFY_RESOLVE_VITE_CONFIG"
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export const skipBuildJarsEnvName = "KEYCLOAKIFY_SKIP_BUILD_JAR";
|
export const BUILD_FOR_KEYCLOAK_MAJOR_VERSION_ENV_NAME =
|
||||||
|
"KEYCLOAKIFY_BUILD_FOR_KEYCLOAK_MAJOR_VERSION";
|
||||||
|
|
||||||
export const loginThemePageIds = [
|
export const LOGIN_THEME_PAGE_IDS = [
|
||||||
"login.ftl",
|
"login.ftl",
|
||||||
"login-username.ftl",
|
"login-username.ftl",
|
||||||
"login-password.ftl",
|
"login-password.ftl",
|
||||||
@ -55,7 +53,7 @@ export const loginThemePageIds = [
|
|||||||
"webauthn-error.ftl"
|
"webauthn-error.ftl"
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const accountThemePageIds = [
|
export const ACCOUNT_THEME_PAGE_IDS = [
|
||||||
"password.ftl",
|
"password.ftl",
|
||||||
"account.ftl",
|
"account.ftl",
|
||||||
"sessions.ftl",
|
"sessions.ftl",
|
||||||
@ -65,7 +63,11 @@ export const accountThemePageIds = [
|
|||||||
"federatedIdentity.ftl"
|
"federatedIdentity.ftl"
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type LoginThemePageId = (typeof loginThemePageIds)[number];
|
export type LoginThemePageId = (typeof LOGIN_THEME_PAGE_IDS)[number];
|
||||||
export type AccountThemePageId = (typeof accountThemePageIds)[number];
|
export type AccountThemePageId = (typeof ACCOUNT_THEME_PAGE_IDS)[number];
|
||||||
|
|
||||||
export const containerName = "keycloak-keycloakify";
|
export const CONTAINER_NAME = "keycloak-keycloakify";
|
||||||
|
|
||||||
|
export const FALLBACK_LANGUAGE_TAG = "en";
|
||||||
|
|
||||||
|
export const LOGIN_THEME_RESOURCES_FROMkEYCLOAK_VERSION_DEFAULT = "24.0.4";
|
||||||
|
@ -1,32 +1,32 @@
|
|||||||
import {
|
import {
|
||||||
downloadKeycloakStaticResources,
|
downloadKeycloakStaticResources,
|
||||||
type BuildOptionsLike as BuildOptionsLike_downloadKeycloakStaticResources
|
type BuildContextLike as BuildContextLike_downloadKeycloakStaticResources
|
||||||
} from "./downloadKeycloakStaticResources";
|
} from "./downloadKeycloakStaticResources";
|
||||||
import { join as pathJoin, relative as pathRelative } from "path";
|
import { join as pathJoin, relative as pathRelative } from "path";
|
||||||
import {
|
import {
|
||||||
themeTypes,
|
THEME_TYPES,
|
||||||
keycloak_resources,
|
KEYCLOAK_RESOURCES,
|
||||||
lastKeycloakVersionWithAccountV1
|
LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1
|
||||||
} from "../shared/constants";
|
} from "../shared/constants";
|
||||||
import { readThisNpmPackageVersion } from "../tools/readThisNpmPackageVersion";
|
import { readThisNpmPackageVersion } from "../tools/readThisNpmPackageVersion";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { rmSync } from "../tools/fs.rmSync";
|
import { rmSync } from "../tools/fs.rmSync";
|
||||||
import type { BuildOptions } from "./buildOptions";
|
import type { BuildContext } from "./buildContext";
|
||||||
|
|
||||||
export type BuildOptionsLike = BuildOptionsLike_downloadKeycloakStaticResources & {
|
export type BuildContextLike = BuildContextLike_downloadKeycloakStaticResources & {
|
||||||
loginThemeResourcesFromKeycloakVersion: string;
|
loginThemeResourcesFromKeycloakVersion: string;
|
||||||
publicDirPath: string;
|
publicDirPath: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export async function copyKeycloakResourcesToPublic(params: {
|
export async function copyKeycloakResourcesToPublic(params: {
|
||||||
buildOptions: BuildOptionsLike;
|
buildContext: BuildContextLike;
|
||||||
}) {
|
}) {
|
||||||
const { buildOptions } = params;
|
const { buildContext } = params;
|
||||||
|
|
||||||
const destDirPath = pathJoin(buildOptions.publicDirPath, keycloak_resources);
|
const destDirPath = pathJoin(buildContext.publicDirPath, KEYCLOAK_RESOURCES);
|
||||||
|
|
||||||
const keycloakifyBuildinfoFilePath = pathJoin(destDirPath, "keycloakify.buildinfo");
|
const keycloakifyBuildinfoFilePath = pathJoin(destDirPath, "keycloakify.buildinfo");
|
||||||
|
|
||||||
@ -34,13 +34,10 @@ export async function copyKeycloakResourcesToPublic(params: {
|
|||||||
{
|
{
|
||||||
destDirPath,
|
destDirPath,
|
||||||
keycloakifyVersion: readThisNpmPackageVersion(),
|
keycloakifyVersion: readThisNpmPackageVersion(),
|
||||||
buildOptions: {
|
buildContext: {
|
||||||
loginThemeResourcesFromKeycloakVersion: readThisNpmPackageVersion(),
|
loginThemeResourcesFromKeycloakVersion: readThisNpmPackageVersion(),
|
||||||
cacheDirPath: pathRelative(destDirPath, buildOptions.cacheDirPath),
|
cacheDirPath: pathRelative(destDirPath, buildContext.cacheDirPath),
|
||||||
npmWorkspaceRootDirPath: pathRelative(
|
fetchOptions: buildContext.fetchOptions
|
||||||
destDirPath,
|
|
||||||
buildOptions.npmWorkspaceRootDirPath
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
null,
|
null,
|
||||||
@ -69,19 +66,19 @@ export async function copyKeycloakResourcesToPublic(params: {
|
|||||||
|
|
||||||
fs.writeFileSync(pathJoin(destDirPath, ".gitignore"), Buffer.from("*", "utf8"));
|
fs.writeFileSync(pathJoin(destDirPath, ".gitignore"), Buffer.from("*", "utf8"));
|
||||||
|
|
||||||
for (const themeType of themeTypes) {
|
for (const themeType of THEME_TYPES) {
|
||||||
await downloadKeycloakStaticResources({
|
await downloadKeycloakStaticResources({
|
||||||
keycloakVersion: (() => {
|
keycloakVersion: (() => {
|
||||||
switch (themeType) {
|
switch (themeType) {
|
||||||
case "login":
|
case "login":
|
||||||
return buildOptions.loginThemeResourcesFromKeycloakVersion;
|
return buildContext.loginThemeResourcesFromKeycloakVersion;
|
||||||
case "account":
|
case "account":
|
||||||
return lastKeycloakVersionWithAccountV1;
|
return LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1;
|
||||||
}
|
}
|
||||||
})(),
|
})(),
|
||||||
themeType,
|
themeType,
|
||||||
themeDirPath: destDirPath,
|
themeDirPath: destDirPath,
|
||||||
buildOptions
|
buildContext
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,44 +1,41 @@
|
|||||||
import { join as pathJoin, relative as pathRelative } from "path";
|
import { join as pathJoin, relative as pathRelative } from "path";
|
||||||
import { type BuildOptions } from "./buildOptions";
|
import { type BuildContext } from "./buildContext";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import { lastKeycloakVersionWithAccountV1 } from "./constants";
|
import { LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1 } from "./constants";
|
||||||
import { downloadAndExtractArchive } from "../tools/downloadAndExtractArchive";
|
import { downloadAndExtractArchive } from "../tools/downloadAndExtractArchive";
|
||||||
import { isInside } from "../tools/isInside";
|
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
export type BuildContextLike = {
|
||||||
cacheDirPath: string;
|
cacheDirPath: string;
|
||||||
npmWorkspaceRootDirPath: string;
|
fetchOptions: BuildContext["fetchOptions"];
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export async function downloadKeycloakDefaultTheme(params: {
|
export async function downloadKeycloakDefaultTheme(params: {
|
||||||
keycloakVersion: string;
|
keycloakVersion: string;
|
||||||
buildOptions: BuildOptionsLike;
|
buildContext: BuildContextLike;
|
||||||
}): Promise<{ defaultThemeDirPath: string }> {
|
}): Promise<{ defaultThemeDirPath: string }> {
|
||||||
const { keycloakVersion, buildOptions } = params;
|
const { keycloakVersion, buildContext } = params;
|
||||||
|
|
||||||
|
let kcNodeModulesKeepFilePaths: Set<string> | undefined = undefined;
|
||||||
|
let kcNodeModulesKeepFilePaths_lastAccountV1: Set<string> | undefined = undefined;
|
||||||
|
|
||||||
const { extractedDirPath } = await downloadAndExtractArchive({
|
const { extractedDirPath } = await downloadAndExtractArchive({
|
||||||
url: `https://repo1.maven.org/maven2/org/keycloak/keycloak-themes/${keycloakVersion}/keycloak-themes-${keycloakVersion}.jar`,
|
url: `https://repo1.maven.org/maven2/org/keycloak/keycloak-themes/${keycloakVersion}/keycloak-themes-${keycloakVersion}.jar`,
|
||||||
cacheDirPath: buildOptions.cacheDirPath,
|
cacheDirPath: buildContext.cacheDirPath,
|
||||||
npmWorkspaceRootDirPath: buildOptions.npmWorkspaceRootDirPath,
|
fetchOptions: buildContext.fetchOptions,
|
||||||
uniqueIdOfOnOnArchiveFile: "downloadKeycloakDefaultTheme",
|
uniqueIdOfOnArchiveFile: "downloadKeycloakDefaultTheme",
|
||||||
onArchiveFile: async params => {
|
onArchiveFile: async params => {
|
||||||
if (!isInside({ dirPath: "theme", filePath: params.fileRelativePath })) {
|
const fileRelativePath = pathRelative("theme", params.fileRelativePath);
|
||||||
|
|
||||||
|
if (fileRelativePath.startsWith("..")) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { readFile, writeFile } = params;
|
const { readFile, writeFile } = params;
|
||||||
|
|
||||||
const fileRelativePath = pathRelative("theme", params.fileRelativePath);
|
|
||||||
|
|
||||||
skip_keycloak_v2: {
|
skip_keycloak_v2: {
|
||||||
if (
|
if (!fileRelativePath.startsWith(pathJoin("keycloak.v2"))) {
|
||||||
!isInside({
|
|
||||||
dirPath: pathJoin("keycloak.v2"),
|
|
||||||
filePath: fileRelativePath
|
|
||||||
})
|
|
||||||
) {
|
|
||||||
break skip_keycloak_v2;
|
break skip_keycloak_v2;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -46,10 +43,109 @@ export async function downloadKeycloakDefaultTheme(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
last_account_v1_transformations: {
|
last_account_v1_transformations: {
|
||||||
if (lastKeycloakVersionWithAccountV1 !== keycloakVersion) {
|
if (LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1 !== keycloakVersion) {
|
||||||
break last_account_v1_transformations;
|
break last_account_v1_transformations;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
skip_web_modules: {
|
||||||
|
if (
|
||||||
|
!fileRelativePath.startsWith(
|
||||||
|
pathJoin("keycloak", "common", "resources", "web_modules")
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
break skip_web_modules;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
skip_lib: {
|
||||||
|
if (
|
||||||
|
!fileRelativePath.startsWith(
|
||||||
|
pathJoin("keycloak", "common", "resources", "lib")
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
break skip_lib;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
skip_node_modules: {
|
||||||
|
const nodeModulesRelativeDirPath = pathJoin(
|
||||||
|
"keycloak",
|
||||||
|
"common",
|
||||||
|
"resources",
|
||||||
|
"node_modules"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!fileRelativePath.startsWith(nodeModulesRelativeDirPath)) {
|
||||||
|
break skip_node_modules;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kcNodeModulesKeepFilePaths_lastAccountV1 === undefined) {
|
||||||
|
kcNodeModulesKeepFilePaths_lastAccountV1 = new Set([
|
||||||
|
pathJoin("patternfly", "dist", "css", "patternfly.min.css"),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"css",
|
||||||
|
"patternfly-additions.min.css"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Regular-webfont.woff2"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Bold-webfont.woff2"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Light-webfont.woff2"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Semibold-webfont.woff2"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"PatternFlyIcons-webfont.ttf"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"PatternFlyIcons-webfont.woff"
|
||||||
|
)
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileRelativeToNodeModulesPath = fileRelativePath.substring(
|
||||||
|
nodeModulesRelativeDirPath.length + 1
|
||||||
|
);
|
||||||
|
|
||||||
|
if (
|
||||||
|
kcNodeModulesKeepFilePaths_lastAccountV1.has(
|
||||||
|
fileRelativeToNodeModulesPath
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
break skip_node_modules;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
patch_account_css: {
|
patch_account_css: {
|
||||||
if (
|
if (
|
||||||
fileRelativePath !==
|
fileRelativePath !==
|
||||||
@ -70,69 +166,6 @@ export async function downloadKeycloakDefaultTheme(params: {
|
|||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
skip_web_modules: {
|
|
||||||
if (
|
|
||||||
!isInside({
|
|
||||||
dirPath: pathJoin(
|
|
||||||
"keycloak",
|
|
||||||
"common",
|
|
||||||
"resources",
|
|
||||||
"web_modules"
|
|
||||||
),
|
|
||||||
filePath: fileRelativePath
|
|
||||||
})
|
|
||||||
) {
|
|
||||||
break skip_web_modules;
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
skip_unused_node_modules: {
|
|
||||||
const nodeModulesDirPath = pathJoin(
|
|
||||||
"keycloak",
|
|
||||||
"common",
|
|
||||||
"resources",
|
|
||||||
"node_modules"
|
|
||||||
);
|
|
||||||
|
|
||||||
if (
|
|
||||||
!isInside({
|
|
||||||
dirPath: nodeModulesDirPath,
|
|
||||||
filePath: fileRelativePath
|
|
||||||
})
|
|
||||||
) {
|
|
||||||
break skip_unused_node_modules;
|
|
||||||
}
|
|
||||||
|
|
||||||
const toKeepPrefixes = [
|
|
||||||
...[
|
|
||||||
"patternfly.min.css",
|
|
||||||
"patternfly-additions.min.css",
|
|
||||||
"patternfly-additions.min.css"
|
|
||||||
].map(fileBasename =>
|
|
||||||
pathJoin(
|
|
||||||
nodeModulesDirPath,
|
|
||||||
"patternfly",
|
|
||||||
"dist",
|
|
||||||
"css",
|
|
||||||
fileBasename
|
|
||||||
)
|
|
||||||
),
|
|
||||||
pathJoin(nodeModulesDirPath, "patternfly", "dist", "fonts")
|
|
||||||
];
|
|
||||||
|
|
||||||
if (
|
|
||||||
toKeepPrefixes.find(prefix =>
|
|
||||||
fileRelativePath.startsWith(prefix)
|
|
||||||
) !== undefined
|
|
||||||
) {
|
|
||||||
break skip_unused_node_modules;
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
skip_unused_resources: {
|
skip_unused_resources: {
|
||||||
@ -140,61 +173,118 @@ export async function downloadKeycloakDefaultTheme(params: {
|
|||||||
break skip_unused_resources;
|
break skip_unused_resources;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const dirBasename of [
|
skip_node_modules: {
|
||||||
"@patternfly-v5",
|
const nodeModulesRelativeDirPath = pathJoin(
|
||||||
"@rollup",
|
"keycloak",
|
||||||
"rollup",
|
"common",
|
||||||
"react",
|
"resources",
|
||||||
"react-dom",
|
"node_modules"
|
||||||
"shx",
|
);
|
||||||
".pnpm"
|
|
||||||
]) {
|
if (!fileRelativePath.startsWith(nodeModulesRelativeDirPath)) {
|
||||||
if (
|
break skip_node_modules;
|
||||||
isInside({
|
|
||||||
dirPath: pathJoin(
|
|
||||||
"keycloak",
|
|
||||||
"common",
|
|
||||||
"resources",
|
|
||||||
"node_modules",
|
|
||||||
dirBasename
|
|
||||||
),
|
|
||||||
filePath: fileRelativePath
|
|
||||||
})
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (kcNodeModulesKeepFilePaths === undefined) {
|
||||||
|
kcNodeModulesKeepFilePaths = new Set([
|
||||||
|
pathJoin("@patternfly", "patternfly", "patternfly.min.css"),
|
||||||
|
pathJoin("patternfly", "dist", "css", "patternfly.min.css"),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"css",
|
||||||
|
"patternfly-additions.min.css"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Regular-webfont.woff2"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Light-webfont.woff2"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Bold-webfont.woff2"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Bold-webfont.woff"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Bold-webfont.ttf"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"fontawesome-webfont.woff2"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"PatternFlyIcons-webfont.ttf"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"PatternFlyIcons-webfont.woff"
|
||||||
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Semibold-webfont.woff2"
|
||||||
|
),
|
||||||
|
pathJoin("patternfly", "dist", "img", "bg-login.jpg"),
|
||||||
|
pathJoin("jquery", "dist", "jquery.min.js")
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileRelativeToNodeModulesPath = fileRelativePath.substring(
|
||||||
|
nodeModulesRelativeDirPath.length + 1
|
||||||
|
);
|
||||||
|
|
||||||
|
if (kcNodeModulesKeepFilePaths.has(fileRelativeToNodeModulesPath)) {
|
||||||
|
break skip_node_modules;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const dirBasename of ["react", "react-dom"]) {
|
skip_vendor: {
|
||||||
if (
|
if (
|
||||||
isInside({
|
!fileRelativePath.startsWith(
|
||||||
dirPath: pathJoin(
|
pathJoin("keycloak", "common", "resources", "vendor")
|
||||||
"keycloak",
|
)
|
||||||
"common",
|
|
||||||
"resources",
|
|
||||||
"vendor",
|
|
||||||
dirBasename
|
|
||||||
),
|
|
||||||
filePath: fileRelativePath
|
|
||||||
})
|
|
||||||
) {
|
) {
|
||||||
return;
|
break skip_vendor;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
skip_rollup_config: {
|
||||||
isInside({
|
if (
|
||||||
dirPath: pathJoin(
|
fileRelativePath !==
|
||||||
"keycloak",
|
pathJoin("keycloak", "common", "resources", "rollup.config.js")
|
||||||
"common",
|
) {
|
||||||
"resources",
|
break skip_rollup_config;
|
||||||
"node_modules",
|
}
|
||||||
"@patternfly",
|
|
||||||
"react-core"
|
|
||||||
),
|
|
||||||
filePath: fileRelativePath
|
|
||||||
})
|
|
||||||
) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,28 +2,28 @@ import { transformCodebase } from "../tools/transformCodebase";
|
|||||||
import { join as pathJoin } from "path";
|
import { join as pathJoin } from "path";
|
||||||
import {
|
import {
|
||||||
downloadKeycloakDefaultTheme,
|
downloadKeycloakDefaultTheme,
|
||||||
type BuildOptionsLike as BuildOptionsLike_downloadKeycloakDefaultTheme
|
type BuildContextLike as BuildContextLike_downloadKeycloakDefaultTheme
|
||||||
} from "./downloadKeycloakDefaultTheme";
|
} from "./downloadKeycloakDefaultTheme";
|
||||||
import { resources_common, type ThemeType } from "./constants";
|
import { RESOURCES_COMMON, type ThemeType } from "./constants";
|
||||||
import type { BuildOptions } from "./buildOptions";
|
import type { BuildContext } from "./buildContext";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import { existsAsync } from "../tools/fs.existsAsync";
|
import { existsAsync } from "../tools/fs.existsAsync";
|
||||||
|
|
||||||
export type BuildOptionsLike = BuildOptionsLike_downloadKeycloakDefaultTheme & {};
|
export type BuildContextLike = BuildContextLike_downloadKeycloakDefaultTheme & {};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export async function downloadKeycloakStaticResources(params: {
|
export async function downloadKeycloakStaticResources(params: {
|
||||||
themeType: ThemeType;
|
themeType: ThemeType;
|
||||||
themeDirPath: string;
|
themeDirPath: string;
|
||||||
keycloakVersion: string;
|
keycloakVersion: string;
|
||||||
buildOptions: BuildOptionsLike;
|
buildContext: BuildContextLike;
|
||||||
}) {
|
}) {
|
||||||
const { themeType, themeDirPath, keycloakVersion, buildOptions } = params;
|
const { themeType, themeDirPath, keycloakVersion, buildContext } = params;
|
||||||
|
|
||||||
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
||||||
keycloakVersion,
|
keycloakVersion,
|
||||||
buildOptions
|
buildContext
|
||||||
});
|
});
|
||||||
|
|
||||||
const resourcesDirPath = pathJoin(themeDirPath, themeType, "resources");
|
const resourcesDirPath = pathJoin(themeDirPath, themeType, "resources");
|
||||||
@ -48,6 +48,6 @@ export async function downloadKeycloakStaticResources(params: {
|
|||||||
|
|
||||||
transformCodebase({
|
transformCodebase({
|
||||||
srcDirPath: pathJoin(defaultThemeDirPath, "keycloak", "common", "resources"),
|
srcDirPath: pathJoin(defaultThemeDirPath, "keycloak", "common", "resources"),
|
||||||
destDirPath: pathJoin(resourcesDirPath, resources_common)
|
destDirPath: pathJoin(resourcesDirPath, RESOURCES_COMMON)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,61 +1,175 @@
|
|||||||
import { assert } from "tsafe/assert";
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
import type { BuildOptions } from "./buildOptions";
|
import { id } from "tsafe/id";
|
||||||
import { getThemeSrcDirPath } from "./getThemeSrcDirPath";
|
import type { BuildContext } from "./buildContext";
|
||||||
import * as fs from "fs/promises";
|
import * as fs from "fs/promises";
|
||||||
import { join as pathJoin } from "path";
|
import { join as pathJoin } from "path";
|
||||||
|
import { existsAsync } from "../tools/fs.existsAsync";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
export type BuildOptionsLike = {
|
export type BuildContextLike = {
|
||||||
reactAppRootDirPath: string;
|
projectDirPath: string;
|
||||||
themeNames: string[];
|
themeNames: string[];
|
||||||
environmentVariables: { name: string; default: string }[];
|
environmentVariables: { name: string; default: string }[];
|
||||||
|
themeSrcDirPath: string;
|
||||||
|
implementedThemeTypes: Pick<
|
||||||
|
BuildContext["implementedThemeTypes"],
|
||||||
|
"login" | "account"
|
||||||
|
>;
|
||||||
|
packageJsonFilePath: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildOptions extends BuildOptionsLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export async function generateKcGenTs(params: {
|
export async function generateKcGenTs(params: {
|
||||||
buildOptions: BuildOptionsLike;
|
buildContext: BuildContextLike;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
const { buildOptions } = params;
|
const { buildContext } = params;
|
||||||
|
|
||||||
const { themeSrcDirPath } = getThemeSrcDirPath({
|
const isReactProject: boolean = await (async () => {
|
||||||
reactAppRootDirPath: buildOptions.reactAppRootDirPath
|
const parsedPackageJson = await (async () => {
|
||||||
});
|
type ParsedPackageJson = {
|
||||||
|
dependencies?: Record<string, string>;
|
||||||
|
devDependencies?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
await fs.writeFile(
|
const zParsedPackageJson = (() => {
|
||||||
pathJoin(themeSrcDirPath, "kc.gen.ts"),
|
type TargetType = ParsedPackageJson;
|
||||||
Buffer.from(
|
|
||||||
[
|
const zTargetType = z.object({
|
||||||
`/* prettier-ignore-start */`,
|
dependencies: z.record(z.string()).optional(),
|
||||||
``,
|
devDependencies: z.record(z.string()).optional()
|
||||||
`/* eslint-disable */`,
|
});
|
||||||
``,
|
|
||||||
`// @ts-nocheck`,
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
``,
|
|
||||||
`// noinspection JSUnusedGlobalSymbols`,
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
``,
|
})();
|
||||||
`// This file is auto-generated by Keycloakify`,
|
|
||||||
``,
|
return zParsedPackageJson.parse(
|
||||||
`export type ThemeName = ${buildOptions.themeNames.map(themeName => `"${themeName}"`).join(" | ")};`,
|
JSON.parse(
|
||||||
``,
|
(await fs.readFile(buildContext.packageJsonFilePath)).toString("utf8")
|
||||||
`export const themeNames: ThemeName[] = [${buildOptions.themeNames.map(themeName => `"${themeName}"`).join(", ")}];`,
|
)
|
||||||
``,
|
);
|
||||||
`export type KcEnvName = ${buildOptions.environmentVariables.length === 0 ? "never" : buildOptions.environmentVariables.map(({ name }) => `"${name}"`).join(" | ")};`,
|
})();
|
||||||
``,
|
|
||||||
`export const KcEnvNames: KcEnvName[] = [${buildOptions.environmentVariables.map(({ name }) => `"${name}"`).join(", ")}];`,
|
return (
|
||||||
``,
|
{
|
||||||
`export const kcEnvDefaults: Record<KcEnvName, string> = ${JSON.stringify(
|
...parsedPackageJson.dependencies,
|
||||||
Object.fromEntries(
|
...parsedPackageJson.devDependencies
|
||||||
buildOptions.environmentVariables.map(
|
}.react !== undefined
|
||||||
({ name, default: defaultValue }) => [name, defaultValue]
|
);
|
||||||
)
|
})();
|
||||||
),
|
|
||||||
null,
|
const filePath = pathJoin(
|
||||||
2
|
buildContext.themeSrcDirPath,
|
||||||
)};`,
|
`kc.gen.ts${isReactProject ? "x" : ""}`
|
||||||
``,
|
|
||||||
`/* prettier-ignore-end */`
|
|
||||||
].join("\n"),
|
|
||||||
"utf8"
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
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`,
|
||||||
|
``,
|
||||||
|
isReactProject && `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;`,
|
||||||
|
` }`,
|
||||||
|
`}`,
|
||||||
|
``,
|
||||||
|
...(!isReactProject
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
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: {
|
||||||
|
if (!isReactProject) {
|
||||||
|
break delete_legacy_file;
|
||||||
|
}
|
||||||
|
|
||||||
|
const legacyFilePath = filePath.replace(/tsx$/, "ts");
|
||||||
|
|
||||||
|
if (!(await existsAsync(legacyFilePath))) {
|
||||||
|
break delete_legacy_file;
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.unlink(legacyFilePath);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,11 +0,0 @@
|
|||||||
import type { KeycloakVersionRange } from "./KeycloakVersionRange";
|
|
||||||
|
|
||||||
export function getJarFileBasename(params: {
|
|
||||||
keycloakVersionRange: KeycloakVersionRange;
|
|
||||||
}) {
|
|
||||||
const { keycloakVersionRange } = params;
|
|
||||||
|
|
||||||
const jarFileBasename = `keycloak-theme-for-kc-${keycloakVersionRange}.jar`;
|
|
||||||
|
|
||||||
return { jarFileBasename };
|
|
||||||
}
|
|
201
src/bin/shared/getLatestsSemVersionedTag.ts
Normal file
201
src/bin/shared/getLatestsSemVersionedTag.ts
Normal file
@ -0,0 +1,201 @@
|
|||||||
|
import { getLatestsSemVersionedTagFactory } from "../tools/octokit-addons/getLatestsSemVersionedTag";
|
||||||
|
import { Octokit } from "@octokit/rest";
|
||||||
|
import type { ReturnType } from "tsafe";
|
||||||
|
import type { Param0 } from "tsafe";
|
||||||
|
import { join as pathJoin, dirname as pathDirname } from "path";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
|
import type { SemVer } from "../tools/SemVer";
|
||||||
|
import { same } from "evt/tools/inDepth/same";
|
||||||
|
import type { BuildContext } from "./buildContext";
|
||||||
|
import fetch from "make-fetch-happen";
|
||||||
|
|
||||||
|
type GetLatestsSemVersionedTag = ReturnType<
|
||||||
|
typeof getLatestsSemVersionedTagFactory
|
||||||
|
>["getLatestsSemVersionedTag"];
|
||||||
|
|
||||||
|
type Params = Param0<GetLatestsSemVersionedTag>;
|
||||||
|
type R = ReturnType<GetLatestsSemVersionedTag>;
|
||||||
|
|
||||||
|
let getLatestsSemVersionedTag_stateless: GetLatestsSemVersionedTag | undefined =
|
||||||
|
undefined;
|
||||||
|
|
||||||
|
const CACHE_VERSION = 1;
|
||||||
|
|
||||||
|
type Cache = {
|
||||||
|
version: typeof CACHE_VERSION;
|
||||||
|
entries: {
|
||||||
|
time: number;
|
||||||
|
params: Params;
|
||||||
|
result: R;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BuildContextLike = {
|
||||||
|
cacheDirPath: string;
|
||||||
|
fetchOptions: BuildContext["fetchOptions"];
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
|
export async function getLatestsSemVersionedTag({
|
||||||
|
buildContext,
|
||||||
|
...params
|
||||||
|
}: Params & {
|
||||||
|
buildContext: BuildContextLike;
|
||||||
|
}): Promise<R> {
|
||||||
|
const cacheFilePath = pathJoin(
|
||||||
|
buildContext.cacheDirPath,
|
||||||
|
"latest-sem-versioned-tags.json"
|
||||||
|
);
|
||||||
|
|
||||||
|
const cacheLookupResult = (() => {
|
||||||
|
const getResult_currentCache = (currentCacheEntries: Cache["entries"]) => ({
|
||||||
|
hasCachedResult: false as const,
|
||||||
|
currentCache: {
|
||||||
|
version: CACHE_VERSION,
|
||||||
|
entries: currentCacheEntries
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!fs.existsSync(cacheFilePath)) {
|
||||||
|
return getResult_currentCache([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let cache_json;
|
||||||
|
|
||||||
|
try {
|
||||||
|
cache_json = fs.readFileSync(cacheFilePath).toString("utf8");
|
||||||
|
} catch {
|
||||||
|
return getResult_currentCache([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let cache_json_parsed: unknown;
|
||||||
|
|
||||||
|
try {
|
||||||
|
cache_json_parsed = JSON.parse(cache_json);
|
||||||
|
} catch {
|
||||||
|
return getResult_currentCache([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const zSemVer = (() => {
|
||||||
|
type TargetType = SemVer;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
major: z.number(),
|
||||||
|
minor: z.number(),
|
||||||
|
patch: z.number(),
|
||||||
|
rc: z.number().optional(),
|
||||||
|
parsedFrom: z.string()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zCache = (() => {
|
||||||
|
type TargetType = Cache;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
version: z.literal(CACHE_VERSION),
|
||||||
|
entries: z.array(
|
||||||
|
z.object({
|
||||||
|
time: z.number(),
|
||||||
|
params: z.object({
|
||||||
|
owner: z.string(),
|
||||||
|
repo: z.string(),
|
||||||
|
count: z.number(),
|
||||||
|
doIgnoreReleaseCandidates: z.boolean()
|
||||||
|
}),
|
||||||
|
result: z.array(
|
||||||
|
z.object({
|
||||||
|
tag: z.string(),
|
||||||
|
version: zSemVer
|
||||||
|
})
|
||||||
|
)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
let cache: Cache;
|
||||||
|
|
||||||
|
try {
|
||||||
|
cache = zCache.parse(cache_json_parsed);
|
||||||
|
} catch {
|
||||||
|
return getResult_currentCache([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cacheEntry = cache.entries.find(e => same(e.params, params));
|
||||||
|
|
||||||
|
if (cacheEntry === undefined) {
|
||||||
|
return getResult_currentCache(cache.entries);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Date.now() - cacheEntry.time > 3_600_000) {
|
||||||
|
return getResult_currentCache(cache.entries.filter(e => e !== cacheEntry));
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
hasCachedResult: true as const,
|
||||||
|
cachedResult: cacheEntry.result
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (cacheLookupResult.hasCachedResult) {
|
||||||
|
return cacheLookupResult.cachedResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { currentCache } = cacheLookupResult;
|
||||||
|
|
||||||
|
getLatestsSemVersionedTag_stateless ??= (() => {
|
||||||
|
const octokit = (() => {
|
||||||
|
const githubToken = process.env.GITHUB_TOKEN;
|
||||||
|
|
||||||
|
const octokit = new Octokit({
|
||||||
|
...(githubToken === undefined ? {} : { auth: githubToken }),
|
||||||
|
request: {
|
||||||
|
fetch: (url: string, options?: any) =>
|
||||||
|
fetch(url, {
|
||||||
|
...options,
|
||||||
|
...buildContext.fetchOptions
|
||||||
|
})
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return octokit;
|
||||||
|
})();
|
||||||
|
|
||||||
|
const { getLatestsSemVersionedTag } = getLatestsSemVersionedTagFactory({
|
||||||
|
octokit
|
||||||
|
});
|
||||||
|
|
||||||
|
return getLatestsSemVersionedTag;
|
||||||
|
})();
|
||||||
|
|
||||||
|
const result = await getLatestsSemVersionedTag_stateless(params);
|
||||||
|
|
||||||
|
currentCache.entries.push({
|
||||||
|
time: Date.now(),
|
||||||
|
params,
|
||||||
|
result
|
||||||
|
});
|
||||||
|
|
||||||
|
{
|
||||||
|
const dirPath = pathDirname(cacheFilePath);
|
||||||
|
|
||||||
|
if (!fs.existsSync(dirPath)) {
|
||||||
|
fs.mkdirSync(dirPath, { recursive: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(cacheFilePath, JSON.stringify(currentCache, null, 2));
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
@ -1,50 +0,0 @@
|
|||||||
import * as fs from "fs";
|
|
||||||
import { exclude } from "tsafe";
|
|
||||||
import { crawl } from "../tools/crawl";
|
|
||||||
import { join as pathJoin } from "path";
|
|
||||||
import { themeTypes } from "./constants";
|
|
||||||
|
|
||||||
const themeSrcDirBasenames = ["keycloak-theme", "keycloak_theme"];
|
|
||||||
|
|
||||||
/** Can't catch error, if the directory isn't found, this function will just exit the process with an error message. */
|
|
||||||
export function getThemeSrcDirPath(params: { reactAppRootDirPath: string }) {
|
|
||||||
const { reactAppRootDirPath } = params;
|
|
||||||
|
|
||||||
const srcDirPath = pathJoin(reactAppRootDirPath, "src");
|
|
||||||
|
|
||||||
const themeSrcDirPath: string | undefined = crawl({
|
|
||||||
dirPath: srcDirPath,
|
|
||||||
returnedPathsType: "relative to dirPath"
|
|
||||||
})
|
|
||||||
.map(fileRelativePath => {
|
|
||||||
for (const themeSrcDirBasename of themeSrcDirBasenames) {
|
|
||||||
const split = fileRelativePath.split(themeSrcDirBasename);
|
|
||||||
if (split.length === 2) {
|
|
||||||
return pathJoin(srcDirPath, split[0] + themeSrcDirBasename);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
})
|
|
||||||
.filter(exclude(undefined))[0];
|
|
||||||
|
|
||||||
if (themeSrcDirPath !== undefined) {
|
|
||||||
return { themeSrcDirPath };
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const themeType of [...themeTypes, "email"]) {
|
|
||||||
if (!fs.existsSync(pathJoin(srcDirPath, themeType))) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
return { themeSrcDirPath: srcDirPath };
|
|
||||||
}
|
|
||||||
|
|
||||||
console.error(
|
|
||||||
[
|
|
||||||
"Can't locate your theme source directory. It should be either: ",
|
|
||||||
"src/ or src/keycloak-theme or src/keycloak_theme.",
|
|
||||||
"Example in the starter: https://github.com/keycloakify/keycloakify-starter/tree/main/src/keycloak-theme"
|
|
||||||
].join("\n")
|
|
||||||
);
|
|
||||||
|
|
||||||
process.exit(-1);
|
|
||||||
}
|
|
@ -6,56 +6,35 @@ export type MetaInfKeycloakTheme = {
|
|||||||
themes: { name: string; types: (ThemeType | "email")[] }[];
|
themes: { name: string; types: (ThemeType | "email")[] }[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export function getMetaInfKeycloakThemesJsonFilePath(params: {
|
|
||||||
keycloakifyBuildDirPath: string;
|
|
||||||
}) {
|
|
||||||
const { keycloakifyBuildDirPath } = params;
|
|
||||||
|
|
||||||
return pathJoin(
|
|
||||||
keycloakifyBuildDirPath === "." ? "" : keycloakifyBuildDirPath,
|
|
||||||
"src",
|
|
||||||
"main",
|
|
||||||
"resources",
|
|
||||||
"META-INF",
|
|
||||||
"keycloak-themes.json"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readMetaInfKeycloakThemes(params: {
|
|
||||||
keycloakifyBuildDirPath: string;
|
|
||||||
}): MetaInfKeycloakTheme {
|
|
||||||
const { keycloakifyBuildDirPath } = params;
|
|
||||||
|
|
||||||
return JSON.parse(
|
|
||||||
fs
|
|
||||||
.readFileSync(
|
|
||||||
getMetaInfKeycloakThemesJsonFilePath({
|
|
||||||
keycloakifyBuildDirPath
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.toString("utf8")
|
|
||||||
) as MetaInfKeycloakTheme;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function writeMetaInfKeycloakThemes(params: {
|
export function writeMetaInfKeycloakThemes(params: {
|
||||||
keycloakifyBuildDirPath: string;
|
resourcesDirPath: string;
|
||||||
metaInfKeycloakThemes: MetaInfKeycloakTheme;
|
getNewMetaInfKeycloakTheme: (params: {
|
||||||
|
metaInfKeycloakTheme: MetaInfKeycloakTheme | undefined;
|
||||||
|
}) => MetaInfKeycloakTheme;
|
||||||
}) {
|
}) {
|
||||||
const { keycloakifyBuildDirPath, metaInfKeycloakThemes } = params;
|
const { resourcesDirPath, getNewMetaInfKeycloakTheme } = params;
|
||||||
|
|
||||||
const metaInfKeycloakThemesJsonPath = getMetaInfKeycloakThemesJsonFilePath({
|
const filePath = pathJoin(resourcesDirPath, "META-INF", "keycloak-themes.json");
|
||||||
keycloakifyBuildDirPath
|
|
||||||
|
const currentMetaInfKeycloakTheme = !fs.existsSync(filePath)
|
||||||
|
? undefined
|
||||||
|
: (JSON.parse(
|
||||||
|
fs.readFileSync(filePath).toString("utf8")
|
||||||
|
) as MetaInfKeycloakTheme);
|
||||||
|
|
||||||
|
const newMetaInfKeycloakThemes = getNewMetaInfKeycloakTheme({
|
||||||
|
metaInfKeycloakTheme: currentMetaInfKeycloakTheme
|
||||||
});
|
});
|
||||||
|
|
||||||
{
|
{
|
||||||
const dirPath = pathDirname(metaInfKeycloakThemesJsonPath);
|
const dirPath = pathDirname(filePath);
|
||||||
if (!fs.existsSync(dirPath)) {
|
if (!fs.existsSync(dirPath)) {
|
||||||
fs.mkdirSync(dirPath, { recursive: true });
|
fs.mkdirSync(dirPath, { recursive: true });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
metaInfKeycloakThemesJsonPath,
|
filePath,
|
||||||
Buffer.from(JSON.stringify(metaInfKeycloakThemes, null, 2), "utf8")
|
Buffer.from(JSON.stringify(newMetaInfKeycloakThemes, null, 2), "utf8")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user