Skip to content
Open
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
8 changes: 4 additions & 4 deletions src/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1049,7 +1049,7 @@ export class CodeGenerator {
result += this.indent(`const ${name} = {};\n`);

// Generate namespace body
if (node.body && node.body.statements) {
if (node.body?.statements) {
for (const stmt of node.body.statements) {
const isExported = (stmt as Statement & { exported?: boolean }).exported;

Expand Down Expand Up @@ -1127,7 +1127,7 @@ export class CodeGenerator {
return (stmt as FunctionDeclaration).name.name;
case 'VariableDeclaration': {
const varDecl = stmt as VariableDeclaration;
if (varDecl.identifier && varDecl.identifier.type === 'Identifier') {
if (varDecl.identifier?.type === 'Identifier') {
return varDecl.identifier.name;
}
break;
Expand All @@ -1150,7 +1150,7 @@ export class CodeGenerator {
let classBody = '';

// Generate class members
if (node.body && node.body.body) {
if (node.body?.body) {
const members = node.body.body
.map(member => {
switch (member.type) {
Expand Down Expand Up @@ -1192,7 +1192,7 @@ export class CodeGenerator {
} else {
// Regular methods have a body
// Handle cases where body might be null or undefined
if (!node.value || !node.value.body) {
if (!node.value?.body) {
return this.indent(`${isStatic}${methodName}(${params}) {}`);
}
const body = this.generateBlockStatement(node.value.body);
Expand Down
6 changes: 3 additions & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ function validateModuleSystem(config: unknown, basePath = 'moduleSystem'): Confi

function validateModuleSystemTopLevel(config: object, basePath: string): ConfigValidationError[] {
const errors: ConfigValidationError[] = [];
const knownTop = [
const knownTop = new Set([
'resolution',
'loading',
'compilation',
Expand All @@ -183,10 +183,10 @@ function validateModuleSystemTopLevel(config: object, basePath: string): ConfigV
'logger',
'managementServer',
'managementPort',
];
]);

for (const key of Object.keys(config)) {
if (!knownTop.includes(key)) {
if (!knownTop.has(key)) {
errors.push({ path: `${basePath}.${key}`, message: `unknown property` });
}
}
Expand Down
2 changes: 0 additions & 2 deletions src/core/application-layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,8 +382,6 @@ export class CompilationUseCase implements ICompilationUseCase {
metrics,
};
} catch (error) {
const totalTime = performance.now() - startTime;

errors.push({
message: `Compilation failed: ${error}`,
line: 0,
Expand Down
2 changes: 1 addition & 1 deletion src/core/modular-lexer-compatible.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ export class OperatorRecognizer extends BaseTokenRecognizer {
canRecognize(input: string, position: number): boolean {
const char = this.peek(input, position);
// Check if any operator starts with this character
return this.sortedOperators.some(op => op[0] === char);
return this.sortedOperators.some(op => op.startsWith(char));
}

recognize(
Expand Down
62 changes: 50 additions & 12 deletions src/lexer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,20 @@
return this.nextToken();
}

const switchResult = this.handleSwitchCharacters(char, startLine, startColumn);
if (switchResult) return switchResult;

const operatorResult = this.handleComparisonAndBitwiseOperators(char, startLine, startColumn);
if (operatorResult) return operatorResult;

return this.handleLiteralsAndIdentifiers(char, startLine, startColumn);
}

private handleSwitchCharacters(

Check warning on line 287 in src/lexer.ts

View workflow job for this annotation

GitHub Actions / Test on Node.js 24.x

Method 'handleSwitchCharacters' has a complexity of 17. Maximum allowed is 15

Check warning on line 287 in src/lexer.ts

View workflow job for this annotation

GitHub Actions / Test on Node.js 23.x

Method 'handleSwitchCharacters' has a complexity of 17. Maximum allowed is 15

Check warning on line 287 in src/lexer.ts

View workflow job for this annotation

GitHub Actions / Test on Node.js 20.x

Method 'handleSwitchCharacters' has a complexity of 17. Maximum allowed is 15

Check warning on line 287 in src/lexer.ts

View workflow job for this annotation

GitHub Actions / Test on Node.js 22.x

Method 'handleSwitchCharacters' has a complexity of 17. Maximum allowed is 15
char: string,
startLine: number,
startColumn: number
): Token | null {
switch (char) {
case '+':
return this.handlePlusOperator();
Expand Down Expand Up @@ -311,22 +325,46 @@
this.line++;
this.column = 1;
return this.createToken(TokenType.NEWLINE, '\n', startLine, startColumn);
default:
return null;
}
}

if (char === '=') return this.handleEqualOperator(startLine, startColumn);
if (char === '!') return this.handleNotOperator(startLine, startColumn);
if (char === '<') return this.handleLessThanOperator(startLine, startColumn);
if (char === '>') return this.handleGreaterThanOperator(startLine, startColumn);
if (char === '&') return this.handleAmpersandOperator(startLine, startColumn);
if (char === '|') return this.handlePipeOperator(startLine, startColumn);
if (char === '^') return this.handleCaretOperator(startLine, startColumn);
if (char === '?') return this.handleQuestionOperator(startLine, startColumn);

if (char === '~') {
this.advance();
return this.createToken(TokenType.BITWISE_NOT, '~', startLine, startColumn);
private handleComparisonAndBitwiseOperators(
char: string,
startLine: number,
startColumn: number
): Token | null {
switch (char) {
case '=':
return this.handleEqualOperator(startLine, startColumn);
case '!':
return this.handleNotOperator(startLine, startColumn);
case '<':
return this.handleLessThanOperator(startLine, startColumn);
case '>':
return this.handleGreaterThanOperator(startLine, startColumn);
case '&':
return this.handleAmpersandOperator(startLine, startColumn);
case '|':
return this.handlePipeOperator(startLine, startColumn);
case '^':
return this.handleCaretOperator(startLine, startColumn);
case '?':
return this.handleQuestionOperator(startLine, startColumn);
case '~':
this.advance();
return this.createToken(TokenType.BITWISE_NOT, '~', startLine, startColumn);
default:
return null;
}
}

private handleLiteralsAndIdentifiers(
char: string,
startLine: number,
startColumn: number
): Token {
if (char === '"' || char === "'") {
return this.readString(char, startLine, startColumn);
}
Expand Down
6 changes: 3 additions & 3 deletions src/module-system/module-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,17 +424,17 @@ export class ModuleRegistry {
}

// For relative paths, try to find the matching module
const possiblePaths = [
const possiblePaths = new Set([
path.resolve(fromDir, specifier),
path.resolve(fromDir, specifier + '.som'),
path.resolve(fromDir, specifier + '.js'),
path.resolve(fromDir, specifier, 'index.som'),
path.resolve(fromDir, specifier, 'index.js'),
];
]);

// Find a registered module that matches one of the possible paths
for (const mod of this.modules.values()) {
if (possiblePaths.includes(mod.resolvedPath)) {
if (possiblePaths.has(mod.resolvedPath)) {
return mod.id;
}
}
Expand Down
18 changes: 11 additions & 7 deletions src/module-system/module-system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,9 +259,8 @@ export class ModuleSystem {
this.validateResourceLimits(options, errors);

if (errors.length > 0) {
throw new Error(
`ModuleSystem configuration validation failed:\n${errors.map((e, i) => ` ${i + 1}. ${e}`).join('\n')}`
);
const formattedErrors = errors.map((e, i) => ` ${i + 1}. ${e}`).join('\n');
throw new Error(`ModuleSystem configuration validation failed:\n${formattedErrors}`);
}
}

Expand Down Expand Up @@ -765,7 +764,12 @@ export class ModuleSystem {

const warningInfo =
compilationResult.warnings.length > 0
? `\n\nWarnings (${compilationResult.warnings.length}):\n${compilationResult.warnings.map((w, i) => ` ${i + 1}. ${w}`).join('\n')}`
? (() => {
const formattedWarnings = compilationResult.warnings
.map((w, i) => ` ${i + 1}. ${w}`)
.join('\n');
return `\n\nWarnings (${compilationResult.warnings.length}):\n${formattedWarnings}`;
})()
: '';

const errorMessage = `Bundle process failed with ${compilationResult.errors.length} error(s):\n\n${errorDetails}${warningInfo}`;
Expand Down Expand Up @@ -1026,20 +1030,20 @@ export class ModuleSystem {

const watcher = chokidar.watch(Array.from(watchRoots), watchConfig);

const supportedEvents: ModuleWatchEventType[] = [
const supportedEvents = new Set<ModuleWatchEventType>([
'add',
'change',
'unlink',
'addDir',
'unlinkDir',
];
]);

watcher.on('all', (event: string, changedPath: string) => {
if (!options.onChange) {
return;
}

if (!supportedEvents.includes(event as ModuleWatchEventType)) {
if (!supportedEvents.has(event as ModuleWatchEventType)) {
return;
}

Expand Down
9 changes: 8 additions & 1 deletion src/module-system/prometheus-metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@
/**
* Helper to add a gauge metric
*/
private addGaugeMetric(

Check warning on line 146 in src/module-system/prometheus-metrics.ts

View workflow job for this annotation

GitHub Actions / Test on Node.js 24.x

Method 'addGaugeMetric' has too many parameters (6). Maximum allowed is 5

Check warning on line 146 in src/module-system/prometheus-metrics.ts

View workflow job for this annotation

GitHub Actions / Test on Node.js 23.x

Method 'addGaugeMetric' has too many parameters (6). Maximum allowed is 5

Check warning on line 146 in src/module-system/prometheus-metrics.ts

View workflow job for this annotation

GitHub Actions / Test on Node.js 20.x

Method 'addGaugeMetric' has too many parameters (6). Maximum allowed is 5

Check warning on line 146 in src/module-system/prometheus-metrics.ts

View workflow job for this annotation

GitHub Actions / Test on Node.js 22.x

Method 'addGaugeMetric' has too many parameters (6). Maximum allowed is 5
lines: string[],
name: string,
help: string,
Expand Down Expand Up @@ -213,7 +213,14 @@
);

for (const [name, status] of Object.entries(cbStats)) {
const stateValue = status.state === 'closed' ? 0 : status.state === 'open' ? 1 : 2;
let stateValue: number;
if (status.state === 'closed') {
stateValue = 0;
} else if (status.state === 'open') {
stateValue = 1;
} else {
stateValue = 2;
}
lines.push(`${this.prefix}_circuit_breaker_state{name="${name}"} ${stateValue} ${timestamp}`);
lines.push(
`${this.prefix}_circuit_breaker_failures{name="${name}"} ${status.failures} ${timestamp}`
Expand Down
4 changes: 2 additions & 2 deletions src/module-system/resource-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Production-grade resource limiting and monitoring
* Prevents memory exhaustion and resource leaks
*/
import * as process from 'process';
import * as process from 'node:process';

export interface ResourceLimits {
/** Maximum heap memory in bytes (default: 1GB) */
Expand Down Expand Up @@ -33,7 +33,7 @@ export type ResourceWarningCallback = (_usage: ResourceUsage, _limit: string) =>
export class ResourceLimiter {
private readonly limits: Required<ResourceLimits>;
private checkIntervalId?: ReturnType<typeof setInterval>;
private warningCallbacks: ResourceWarningCallback[] = [];
private readonly warningCallbacks: ResourceWarningCallback[] = [];
private moduleCount = 0;
private fileHandleCount = 0;

Expand Down
4 changes: 2 additions & 2 deletions src/module-system/runtime-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
* Runtime configuration and health check system
* Provides dynamic configuration updates and HTTP management endpoints
*/
import * as http from 'http';
import * as url from 'url';
import * as http from 'node:http';
import * as url from 'node:url';
import { ModuleSystemMetrics } from './metrics';
import { CircuitBreakerManager } from './circuit-breaker';
import { LoggerFactory, LogLevel } from './logger';
Expand Down
2 changes: 1 addition & 1 deletion src/module-system/signal-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface SignalHandlerOptions {
* Graceful shutdown manager for production systems
*/
export class SignalHandler {
private handlers: ShutdownHandler[] = [];
private readonly handlers: ShutdownHandler[] = [];
private isShuttingDown = false;
private readonly shutdownTimeout: number;
private readonly logger?: SignalHandlerOptions['logger'];
Expand Down
4 changes: 2 additions & 2 deletions src/module-system/structured-logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* Structured logging with JSON support and correlation IDs
*/
import { randomBytes } from 'crypto';
import { randomBytes } from 'node:crypto';

export interface LogContext {
correlationId?: string;
Expand Down Expand Up @@ -207,7 +207,7 @@ export class StructuredLogger {
* Global logger factory with structured logging support
*/
export class StructuredLoggerFactory {
private static loggers = new Map<string, StructuredLogger>();
private static readonly loggers = new Map<string, StructuredLogger>();
private static globalOptions: StructuredLoggerOptions = {
format: process.env.LOG_FORMAT === 'json' ? 'json' : 'text',
level: (process.env.LOG_LEVEL as LogLevel) || 'info',
Expand Down
6 changes: 3 additions & 3 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ export class Parser {
private tokens: Token[];
private current: number = 0;
private errors: string[] = [];
private importHandler: ImportHandler;
private declarationHandler: DeclarationHandler;
private loopHandler: LoopHandler;
private readonly importHandler: ImportHandler;
private readonly declarationHandler: DeclarationHandler;
private readonly loopHandler: LoopHandler;

constructor(tokens: Token[]) {
this.tokens = tokens;
Expand Down
4 changes: 2 additions & 2 deletions src/production-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
* Implements AGENTS.md principle: "Fail fast, fail clearly"
*/

import * as fs from 'fs';
import * as path from 'path';
import * as fs from 'node:fs';
import * as path from 'node:path';

export interface ValidationError {
category: 'environment' | 'permissions' | 'configuration';
Expand Down
Loading
Loading