mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-16 21:08:17 +00:00
* feat: Paint Inline Deployment Themes From the First Frame * test: Point the Theme Pin Mutations at the Provider Bundle
103 lines
3.9 KiB
TypeScript
103 lines
3.9 KiB
TypeScript
import fs from 'fs';
|
|
import path from 'path';
|
|
import { logger } from '@librechat/data-schemas';
|
|
import {
|
|
THEME_BOOT_FILE,
|
|
isBundledThemeName,
|
|
describeThemeModes,
|
|
validateThemeDefinition,
|
|
DEPLOYMENT_THEME_BOOT_ID,
|
|
} from 'librechat-data-provider';
|
|
import type {
|
|
ThemeBootModes,
|
|
ThemeDefinition,
|
|
BundledThemeBoot,
|
|
DeploymentThemeBoot,
|
|
} from 'librechat-data-provider';
|
|
import type { Request, Response } from 'express';
|
|
import { rejectTenantHeader } from '../middleware/tenantHeader';
|
|
import { isEnabled } from '../utils/common';
|
|
|
|
const TENANT_HEADER = 'X-Tenant-Id';
|
|
|
|
/**
|
|
* The bundled themes the client build resolved. Empty when the build predates them, which
|
|
* leaves a bundled name to the bundle's first render, as for an inline definition; a file that
|
|
* exists but cannot be read is reported, since the deployment then loses the first paint.
|
|
*/
|
|
export function readBundledThemeBoot(distPath: string): BundledThemeBoot {
|
|
const file = path.join(distPath, THEME_BOOT_FILE);
|
|
try {
|
|
const bundled = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
if (typeof bundled === 'object' && bundled !== null) {
|
|
return bundled;
|
|
}
|
|
logger.warn(`[DeploymentTheme] Ignoring ${file}: it does not hold an object`);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
|
logger.warn(`[DeploymentTheme] Ignoring unreadable ${file}`, error);
|
|
}
|
|
}
|
|
return {};
|
|
}
|
|
|
|
/**
|
|
* Both modes of the deployment theme as the boot script replays them: a bundled name from the
|
|
* build's file, an inline definition resolved here by the resolver the client runs. A definition
|
|
* the client would reject has none, so the shell keeps the stock palette the bundle falls back to.
|
|
*/
|
|
function resolveBootModes(
|
|
source: DeploymentThemeBoot['source'],
|
|
bundled: BundledThemeBoot,
|
|
): ThemeBootModes | undefined {
|
|
if (typeof source === 'string') {
|
|
return isBundledThemeName(source) ? bundled[source] : undefined;
|
|
}
|
|
const definition = source as ThemeDefinition;
|
|
return validateThemeDefinition(definition).length === 0
|
|
? describeThemeModes(definition)
|
|
: undefined;
|
|
}
|
|
|
|
/**
|
|
* Embeds the deployment's `interface.theme` ahead of the shell's boot script, so a first-ever
|
|
* visit paints it before `/api/config` answers, with both resolved modes for the boot script.
|
|
*/
|
|
export function injectDeploymentThemeBoot(
|
|
html: string,
|
|
source: DeploymentThemeBoot['source'] | undefined,
|
|
bundled: BundledThemeBoot,
|
|
): string {
|
|
if (source == null || html.includes(`id="${DEPLOYMENT_THEME_BOOT_ID}"`)) {
|
|
return html;
|
|
}
|
|
const modes = resolveBootModes(source, bundled);
|
|
const boot: DeploymentThemeBoot = { source, ...(modes && { modes }) };
|
|
/** A `<` in the payload could close the block; it never has to be raw. */
|
|
const payload = JSON.stringify(boot).replace(/</g, '\\u003c');
|
|
const block = `<script type="application/json" id="${DEPLOYMENT_THEME_BOOT_ID}">${payload}</script>`;
|
|
return html.replace(/<head([^>]*)>/i, (match) => `${match}${block}`);
|
|
}
|
|
|
|
/**
|
|
* The shell for a request. The deployment's base theme is only the right first paint where
|
|
* the signed-out config resolves to the base: a request whose trusted `X-Tenant-Id` header
|
|
* scopes it to a tenant, by the rule `preAuthTenantMiddleware` applies, gets the shell without
|
|
* it, since that tenant's theme may differ.
|
|
*/
|
|
export function createDeploymentThemeShell(
|
|
html: string,
|
|
source: DeploymentThemeBoot['source'] | undefined,
|
|
bundled: BundledThemeBoot,
|
|
env: NodeJS.ProcessEnv = process.env,
|
|
): (req: Pick<Request, 'get'>, res: Pick<Response, 'vary'>) => string {
|
|
const themed = injectDeploymentThemeBoot(html, source, bundled);
|
|
if (themed === html || !isEnabled(env.TRUST_TENANT_HEADER)) {
|
|
return () => themed;
|
|
}
|
|
return (req, res) => {
|
|
res.vary(TENANT_HEADER);
|
|
const tenantId = req.get(TENANT_HEADER)?.trim();
|
|
return tenantId && !rejectTenantHeader(tenantId) ? html : themed;
|
|
};
|
|
}
|