@soulcraft/brainy 2.15.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +249 -152
  3. package/dist/api/ConfigAPI.d.ts +67 -0
  4. package/dist/api/ConfigAPI.js +166 -0
  5. package/dist/api/DataAPI.d.ts +123 -0
  6. package/dist/api/DataAPI.js +391 -0
  7. package/dist/api/SecurityAPI.d.ts +50 -0
  8. package/dist/api/SecurityAPI.js +139 -0
  9. package/dist/api/UniversalImportAPI.d.ts +134 -0
  10. package/dist/api/UniversalImportAPI.js +615 -0
  11. package/dist/augmentationManager.js +12 -7
  12. package/dist/augmentationPipeline.d.ts +0 -61
  13. package/dist/augmentationPipeline.js +0 -87
  14. package/dist/augmentationRegistry.d.ts +1 -1
  15. package/dist/augmentationRegistry.js +1 -1
  16. package/dist/augmentations/apiServerAugmentation.d.ts +27 -1
  17. package/dist/augmentations/apiServerAugmentation.js +288 -7
  18. package/dist/augmentations/auditLogAugmentation.d.ts +109 -0
  19. package/dist/augmentations/auditLogAugmentation.js +358 -0
  20. package/dist/augmentations/batchProcessingAugmentation.d.ts +3 -2
  21. package/dist/augmentations/batchProcessingAugmentation.js +123 -22
  22. package/dist/augmentations/brainyAugmentation.d.ts +87 -8
  23. package/dist/augmentations/brainyAugmentation.js +159 -2
  24. package/dist/augmentations/cacheAugmentation.d.ts +6 -5
  25. package/dist/augmentations/cacheAugmentation.js +113 -17
  26. package/dist/augmentations/conduitAugmentations.d.ts +2 -2
  27. package/dist/augmentations/conduitAugmentations.js +2 -2
  28. package/dist/augmentations/configResolver.d.ts +122 -0
  29. package/dist/augmentations/configResolver.js +440 -0
  30. package/dist/augmentations/connectionPoolAugmentation.d.ts +3 -1
  31. package/dist/augmentations/connectionPoolAugmentation.js +37 -12
  32. package/dist/augmentations/defaultAugmentations.d.ts +9 -11
  33. package/dist/augmentations/defaultAugmentations.js +4 -11
  34. package/dist/augmentations/discovery/catalogDiscovery.d.ts +142 -0
  35. package/dist/augmentations/discovery/catalogDiscovery.js +249 -0
  36. package/dist/augmentations/discovery/localDiscovery.d.ts +84 -0
  37. package/dist/augmentations/discovery/localDiscovery.js +246 -0
  38. package/dist/augmentations/discovery/runtimeLoader.d.ts +97 -0
  39. package/dist/augmentations/discovery/runtimeLoader.js +337 -0
  40. package/dist/augmentations/discovery.d.ts +152 -0
  41. package/dist/augmentations/discovery.js +441 -0
  42. package/dist/augmentations/display/intelligentComputation.d.ts +1 -1
  43. package/dist/augmentations/display/intelligentComputation.js +4 -4
  44. package/dist/augmentations/entityRegistryAugmentation.d.ts +3 -1
  45. package/dist/augmentations/entityRegistryAugmentation.js +5 -1
  46. package/dist/augmentations/indexAugmentation.d.ts +3 -3
  47. package/dist/augmentations/indexAugmentation.js +2 -2
  48. package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +22 -6
  49. package/dist/augmentations/intelligentVerbScoringAugmentation.js +106 -23
  50. package/dist/augmentations/manifest.d.ts +176 -0
  51. package/dist/augmentations/manifest.js +8 -0
  52. package/dist/augmentations/marketplace/AugmentationMarketplace.d.ts +168 -0
  53. package/dist/augmentations/marketplace/AugmentationMarketplace.js +329 -0
  54. package/dist/augmentations/marketplace/cli.d.ts +47 -0
  55. package/dist/augmentations/marketplace/cli.js +265 -0
  56. package/dist/augmentations/metricsAugmentation.d.ts +3 -3
  57. package/dist/augmentations/metricsAugmentation.js +2 -2
  58. package/dist/augmentations/monitoringAugmentation.d.ts +3 -3
  59. package/dist/augmentations/monitoringAugmentation.js +2 -2
  60. package/dist/augmentations/neuralImport.d.ts +1 -1
  61. package/dist/augmentations/rateLimitAugmentation.d.ts +82 -0
  62. package/dist/augmentations/rateLimitAugmentation.js +321 -0
  63. package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +2 -2
  64. package/dist/augmentations/requestDeduplicatorAugmentation.js +1 -1
  65. package/dist/augmentations/storageAugmentation.d.ts +1 -1
  66. package/dist/augmentations/storageAugmentation.js +2 -2
  67. package/dist/augmentations/storageAugmentations.d.ts +37 -8
  68. package/dist/augmentations/storageAugmentations.js +204 -15
  69. package/dist/augmentations/synapseAugmentation.d.ts +1 -1
  70. package/dist/augmentations/synapseAugmentation.js +35 -16
  71. package/dist/augmentations/typeMatching/intelligentTypeMatcher.d.ts +39 -59
  72. package/dist/augmentations/typeMatching/intelligentTypeMatcher.js +103 -389
  73. package/dist/augmentations/universalDisplayAugmentation.d.ts +2 -2
  74. package/dist/augmentations/universalDisplayAugmentation.js +2 -2
  75. package/dist/brainy-unified.d.ts +106 -0
  76. package/dist/brainy-unified.js +327 -0
  77. package/dist/brainy.d.ts +273 -0
  78. package/dist/brainy.js +1181 -0
  79. package/dist/brainyData.d.ts +29 -72
  80. package/dist/brainyData.js +350 -304
  81. package/dist/brainyDataV3.d.ts +186 -0
  82. package/dist/brainyDataV3.js +337 -0
  83. package/dist/browserFramework.d.ts +6 -6
  84. package/dist/browserFramework.js +11 -8
  85. package/dist/browserFramework.minimal.d.ts +5 -5
  86. package/dist/browserFramework.minimal.js +11 -8
  87. package/dist/config/index.d.ts +2 -2
  88. package/dist/config/index.js +3 -3
  89. package/dist/config/modelAutoConfig.d.ts +6 -7
  90. package/dist/config/modelAutoConfig.js +17 -76
  91. package/dist/cortex/backupRestore.d.ts +2 -2
  92. package/dist/cortex/backupRestore.js +85 -27
  93. package/dist/cortex/healthCheck.d.ts +2 -2
  94. package/dist/cortex/neuralImport.d.ts +2 -2
  95. package/dist/cortex/neuralImport.js +18 -13
  96. package/dist/cortex/performanceMonitor.d.ts +2 -2
  97. package/dist/critical/model-guardian.d.ts +4 -0
  98. package/dist/critical/model-guardian.js +31 -11
  99. package/dist/demo.d.ts +4 -4
  100. package/dist/demo.js +7 -7
  101. package/dist/distributed/cacheSync.d.ts +112 -0
  102. package/dist/distributed/cacheSync.js +265 -0
  103. package/dist/distributed/coordinator.d.ts +193 -0
  104. package/dist/distributed/coordinator.js +548 -0
  105. package/dist/distributed/httpTransport.d.ts +120 -0
  106. package/dist/distributed/httpTransport.js +446 -0
  107. package/dist/distributed/index.d.ts +8 -0
  108. package/dist/distributed/index.js +5 -0
  109. package/dist/distributed/networkTransport.d.ts +132 -0
  110. package/dist/distributed/networkTransport.js +633 -0
  111. package/dist/distributed/queryPlanner.d.ts +104 -0
  112. package/dist/distributed/queryPlanner.js +327 -0
  113. package/dist/distributed/readWriteSeparation.d.ts +134 -0
  114. package/dist/distributed/readWriteSeparation.js +350 -0
  115. package/dist/distributed/shardManager.d.ts +114 -0
  116. package/dist/distributed/shardManager.js +357 -0
  117. package/dist/distributed/shardMigration.d.ts +110 -0
  118. package/dist/distributed/shardMigration.js +289 -0
  119. package/dist/distributed/storageDiscovery.d.ts +160 -0
  120. package/dist/distributed/storageDiscovery.js +551 -0
  121. package/dist/embeddings/EmbeddingManager.d.ts +0 -4
  122. package/dist/embeddings/EmbeddingManager.js +21 -26
  123. package/dist/errors/brainyError.d.ts +5 -1
  124. package/dist/errors/brainyError.js +12 -0
  125. package/dist/examples/basicUsage.js +3 -3
  126. package/dist/graph/graphAdjacencyIndex.d.ts +96 -0
  127. package/dist/graph/graphAdjacencyIndex.js +288 -0
  128. package/dist/graph/pathfinding.js +4 -2
  129. package/dist/hnsw/scaledHNSWSystem.js +11 -2
  130. package/dist/importManager.js +6 -3
  131. package/dist/index.d.ts +12 -21
  132. package/dist/index.js +14 -22
  133. package/dist/mcp/brainyMCPAdapter.d.ts +4 -4
  134. package/dist/mcp/brainyMCPAdapter.js +5 -5
  135. package/dist/mcp/brainyMCPService.d.ts +3 -3
  136. package/dist/mcp/brainyMCPService.js +3 -11
  137. package/dist/mcp/mcpAugmentationToolset.js +20 -30
  138. package/dist/neural/embeddedPatterns.d.ts +1 -1
  139. package/dist/neural/embeddedPatterns.js +2 -2
  140. package/dist/neural/entityExtractor.d.ts +65 -0
  141. package/dist/neural/entityExtractor.js +316 -0
  142. package/dist/neural/improvedNeuralAPI.js +90 -79
  143. package/dist/neural/naturalLanguageProcessor.d.ts +155 -10
  144. package/dist/neural/naturalLanguageProcessor.js +941 -66
  145. package/dist/neural/naturalLanguageProcessorStatic.d.ts +2 -2
  146. package/dist/neural/naturalLanguageProcessorStatic.js +3 -3
  147. package/dist/neural/neuralAPI.js +8 -2
  148. package/dist/neural/patternLibrary.d.ts +57 -3
  149. package/dist/neural/patternLibrary.js +348 -13
  150. package/dist/neural/staticPatternMatcher.d.ts +2 -2
  151. package/dist/neural/staticPatternMatcher.js +2 -2
  152. package/dist/shared/default-augmentations.d.ts +3 -3
  153. package/dist/shared/default-augmentations.js +5 -5
  154. package/dist/storage/adapters/fileSystemStorage.d.ts +4 -0
  155. package/dist/storage/adapters/fileSystemStorage.js +54 -1
  156. package/dist/storage/adapters/memoryStorage.js +13 -8
  157. package/dist/storage/backwardCompatibility.d.ts +10 -78
  158. package/dist/storage/backwardCompatibility.js +17 -132
  159. package/dist/storage/baseStorage.d.ts +6 -0
  160. package/dist/storage/baseStorage.js +17 -0
  161. package/dist/storage/cacheManager.js +2 -2
  162. package/dist/storage/readOnlyOptimizations.js +8 -3
  163. package/dist/streaming/pipeline.d.ts +154 -0
  164. package/dist/streaming/pipeline.js +551 -0
  165. package/dist/triple/TripleIntelligence.d.ts +25 -110
  166. package/dist/triple/TripleIntelligence.js +4 -574
  167. package/dist/triple/TripleIntelligenceSystem.d.ts +159 -0
  168. package/dist/triple/TripleIntelligenceSystem.js +519 -0
  169. package/dist/types/apiTypes.d.ts +278 -0
  170. package/dist/types/apiTypes.js +33 -0
  171. package/dist/types/brainy.types.d.ts +308 -0
  172. package/dist/types/brainy.types.js +8 -0
  173. package/dist/types/brainyDataInterface.d.ts +3 -3
  174. package/dist/types/brainyDataInterface.js +2 -2
  175. package/dist/types/graphTypes.js +2 -2
  176. package/dist/utils/cacheAutoConfig.d.ts +3 -3
  177. package/dist/utils/embedding.js +8 -14
  178. package/dist/utils/enhancedLogger.d.ts +104 -0
  179. package/dist/utils/enhancedLogger.js +232 -0
  180. package/dist/utils/index.d.ts +1 -1
  181. package/dist/utils/index.js +1 -1
  182. package/dist/utils/intelligentTypeMapper.d.ts +60 -0
  183. package/dist/utils/intelligentTypeMapper.js +349 -0
  184. package/dist/utils/metadataIndex.d.ts +118 -1
  185. package/dist/utils/metadataIndex.js +539 -16
  186. package/dist/utils/paramValidation.d.ts +39 -0
  187. package/dist/utils/paramValidation.js +192 -0
  188. package/dist/utils/rateLimiter.d.ts +160 -0
  189. package/dist/utils/rateLimiter.js +271 -0
  190. package/dist/utils/statistics.d.ts +4 -4
  191. package/dist/utils/statistics.js +3 -3
  192. package/dist/utils/structuredLogger.d.ts +146 -0
  193. package/dist/utils/structuredLogger.js +394 -0
  194. package/dist/utils/textEncoding.js +2 -1
  195. package/dist/utils/typeValidation.d.ts +34 -0
  196. package/dist/utils/typeValidation.js +247 -0
  197. package/package.json +14 -6
  198. package/scripts/download-models.cjs +6 -15
  199. package/dist/augmentations/walAugmentation.d.ts +0 -111
  200. package/dist/augmentations/walAugmentation.js +0 -519
  201. package/dist/chat/BrainyChat.d.ts +0 -121
  202. package/dist/chat/BrainyChat.js +0 -396
  203. package/dist/chat/ChatCLI.d.ts +0 -61
  204. package/dist/chat/ChatCLI.js +0 -351
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Enhanced Structured Logging System for Brainy
3
+ * Provides production-ready logging with structured output, context preservation,
4
+ * performance tracking, and multiple transport support
5
+ */
6
+ export declare enum LogLevel {
7
+ SILENT = -1,
8
+ FATAL = 0,
9
+ ERROR = 1,
10
+ WARN = 2,
11
+ INFO = 3,
12
+ DEBUG = 4,
13
+ TRACE = 5
14
+ }
15
+ export interface LogContext {
16
+ requestId?: string;
17
+ userId?: string;
18
+ operation?: string;
19
+ entityId?: string;
20
+ entityType?: string;
21
+ [key: string]: any;
22
+ }
23
+ export interface LogEntry {
24
+ timestamp: string;
25
+ level: string;
26
+ levelNumeric: number;
27
+ module: string;
28
+ message: string;
29
+ context?: LogContext;
30
+ data?: any;
31
+ error?: {
32
+ name: string;
33
+ message: string;
34
+ stack?: string;
35
+ code?: string;
36
+ };
37
+ performance?: {
38
+ duration?: number;
39
+ memory?: {
40
+ used: number;
41
+ total: number;
42
+ };
43
+ };
44
+ host?: string;
45
+ pid: number;
46
+ version?: string;
47
+ }
48
+ export interface LogTransport {
49
+ name: string;
50
+ log(entry: LogEntry): void | Promise<void>;
51
+ flush?(): Promise<void>;
52
+ }
53
+ export interface StructuredLoggerConfig {
54
+ level: LogLevel;
55
+ modules?: Record<string, LogLevel>;
56
+ format: 'json' | 'pretty' | 'simple';
57
+ transports: LogTransport[];
58
+ context?: LogContext;
59
+ includeHost?: boolean;
60
+ includeMemory?: boolean;
61
+ bufferSize?: number;
62
+ flushInterval?: number;
63
+ version?: string;
64
+ }
65
+ export declare class StructuredLogger {
66
+ private static instance;
67
+ private config;
68
+ private defaultContext;
69
+ private performanceMarks;
70
+ private constructor();
71
+ private loadEnvironmentConfig;
72
+ static getInstance(): StructuredLogger;
73
+ configure(config: Partial<StructuredLoggerConfig>): void;
74
+ setContext(context: LogContext): void;
75
+ clearContext(): void;
76
+ withContext(context: LogContext): StructuredLogger;
77
+ startTimer(label: string): void;
78
+ endTimer(label: string): number | undefined;
79
+ private shouldLog;
80
+ private createLogEntry;
81
+ private log;
82
+ fatal(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
83
+ error(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
84
+ warn(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
85
+ info(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
86
+ debug(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
87
+ trace(module: string, message: string, contextOrData?: LogContext | any, data?: any): void;
88
+ createModuleLogger(module: string): {
89
+ fatal: (message: string, contextOrData?: LogContext | any, data?: any) => void;
90
+ error: (message: string, contextOrData?: LogContext | any, data?: any) => void;
91
+ warn: (message: string, contextOrData?: LogContext | any, data?: any) => void;
92
+ info: (message: string, contextOrData?: LogContext | any, data?: any) => void;
93
+ debug: (message: string, contextOrData?: LogContext | any, data?: any) => void;
94
+ trace: (message: string, contextOrData?: LogContext | any, data?: any) => void;
95
+ withContext: (context: LogContext) => {
96
+ fatal: (message: string, contextOrData?: LogContext | any, data?: any) => void;
97
+ error: (message: string, contextOrData?: LogContext | any, data?: any) => void;
98
+ warn: (message: string, contextOrData?: LogContext | any, data?: any) => void;
99
+ info: (message: string, contextOrData?: LogContext | any, data?: any) => void;
100
+ debug: (message: string, contextOrData?: LogContext | any, data?: any) => void;
101
+ trace: (message: string, contextOrData?: LogContext | any, data?: any) => void;
102
+ withContext: (context: LogContext) => /*elided*/ any;
103
+ startTimer: (label: string) => void;
104
+ endTimer: (label: string) => number | undefined;
105
+ };
106
+ startTimer: (label: string) => void;
107
+ endTimer: (label: string) => number | undefined;
108
+ };
109
+ flush(): Promise<void>;
110
+ addTransport(transport: LogTransport): void;
111
+ removeTransport(name: string): void;
112
+ child(context: LogContext): StructuredLogger;
113
+ }
114
+ export declare const structuredLogger: StructuredLogger;
115
+ export declare function createModuleLogger(module: string): {
116
+ fatal: (message: string, contextOrData?: LogContext | any, data?: any) => void;
117
+ error: (message: string, contextOrData?: LogContext | any, data?: any) => void;
118
+ warn: (message: string, contextOrData?: LogContext | any, data?: any) => void;
119
+ info: (message: string, contextOrData?: LogContext | any, data?: any) => void;
120
+ debug: (message: string, contextOrData?: LogContext | any, data?: any) => void;
121
+ trace: (message: string, contextOrData?: LogContext | any, data?: any) => void;
122
+ withContext: (context: LogContext) => /*elided*/ any;
123
+ startTimer: (label: string) => void;
124
+ endTimer: (label: string) => number | undefined;
125
+ };
126
+ export declare function setLogContext(context: LogContext): void;
127
+ export declare function withLogContext(context: LogContext): StructuredLogger;
128
+ export declare function createCorrelationId(): string;
129
+ export declare function logPerformance(logger: ReturnType<typeof createModuleLogger>, operation: string, fn: () => any): any;
130
+ export declare class LoggerCompatibilityWrapper {
131
+ private moduleLogger;
132
+ constructor(module?: string);
133
+ error(module: string, message: string, ...args: any[]): void;
134
+ warn(module: string, message: string, ...args: any[]): void;
135
+ info(module: string, message: string, ...args: any[]): void;
136
+ debug(module: string, message: string, ...args: any[]): void;
137
+ trace(module: string, message: string, ...args: any[]): void;
138
+ createModuleLogger(module: string): {
139
+ error: (message: string, ...args: any[]) => void;
140
+ warn: (message: string, ...args: any[]) => void;
141
+ info: (message: string, ...args: any[]) => void;
142
+ debug: (message: string, ...args: any[]) => void;
143
+ trace: (message: string, ...args: any[]) => void;
144
+ };
145
+ }
146
+ export type ModuleLogger = ReturnType<typeof createModuleLogger>;
@@ -0,0 +1,394 @@
1
+ /**
2
+ * Enhanced Structured Logging System for Brainy
3
+ * Provides production-ready logging with structured output, context preservation,
4
+ * performance tracking, and multiple transport support
5
+ */
6
+ import { performance } from 'perf_hooks';
7
+ import { hostname } from 'os';
8
+ import { randomUUID } from 'crypto';
9
+ export var LogLevel;
10
+ (function (LogLevel) {
11
+ LogLevel[LogLevel["SILENT"] = -1] = "SILENT";
12
+ LogLevel[LogLevel["FATAL"] = 0] = "FATAL";
13
+ LogLevel[LogLevel["ERROR"] = 1] = "ERROR";
14
+ LogLevel[LogLevel["WARN"] = 2] = "WARN";
15
+ LogLevel[LogLevel["INFO"] = 3] = "INFO";
16
+ LogLevel[LogLevel["DEBUG"] = 4] = "DEBUG";
17
+ LogLevel[LogLevel["TRACE"] = 5] = "TRACE";
18
+ })(LogLevel || (LogLevel = {}));
19
+ class ConsoleTransport {
20
+ constructor(format = 'json') {
21
+ this.name = 'console';
22
+ this.format = format;
23
+ }
24
+ log(entry) {
25
+ const method = this.getConsoleMethod(entry.levelNumeric);
26
+ if (this.format === 'json') {
27
+ method(JSON.stringify(entry));
28
+ }
29
+ else if (this.format === 'pretty') {
30
+ const color = this.getColor(entry.levelNumeric);
31
+ const prefix = `${entry.timestamp} ${color}[${entry.level}]\\x1b[0m [${entry.module}]`;
32
+ const message = entry.message;
33
+ if (entry.error) {
34
+ method(`${prefix} ${message}`, entry.error);
35
+ }
36
+ else if (entry.data) {
37
+ method(`${prefix} ${message}`, entry.data);
38
+ }
39
+ else {
40
+ method(`${prefix} ${message}`);
41
+ }
42
+ }
43
+ else {
44
+ // Simple format
45
+ method(`[${entry.level}] ${entry.message}`);
46
+ }
47
+ }
48
+ getConsoleMethod(level) {
49
+ switch (level) {
50
+ case LogLevel.FATAL:
51
+ case LogLevel.ERROR:
52
+ return console.error;
53
+ case LogLevel.WARN:
54
+ return console.warn;
55
+ case LogLevel.INFO:
56
+ return console.info;
57
+ default:
58
+ return console.log;
59
+ }
60
+ }
61
+ getColor(level) {
62
+ switch (level) {
63
+ case LogLevel.FATAL:
64
+ return '\\x1b[35m'; // Magenta
65
+ case LogLevel.ERROR:
66
+ return '\\x1b[31m'; // Red
67
+ case LogLevel.WARN:
68
+ return '\\x1b[33m'; // Yellow
69
+ case LogLevel.INFO:
70
+ return '\\x1b[36m'; // Cyan
71
+ case LogLevel.DEBUG:
72
+ return '\\x1b[32m'; // Green
73
+ case LogLevel.TRACE:
74
+ return '\\x1b[90m'; // Gray
75
+ default:
76
+ return '\\x1b[0m'; // Reset
77
+ }
78
+ }
79
+ }
80
+ class BufferedTransport {
81
+ constructor(innerTransport, bufferSize = 100, flushInterval = 5000) {
82
+ this.name = 'buffered';
83
+ this.buffer = [];
84
+ this.innerTransport = innerTransport;
85
+ this.bufferSize = bufferSize;
86
+ if (flushInterval > 0) {
87
+ this.flushTimer = setInterval(() => this.flush(), flushInterval);
88
+ }
89
+ }
90
+ log(entry) {
91
+ this.buffer.push(entry);
92
+ if (this.buffer.length >= this.bufferSize) {
93
+ this.flush();
94
+ }
95
+ }
96
+ async flush() {
97
+ const entries = this.buffer.splice(0);
98
+ for (const entry of entries) {
99
+ await this.innerTransport.log(entry);
100
+ }
101
+ if (this.innerTransport.flush) {
102
+ await this.innerTransport.flush();
103
+ }
104
+ }
105
+ destroy() {
106
+ if (this.flushTimer) {
107
+ clearInterval(this.flushTimer);
108
+ }
109
+ this.flush();
110
+ }
111
+ }
112
+ export class StructuredLogger {
113
+ constructor() {
114
+ this.defaultContext = {};
115
+ this.performanceMarks = new Map();
116
+ const isDevelopment = process.env.NODE_ENV !== 'production';
117
+ const format = isDevelopment ? 'pretty' : 'json';
118
+ this.config = {
119
+ level: isDevelopment ? LogLevel.DEBUG : LogLevel.INFO,
120
+ format,
121
+ transports: [new ConsoleTransport(format)],
122
+ includeHost: !isDevelopment,
123
+ includeMemory: false,
124
+ bufferSize: 100,
125
+ flushInterval: 5000,
126
+ version: process.env.npm_package_version
127
+ };
128
+ // Load from environment
129
+ this.loadEnvironmentConfig();
130
+ }
131
+ loadEnvironmentConfig() {
132
+ const envLevel = process.env.BRAINY_LOG_LEVEL;
133
+ if (envLevel) {
134
+ const level = LogLevel[envLevel.toUpperCase()];
135
+ if (level !== undefined) {
136
+ this.config.level = level;
137
+ }
138
+ }
139
+ const envFormat = process.env.BRAINY_LOG_FORMAT;
140
+ if (envFormat && ['json', 'pretty', 'simple'].includes(envFormat)) {
141
+ this.config.format = envFormat;
142
+ }
143
+ const moduleConfig = process.env.BRAINY_MODULE_LOG_LEVELS;
144
+ if (moduleConfig) {
145
+ try {
146
+ this.config.modules = JSON.parse(moduleConfig);
147
+ }
148
+ catch {
149
+ // Ignore parse errors
150
+ }
151
+ }
152
+ }
153
+ static getInstance() {
154
+ if (!StructuredLogger.instance) {
155
+ StructuredLogger.instance = new StructuredLogger();
156
+ }
157
+ return StructuredLogger.instance;
158
+ }
159
+ configure(config) {
160
+ this.config = { ...this.config, ...config };
161
+ }
162
+ setContext(context) {
163
+ this.defaultContext = { ...this.defaultContext, ...context };
164
+ }
165
+ clearContext() {
166
+ this.defaultContext = {};
167
+ }
168
+ withContext(context) {
169
+ const contextualLogger = Object.create(this);
170
+ contextualLogger.defaultContext = { ...this.defaultContext, ...context };
171
+ return contextualLogger;
172
+ }
173
+ startTimer(label) {
174
+ this.performanceMarks.set(label, performance.now());
175
+ }
176
+ endTimer(label) {
177
+ const start = this.performanceMarks.get(label);
178
+ if (start === undefined)
179
+ return undefined;
180
+ const duration = performance.now() - start;
181
+ this.performanceMarks.delete(label);
182
+ return duration;
183
+ }
184
+ shouldLog(level, module) {
185
+ if (this.config.modules?.[module] !== undefined) {
186
+ return level <= this.config.modules[module];
187
+ }
188
+ return level <= this.config.level;
189
+ }
190
+ createLogEntry(level, module, message, context, data, error) {
191
+ const entry = {
192
+ timestamp: new Date().toISOString(),
193
+ level: LogLevel[level],
194
+ levelNumeric: level,
195
+ module,
196
+ message,
197
+ pid: process.pid,
198
+ version: this.config.version
199
+ };
200
+ // Merge contexts
201
+ const mergedContext = { ...this.defaultContext, ...context };
202
+ if (Object.keys(mergedContext).length > 0) {
203
+ entry.context = mergedContext;
204
+ }
205
+ if (data !== undefined) {
206
+ entry.data = data;
207
+ }
208
+ if (error) {
209
+ entry.error = {
210
+ name: error.name,
211
+ message: error.message,
212
+ stack: error.stack,
213
+ code: error.code
214
+ };
215
+ }
216
+ if (this.config.includeHost) {
217
+ entry.host = hostname();
218
+ }
219
+ if (this.config.includeMemory) {
220
+ const mem = process.memoryUsage();
221
+ entry.performance = {
222
+ memory: {
223
+ used: Math.round(mem.heapUsed / 1024 / 1024),
224
+ total: Math.round(mem.heapTotal / 1024 / 1024)
225
+ }
226
+ };
227
+ }
228
+ return entry;
229
+ }
230
+ log(level, module, message, contextOrData, data) {
231
+ if (!this.shouldLog(level, module)) {
232
+ return;
233
+ }
234
+ // Handle overloaded parameters
235
+ let context;
236
+ let logData;
237
+ if (contextOrData && typeof contextOrData === 'object' && !Array.isArray(contextOrData)) {
238
+ // Check if it looks like a context object
239
+ const hasContextKeys = ['requestId', 'userId', 'operation', 'entityId', 'entityType']
240
+ .some(key => key in contextOrData);
241
+ if (hasContextKeys) {
242
+ context = contextOrData;
243
+ logData = data;
244
+ }
245
+ else {
246
+ logData = contextOrData;
247
+ }
248
+ }
249
+ else {
250
+ logData = contextOrData;
251
+ }
252
+ // Extract error if present
253
+ let error;
254
+ if (logData instanceof Error) {
255
+ error = logData;
256
+ logData = undefined;
257
+ }
258
+ else if (logData?.error instanceof Error) {
259
+ error = logData.error;
260
+ delete logData.error;
261
+ }
262
+ const entry = this.createLogEntry(level, module, message, context, logData, error);
263
+ // Send to all transports
264
+ for (const transport of this.config.transports) {
265
+ try {
266
+ transport.log(entry);
267
+ }
268
+ catch (err) {
269
+ // Fallback to console.error if transport fails
270
+ console.error('Logger transport error:', err);
271
+ }
272
+ }
273
+ }
274
+ fatal(module, message, contextOrData, data) {
275
+ this.log(LogLevel.FATAL, module, message, contextOrData, data);
276
+ }
277
+ error(module, message, contextOrData, data) {
278
+ this.log(LogLevel.ERROR, module, message, contextOrData, data);
279
+ }
280
+ warn(module, message, contextOrData, data) {
281
+ this.log(LogLevel.WARN, module, message, contextOrData, data);
282
+ }
283
+ info(module, message, contextOrData, data) {
284
+ this.log(LogLevel.INFO, module, message, contextOrData, data);
285
+ }
286
+ debug(module, message, contextOrData, data) {
287
+ this.log(LogLevel.DEBUG, module, message, contextOrData, data);
288
+ }
289
+ trace(module, message, contextOrData, data) {
290
+ this.log(LogLevel.TRACE, module, message, contextOrData, data);
291
+ }
292
+ createModuleLogger(module) {
293
+ const self = this;
294
+ return {
295
+ fatal: (message, contextOrData, data) => self.fatal(module, message, contextOrData, data),
296
+ error: (message, contextOrData, data) => self.error(module, message, contextOrData, data),
297
+ warn: (message, contextOrData, data) => self.warn(module, message, contextOrData, data),
298
+ info: (message, contextOrData, data) => self.info(module, message, contextOrData, data),
299
+ debug: (message, contextOrData, data) => self.debug(module, message, contextOrData, data),
300
+ trace: (message, contextOrData, data) => self.trace(module, message, contextOrData, data),
301
+ withContext: (context) => {
302
+ const contextual = self.withContext(context);
303
+ return contextual.createModuleLogger(module);
304
+ },
305
+ startTimer: (label) => self.startTimer(`${module}:${label}`),
306
+ endTimer: (label) => self.endTimer(`${module}:${label}`)
307
+ };
308
+ }
309
+ async flush() {
310
+ const flushPromises = this.config.transports
311
+ .filter(t => t.flush)
312
+ .map(t => t.flush());
313
+ await Promise.all(flushPromises);
314
+ }
315
+ addTransport(transport) {
316
+ this.config.transports.push(transport);
317
+ }
318
+ removeTransport(name) {
319
+ this.config.transports = this.config.transports.filter(t => t.name !== name);
320
+ }
321
+ child(context) {
322
+ return this.withContext(context);
323
+ }
324
+ }
325
+ // Singleton instance
326
+ export const structuredLogger = StructuredLogger.getInstance();
327
+ // Convenience functions
328
+ export function createModuleLogger(module) {
329
+ return structuredLogger.createModuleLogger(module);
330
+ }
331
+ export function setLogContext(context) {
332
+ structuredLogger.setContext(context);
333
+ }
334
+ export function withLogContext(context) {
335
+ return structuredLogger.withContext(context);
336
+ }
337
+ // Correlation ID middleware helper
338
+ export function createCorrelationId() {
339
+ return randomUUID();
340
+ }
341
+ // Performance logging helper
342
+ export function logPerformance(logger, operation, fn) {
343
+ logger.startTimer(operation);
344
+ try {
345
+ const result = fn();
346
+ if (result && typeof result.then === 'function') {
347
+ return result.finally(() => {
348
+ const duration = logger.endTimer(operation);
349
+ logger.debug(`${operation} completed`, { duration });
350
+ });
351
+ }
352
+ const duration = logger.endTimer(operation);
353
+ logger.debug(`${operation} completed`, { duration });
354
+ return result;
355
+ }
356
+ catch (error) {
357
+ const duration = logger.endTimer(operation);
358
+ logger.error(`${operation} failed`, { duration, error });
359
+ throw error;
360
+ }
361
+ }
362
+ // Backward compatibility wrapper for existing logger
363
+ export class LoggerCompatibilityWrapper {
364
+ constructor(module = 'legacy') {
365
+ this.moduleLogger = createModuleLogger(module);
366
+ }
367
+ error(module, message, ...args) {
368
+ this.moduleLogger.error(message, { module, data: args });
369
+ }
370
+ warn(module, message, ...args) {
371
+ this.moduleLogger.warn(message, { module, data: args });
372
+ }
373
+ info(module, message, ...args) {
374
+ this.moduleLogger.info(message, { module, data: args });
375
+ }
376
+ debug(module, message, ...args) {
377
+ this.moduleLogger.debug(message, { module, data: args });
378
+ }
379
+ trace(module, message, ...args) {
380
+ this.moduleLogger.trace(message, { module, data: args });
381
+ }
382
+ createModuleLogger(module) {
383
+ const logger = createModuleLogger(module);
384
+ return {
385
+ error: (message, ...args) => logger.error(message, { data: args }),
386
+ warn: (message, ...args) => logger.warn(message, { data: args }),
387
+ info: (message, ...args) => logger.info(message, { data: args }),
388
+ debug: (message, ...args) => logger.debug(message, { data: args }),
389
+ trace: (message, ...args) => logger.trace(message, { data: args })
390
+ };
391
+ }
392
+ }
393
+ // Types are already exported above, no need to re-export
394
+ //# sourceMappingURL=structuredLogger.js.map
@@ -26,7 +26,8 @@ export async function applyTensorFlowPatch() {
26
26
  return globalThis;
27
27
  if (typeof global !== 'undefined')
28
28
  return global;
29
- return {};
29
+ throw new Error('Cannot apply TextEncoder/TextDecoder patches: No global object found. ' +
30
+ 'This environment does not have globalThis or global defined.');
30
31
  })();
31
32
  // Make sure TextEncoder and TextDecoder are available globally
32
33
  if (!globalObj.TextEncoder) {
@@ -23,3 +23,37 @@ export interface ValidationStats {
23
23
  }
24
24
  export declare function getValidationStats(): ValidationStats;
25
25
  export declare function resetValidationStats(): void;
26
+ export declare class ValidationError extends Error {
27
+ readonly parameter: string;
28
+ readonly value: any;
29
+ readonly constraint: string;
30
+ constructor(parameter: string, value: any, constraint: string);
31
+ }
32
+ /**
33
+ * Validate required ID parameter
34
+ * Standard validation for all ID-based operations
35
+ */
36
+ export declare function validateId(id: unknown, paramName?: string): string;
37
+ /**
38
+ * Validate search query input
39
+ * Handles string queries, vectors, and objects for search operations
40
+ */
41
+ export declare function validateSearchQuery(query: unknown, paramName?: string): any;
42
+ /**
43
+ * Validate data input for addNoun/updateNoun operations
44
+ * Handles vectors, objects, strings, and validates structure
45
+ */
46
+ export declare function validateDataInput(data: unknown, paramName?: string, allowNull?: boolean): any;
47
+ /**
48
+ * Validate search options
49
+ * Comprehensive validation for search API options
50
+ */
51
+ export declare function validateSearchOptions(options: unknown, paramName?: string): any;
52
+ /**
53
+ * Validate ID arrays (for bulk operations)
54
+ */
55
+ export declare function validateIdArray(ids: unknown, paramName?: string): string[];
56
+ /**
57
+ * Track validation stats for monitoring
58
+ */
59
+ export declare function recordValidation(success: boolean): void;