@json-to-office/shared 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wiseair srl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
6
+ associated documentation files (the "Software"), to deal in the Software without restriction, including
7
+ without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
9
+ following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all copies or substantial
12
+ portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
15
+ LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
16
+ EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
18
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # @json-to-office/shared
2
+
3
+ Format-agnostic shared types, schemas and validation utilities.
4
+
5
+ > **Internal package** — used by other @json-to-office packages. You probably want [`@json-to-office/json-to-docx`](../json-to-docx) or [`@json-to-office/json-to-pptx`](../json-to-pptx) instead.
6
+
7
+ ## License
8
+
9
+ [MIT](../../LICENSE)
@@ -0,0 +1,464 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ /**
4
+ * Cache Types and Interfaces
5
+ * Core type definitions for the component caching system
6
+ */
7
+ /**
8
+ * Cache entry metadata
9
+ */
10
+ interface CacheMetadata {
11
+ /** Creation timestamp */
12
+ timestamp: number;
13
+ /** Number of cache hits */
14
+ hits: number;
15
+ /** Size in bytes */
16
+ size: number;
17
+ /** Component dependencies */
18
+ dependencies: string[];
19
+ /** Content signature for validation */
20
+ signature: string;
21
+ /** Time-to-live in seconds */
22
+ ttl?: number;
23
+ /** Last access timestamp */
24
+ lastAccessed: number;
25
+ }
26
+ /**
27
+ * Cached component entry
28
+ */
29
+ interface CachedComponent extends CacheMetadata {
30
+ /** Processed component result */
31
+ result: unknown;
32
+ /** Component name for analytics */
33
+ componentName: string;
34
+ /** Original component props hash */
35
+ propsHash: string;
36
+ }
37
+ /**
38
+ * Cache statistics
39
+ */
40
+ interface CacheStatistics {
41
+ /** Total number of entries */
42
+ entries: number;
43
+ /** Total cache size in bytes */
44
+ totalSize: number;
45
+ /** Cache hit rate (0-1) */
46
+ hitRate: number;
47
+ /** Cache miss rate (0-1) */
48
+ missRate: number;
49
+ /** Total hits */
50
+ totalHits: number;
51
+ /** Total misses */
52
+ totalMisses: number;
53
+ /** Average response time in ms */
54
+ avgResponseTime: number;
55
+ /** Eviction count */
56
+ evictions: number;
57
+ /** Per-component statistics */
58
+ componentStats: Map<string, ComponentStatistics>;
59
+ }
60
+ /**
61
+ * Component-specific statistics
62
+ */
63
+ interface ComponentStatistics {
64
+ /** Component name */
65
+ name: string;
66
+ /** Number of cache hits */
67
+ hits: number;
68
+ /** Number of cache misses */
69
+ misses: number;
70
+ /** Average processing time when missed */
71
+ avgProcessTime: number;
72
+ /** Average size of cached entries */
73
+ avgSize: number;
74
+ /** Number of cached entries */
75
+ entries: number;
76
+ }
77
+ /**
78
+ * Cache key options
79
+ */
80
+ interface CacheKeyOptions {
81
+ /** Include theme in key generation */
82
+ includeTheme?: boolean;
83
+ /** Include render context in key */
84
+ includeContext?: boolean;
85
+ /** Additional key components */
86
+ additionalKeys?: string[];
87
+ /** Key version for cache busting */
88
+ version?: string;
89
+ }
90
+ /**
91
+ * Cache configuration
92
+ */
93
+ interface CacheConfiguration {
94
+ /** Enable/disable caching globally */
95
+ enabled: boolean;
96
+ /** Memory cache configuration */
97
+ memory: {
98
+ enabled: boolean;
99
+ /** Maximum cache size in MB */
100
+ maxSize: number;
101
+ /** Maximum number of entries */
102
+ maxEntries: number;
103
+ /** Default TTL in seconds */
104
+ defaultTTL: number;
105
+ /** Check expired entries interval in seconds */
106
+ cleanupInterval: number;
107
+ };
108
+ /** Disk cache configuration (future) */
109
+ disk?: {
110
+ enabled: boolean;
111
+ /** Cache directory path */
112
+ path: string;
113
+ /** Maximum cache size in MB */
114
+ maxSize: number;
115
+ /** Default TTL in seconds */
116
+ defaultTTL: number;
117
+ /** Compression enabled */
118
+ compression: boolean;
119
+ };
120
+ /** Eviction policy */
121
+ evictionPolicy: 'lru' | 'lfu' | 'fifo' | 'ttl';
122
+ /** Component-specific configurations */
123
+ componentConfig?: {
124
+ [componentName: string]: {
125
+ /** Whether this component is cacheable */
126
+ cacheable: boolean;
127
+ /** Custom TTL for this component */
128
+ ttl?: number;
129
+ /** Maximum entries for this component */
130
+ maxEntries?: number;
131
+ };
132
+ };
133
+ /** Performance settings */
134
+ performance: {
135
+ /** Enable performance tracking */
136
+ trackMetrics: boolean;
137
+ /** Metrics sampling rate (0-1) */
138
+ metricsSampleRate: number;
139
+ /** Enable cache warming */
140
+ enableWarming: boolean;
141
+ /** Parallel processing for batch operations */
142
+ parallelProcessing: boolean;
143
+ };
144
+ }
145
+ /**
146
+ * Cache events for monitoring
147
+ */
148
+ interface CacheEvents {
149
+ hit: (key: string, component: CachedComponent) => void;
150
+ miss: (key: string) => void;
151
+ set: (key: string, component: CachedComponent) => void;
152
+ evict: (key: string, reason: 'ttl' | 'size' | 'manual') => void;
153
+ error: (error: Error) => void;
154
+ stats: (stats: CacheStatistics) => void;
155
+ }
156
+
157
+ /**
158
+ * Cache Manager Base Class
159
+ * Abstract base class for cache implementations
160
+ */
161
+
162
+ /**
163
+ * Main cache manager abstract class
164
+ */
165
+ declare abstract class ComponentCacheManager extends EventEmitter {
166
+ protected config: CacheConfiguration;
167
+ protected stats: CacheStatistics;
168
+ constructor(config: CacheConfiguration);
169
+ /**
170
+ * Get a cached component
171
+ */
172
+ abstract get(key: string): Promise<CachedComponent | undefined>;
173
+ /**
174
+ * Set a cached component
175
+ */
176
+ abstract set(key: string, component: CachedComponent): Promise<void>;
177
+ /**
178
+ * Check if key exists
179
+ */
180
+ abstract has(key: string): Promise<boolean>;
181
+ /**
182
+ * Delete a cached entry
183
+ */
184
+ abstract delete(key: string): Promise<boolean>;
185
+ /**
186
+ * Clear all cache entries
187
+ */
188
+ abstract clear(): Promise<void>;
189
+ /**
190
+ * Get all keys (for utilities)
191
+ */
192
+ abstract getKeys(): Promise<string[]>;
193
+ /**
194
+ * Get cache statistics with deep immutability
195
+ */
196
+ getStats(): CacheStatistics;
197
+ /**
198
+ * Get configuration with deep immutability
199
+ */
200
+ getConfig(): CacheConfiguration;
201
+ /**
202
+ * Get multiple entries (batch operation)
203
+ */
204
+ getMany(keys: string[]): Promise<Map<string, CachedComponent>>;
205
+ /**
206
+ * Set multiple entries (batch operation)
207
+ */
208
+ setMany(entries: [string, CachedComponent][]): Promise<void>;
209
+ /**
210
+ * Delete multiple entries
211
+ */
212
+ deleteMany(keys: string[]): Promise<number>;
213
+ /**
214
+ * Initialize statistics
215
+ */
216
+ protected initializeStats(): CacheStatistics;
217
+ /**
218
+ * Update statistics on cache hit
219
+ */
220
+ protected updateHitStats(key: string, component: CachedComponent): void;
221
+ /**
222
+ * Update statistics on cache miss
223
+ */
224
+ protected updateMissStats(key: string, componentName?: string): void;
225
+ /**
226
+ * Update component-specific statistics
227
+ */
228
+ protected updateComponentStats(componentName: string, event: 'hit' | 'miss'): void;
229
+ /**
230
+ * Recalculate hit/miss rates
231
+ */
232
+ protected recalculateRates(): void;
233
+ /**
234
+ * Emit statistics periodically
235
+ */
236
+ protected emitStats(): void;
237
+ }
238
+
239
+ /**
240
+ * Memory Cache Implementation
241
+ * In-memory cache with LRU eviction policy
242
+ */
243
+
244
+ /**
245
+ * In-memory cache with LRU eviction
246
+ */
247
+ declare class MemoryCache extends ComponentCacheManager {
248
+ private cache;
249
+ private head;
250
+ private tail;
251
+ private currentSize;
252
+ private keyToComponentName;
253
+ private cleanupTimer?;
254
+ constructor(config: CacheConfiguration);
255
+ get(key: string): Promise<CachedComponent | undefined>;
256
+ set(key: string, component: CachedComponent): Promise<void>;
257
+ has(key: string): Promise<boolean>;
258
+ delete(key: string): Promise<boolean>;
259
+ clear(): Promise<void>;
260
+ getKeys(): Promise<string[]>;
261
+ /**
262
+ * Extract component name from cache key
263
+ */
264
+ private extractComponentNameFromKey;
265
+ /**
266
+ * Check if component is expired
267
+ */
268
+ private isExpired;
269
+ /**
270
+ * Check if component is cacheable
271
+ */
272
+ private isCacheable;
273
+ /**
274
+ * Ensure enough space for new entry
275
+ */
276
+ private ensureSpace;
277
+ /**
278
+ * LRU operations - Add node to head
279
+ */
280
+ private addToHead;
281
+ /**
282
+ * Remove node from list
283
+ */
284
+ private removeNode;
285
+ /**
286
+ * Move node to head
287
+ */
288
+ private moveToHead;
289
+ /**
290
+ * Start cleanup timer for expired entries
291
+ */
292
+ private startCleanupTimer;
293
+ /**
294
+ * Stop cleanup timer
295
+ */
296
+ destroy(): void;
297
+ }
298
+
299
+ /**
300
+ * Cache Configuration
301
+ * Default configuration and environment-based configuration
302
+ */
303
+
304
+ /**
305
+ * Default cache configuration
306
+ */
307
+ declare const DEFAULT_CACHE_CONFIG: CacheConfiguration;
308
+ /**
309
+ * Get cache configuration from environment variables
310
+ */
311
+ declare function getCacheConfigFromEnv(): Partial<CacheConfiguration>;
312
+ /**
313
+ * Merge configurations with priority
314
+ */
315
+ declare function mergeConfigs(...configs: Partial<CacheConfiguration>[]): CacheConfiguration;
316
+
317
+ /**
318
+ * Component Cache Analytics
319
+ * Advanced analytics and insights for component-level caching
320
+ */
321
+
322
+ /**
323
+ * Time-series data point for tracking metrics over time
324
+ */
325
+ interface TimeSeriesPoint {
326
+ timestamp: number;
327
+ value: number;
328
+ }
329
+ /**
330
+ * Component performance metrics
331
+ */
332
+ interface ComponentPerformanceMetrics {
333
+ /** Component name identifier */
334
+ componentName: string;
335
+ /** Cache hit rate (0-1) */
336
+ hitRate: number;
337
+ /** Total requests (hits + misses) */
338
+ totalRequests: number;
339
+ /** Average response time for cache hits (ms) */
340
+ avgHitTime: number;
341
+ /** Average response time for cache misses (ms) */
342
+ avgMissTime: number;
343
+ /** Cache efficiency score (0-100) */
344
+ efficiencyScore: number;
345
+ /** Memory usage in bytes */
346
+ memoryUsage: number;
347
+ /** Time saved by caching (ms) */
348
+ timeSaved: number;
349
+ /** Cost-benefit ratio */
350
+ costBenefitRatio: number;
351
+ }
352
+ /**
353
+ * Component cache trends over time
354
+ */
355
+ interface ComponentCacheTrends {
356
+ /** Component name */
357
+ componentName: string;
358
+ /** Hit rate trend */
359
+ hitRateTrend: TimeSeriesPoint[];
360
+ /** Request volume trend */
361
+ requestVolumeTrend: TimeSeriesPoint[];
362
+ /** Response time trend */
363
+ responseTimeTrend: TimeSeriesPoint[];
364
+ /** Memory usage trend */
365
+ memoryUsageTrend: TimeSeriesPoint[];
366
+ }
367
+ /**
368
+ * Cache optimization recommendations
369
+ */
370
+ interface CacheOptimizationRecommendation {
371
+ /** Component name to optimize */
372
+ componentName: string;
373
+ /** Recommendation type */
374
+ type: 'increase_ttl' | 'decrease_ttl' | 'increase_size' | 'disable_cache' | 'enable_cache';
375
+ /** Recommendation description */
376
+ description: string;
377
+ /** Expected improvement percentage */
378
+ expectedImprovement: number;
379
+ /** Priority level (1-5, 5 being highest) */
380
+ priority: number;
381
+ /** Detailed reasoning */
382
+ reasoning: string;
383
+ }
384
+ /**
385
+ * Comprehensive cache analytics report
386
+ */
387
+ interface CacheAnalyticsReport {
388
+ /** Report generation timestamp */
389
+ timestamp: number;
390
+ /** Overall cache health score (0-100) */
391
+ healthScore: number;
392
+ /** Total cache efficiency percentage */
393
+ overallEfficiency: number;
394
+ /** Per-component performance metrics */
395
+ componentMetrics: ComponentPerformanceMetrics[];
396
+ /** Component cache trends */
397
+ trends: ComponentCacheTrends[];
398
+ /** Optimization recommendations */
399
+ recommendations: CacheOptimizationRecommendation[];
400
+ /** Top performing components */
401
+ topPerformers: string[];
402
+ /** Components needing attention */
403
+ needsAttention: string[];
404
+ /** Estimated performance gain from caching */
405
+ performanceGain: {
406
+ timeReduction: number;
407
+ cpuReduction: number;
408
+ memoryOptimization: number;
409
+ };
410
+ }
411
+ /**
412
+ * Component Cache Analytics Engine
413
+ */
414
+ declare class ComponentCacheAnalytics {
415
+ private historyWindow;
416
+ private metricsHistory;
417
+ private performanceBaseline;
418
+ /**
419
+ * Analyze cache statistics and generate comprehensive report
420
+ */
421
+ analyzeCache(stats: CacheStatistics): CacheAnalyticsReport;
422
+ /**
423
+ * Calculate detailed metrics for each component
424
+ */
425
+ private calculateComponentMetrics;
426
+ /**
427
+ * Calculate efficiency score for a component
428
+ */
429
+ private calculateEfficiencyScore;
430
+ /**
431
+ * Calculate trends over time
432
+ */
433
+ private calculateTrends;
434
+ /**
435
+ * Get or create history for a metric
436
+ */
437
+ private getOrCreateHistory;
438
+ /**
439
+ * Generate optimization recommendations
440
+ */
441
+ private generateRecommendations;
442
+ /**
443
+ * Check if a trend is declining
444
+ */
445
+ private isDecliningSlopbankTrend;
446
+ /**
447
+ * Calculate overall cache health score
448
+ */
449
+ private calculateHealthScore;
450
+ /**
451
+ * Calculate overall cache efficiency
452
+ */
453
+ private calculateOverallEfficiency;
454
+ /**
455
+ * Calculate performance gain from caching
456
+ */
457
+ private calculatePerformanceGain;
458
+ /**
459
+ * Reset analytics history
460
+ */
461
+ reset(): void;
462
+ }
463
+
464
+ export { type CacheAnalyticsReport, type CacheConfiguration, type CacheEvents, type CacheKeyOptions, type CacheMetadata, type CacheOptimizationRecommendation, type CacheStatistics, type CachedComponent, ComponentCacheAnalytics, ComponentCacheManager, type ComponentCacheTrends, type ComponentPerformanceMetrics, type ComponentStatistics, DEFAULT_CACHE_CONFIG, MemoryCache, type TimeSeriesPoint, getCacheConfigFromEnv, mergeConfigs };