changemaker.lite/mkdocs/docs/hooks/env_config_hook.py

89 lines
3.1 KiB
Python

"""
MkDocs Hook for Environment Variable Injection
Injects environment variables into the site as JavaScript configuration.
This allows client-side code to access server-side config values.
"""
import os
import logging
from typing import Dict, Any
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def on_config(config: Dict[str, Any]) -> Dict[str, Any]:
"""
Hook that runs when MkDocs loads the configuration.
Injects environment variables as extra JavaScript.
"""
# Read environment variables (with fallbacks)
media_api_url = os.environ.get('MEDIA_API_PUBLIC_URL', 'http://localhost:4100')
public_url = os.environ.get('ADMIN_URL', 'http://localhost:3000')
# For production, check for public-facing URLs
# Fallback to subdomain-based URLs if available
base_domain = os.environ.get('BASE_DOMAIN', '')
if base_domain and not base_domain.startswith('http'):
base_domain = f'https://{base_domain}'
# Use base_domain to construct URLs if env vars not explicitly set
if media_api_url == 'http://localhost:4100' and base_domain:
media_api_url = base_domain.replace('cmlite.org', 'media.cmlite.org')
if public_url == 'http://localhost:3000' and base_domain:
public_url = base_domain.replace('cmlite.org', 'app.cmlite.org')
# Create inline JavaScript with config
config_script = f"""
// Auto-generated video player configuration from environment variables
// Generated by mkdocs/docs/hooks/env_config_hook.py
(function() {{
window.MEDIA_API_URL = '{media_api_url}';
window.PUBLIC_URL = '{public_url}';
window.VIDEO_PLAYER_DEBUG = {str(os.environ.get('VIDEO_PLAYER_DEBUG', 'false')).lower()};
console.log('[Video Config] Loaded from environment:', {{
mediaApiUrl: window.MEDIA_API_URL,
publicUrl: window.PUBLIC_URL,
debug: window.VIDEO_PLAYER_DEBUG
}});
}})();
""".strip()
# Inject as extra_javascript (inline script)
# MkDocs will include this before other scripts
if 'extra_javascript' not in config:
config['extra_javascript'] = []
# Prepend inline config script (load before video-player.js)
# Note: We'll need to create a file for this
env_config_path = 'assets/js/env-config.js'
# Write the generated config to a file
import pathlib
docs_dir = pathlib.Path(config['docs_dir'])
env_config_file = docs_dir / env_config_path
env_config_file.parent.mkdir(parents=True, exist_ok=True)
with open(env_config_file, 'w') as f:
f.write(config_script)
logger.info(f"✓ Generated video config: {env_config_file}")
logger.info(f" MEDIA_API_URL: {media_api_url}")
logger.info(f" PUBLIC_URL: {public_url}")
# Insert at the beginning of extra_javascript list
if env_config_path not in config['extra_javascript']:
config['extra_javascript'].insert(0, env_config_path)
return config
def on_pre_build(config: Dict[str, Any]) -> None:
"""
Hook that runs before build starts.
Ensures config is regenerated on each build.
"""
logger.info("Video player configuration will be generated from environment variables")