Files
boursecu_admin/src/config-loader.js
T

182 lines
5.5 KiB
JavaScript
Raw Normal View History

2026-01-24 17:45:54 +03:30
(function() {
'use strict';
//debugger
// Store config in window object
window.__APP_CONFIG__ = window.__APP_CONFIG__ || {};
window.__CONFIG_READY__ = false;
// Create a promise that will be resolved when config is loaded
let configResolve;
let configReject;
window.__CONFIG_PROMISE__ = new Promise((resolve, reject) => {
configResolve = resolve;
configReject = reject;
});
// API endpoint for config - you can change this URL
// You can also set it via a data attribute: <script src="/config-loader.js" data-config-url="https://your-api.com/config"></script>
//const scriptTag = document.currentScript || document.querySelector('script[src*="config-loader.js"]');
//const customUrl = scriptTag ? scriptTag.getAttribute('data-config-url') : null;
const CONFIG_URL = 'https://nerkh.gold/get_user' //customUrl || window.location.origin + '/api/config';
// Timeout to ensure main.ts loads even if config fails (5 seconds)
const CONFIG_TIMEOUT = 5000;
let configTimeoutId;
let mainScriptLoaded = false;
// Fetch config from server
async function loadConfig() {
try {
const response = await fetch(CONFIG_URL, {
method: 'GET',
headers: {
'Accept': 'application/json',
},
cache: 'no-cache'
});
if (!response.ok) {
throw new Error('Failed to fetch config: ' + response.status);
}
// Check if response is actually JSON
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
const text = await response.text();
throw new Error('Response is not JSON. Received: ' + text.substring(0, 100));
}
const config = await response.json();
// Store config in window object
window.__APP_CONFIG__ = config;
window.__CONFIG_READY__ = true;
if (config?.user?.name_fa) {
document.title = 'پنل مدیریت '+ '-'+config.user.name_fa;
}
// ---------- Dynamic Favicon ----------
if (config?.user?.avatar) {
const faviconUrl = config.user.avatar;
// remove existing favicon(s)
const existingIcons = document.querySelectorAll('link[rel*="icon"]');
existingIcons.forEach(icon => icon.remove());
// create new favicon
const link = document.createElement('link');
link.rel = 'icon';
link.type = 'image/png'; // یا image/x-icon
link.href = faviconUrl + '?v=' + Date.now();
document.head.appendChild(link);
}
// Resolve the promise
if (configResolve) {
configResolve(config);
}
// Dispatch custom event to notify that config is ready
window.dispatchEvent(new CustomEvent('configReady', { detail: config }));
console.log('Config loaded successfully:', config);
// Clear timeout if config loaded successfully
if (configTimeoutId) {
clearTimeout(configTimeoutId);
configTimeoutId = null;
}
// Load main.ts after config is ready
loadMainScript();
} catch (error) {
console.warn('Config loader: Could not fetch config from', CONFIG_URL);
console.warn('Error details:', error.message);
console.warn('This is normal if the endpoint does not exist yet. App will continue with empty config.');
// Set default empty config on error
window.__APP_CONFIG__ = {};
window.__CONFIG_READY__ = true;
// Resolve the promise even on error (with empty config)
if (configResolve) {
configResolve({});
}
window.dispatchEvent(new CustomEvent('configError', { detail: error }));
// Clear timeout if error occurred
if (configTimeoutId) {
clearTimeout(configTimeoutId);
configTimeoutId = null;
}
// Load main.ts even on error (with empty config)
loadMainScript();
}
}
// Function to dynamically load main.ts script
function loadMainScript() {
//const config= window.__APP_CONFIG__
// Check if main.ts is already loaded
if (mainScriptLoaded || document.querySelector('script[src="/src/main.ts"]')) {
return;
}
mainScriptLoaded = true;
/*const manifestLink = document.createElement("link")
manifestLink.rel = "manifest"
manifestLink.id= "manifestsdfsdfsdfsdfsdfsdf"
manifestLink.href = `https://nerkh.gold/get_user/${config.user.id}/monifist.json`
document.head.appendChild(manifestLink)*/
import('/src/main.ts').then(() => {
console.log('Main script loaded and executed');
});
/*const script = document.createElement('script');
script.type = 'module';
script.src = '/src/main.ts';
script.async = true;*/
// Handle script load errors
/*script.onerror = function() {
console.error('Failed to load main.ts script');
mainScriptLoaded = false;
};
script.onload = function() {
console.log('Main script loaded successfully');
};
document.body.appendChild(script);*/
//console.log('Main script loading started...');
}
// Set timeout to ensure main.ts loads even if config fails
configTimeoutId = setTimeout(function() {
if (!mainScriptLoaded) {
console.warn('Config loader: Timeout reached. Loading main.ts with empty config.');
// Set default empty config
window.__APP_CONFIG__ = window.__APP_CONFIG__ || {};
window.__CONFIG_READY__ = true;
// Resolve promise with empty config
if (configResolve) {
configResolve({});
}
loadMainScript();
}
}, CONFIG_TIMEOUT);
// Start loading config immediately
loadConfig();
})();