11import type { StorageMounts } from 'nitropack'
22import type { Storage , StorageValue } from 'unstorage'
33import type { NuxtDevtoolsServerContext , ServerFunctions } from '../types'
4+ import { watchStorageMount } from './storage-watch'
45
56const IGNORE_STORAGE_MOUNTS = [ 'root' , 'build' , 'src' , 'cache' ]
67function shouldIgnoreStorageKey ( key : string ) {
@@ -15,32 +16,44 @@ export function setupStorageRPC({
1516 const storageMounts : StorageMounts = { }
1617
1718 let storage : Storage | undefined
19+ let unwatchStorageMounts : Array < ( ) => Promise < void > | void > = [ ]
1820
1921 nuxt . hook ( 'nitro:init' , ( nitro ) => {
2022 storage = nitro . storage
2123
22- nuxt . hook ( 'ready' , ( ) => {
23- storage ! . watch ( ( event , key ) => {
24- if ( shouldIgnoreStorageKey ( key ) )
25- return
26- rpc . broadcast . callHook . asEvent ( 'storage:key:update' , key , event )
27- } )
28- } )
29-
3024 // Taken from https://github.com/unjs/nitro/blob/d83f2b65165d7ba996e7ef129ea99ff5b551dccc/src/storage.ts#L7-L10
3125 // Waiting for https://github.com/unjs/unstorage/issues/53
3226 const mounts = {
3327 ...nitro . options . storage ,
3428 ...nitro . options . devStorage ,
3529 }
3630
31+ for ( const key of Object . keys ( storageMounts ) )
32+ delete storageMounts [ key ]
33+
3734 for ( const name of Object . keys ( mounts ) ) {
3835 if ( shouldIgnoreStorageKey ( name ) )
3936 continue
4037 storageMounts [ name ] = mounts [ name ] !
4138 }
4239 } )
4340
41+ nuxt . hook ( 'ready' , async ( ) => {
42+ const activeStorage = storage
43+ if ( ! activeStorage )
44+ return
45+ await Promise . all ( unwatchStorageMounts . map ( unwatch => unwatch ( ) ) )
46+ unwatchStorageMounts = await Promise . all ( Object . keys ( storageMounts ) . map ( mountName =>
47+ watchStorageMount ( activeStorage , mountName , ( event , key ) => {
48+ rpc . broadcast . callHook . asEvent ( 'storage:key:update' , key , event )
49+ } ) ) )
50+ } )
51+
52+ nuxt . hook ( 'close' , async ( ) => {
53+ await Promise . all ( unwatchStorageMounts . map ( unwatch => unwatch ( ) ) )
54+ unwatchStorageMounts = [ ]
55+ } )
56+
4457 return {
4558 async getStorageMounts ( ) {
4659 return storageMounts
0 commit comments