Skip to content

Commit 6b35809

Browse files
committed
feat(core): storage creator
1 parent 52a0fb3 commit 6b35809

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

packages/core/src/node/context.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { DevToolsNodeContext } from '@vitejs/devtools-kit'
22
import type { ResolvedConfig, ViteDevServer } from 'vite'
33
import Debug from 'debug'
44
import { debounce } from 'perfect-debounce'
5+
import { searchForWorkspaceRoot } from 'vite'
56
import { ContextUtils } from './context-utils'
67
import { DevToolsDockHost } from './host-docks'
78
import { RpcFunctionsHost } from './host-functions'
@@ -19,6 +20,7 @@ export async function createDevToolsContext(
1920

2021
const context: DevToolsNodeContext = {
2122
cwd,
23+
workspaceRoot: searchForWorkspaceRoot(cwd) ?? cwd,
2224
viteConfig,
2325
viteServer,
2426
mode: viteConfig.command === 'serve' ? 'dev' : 'build',

packages/core/src/node/storage.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import fs from 'node:fs'
2+
import { createSharedState } from '@vitejs/devtools-kit/utils/shared-state'
3+
4+
export interface CreateStorageOptions<T extends object> {
5+
filepath: string
6+
initialValue: T
7+
}
8+
9+
export async function createStorage<T extends object>(options: CreateStorageOptions<T>) {
10+
let initialState: T
11+
if (fs.existsSync(options.filepath)) {
12+
initialState = JSON.parse(await fs.readFileSync(options.filepath, 'utf-8')) as T
13+
}
14+
else {
15+
initialState = options.initialValue
16+
}
17+
18+
const state = createSharedState<T>({
19+
initialState,
20+
enablePatches: false,
21+
})
22+
23+
state.on('updated', (newState) => {
24+
fs.writeFileSync(options.filepath, `${JSON.stringify(newState, null, 2)}\n`)
25+
})
26+
27+
return state
28+
}

packages/kit/src/types/vite-plugin.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ export interface DevToolsPluginOptions {
1919
}
2020

2121
export interface DevToolsNodeContext {
22+
/**
23+
* Workspace root directory of Vite DevTools
24+
*/
25+
readonly workspaceRoot: string
2226
/**
2327
* Current working directory of Vite DevTools
2428
*/

0 commit comments

Comments
 (0)