@@ -38,6 +38,7 @@ const {
3838 ObjectValues,
3939 ReflectApply,
4040 RegExpPrototypeExec,
41+ SafeMap,
4142 StringPrototypeSlice,
4243 StringPrototypeToWellFormed,
4344} = primordials ;
@@ -118,7 +119,29 @@ const kBoldCode = 1;
118119const kHexCloseSeq = kEscape + '39' + kEscapeEnd ;
119120
120121let styleCache ;
121- const hexStyleCache = { __proto__ : null } ;
122+
123+ const kHexStyleCacheMax = 256 ;
124+
125+ class HexStyleFIFOCache {
126+ #cache = new SafeMap ( ) ;
127+
128+ get ( key ) {
129+ return this . #cache. get ( key ) ;
130+ }
131+
132+ set ( key , value ) {
133+ if ( this . #cache. size >= kHexStyleCacheMax )
134+ this . #cache. delete ( this . #cache. keys ( ) . next ( ) . value ) ;
135+ this . #cache. set ( key , value ) ;
136+ }
137+ }
138+
139+ let hexStyleCache ;
140+
141+ function getHexStyleCache ( ) {
142+ hexStyleCache ??= new HexStyleFIFOCache ( ) ;
143+ return hexStyleCache ;
144+ }
122145
123146function getStyleCache ( ) {
124147 if ( styleCache === undefined ) {
@@ -148,15 +171,16 @@ function getStyleCache() {
148171 * @returns {{openSeq: string, closeSeq: string} }
149172 */
150173function getHexStyle ( hex ) {
151- const cached = hexStyleCache [ hex ] ;
174+ const cache = getHexStyleCache ( ) ;
175+ const cached = cache . get ( hex ) ;
152176 if ( cached !== undefined ) return cached ;
153177 const { 0 : r , 1 : g , 2 : b } = hexToRgb ( hex ) ;
154178 const style = {
155179 __proto__ : null ,
156180 openSeq : kEscape + rgbToAnsi24Bit ( r , g , b ) + kEscapeEnd ,
157181 closeSeq : kHexCloseSeq ,
158182 } ;
159- hexStyleCache [ hex ] = style ;
183+ cache . set ( hex , style ) ;
160184 return style ;
161185}
162186
@@ -241,7 +265,7 @@ function styleText(format, text, options) {
241265 }
242266
243267 if ( format [ 0 ] === '#' ) {
244- let hexStyle = hexStyleCache [ format ] ;
268+ let hexStyle = getHexStyleCache ( ) . get ( format ) ;
245269 if ( hexStyle === undefined && RegExpPrototypeExec ( hexColorRegExp , format ) !== null ) {
246270 hexStyle = getHexStyle ( format ) ;
247271 }
@@ -281,7 +305,7 @@ function styleText(format, text, options) {
281305 if ( key === 'none' ) continue ;
282306
283307 if ( typeof key === 'string' && key [ 0 ] === '#' ) {
284- let hexStyle = hexStyleCache [ key ] ;
308+ let hexStyle = getHexStyleCache ( ) . get ( key ) ;
285309 if ( hexStyle === undefined ) {
286310 if ( RegExpPrototypeExec ( hexColorRegExp , key ) === null ) {
287311 throw new ERR_INVALID_ARG_VALUE ( 'format' , key ,
0 commit comments