Skip to content

Commit

Permalink
Fix Styles Rendering
Browse files Browse the repository at this point in the history
  • Loading branch information
zx8086 committed Feb 1, 2025
1 parent 18b8f59 commit 77c9f99
Show file tree
Hide file tree
Showing 6 changed files with 228 additions and 29 deletions.
48 changes: 39 additions & 9 deletions hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,51 @@
import type { Handle } from '@sveltejs/kit';
import { redirect } from '@sveltejs/kit';

// Define paths that should be public
const PUBLIC_PATHS = [
'/login',
'/_app', // All SvelteKit app assets
'/build', // Built assets
'/favicon.ico', // Favicon
'/static', // Static assets
];

// Add specific asset extensions that should always be public
const PUBLIC_EXTENSIONS = ['.css', '.js', '.woff', '.woff2', '.ttf', '.png', '.jpg', '.svg'];

// Add specific immutable paths
const IMMUTABLE_PATHS = [
'/_app/immutable/',
'/_app/version.json',
];

export const handle: Handle = async ({ event, resolve }) => {
// Authentication logic
const publicPaths = ['/login'];
const isPublicPath = publicPaths.some(path => event.url.pathname.startsWith(path));

if (!isPublicPath) {
const authCookie = event.cookies.get('auth');
if (!authCookie) {
throw redirect(307, '/login');
const pathname = event.url.pathname;

// Check if path should be public
const isPublicPath = PUBLIC_PATHS.some(path => pathname.startsWith(path));
const hasPublicExtension = PUBLIC_EXTENSIONS.some(ext => pathname.endsWith(ext));
const isImmutablePath = IMMUTABLE_PATHS.some(path => pathname.startsWith(path));

// Allow access to public paths and assets
if (isPublicPath || hasPublicExtension || isImmutablePath) {
const response = await resolve(event);
// Add cache headers for immutable content
if (isImmutablePath) {
response.headers.set('Cache-Control', 'public, max-age=31536000, immutable');
}
return response;
}

// Authentication check for non-public paths
const authCookie = event.cookies.get('auth');
if (!authCookie) {
throw redirect(307, '/login');
}

const response = await resolve(event);

// Add security headers
// Security headers
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
Expand Down
32 changes: 18 additions & 14 deletions src/lib/context/tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export async function initTracker() {
ingestPoint: getIngestPoint(),
__DISABLE_SECURE_MODE: import.meta.env.DEV,
resourceBaseHref: getResourceBaseHref(),
disableStringDict: true,
network: {
failuresOnly: false,
ignoreHeaders: [
Expand All @@ -92,6 +93,9 @@ export async function initTracker() {
maxOtherResourceSize: 2 * 1024 * 1024 // 2MB
},
captureResourceMetrics: true,
defaultInputMode: 0,
obscureTextEmails: false,
obscureTextNumbers: false,
onStart: () => {
console.log('OpenReplay session started:', trackerInstance?.__sessionID);
// Initial user identification for replays
Expand Down Expand Up @@ -463,11 +467,11 @@ export function debugAssetAccess() {
try {
// @ts-ignore - accessing internal property
const sessionID = tracker.__sessionID;

// Log relevant info
console.log('Session ID:', sessionID);
console.log('Resource Base URL:', getResourceBaseHref());

// Log all stylesheets
const styles = document.styleSheets;
console.log('Active Stylesheets:', Array.from(styles).map(sheet => ({
Expand All @@ -488,16 +492,6 @@ export function debugAssetAccess() {
console.groupEnd();
}

// Update the APM integration setup
export function setupAPMIntegration(tracker: Tracker) {
if (!apm || import.meta.env.DEV) return; // Skip in development

tracker.setAPMIntegration?.({
captureTracing: false,
propagateTraceContext: false
});
}

export function debugResourceLoading() {
const tracker = getTracker();
if (!tracker) {
Expand All @@ -510,7 +504,7 @@ export function debugResourceLoading() {
// Check all stylesheets
const styles = document.styleSheets;
console.log('Stylesheet Count:', styles.length);

Array.from(styles).forEach((sheet, index) => {
console.log(`Stylesheet ${index}:`, {
href: sheet.href,
Expand All @@ -523,7 +517,7 @@ export function debugResourceLoading() {
// Check if base href is correct
console.log('Base HREF:', document.baseURI);
console.log('Resource Base HREF:', getResourceBaseHref());

// Log performance metrics
const perfEntries = performance.getEntriesByType('resource');
console.log('Resource Performance:', perfEntries.map(entry => ({
Expand All @@ -536,3 +530,13 @@ export function debugResourceLoading() {
}
console.groupEnd();
}

// Update the APM integration setup
export function setupAPMIntegration(tracker: Tracker) {
if (!apm || import.meta.env.DEV) return; // Skip in development

tracker.setAPMIntegration?.({
captureTracing: false,
propagateTraceContext: false
});
}
2 changes: 1 addition & 1 deletion src/routes/api/health-check/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@
</svelte:head>

<div class="container mx-auto px-4 py-8">
<h1 class="text-3xl font-bold mb-4">Status - API Health Check</h1>
<h1 class="text-3xl font-bold mb-4">Health Check Status</h1>

<div class="mb-6">
<button
Expand Down
19 changes: 19 additions & 0 deletions src/routes/debug/assets/+server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { dev } from '$app/environment';

export const GET: RequestHandler = async () => {
// Only enable in development
if (!dev) {
return new Response('Not Found', { status: 404 });
}

return json({
paths: {
app: '/_app',
immutable: '/_app/immutable',
static: '/static',
},
message: 'Use these paths to verify asset accessibility'
});
};
143 changes: 140 additions & 3 deletions src/routes/login/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,161 @@
}
}
// Initialize Tracker After Login
onMount(async () => {
try {
// Initialize tracker first
// Initialize tracker first, before auth
$trackerLoading = true;
await initTracker();
// Then proceed with auth initialization
// Then initialize auth
await auth.initialize();
if ($isAuthenticated) {
await goto('/', { replaceState: true });
return;
}
} catch (error) {
console.error('Initialization error:', error);
} finally {
$trackerLoading = false;
}
});
onMount(() => {
// Debug CSS locations
const styleSheets = Array.from(document.styleSheets);
console.log('🎨 CSS Files:', styleSheets.map(sheet => ({
href: sheet.href,
ownerNode: sheet.ownerNode?.nodeName,
rules: sheet.cssRules?.length
})));
// Debug JS files that might contain CSS
const scripts = Array.from(document.scripts);
console.log('📜 Script Files:', scripts.map(script => ({
src: script.src,
type: script.type,
module: script.type === 'module'
})));
// Log all asset URLs from /_app/immutable
const immutableAssets = Array.from(document.querySelectorAll('link[href*="/_app/immutable"], script[src*="/_app/immutable"]'));
console.log('🔒 Immutable Assets:', immutableAssets.map(el => ({
type: el.nodeName,
url: el.getAttribute('href') || el.getAttribute('src')
})));
// Debug all <link> and <style> tags
console.log('📝 Style Elements:', Array.from(document.querySelectorAll('link[rel="stylesheet"], style')).map(el => ({
type: el.nodeName,
href: el.getAttribute('href'),
textLength: el.textContent?.length || 0,
firstRules: el.textContent?.slice(0, 100) + '...'
})));
// More comprehensive CSS loading checks
const checkStyles = () => {
// 1. Check all stylesheets
const styleSheets = Array.from(document.styleSheets).map(sheet => ({
href: sheet.href,
rules: sheet.cssRules?.length,
loaded: !!sheet.cssRules?.length,
type: sheet.ownerNode?.nodeName,
media: sheet.media.mediaText
}));
// 2. Check critical Tailwind classes
const criticalClasses = [
'bg-[#00174f]',
'text-white',
'container',
'rounded-lg'
];
const computedStyles = criticalClasses.map(className => {
const testDiv = document.createElement('div');
testDiv.className = className;
document.body.appendChild(testDiv);
const styles = window.getComputedStyle(testDiv);
const computed = {
className,
backgroundColor: styles.backgroundColor,
color: styles.color,
display: styles.display
};
document.body.removeChild(testDiv);
return computed;
});
// 3. Check if styles are actually applying
const styleCheck = {
totalStylesheets: styleSheets.length,
loadedStylesheets: styleSheets.filter(s => s.loaded).length,
tailwindLoaded: styleSheets.some(s =>
s.rules && Array.from(s.rules).some(rule =>
rule.cssText?.includes('@tailwind') ||
rule.cssText?.includes('--tw-') ||
rule.cssText?.includes('container') ||
rule.cssText?.includes('text-white') ||
rule.cssText?.includes('bg-[#00174f]')
)
),
criticalStylesApplied: computedStyles.every(style =>
style.backgroundColor !== 'rgba(0, 0, 0, 0)' ||
style.color !== 'rgb(0, 0, 0)' ||
style.className === 'container'
),
styleValues: computedStyles.reduce((acc, style) => ({
...acc,
[style.className]: {
backgroundColor: style.backgroundColor,
color: style.color,
display: style.display
}
}), {}),
details: {
styleSheets,
computedStyles
}
};
console.log('🎨 OpenReplay Style Check:', styleCheck);
// 4. Alert if there are issues
if (!styleCheck.criticalStylesApplied) {
console.error('⚠️ Critical styles not applying:', styleCheck.styleValues);
}
};
// Check immediately and after a delay to catch any async loading
checkStyles();
setTimeout(checkStyles, 2000);
// Also check when window loads
window.addEventListener('load', checkStyles);
// Check if styles change
const observer = new MutationObserver((mutations) => {
const hasStyleChanges = mutations.some(mutation =>
mutation.target.nodeName === 'STYLE' ||
mutation.target.nodeName === 'LINK'
);
if (hasStyleChanges) {
console.log('🔄 Style changes detected, rechecking...');
checkStyles();
}
});
observer.observe(document.head, {
childList: true,
subtree: true
});
return () => {
observer.disconnect();
window.removeEventListener('load', checkStyles);
};
});
</script>
<svelte:head>
<title>Capella Document Search</title>
Expand Down
13 changes: 11 additions & 2 deletions svelte.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,14 @@ const config = {
kit: {
adapter: adapter({
dynamic_origin: true,
precompress: false
precompress: false,
}),
files: {
assets: 'static',
},
paths: {
assets: '',
},
alias: {
$lib: path.resolve("./src/lib"),
$utils: path.resolve("./src/utils"),
Expand Down Expand Up @@ -46,6 +52,7 @@ const config = {
"wss://openreplay.prd.shared-services.eu.pvh.cloud",
"ws://openreplay.prd.shared-services.eu.pvh.cloud",
// Other necessary endpoints
"https://capella-document-search.prd.shared-services.eu.pvh.cloud",
"https://login.microsoftonline.com",
"https://*.microsoftonline.com",
"https://graph.microsoft.com",
Expand All @@ -67,14 +74,16 @@ const config = {
'script-src': [
"'self'",
"'unsafe-eval'",
"'unsafe-inline'",
"https://api.openreplay.com",
"https://openreplay.prd.shared-services.eu.pvh.cloud",
"https://capella-document-search.prd.shared-services.eu.pvh.cloud"
],
'style-src': [
"'self'",
"'unsafe-inline'",
"https://capella-document-search.prd.shared-services.eu.pvh.cloud"
"https://capella-document-search.prd.shared-services.eu.pvh.cloud",
"https://openreplay.prd.shared-services.eu.pvh.cloud"
],
'img-src': [
"'self'",
Expand Down

0 comments on commit 77c9f99

Please sign in to comment.