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

45 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-06-09 09:15:16 +02:00
import type { BuildContext } from "../../shared/buildContext";
2022-08-16 14:41:06 +07:00
import { assert } from "tsafe/assert";
import { posix } from "path";
2022-08-16 14:41:06 +07:00
2024-06-09 09:15:16 +02:00
export type BuildContextLike = {
2022-08-16 14:41:06 +07:00
urlPathname: string | undefined;
};
2024-06-09 09:15:16 +02:00
assert<BuildContext extends BuildContextLike ? true : false>();
2022-08-16 14:41:06 +07:00
export function replaceImportsInCssCode(params: {
cssCode: string;
fileRelativeDirPath: string;
2024-06-09 09:15:16 +02:00
buildContext: BuildContextLike;
2024-05-20 15:48:51 +02:00
}): {
fixedCssCode: string;
2022-08-16 14:41:06 +07:00
} {
const { cssCode, fileRelativeDirPath, buildContext } = params;
const fixedCssCode = cssCode.replace(
/url\(["']?(\/[^/][^)"']+)["']?\)/g,
(match, assetFileAbsoluteUrlPathname) => {
if (buildContext.urlPathname !== undefined) {
if (!assetFileAbsoluteUrlPathname.startsWith(buildContext.urlPathname)) {
// NOTE: Should never happen
return match;
}
assetFileAbsoluteUrlPathname = assetFileAbsoluteUrlPathname.replace(
buildContext.urlPathname,
"/"
);
}
const assetFileRelativeUrlPathname = posix.relative(
fileRelativeDirPath.replace(/\\/g, "/"),
assetFileAbsoluteUrlPathname.replace(/^\//, "")
);
return `url(${assetFileRelativeUrlPathname})`;
}
);
2022-08-16 14:41:06 +07:00
return { fixedCssCode };
2022-08-16 14:41:06 +07:00
}