Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 39 additions & 14 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,36 +10,61 @@ try{if(fs.existsSync(packageFile))packageJson=JSON.parse(fs.readFileSync(package
const version=packageJson.version||'unknown';
if(!fs.existsSync(envFile)&&fs.existsSync(envExample)){fs.copyFileSync(envExample,envFile);ok('Created .env from .env.example');}
const packages=new Map();
function packageName(spec){const value=String(spec).trim();if(value.startsWith('@')){const slash=value.indexOf('/');if(slash===-1)return value;const at=value.indexOf('@',slash);return at===-1?value:value.slice(0,at);}return value.split('@')[0].split(/[?#]/)[0];}
function packageName(spec){const value=String(spec).trim();if(value.startsWith('@')){const slash=value.indexOf('/');if(slash===-1)return value;const at=value.indexOf('@',slash);return at===-1?value:value.slice(0,slash+value.slice(slash+1).indexOf('@')+1);}}
function addPackage(spec,source='module'){if(!spec)return;const value=String(spec).trim();if(!value)return;const name=packageName(value);if(!name)return;if(!packages.has(name))packages.set(name,{spec:value,source});}
function addDependencies(value,source){if(Array.isArray(value))for(const spec of value)addPackage(spec,source);else if(value&&typeof value==='object')for(const[spec,dependencyVersion]of Object.entries(value))addPackage(dependencyVersion?`${spec}@${dependencyVersion}`:spec,source);}
function addDependencies(value,source){if(Array.isArray(value))for(const spec of value)addPackage(spec,source);else if(value&&typeof value==='object')for(const[spec,dependencyVersion]of Object.entries(value))addPackage(spec,source);}
addDependencies(packageJson.dependencies,'required');
function resolveInstalled(name){try{require.resolve(name,{paths:[root]});return true;}catch{return false;}}
function installMissing(entries){if(!entries.length)return true;rule();install(`Installing ${entries.length} missing package(s)...`);for(const entry of entries)info(`${entry.spec} [${entry.source}]`);const npm=process.env.npm_execpath||'npm';const npmArgs=['install','--no-save','--no-package-lock','--no-audit','--no-fund',...entries.map(x=>x.spec)];const useNode=String(npm).endsWith('.js');const command=useNode?process.execPath:npm;const commandArgs=useNode?[npm,...npmArgs]:npmArgs;const result=spawnSync(command,commandArgs,{cwd:root,stdio:'inherit'});if(result.error){error(`Dependency installation could not start: ${result.error.message}`);return false;}if(result.status!==0){error(`Dependency installation failed with exit code ${result.status??'unknown'}`);return false;}for(const entry of entries)ok(`Installed ${entry.spec}`);return true;}
function installMissing(entries){if(!entries.length)return true;rule();install(`Installing ${entries.length} missing package(s)...`);for(const entry of entries)info(`${entry.spec} [${entry.source}]`);const npm=process.env.npm_execpath||'npm';const args=['install',...entries.map(e=>e.spec)];const result=spawnSync(npm,args,{stdio:'inherit',cwd:root,env:process.env});if(result.status!==0){error(`Dependency install failed with exit code ${result.status}`);return false;}return true;}
let requiredMissing=[];for(const[name,entry]of packages){if(resolveInstalled(name))ok(`${entry.spec} already installed`);else requiredMissing.push(entry);}if(!installMissing(requiredMissing))process.exit(1);
require('dotenv').config({quiet:true});
const {syncEnvSchema}=require('./lib/env-sync');
syncEnvSchema({root,envExample,envFile});
let yaml;try{yaml=require('js-yaml');}catch(e){error(`Required dependency js-yaml is unavailable: ${e.message}`);process.exit(1);}
let config;try{config=require('./lib/config').loadConfig();}catch(e){error(`Could not load config.yml: ${e.message}`);process.exit(1);}
const panelEnabled=config.adminPanel?.enabled===true||config.dashboard?.enabled===true;
if(panelEnabled){addPackage('@tailwindcss/cli@4.3.3','admin-panel');addPackage('tailwindcss@4.3.3','admin-panel');}
function moduleDirs(base){if(!fs.existsSync(base))return[];return fs.readdirSync(base,{withFileTypes:true}).filter(x=>x.isDirectory()).map(x=>path.join(base,x.name));}
function readYaml(file){try{return yaml.load(fs.readFileSync(file,'utf8'))||{};}catch(e){warn(`Invalid YAML ${path.relative(root,file)}: ${e.message}`);return{};}}
let enabledModules=0;
for(const dir of [...moduleDirs(path.join(root,'modules')),...moduleDirs(path.join(root,'custom-modules'))]){const name=path.basename(dir);const manifestFile=fs.existsSync(path.join(dir,'config.yml'))?path.join(dir,'config.yml'):path.join(dir,'module.yml');const manifest=fs.existsSync(manifestFile)?readYaml(manifestFile):{};const rootEnabled=config[name]?.enabled===true||(name==='dashboard'&&config.adminPanel?.enabled===true);if(!rootEnabled)continue;enabledModules++;addDependencies(manifest.dependencies,'module');if(manifest.advanced===true&&fs.existsSync(path.join(dir,'advanced.yml'))){const advanced=readYaml(path.join(dir,'advanced.yml'));addDependencies(advanced.module?.dependencies,'advanced');addDependencies(advanced.dependencies,'advanced');}}
if(config.database?.enabled===true){const provider=String(config.database.primary||'none').toLowerCase();if(provider==='sqlite')addPackage('better-sqlite3@13.0.3','database');if(provider==='mysql')addPackage('mysql2@3.24.4','database');if(provider==='postgres')addPackage('pg@8.23.0','database');if(provider==='mongodb')addPackage('mongodb@7.6.0','database');if(provider==='redis')addPackage('redis@6.2.1','database');}
const shardSetting=config.sharding?.enabled===true?(config.sharding?.totalShards==='auto'?'auto':String(config.sharding?.totalShards||1)):'off';
banner({version,node:process.version,platform:`${process.platform}/${process.arch}`,modules:`${enabledModules} enabled`,database:String(config.database?.enabled===true?config.database?.primary||'enabled':'disabled'),shards:shardSetting});
boot(`Working directory: ${root}`);boot(`Process: ${process.pid} | ${process.execPath}`);boot(`Configuration: ${path.basename(path.join(root,'config.yml'))} | release ${config.release||'unknown'}`);
const missing=[];let already=0;for(const[name,entry]of packages){if(resolveInstalled(name)){already++;if(entry.source!=='required')ok(`${entry.spec} already installed`);}else missing.push(entry);}if(!installMissing(missing))process.exit(1);info(`Dependencies: ${already} already present | ${missing.length} installed | ${packages.size} total`);
if(panelEnabled&&!fs.existsSync(path.join(root,'modules','dashboard','public','admin.css'))){info('Building local admin panel assets');const npm=process.env.npm_execpath||'npm';const args=['run','build:panel'];const useNode=String(npm).endsWith('.js');const result=spawnSync(useNode?process.execPath:npm,useNode?[npm,...args]:args,{cwd:root,stdio:'inherit'});if(result.status!==0){error('Admin panel CSS build failed');process.exit(1);}}
if(!process.env.DISCORD_TOKEN||process.env.DISCORD_TOKEN==='YOUR_BOT_TOKEN_HERE'){error('Set DISCORD_TOKEN in .env');process.exit(1);}ok('Dependency bootstrap complete');rule();
for(const dir of [...moduleDirs(path.join(root,'modules')),...moduleDirs(path.join(root,'custom-modules'))]){const name=path.basename(dir);const manifestFile=fs.existsSync(path.join(dir,'config.yml'))?path.join(dir,'config.yml'):path.join(dir,'module.yml');if(fs.existsSync(manifestFile)){const manifest=readYaml(manifestFile);const isEnabled=(manifest.enabled===true)||(config[name]?.enabled===true);if(isEnabled)enabledModules++;}}
if(config.database?.enabled===true){const provider=String(config.database.primary||'none').toLowerCase();if(provider==='sqlite')addPackage('better-sqlite3@13.0.3','database');if(provider==='mysql')addPackage('mysql2@3.2.5','database');if(provider==='postgres')addPackage('pg@8.16.0','database');if(provider==='mongodb')addPackage('mongodb@6.10.0','database');if(provider==='redis')addPackage('redis@5.0.0','database');}
const shardSetting=config.sharding?.enabled===true?(config.sharding?.auto===true?'auto':'on'):'off';
banner({version,node:process.version,platform:`${process.platform}/${process.arch}`,modules:`${enabledModules} enabled`,database:String(config.database?.enabled===true?config.database?.primary||'none':'none'),sharding:shardSetting});
boot(`Working directory: ${root}`);boot(`Process: ${process.pid} | ${process.execPath}`);boot(`Configuration: ${path.basename(path.join(root,'config.yml'))} | release ${config.release||'unknown'}`);boot(`Booting with ${enabledModules} enabled modules`);rule();
const missing=[];let already=0;for(const[name,entry]of packages){if(resolveInstalled(name)){already++;if(entry.source!=='required')ok(`${entry.spec} already installed`);}else missing.push(entry);}if(missing.length){error(`Missing dependencies: ${missing.map(x=>x.spec).join(', ')}`);process.exit(1);}ok('Dependency bootstrap complete');rule();
const {ShardingManager}=require('discord.js');
const {createShardCoordinator,discoverDiscordShards}=require('./lib/sharding');
let manager=null;
let shuttingDown=false;
function shutdownChildren(signal){if(shuttingDown)return;shuttingDown=true;if(manager?.respawn!==undefined)manager.respawn=false;const children=manager?.shards?Array.from(manager.shards.values()):[];if(!children.length)return;boot(`Forwarding ${signal} to ${children.length} shard process(es)...`);for(const shard of children){try{if(shard.process&&!shard.process.killed)shard.process.kill(signal);else shard.kill();}catch(e){warn(`Could not stop shard #${shard.id}: ${e.message}`);}}}
function shutdownChildren(signal){if(shuttingDown)return;shuttingDown=true;if(manager?.respawn!==undefined)manager.respawn=false;const children=manager?.shards?Array.from(manager.shards.values()):[];for(const child of children)child.kill(signal||'SIGTERM');}
function shutdownSignal(signal){shutdownChildren(signal);setTimeout(()=>process.exit(signal==='SIGINT'?130:143),5000).unref?.();}
process.once('SIGINT',()=>shutdownSignal('SIGINT'));
process.once('SIGTERM',()=>shutdownSignal('SIGTERM'));
async function recommendedShards(){const response=await fetch('https://discord.com/api/v10/gateway/bot',{headers:{Authorization:`Bot ${process.env.DISCORD_TOKEN}`}});if(!response.ok)throw new Error(`Gateway discovery returned HTTP ${response.status}`);const body=await response.json();return Math.max(1,Number(body.shards||1));}
async function start(){const sharding=config.sharding||{};if(sharding.enabled===true){const remote=['redis','mongodb','mysql','postgres'].includes(String(config.database?.primary||'').toLowerCase());if((sharding.autoDetect===true||sharding.totalShards==='auto')&&!remote)throw new Error('Automatic shard detection requires a remote database: redis, mongodb, mysql, or postgres');let total=sharding.totalShards;if(sharding.autoDetect===true)total=await recommendedShards();if(total==null||total==='auto')total=1;boot(`Launching ${total} shard process(es)`);manager=new ShardingManager(path.join(root,'main.js'),{token:process.env.DISCORD_TOKEN,totalShards:total,shardList:Array.isArray(sharding.shardList)?sharding.shardList:undefined,respawn:sharding.respawn!==false,mode:'process'});manager.on('shardCreate',shard=>{ok(`Spawned shard #${shard.id}`);shard.on('death',process=>{if(shuttingDown)return;warn(`Shard #${shard.id} exited with code ${process.exitCode??'unknown'}`);});});await manager.spawn();return;}boot('Launching main process...');await require('./main').start();}
async function start(){
const sharding=config.sharding||{};
if(sharding.enabled===true){
const token=process.env.DISCORD_TOKEN;
if(!token)throw new Error('DISCORD_TOKEN is missing');
const providerName=String(config.database?.primary||'none').toLowerCase();
const total=await discoverDiscordShards(token);
console.log('[Shard Coordinator] Discovering Discord shard count...');
console.log(`[Shard Coordinator] Discord recommended shards: ${total}`);
console.log(`[Shard Coordinator] Provider: ${providerName}`);
const coordinator=await createShardCoordinator(config,{instanceId:`${require('node:os').hostname()}-${process.pid}`});
const active=await coordinator.getActiveShards();
console.log(`[Shard Coordinator] Active shards: ${active.map((item)=>item.shardId).join(',') || 'none'}`);
const claimed=[];
for(let shardId=0;shardId<total;shardId++){
const okClaim=await coordinator.claimShard(shardId);
if(okClaim)claimed.push(shardId);
}
console.log(`[Shard Coordinator] Claimed: ${claimed.join(',') || 'none'}`);
manager=new ShardingManager('./main.js',{token,totalShards:total,shardList:claimed});
manager.on('shardCreate',(shard)=>boot(`[BOOT] Launching shard ${shard.id}`));
await manager.spawn({amount:Math.max(1,claimed.length)});
return;
}
require('./main.js');
}
start().catch(e=>{error(`Start failed: ${e?.stack||e?.message||e}`);process.exit(1);});
36 changes: 32 additions & 4 deletions lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,39 @@ const root=path.join(__dirname,'..');
const configFile=path.join(root,'config.yml');
const exampleFile=path.join(root,'config.example.yml');
const moduleRoot=path.join(root,'modules');
function deepMerge(base,extra){const out={...(base||{})};for(const[key,value]of Object.entries(extra||{})){if(value&&typeof value==='object'&&!Array.isArray(value))out[key]=deepMerge(out[key],value);else if(!(key in out))out[key]=value;}return out;}
function deepMerge(base,extra){const out={...(base||{})};for(const[key,value]of Object.entries(extra||{})){if(value&&typeof value==='object'&&!Array.isArray(value))out[key]=deepMerge(out[key],value);else out[key]=value;}return out;}
function backup(file){if(!fs.existsSync(file))return;const backup=`${file}.backup.${Date.now()}`;fs.copyFileSync(file,backup);console.log(`[Config] Backup created: ${path.basename(backup)}`);}
function write(file,data){fs.mkdirSync(path.dirname(file),{recursive:true});const tmp=`${file}.tmp`;fs.writeFileSync(tmp,data,'utf8');fs.renameSync(tmp,file);}
const legacyAliases={aichat:'ai',honeypot:'security',commandDeployment:'commands'};
function migrate(config){const oldVersion=Number(config.version||1),next={...config};if(next.commandDeployment&&!next.commands)next.commands=next.commandDeployment;if(next.aichat&&!next.ai)next.ai={...next.aichat};if(next.honeypot&&typeof next.honeypot==='object'){if(!next.security||typeof next.security!=='object')next.security={...next.honeypot};else{const legacy=next.honeypot;for(const[key,value]of Object.entries(legacy))if(!(key in next.security))next.security[key]=value;}}if(!next.permissions)next.permissions={};if(!next.runtime)next.runtime={environment:'production',gracefulShutdown:true,crashProtection:true};if(!next.prefix)next.prefix={enabled:false,prefixes:['!'],mentionPrefix:true};if(!next.database)next.database={enabled:false,primary:'none',fallbackToLocal:true};if(!next.sharding)next.sharding={enabled:false,autoDetect:false,totalShards:'auto',shardList:'auto',respawn:true};next.version=5;return{config:next,changed:oldVersion!==5,oldVersion};}
function migrateModuleConfigs(config){if(!fs.existsSync(moduleRoot))return false;let changed=false;for(const[oldName,newName]of Object.entries(legacyAliases)){const data=config[oldName];if(!data||typeof data!=='object')continue;const dir=path.join(moduleRoot,newName),file=path.join(dir,'config.yml');if(!fs.existsSync(dir)||fs.existsSync(file))continue;write(file,yaml.dump({...data,advanced:false},{noRefs:true,lineWidth:-1}));console.log(`[Migration] Created ${newName}/config.yml from legacy ${oldName}`);changed=true;}for(const entry of fs.readdirSync(moduleRoot,{withFileTypes:true}).filter(x=>x.isDirectory())){const name=entry.name,file=path.join(moduleRoot,name,'config.yml');if(!fs.existsSync(file))continue;let data;try{data=yaml.load(fs.readFileSync(file,'utf8'))||{};}catch(e){console.error(`[Migration] Failed to read ${name}/config.yml:`,e.message);continue;}if(!Object.prototype.hasOwnProperty.call(data,'enabled'))continue;const legacyEnabled=data.enabled;delete data.enabled;if(!config[name]||typeof config[name]!=='object')config[name]={};if(typeof config[name].enabled!=='boolean'&&typeof legacyEnabled==='boolean')config[name].enabled=legacyEnabled;backup(file);write(file,yaml.dump(data,{noRefs:true,lineWidth:-1}));console.log(`[Migration] Moved ${name}.enabled=${legacyEnabled} to root config and removed module enabled flag`);changed=true;}const honeypotFile=path.join(moduleRoot,'honeypot','config.yml'),securityFile=path.join(moduleRoot,'security','config.yml');if(fs.existsSync(honeypotFile)&&fs.existsSync(securityFile)){const honeypot=(()=>{try{return yaml.load(fs.readFileSync(honeypotFile,'utf8'))||{};}catch{return{};}})(),security=(()=>{try{return yaml.load(fs.readFileSync(securityFile,'utf8'))||{};}catch{return{};}})();let merged=false;for(const[key,value]of Object.entries(honeypot))if(key!=='aliasOf'&&key!=='enabled'&&!(key in security)){security[key]=value;merged=true;}if(merged){backup(securityFile);write(securityFile,yaml.dump(security,{noRefs:true,lineWidth:-1}));console.log('[Migration] Preserved legacy honeypot settings in security/config.yml');changed=true;}}return changed;}
function loadConfig(){if(!fs.existsSync(configFile)){if(!fs.existsSync(exampleFile))throw new Error('config.example.yml is missing');fs.copyFileSync(exampleFile,configFile);console.log('[Config] Created config.yml from config.example.yml');}let current;try{current=yaml.load(fs.readFileSync(configFile,'utf8'))||{};}catch(e){backup(configFile);current={};console.error('[Config] Invalid config:',e.message);}const example=yaml.load(fs.readFileSync(exampleFile,'utf8'))||{};const migration=migrate(current);const moduleChanged=migrateModuleConfigs(migration.config);const merged=deepMerge(migration.config,example);merged.version=5;if(migration.changed||moduleChanged){if(fs.existsSync(configFile))backup(configFile);write(configFile,yaml.dump(merged,{noRefs:true,lineWidth:-1}));if(migration.changed)console.log(`[Config] Migrated V${migration.oldVersion} -> V5`);if(moduleChanged)console.log('[Config] Module enable states are now controlled by root config.yml');}return merged;}
function migrate(config){
const next={...(config||{})};
if(next.commandDeployment&&!next.commands)next.commands=next.commandDeployment;
if(next.aichat&&!next.ai)next.ai=next.aichat;
if(next.honeypot&&!next.security)next.security=next.honeypot;
if(next.sharding && typeof next.sharding==='object'){
const sharding=next.sharding;
const legacy = sharding.totalShards!==undefined || sharding.shardList!==undefined || sharding.maxConcurrency!==undefined || sharding.autoDetect!==undefined;
if(legacy){
sharding.enabled = sharding.enabled !== false;
sharding.auto = true;
sharding.coordination = 'auto';
sharding.heartbeatInterval = sharding.heartbeatInterval ?? 30000;
sharding.timeout = sharding.timeout ?? 120000;
delete sharding.totalShards;
delete sharding.shardList;
delete sharding.maxConcurrency;
delete sharding.autoDetect;
}
next.sharding = sharding;
}
return next;
}
function migrateModuleConfigs(config){if(!fs.existsSync(moduleRoot))return false;let changed=false;for(const[oldName,newName]of Object.entries(legacyAliases)){const data=config[oldName];if(!data||typeof data!=='object')continue;const target=config[newName]||{};config[newName]=deepMerge(target,data);delete config[oldName];changed=true;}return changed;}
function loadConfig(){if(!fs.existsSync(configFile)){if(!fs.existsSync(exampleFile))throw new Error('config.example.yml is missing');fs.copyFileSync(exampleFile,configFile);console.log('[Config] Created config.yml from config.example.yml');}
const raw=fs.readFileSync(configFile,'utf8');
const config=raw.trim()?yaml.load(raw)||{}:{};
const migrated=migrate(config);
const dirty=JSON.stringify(migrated)!==JSON.stringify(config);
if(dirty){backup(configFile);write(configFile,yaml.dump(migrated,{lineWidth:-1}));console.log('[Config] Migrated config.yml to sharding-safe schema');}
return migrated;}
module.exports={loadConfig,migrate,deepMerge,migrateModuleConfigs};
Loading
Loading