1+ /** Max entries before evicting oldest (FIFO). Keeps lib lightweight, avoids memory leaks. */
2+ const MAX_IMAGE = 100
3+ const MAX_BACKGROUND = 100
4+ const MAX_RESOURCE = 150
5+ const MAX_BASE_STYLE = 50
6+ const MAX_DEFAULT_STYLE = 30
7+
8+ /**
9+ * Map that evicts oldest entries when exceeding maxSize. FIFO order.
10+ * @extends Map
11+ */
12+ class EvictingMap extends Map {
13+ constructor ( maxSize = 100 , ...args ) {
14+ super ( ...args )
15+ this . _maxSize = maxSize
16+ }
17+ set ( key , value ) {
18+ if ( this . size >= this . _maxSize && ! this . has ( key ) ) {
19+ const first = this . keys ( ) . next ( ) . value
20+ if ( first !== undefined ) this . delete ( first )
21+ }
22+ return super . set ( key , value )
23+ }
24+ }
25+
126/**
227 * Global caches for images, styles, and resources.
28+ * Persistent caches use EvictingMap to avoid unbounded memory growth.
329 */
430export const cache = {
5- image : new Map ( ) ,
6- background : new Map ( ) ,
7- resource : new Map ( ) ,
8- defaultStyle : new Map ( ) ,
9- baseStyle : new Map ( ) ,
31+ image : new EvictingMap ( MAX_IMAGE ) ,
32+ background : new EvictingMap ( MAX_BACKGROUND ) ,
33+ resource : new EvictingMap ( MAX_RESOURCE ) ,
34+ defaultStyle : new EvictingMap ( MAX_DEFAULT_STYLE ) ,
35+ baseStyle : new EvictingMap ( MAX_BASE_STYLE ) ,
1036 computedStyle : new WeakMap ( ) ,
1137 font : new Set ( ) ,
1238 session : {
@@ -16,6 +42,8 @@ export const cache = {
1642 }
1743}
1844
45+ export { EvictingMap }
46+
1947/**
2048 * Normalizes shorthand values to canonical cache policies.
2149 * - true => "soft"
@@ -64,13 +92,12 @@ export function applyCachePolicy(policy = 'soft') {
6492 cache . session . styleCache = new WeakMap ( )
6593
6694 cache . computedStyle = new WeakMap ( )
67- cache . baseStyle = new Map ( )
68- cache . defaultStyle = new Map ( )
69-
70- cache . image = new Map ( )
71- cache . background = new Map ( )
72- cache . resource = new Map ( )
73- cache . font = new Set ( )
95+ cache . baseStyle = new EvictingMap ( MAX_BASE_STYLE )
96+ cache . defaultStyle = new EvictingMap ( MAX_DEFAULT_STYLE )
97+ cache . image = new EvictingMap ( MAX_IMAGE )
98+ cache . background = new EvictingMap ( MAX_BACKGROUND )
99+ cache . resource = new EvictingMap ( MAX_RESOURCE )
100+ cache . font = new Set ( )
74101 return
75102 }
76103 default : {
0 commit comments