Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 4x 12x 12x 25x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 6x 3x 6x 1x 11x 1x 9x 1x 7x 3x 2x 2x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 22x 20x 19x 1x 2x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 3x 3x 1x 1x 3x 6x 3x 3x 3x 1x 1x 3x 6x 3x | import type {
ICoreAction,
ICoreAnyModule,
ICoreCClient,
ICoreDb,
ICoreKernel,
ICoreKernelModule,
ICoreModule,
ICoreService,
IHaveLogger,
IStore,
KernelEvent,
} from './lib';
import initHandler from './utils/initHandler';
import { CMap, CoreLogChannel, CoreLogger } from './classes';
import {
DefaultLogger,
EnvStore,
type EnvStoreCProps,
InMemDB,
StoreGlobal,
} from './modules';
import CoreModule from './CoreModule';
import { XUtil } from './utils';
import CoreKernelExtension from './classes/CoreKernelExtension';
/**
* Core Kernel class
* @typeParam X Type of Crypto client.
* ```typescript
* // Default use
* class Kernel extends CoreKernel<any> {
* constructor() {
* super({ appName: 'TestName', appCode: 'testcode' });
* }
* }
* const kernel = new Kernel();
* kernel.start();
* ```
*/
export type GlobalFolder = {
storeKey: string;
base: 'root' | 'config';
folderName: string;
};
/**
* Configuration options for initializing the CoreKernel instance.
* Combines application identification and behavior settings with extended environment store properties, while excluding log and appName fields.
*/
export type CoreKernelProps = {
appName: string;
appCode: string;
folderCreateSkip?: boolean;
logger?: (kernel: CoreKernel<any>) => CoreLogger;
// Override the globalThis console log with the internal logger
overrideGlobalConsoleLog?: boolean;
} & Omit<EnvStoreCProps, 'log' | 'appName'>;
/**
* Abstract base class that implements the core kernel functionality.
*
* Provides a foundation for registering modules, handling lifecycle
* events, managing configuration, logging, and cryptographic
* operations. Concrete kernels should extend this class, supply a
* specific base module via {@link setBaseModule}, and optionally
* customize behaviour.
*
* The kernel is generic over a cryptographic client type {@link ICoreCClient}
* and a base module type {@link ICoreKernelModule}. It extends
* {@link CoreLogChannel} and implements {@link ICoreKernel} and
* {@link IHaveLogger}.
*
* @template X - Type of the global crypto client.
* @template Y - Type of the base kernel module, defaults to
* {@link ICoreAnyModule}.
* @param {CoreKernelProps} options - Configuration options for the kernel.
*/
export default abstract class CoreKernel<
X extends ICoreCClient,
Y extends ICoreAnyModule = ICoreAnyModule,
>
extends CoreLogChannel
implements ICoreKernel<X>, IHaveLogger
{
protected devMode: boolean;
protected appCode: string;
protected appName: string;
protected appVersion: string;
protected cryptoClient: X | null;
protected state: any = null;
protected moduleList: ICoreAnyModule[];
protected coreModule: ICoreModule;
protected kernelModule: Y | null;
protected offline: boolean;
protected updateSkip: boolean;
protected folderCreateSkip: boolean;
protected globalFolderKeys: string[];
protected envStore: IStore;
protected eventMap: Map<
string,
(kernel: CoreKernel<X>, payload?: any) => Promise<unknown>
>;
protected extension: CMap<string, CoreKernelExtension>;
protected globalLogger: CoreLogger;
/**
* Default Constructor
* - appName: string - AppName
* - appCode: string - AppCode only lower case letters
* - pathOverride: string - Path to config folder [optional]
* > Default path is ${HOME}/AppName or ${HOME}/Library/AppName (osx)
* - logger: CoreLogger {@link CoreLogger} [optional]
* @param options Kernel options
*/
protected constructor(options: CoreKernelProps) {
const {
appCode,
appName,
folderCreateSkip,
logger,
overrideGlobalConsoleLog,
globalFolder,
} = options;
super('kernel', null);
this.appName = appName;
this.devMode = false;
this.appCode = appCode;
this.cryptoClient = null;
this.moduleList = [];
this.offline = false;
this.folderCreateSkip = folderCreateSkip ?? false;
this.updateSkip = false;
this.appVersion = 'noVersion';
this.triggerEvent = this.triggerEvent.bind(this);
this.extension = new CMap<string, CoreKernelExtension>();
this.eventMap = new Map<
string,
(kernel: CoreKernel<X>) => Promise<unknown>
>();
this.envStore = new EnvStore({
...options,
log: this,
appName: this.getAppName(),
});
Iif (logger === undefined) {
this.globalLogger = new DefaultLogger();
} else {
this.globalLogger = logger(this);
}
this.setLogger(this.globalLogger);
const log = this.envStore.get(StoreGlobal.GLOBAL_LOG_LEVEL);
Eif (log) {
this.globalLogger.setLogLevel(log);
}
Iif (overrideGlobalConsoleLog) {
globalThis.console.log = (x: any) => this.log(x);
globalThis.console.warn = (x: any) => this.warn(x);
globalThis.console.error = (x: any) => this.error(x);
}
this.globalFolderKeys =
globalFolder?.map(
({ storeKey }) => `GLOBAL_FOLDER_${storeKey.toUpperCase()}`,
) || [];
this.coreModule = new CoreModule(this, (mod) => new InMemDB(mod));
this.kernelModule = null;
this.setState('init');
}
/**
* get core kernel module
*/
getCoreModule(): ICoreModule {
return this.coreModule;
}
/**
* get base kernel module
*/
getModule(): Y {
Eif (this.kernelModule) {
return this.kernelModule;
}
throw this.lError('No Base module found');
}
/**
* get global logger
*/
getLogger(): CoreLogger {
return this.globalLogger;
}
/**
* get app name
*/
getAppName(): string {
return this.appName;
}
/**
* get app code
*/
getAppCode(): string {
return this.appCode;
}
/**
* startup kernel
*/
public async start(): Promise<boolean> {
this.startUpInfo();
this.debug('Run startup script');
this.preloadSetup();
await this.triggerEvent('pre');
this.info('Startup script complete');
this.debug('Run launcher');
await this.startUp();
this.setState('running');
return true;
}
/**
* Run trigger function
* Cycle functions
* @see KernelEvent
* @param event
*/
async triggerEvent<A = any>(
event: KernelEvent,
payload?: A,
): Promise<unknown> {
const fc = this.eventMap.get(event);
Iif (!fc) {
this.debug(`Trigger not implemented. [${event}]`);
return undefined;
}
return fc(this, payload);
}
/**
* Set function run on trigger
* Cycle functions
* @see KernelTrigger
* @param event
* @param callback
*/
on<A = any>(
event: KernelEvent,
callback: (ik: CoreKernel<X>, payload?: A) => Promise<unknown>,
): void {
this.eventMap.set(event, callback);
}
/**
* Set core state code
* @param message
*/
setState(message: string): void {
this.state = message;
}
/**
* Get core state code
*/
getState(): string {
return this.state;
}
/**
* Set global crypt client
* @link ICoreCClient
* @param crypto
*/
setCryptoClient(crypto: X | null): void {
this.cryptoClient = crypto;
}
/**
* Get global crypt client
* @link ICoreCClient
*/
getCryptoClient(): X | null {
return this.cryptoClient;
}
/**
* Has global crypt client
* @link ICoreCClient
*/
hasCryptoClient(): boolean {
return this.cryptoClient !== null;
}
/**
* Get database object of the core kernel module
* @link ICoreDb
*/
getDb(): ICoreDb {
return this.coreModule.getDb();
}
/**
* Get the offline flag
*/
getOffline(): boolean {
return this.offline;
}
/**
* Set the offline flag
* @param mode
*/
setOffline(mode: boolean): void {
this.offline = mode;
}
/**
* Get environment config store
* @link EnvStore
*/
getConfigStore(): IStore {
return this.envStore;
}
/**
* Get dev mode flag
*/
getDevMode(): boolean {
return this.devMode;
}
/**
* Set dev mode flag
*/
setDevMode(mode: boolean): void {
this.devMode = mode;
}
/**
* register new module
* @see CoreKernelModule
* @param module
* @typeParam X Type of Crypto client.
*/
addModule(...module: ICoreKernelModule<any, any, any, any, any>[]): void {
this.moduleList.push(...module);
}
/**
* @see CoreKernelExtension
* @param name Name of the extension
* @param ext Extension to add
*/
addExtension(name: string, ext: CoreKernelExtension): void {
this.extension.set(name, ext);
}
/**
* @see CoreKernelExtension
* @param name Name of the extension
*/
getExtension<A extends CoreKernelExtension>(name: string): A {
if (!this.extension.get(name)) {
throw this.lError('Extension missing in CoreKernelExtension');
}
return this.extension.get(name) as A;
}
setBaseModule(module: Y): void {
this.kernelModule = module;
}
setCoreModule<E extends ICoreModule>(module: E): void {
this.coreModule = module;
}
async stop(): Promise<boolean> {
const workload: Promise<void>[] = [];
await this.triggerEvent('stop');
await Promise.all(this.extension.map((e) => e.stop()));
this.moduleList.forEach((el) => workload.push(el.shutdown()));
await Promise.all(workload);
await this.getModule().shutdown();
await this.getCoreModule().shutdown();
this.setState('exited');
return true;
}
getChildModule<T extends ICoreAnyModule = ICoreAnyModule>(
modName: string,
): T {
const mod = this.moduleList.find((mo) => mo.getName() === modName);
if (mod) {
return mod as T;
}
throw this.lError(`Module ${modName} not found`);
}
getModCount(full = false): number {
return this.moduleList.length + (full ? 2 : 0);
}
private preloadSetup() {
const st = this.getConfigStore();
this.appVersion = st.get(StoreGlobal.GLOBAL_APP_VERSION) ?? '';
Eif (!this.folderCreateSkip) {
try {
XUtil.createFolderBulk(
st.get(StoreGlobal.GLOBAL_PATH_HOME) || '',
st.get(StoreGlobal.GLOBAL_PATH_DATA) || '',
st.get(StoreGlobal.GLOBAL_PATH_DB) || '',
st.get(StoreGlobal.GLOBAL_PATH_TEMP) || '',
);
} catch (e) {
console.error(e);
console.error(`Cant create config folder at $GLOBAL_PATH_HOME`);
this.error(e);
this.error(`Cant create config folder at $GLOBAL_PATH_HOME`);
process.exit(1);
}
for (const folder of this.globalFolderKeys) {
const fPath = st.get(folder)!;
Eif (XUtil.createFolderIfNotExist(fPath)) {
this.debug(`Global folder for ${folder} @${fPath} created`);
}
}
}
}
/**
* Prints the default startup message
* @private
*/
private startUpInfo() {
const out = [
`Starting Kernel`,
`⊢ Code: ${this.appCode}`,
`⊢ Version: ${this.envStore.get(StoreGlobal.GLOBAL_APP_VERSION)}`,
`⊢ Mode: ${this.devMode ? 'Dev' : 'Prod'}`,
`⊢ Mod count: ${this.moduleList.length}`,
`⊢ Action count: ${this.getActionList().length}`,
`⊢ Service count: ${this.getServiceList().length}`,
`⊢ Log level: ${this.globalLogger.getLogLevel()}`,
];
out.forEach((x) => this.info(x));
}
/**
* @private
*/
private async startUp() {
await this.getCoreModule().register('core-load');
await this.getModule().register('load');
await initHandler(this.moduleList, this);
await this.getCoreModule().start();
await this.getModule().start();
await Promise.all(
this.extension.map((e) => {
Eif (e.start !== undefined) {
return e.start();
}
return Promise.resolve();
}),
);
await this.getCoreModule().final();
await this.getModule().final();
for (const mod of this.moduleList) {
Eif (mod.final !== undefined) {
await mod.final();
}
}
await this.triggerEvent('start');
}
getActionList(full = false): ICoreAction[] {
const out: ICoreAction[] = [];
if (full) {
this.coreModule.getActionList().forEach((el) => out.push(el));
this.kernelModule?.getActionList().forEach((el) => out.push(el));
}
this.moduleList.forEach((el) => {
out.push(...el.getActionList());
});
return out;
}
getServiceList(full = false): ICoreService[] {
const out: ICoreService[] = [];
if (full) {
this.coreModule.getServiceList().forEach((el) => out.push(el));
this.kernelModule?.getServiceList().forEach((el) => out.push(el));
}
this.moduleList.forEach((el) => {
out.push(...el.getServiceList());
});
return out;
}
}
|