@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,246 @@
1
+ /**
2
+ * Local Augmentation Discovery
3
+ *
4
+ * Discovers augmentations installed locally in node_modules
5
+ * and built-in augmentations that ship with Brainy
6
+ */
7
+ import { existsSync, readdirSync, readFileSync } from 'fs';
8
+ import { join } from 'path';
9
+ /**
10
+ * Discovers augmentations installed locally
11
+ */
12
+ export class LocalAugmentationDiscovery {
13
+ constructor(options = {}) {
14
+ this.options = options;
15
+ this.builtInAugmentations = new Map();
16
+ this.installedAugmentations = new Map();
17
+ this.options = {
18
+ brainyPath: this.options.brainyPath || this.findBrainyPath(),
19
+ projectPath: this.options.projectPath || process.cwd(),
20
+ scanNodeModules: this.options.scanNodeModules ?? true
21
+ };
22
+ // Register built-in augmentations
23
+ this.registerBuiltIn();
24
+ }
25
+ /**
26
+ * Register built-in augmentations that ship with Brainy
27
+ */
28
+ registerBuiltIn() {
29
+ const builtIn = [
30
+ { id: 'cache', name: 'Cache', path: 'cacheAugmentation' },
31
+ { id: 'batch', name: 'Batch Processing', path: 'batchProcessingAugmentation' },
32
+ { id: 'entity-registry', name: 'Entity Registry', path: 'entityRegistryAugmentation' },
33
+ { id: 'index', name: 'Index', path: 'indexAugmentation' },
34
+ { id: 'metrics', name: 'Metrics', path: 'metricsAugmentation' },
35
+ { id: 'monitoring', name: 'Monitoring', path: 'monitoringAugmentation' },
36
+ { id: 'connection-pool', name: 'Connection Pool', path: 'connectionPoolAugmentation' },
37
+ { id: 'request-deduplicator', name: 'Request Deduplicator', path: 'requestDeduplicatorAugmentation' },
38
+ { id: 'api-server', name: 'API Server', path: 'apiServerAugmentation' },
39
+ { id: 'neural-import', name: 'Neural Import', path: 'neuralImport' },
40
+ { id: 'intelligent-verb-scoring', name: 'Intelligent Verb Scoring', path: 'intelligentVerbScoringAugmentation' },
41
+ { id: 'universal-display', name: 'Universal Display', path: 'universalDisplayAugmentation' },
42
+ // Storage augmentations
43
+ { id: 'memory-storage', name: 'Memory Storage', path: 'storageAugmentations', export: 'MemoryStorageAugmentation' },
44
+ { id: 'filesystem-storage', name: 'FileSystem Storage', path: 'storageAugmentations', export: 'FileSystemStorageAugmentation' },
45
+ { id: 'opfs-storage', name: 'OPFS Storage', path: 'storageAugmentations', export: 'OPFSStorageAugmentation' },
46
+ { id: 's3-storage', name: 'S3 Storage', path: 'storageAugmentations', export: 'S3StorageAugmentation' },
47
+ ];
48
+ for (const aug of builtIn) {
49
+ this.builtInAugmentations.set(aug.id, {
50
+ id: aug.id,
51
+ name: aug.name,
52
+ source: 'builtin',
53
+ path: `@soulcraft/brainy/augmentations/${aug.path}`,
54
+ package: {
55
+ name: '@soulcraft/brainy',
56
+ version: 'builtin',
57
+ description: `Built-in ${aug.name} augmentation`
58
+ }
59
+ });
60
+ }
61
+ }
62
+ /**
63
+ * Find Brainy installation path
64
+ */
65
+ findBrainyPath() {
66
+ // Try to find brainy in node_modules
67
+ const possiblePaths = [
68
+ join(process.cwd(), 'node_modules', '@soulcraft', 'brainy'),
69
+ join(process.cwd(), 'node_modules', 'brainy'),
70
+ join(process.cwd(), '..', 'node_modules', '@soulcraft', 'brainy'),
71
+ ];
72
+ for (const path of possiblePaths) {
73
+ if (existsSync(path)) {
74
+ return path;
75
+ }
76
+ }
77
+ // Fallback to current directory
78
+ return process.cwd();
79
+ }
80
+ /**
81
+ * Discover all augmentations
82
+ */
83
+ async discoverAll() {
84
+ const augmentations = [];
85
+ // Add built-in augmentations
86
+ augmentations.push(...this.builtInAugmentations.values());
87
+ // Scan node_modules if enabled
88
+ if (this.options.scanNodeModules) {
89
+ const installed = await this.scanNodeModules();
90
+ augmentations.push(...installed);
91
+ }
92
+ // Scan local project
93
+ const local = await this.scanLocalProject();
94
+ augmentations.push(...local);
95
+ return augmentations;
96
+ }
97
+ /**
98
+ * Scan node_modules for installed augmentations
99
+ */
100
+ async scanNodeModules() {
101
+ const augmentations = [];
102
+ const nodeModulesPath = join(this.options.projectPath, 'node_modules');
103
+ if (!existsSync(nodeModulesPath)) {
104
+ return augmentations;
105
+ }
106
+ // Scan @brainy/* packages
107
+ const brainyPath = join(nodeModulesPath, '@brainy');
108
+ if (existsSync(brainyPath)) {
109
+ const packages = readdirSync(brainyPath);
110
+ for (const pkg of packages) {
111
+ const augmentation = await this.loadPackageAugmentation(join(brainyPath, pkg));
112
+ if (augmentation) {
113
+ augmentations.push(augmentation);
114
+ }
115
+ }
116
+ }
117
+ // Scan packages with brainy-augmentation keyword
118
+ const packages = readdirSync(nodeModulesPath);
119
+ for (const pkg of packages) {
120
+ if (pkg.startsWith('@') || pkg.startsWith('.'))
121
+ continue;
122
+ const pkgPath = join(nodeModulesPath, pkg);
123
+ const packageJson = this.loadPackageJson(pkgPath);
124
+ if (packageJson?.keywords?.includes('brainy-augmentation')) {
125
+ const augmentation = await this.loadPackageAugmentation(pkgPath);
126
+ if (augmentation) {
127
+ augmentations.push(augmentation);
128
+ }
129
+ }
130
+ }
131
+ return augmentations;
132
+ }
133
+ /**
134
+ * Scan local project for augmentations
135
+ */
136
+ async scanLocalProject() {
137
+ const augmentations = [];
138
+ // Check for augmentations directory
139
+ const augPath = join(this.options.projectPath, 'augmentations');
140
+ if (existsSync(augPath)) {
141
+ const files = readdirSync(augPath);
142
+ for (const file of files) {
143
+ if (file.endsWith('.ts') || file.endsWith('.js')) {
144
+ const name = file.replace(/\.(ts|js)$/, '');
145
+ augmentations.push({
146
+ id: name,
147
+ name: this.humanizeName(name),
148
+ source: 'local',
149
+ path: join(augPath, file)
150
+ });
151
+ }
152
+ }
153
+ }
154
+ return augmentations;
155
+ }
156
+ /**
157
+ * Load augmentation from package
158
+ */
159
+ async loadPackageAugmentation(pkgPath) {
160
+ const packageJson = this.loadPackageJson(pkgPath);
161
+ if (!packageJson)
162
+ return null;
163
+ // Check if it's a brainy augmentation
164
+ const isBrainyAug = packageJson.keywords?.includes('brainy-augmentation') ||
165
+ packageJson.brainy?.type === 'augmentation';
166
+ if (!isBrainyAug)
167
+ return null;
168
+ const manifest = packageJson.brainy?.manifest || null;
169
+ return {
170
+ id: packageJson.brainy?.id || packageJson.name.replace('@brainy/', ''),
171
+ name: packageJson.brainy?.name || packageJson.name,
172
+ source: 'npm',
173
+ path: pkgPath,
174
+ manifest,
175
+ package: {
176
+ name: packageJson.name,
177
+ version: packageJson.version,
178
+ description: packageJson.description
179
+ }
180
+ };
181
+ }
182
+ /**
183
+ * Load package.json
184
+ */
185
+ loadPackageJson(pkgPath) {
186
+ const packageJsonPath = join(pkgPath, 'package.json');
187
+ if (!existsSync(packageJsonPath))
188
+ return null;
189
+ try {
190
+ return JSON.parse(readFileSync(packageJsonPath, 'utf8'));
191
+ }
192
+ catch {
193
+ return null;
194
+ }
195
+ }
196
+ /**
197
+ * Convert name to human-readable format
198
+ */
199
+ humanizeName(name) {
200
+ return name
201
+ .replace(/[-_]/g, ' ')
202
+ .replace(/augmentation/gi, '')
203
+ .replace(/\b\w/g, l => l.toUpperCase())
204
+ .trim();
205
+ }
206
+ /**
207
+ * Get built-in augmentations
208
+ */
209
+ getBuiltIn() {
210
+ return Array.from(this.builtInAugmentations.values());
211
+ }
212
+ /**
213
+ * Get installed augmentations
214
+ */
215
+ getInstalled() {
216
+ return Array.from(this.installedAugmentations.values());
217
+ }
218
+ /**
219
+ * Check if augmentation is installed
220
+ */
221
+ isInstalled(id) {
222
+ return this.builtInAugmentations.has(id) ||
223
+ this.installedAugmentations.has(id);
224
+ }
225
+ /**
226
+ * Get import path for augmentation
227
+ */
228
+ getImportPath(id) {
229
+ const aug = this.builtInAugmentations.get(id) ||
230
+ this.installedAugmentations.get(id);
231
+ return aug?.path || null;
232
+ }
233
+ /**
234
+ * Load augmentation module dynamically
235
+ */
236
+ async loadAugmentation(id) {
237
+ const path = this.getImportPath(id);
238
+ if (!path) {
239
+ throw new Error(`Augmentation ${id} not found`);
240
+ }
241
+ // Dynamic import
242
+ const module = await import(path);
243
+ return module.default || module;
244
+ }
245
+ }
246
+ //# sourceMappingURL=localDiscovery.js.map
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Runtime Augmentation Loader
3
+ *
4
+ * Dynamically loads and registers augmentations at runtime
5
+ * Supports CDN loading for browser environments and npm imports for Node.js
6
+ */
7
+ import { BrainyAugmentation, AugmentationRegistry } from '../brainyAugmentation.js';
8
+ import { AugmentationManifest } from '../manifest.js';
9
+ export interface LoaderOptions {
10
+ cdnUrl?: string;
11
+ allowUnsafe?: boolean;
12
+ sandbox?: boolean;
13
+ timeout?: number;
14
+ cache?: boolean;
15
+ }
16
+ export interface LoadedAugmentation {
17
+ id: string;
18
+ instance: BrainyAugmentation;
19
+ manifest: AugmentationManifest;
20
+ source: 'cdn' | 'npm' | 'local';
21
+ loadTime: number;
22
+ }
23
+ /**
24
+ * Runtime Augmentation Loader
25
+ *
26
+ * Enables dynamic loading of augmentations from various sources
27
+ */
28
+ export declare class RuntimeAugmentationLoader {
29
+ private options;
30
+ private loaded;
31
+ private cdnCache;
32
+ private registry?;
33
+ constructor(options?: LoaderOptions);
34
+ /**
35
+ * Set the augmentation registry
36
+ */
37
+ setRegistry(registry: AugmentationRegistry): void;
38
+ /**
39
+ * Load augmentation from CDN (browser)
40
+ */
41
+ loadFromCDN(id: string, version?: string, config?: any): Promise<LoadedAugmentation>;
42
+ /**
43
+ * Load augmentation from NPM (Node.js)
44
+ */
45
+ loadFromNPM(packageName: string, config?: any): Promise<LoadedAugmentation>;
46
+ /**
47
+ * Load augmentation from local file
48
+ */
49
+ loadFromFile(path: string, config?: any): Promise<LoadedAugmentation>;
50
+ /**
51
+ * Load multiple augmentations
52
+ */
53
+ loadBatch(augmentations: Array<{
54
+ source: 'cdn' | 'npm' | 'local';
55
+ id: string;
56
+ version?: string;
57
+ path?: string;
58
+ config?: any;
59
+ }>): Promise<LoadedAugmentation[]>;
60
+ /**
61
+ * Unload augmentation
62
+ */
63
+ unload(id: string): boolean;
64
+ /**
65
+ * Get loaded augmentations
66
+ */
67
+ getLoaded(): LoadedAugmentation[];
68
+ /**
69
+ * Check if augmentation is loaded
70
+ */
71
+ isLoaded(id: string): boolean;
72
+ /**
73
+ * Get loaded augmentation
74
+ */
75
+ getAugmentation(id: string): BrainyAugmentation | null;
76
+ /**
77
+ * Load CDN module (browser-specific)
78
+ */
79
+ private loadCDNModule;
80
+ /**
81
+ * Validate augmentation instance
82
+ */
83
+ private isValidAugmentation;
84
+ /**
85
+ * Clear all caches
86
+ */
87
+ clearCache(): void;
88
+ /**
89
+ * Get load statistics
90
+ */
91
+ getStats(): {
92
+ loaded: number;
93
+ totalLoadTime: number;
94
+ averageLoadTime: number;
95
+ sources: Record<string, number>;
96
+ };
97
+ }
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Runtime Augmentation Loader
3
+ *
4
+ * Dynamically loads and registers augmentations at runtime
5
+ * Supports CDN loading for browser environments and npm imports for Node.js
6
+ */
7
+ /**
8
+ * Runtime Augmentation Loader
9
+ *
10
+ * Enables dynamic loading of augmentations from various sources
11
+ */
12
+ export class RuntimeAugmentationLoader {
13
+ constructor(options = {}) {
14
+ this.options = options;
15
+ this.loaded = new Map();
16
+ this.cdnCache = new Map();
17
+ this.options = {
18
+ cdnUrl: options.cdnUrl || 'https://cdn.soulcraft.com/augmentations',
19
+ allowUnsafe: options.allowUnsafe || false,
20
+ sandbox: options.sandbox || true,
21
+ timeout: options.timeout || 30000,
22
+ cache: options.cache ?? true
23
+ };
24
+ }
25
+ /**
26
+ * Set the augmentation registry
27
+ */
28
+ setRegistry(registry) {
29
+ this.registry = registry;
30
+ }
31
+ /**
32
+ * Load augmentation from CDN (browser)
33
+ */
34
+ async loadFromCDN(id, version = 'latest', config) {
35
+ // Check if already loaded
36
+ if (this.loaded.has(id)) {
37
+ return this.loaded.get(id);
38
+ }
39
+ const url = `${this.options.cdnUrl}/${id}@${version}/index.js`;
40
+ const startTime = Date.now();
41
+ try {
42
+ // Load module from CDN
43
+ const module = await this.loadCDNModule(url);
44
+ // Extract augmentation class
45
+ const AugmentationClass = module.default || module[Object.keys(module)[0]];
46
+ if (!AugmentationClass) {
47
+ throw new Error(`No augmentation class found in module ${id}`);
48
+ }
49
+ // Create instance
50
+ const instance = new AugmentationClass(config);
51
+ // Validate it's a proper augmentation
52
+ if (!this.isValidAugmentation(instance)) {
53
+ throw new Error(`Invalid augmentation: ${id}`);
54
+ }
55
+ // Get manifest
56
+ const manifest = instance.getManifest ? instance.getManifest() : {
57
+ id,
58
+ name: id,
59
+ version: version,
60
+ description: `Dynamically loaded ${id}`,
61
+ category: 'external'
62
+ };
63
+ const loaded = {
64
+ id,
65
+ instance,
66
+ manifest,
67
+ source: 'cdn',
68
+ loadTime: Date.now() - startTime
69
+ };
70
+ // Cache
71
+ this.loaded.set(id, loaded);
72
+ // Auto-register if registry is set
73
+ if (this.registry) {
74
+ this.registry.register(instance);
75
+ }
76
+ return loaded;
77
+ }
78
+ catch (error) {
79
+ throw new Error(`Failed to load augmentation ${id} from CDN: ${error}`);
80
+ }
81
+ }
82
+ /**
83
+ * Load augmentation from NPM (Node.js)
84
+ */
85
+ async loadFromNPM(packageName, config) {
86
+ // Check if already loaded
87
+ const id = packageName.replace('@', '').replace('/', '-');
88
+ if (this.loaded.has(id)) {
89
+ return this.loaded.get(id);
90
+ }
91
+ const startTime = Date.now();
92
+ try {
93
+ // Dynamic import
94
+ const module = await import(packageName);
95
+ // Extract augmentation class
96
+ const AugmentationClass = module.default || module[Object.keys(module)[0]];
97
+ if (!AugmentationClass) {
98
+ throw new Error(`No augmentation class found in package ${packageName}`);
99
+ }
100
+ // Create instance
101
+ const instance = new AugmentationClass(config);
102
+ // Validate
103
+ if (!this.isValidAugmentation(instance)) {
104
+ throw new Error(`Invalid augmentation in package: ${packageName}`);
105
+ }
106
+ // Get manifest
107
+ const manifest = instance.getManifest ? instance.getManifest() : {
108
+ id,
109
+ name: packageName,
110
+ version: 'unknown',
111
+ description: `Loaded from ${packageName}`,
112
+ category: 'external'
113
+ };
114
+ const loaded = {
115
+ id,
116
+ instance,
117
+ manifest,
118
+ source: 'npm',
119
+ loadTime: Date.now() - startTime
120
+ };
121
+ // Cache
122
+ this.loaded.set(id, loaded);
123
+ // Auto-register
124
+ if (this.registry) {
125
+ this.registry.register(instance);
126
+ }
127
+ return loaded;
128
+ }
129
+ catch (error) {
130
+ throw new Error(`Failed to load augmentation from NPM ${packageName}: ${error}`);
131
+ }
132
+ }
133
+ /**
134
+ * Load augmentation from local file
135
+ */
136
+ async loadFromFile(path, config) {
137
+ const startTime = Date.now();
138
+ try {
139
+ // Dynamic import
140
+ const module = await import(path);
141
+ // Extract augmentation class
142
+ const AugmentationClass = module.default || module[Object.keys(module)[0]];
143
+ if (!AugmentationClass) {
144
+ throw new Error(`No augmentation class found in file ${path}`);
145
+ }
146
+ // Create instance
147
+ const instance = new AugmentationClass(config);
148
+ // Validate
149
+ if (!this.isValidAugmentation(instance)) {
150
+ throw new Error(`Invalid augmentation in file: ${path}`);
151
+ }
152
+ // Extract ID from path
153
+ const id = path.split('/').pop()?.replace(/\.(js|ts)$/, '') || 'unknown';
154
+ // Get manifest
155
+ const manifest = instance.getManifest ? instance.getManifest() : {
156
+ id,
157
+ name: id,
158
+ version: 'local',
159
+ description: `Loaded from ${path}`,
160
+ category: 'local'
161
+ };
162
+ const loaded = {
163
+ id,
164
+ instance,
165
+ manifest,
166
+ source: 'local',
167
+ loadTime: Date.now() - startTime
168
+ };
169
+ // Cache
170
+ this.loaded.set(id, loaded);
171
+ // Auto-register
172
+ if (this.registry) {
173
+ this.registry.register(instance);
174
+ }
175
+ return loaded;
176
+ }
177
+ catch (error) {
178
+ throw new Error(`Failed to load augmentation from file ${path}: ${error}`);
179
+ }
180
+ }
181
+ /**
182
+ * Load multiple augmentations
183
+ */
184
+ async loadBatch(augmentations) {
185
+ const results = await Promise.allSettled(augmentations.map(aug => {
186
+ switch (aug.source) {
187
+ case 'cdn':
188
+ return this.loadFromCDN(aug.id, aug.version, aug.config);
189
+ case 'npm':
190
+ return this.loadFromNPM(aug.id, aug.config);
191
+ case 'local':
192
+ return this.loadFromFile(aug.path || aug.id, aug.config);
193
+ default:
194
+ return Promise.reject(new Error(`Unknown source: ${aug.source}`));
195
+ }
196
+ }));
197
+ const loaded = [];
198
+ const errors = [];
199
+ for (const result of results) {
200
+ if (result.status === 'fulfilled') {
201
+ loaded.push(result.value);
202
+ }
203
+ else {
204
+ errors.push(result.reason.message);
205
+ }
206
+ }
207
+ if (errors.length > 0) {
208
+ console.warn('Some augmentations failed to load:', errors);
209
+ }
210
+ return loaded;
211
+ }
212
+ /**
213
+ * Unload augmentation
214
+ */
215
+ unload(id) {
216
+ const loaded = this.loaded.get(id);
217
+ if (!loaded)
218
+ return false;
219
+ // Shutdown if possible
220
+ if (loaded.instance.shutdown) {
221
+ loaded.instance.shutdown();
222
+ }
223
+ // Remove from registry if set
224
+ // Note: Registry doesn't have unregister yet, would need to add
225
+ // Remove from cache
226
+ this.loaded.delete(id);
227
+ return true;
228
+ }
229
+ /**
230
+ * Get loaded augmentations
231
+ */
232
+ getLoaded() {
233
+ return Array.from(this.loaded.values());
234
+ }
235
+ /**
236
+ * Check if augmentation is loaded
237
+ */
238
+ isLoaded(id) {
239
+ return this.loaded.has(id);
240
+ }
241
+ /**
242
+ * Get loaded augmentation
243
+ */
244
+ getAugmentation(id) {
245
+ return this.loaded.get(id)?.instance || null;
246
+ }
247
+ /**
248
+ * Load CDN module (browser-specific)
249
+ */
250
+ async loadCDNModule(url) {
251
+ // Check cache
252
+ if (this.options.cache && this.cdnCache.has(url)) {
253
+ return this.cdnCache.get(url);
254
+ }
255
+ // In browser environment
256
+ if (typeof window !== 'undefined') {
257
+ return new Promise((resolve, reject) => {
258
+ const timeout = setTimeout(() => {
259
+ reject(new Error(`Timeout loading ${url}`));
260
+ }, this.options.timeout);
261
+ // Create script element
262
+ const script = document.createElement('script');
263
+ script.type = 'module';
264
+ script.src = url;
265
+ // Handle load
266
+ script.onload = async () => {
267
+ clearTimeout(timeout);
268
+ // The module should register itself on window
269
+ const moduleId = url.split('/').pop()?.split('@')[0];
270
+ if (moduleId && window[moduleId]) {
271
+ const module = window[moduleId];
272
+ // Cache
273
+ if (this.options.cache) {
274
+ this.cdnCache.set(url, module);
275
+ }
276
+ resolve(module);
277
+ }
278
+ else {
279
+ reject(new Error(`Module not found on window: ${moduleId}`));
280
+ }
281
+ };
282
+ // Handle error
283
+ script.onerror = () => {
284
+ clearTimeout(timeout);
285
+ reject(new Error(`Failed to load script: ${url}`));
286
+ };
287
+ // Add to document
288
+ document.head.appendChild(script);
289
+ });
290
+ }
291
+ else {
292
+ // In Node.js, use dynamic import
293
+ const module = await import(url);
294
+ // Cache
295
+ if (this.options.cache) {
296
+ this.cdnCache.set(url, module);
297
+ }
298
+ return module;
299
+ }
300
+ }
301
+ /**
302
+ * Validate augmentation instance
303
+ */
304
+ isValidAugmentation(instance) {
305
+ // Check required properties
306
+ return !!(instance.name &&
307
+ instance.timing &&
308
+ instance.operations &&
309
+ instance.priority !== undefined &&
310
+ typeof instance.execute === 'function' &&
311
+ typeof instance.initialize === 'function');
312
+ }
313
+ /**
314
+ * Clear all caches
315
+ */
316
+ clearCache() {
317
+ this.cdnCache.clear();
318
+ }
319
+ /**
320
+ * Get load statistics
321
+ */
322
+ getStats() {
323
+ const loaded = Array.from(this.loaded.values());
324
+ const totalLoadTime = loaded.reduce((sum, aug) => sum + aug.loadTime, 0);
325
+ const sources = loaded.reduce((acc, aug) => {
326
+ acc[aug.source] = (acc[aug.source] || 0) + 1;
327
+ return acc;
328
+ }, {});
329
+ return {
330
+ loaded: loaded.length,
331
+ totalLoadTime,
332
+ averageLoadTime: loaded.length > 0 ? totalLoadTime / loaded.length : 0,
333
+ sources
334
+ };
335
+ }
336
+ }
337
+ //# sourceMappingURL=runtimeLoader.js.map