@vitejs/devtools-kit 0.0.0-alpha.3 → 0.0.0-alpha.31

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.
@@ -0,0 +1,290 @@
1
+ # Shared State Patterns
2
+
3
+ Synchronized state between server and all clients.
4
+
5
+ ## Basic Usage
6
+
7
+ ### Server-Side
8
+
9
+ ```ts
10
+ const state = await ctx.rpc.sharedState.get('my-plugin:state', {
11
+ initialValue: {
12
+ count: 0,
13
+ items: [],
14
+ settings: { theme: 'dark' },
15
+ },
16
+ })
17
+
18
+ // Read
19
+ const current = state.value()
20
+
21
+ // Mutate (syncs to all clients)
22
+ state.mutate((draft) => {
23
+ draft.count += 1
24
+ draft.items.push({ id: Date.now(), name: 'New' })
25
+ })
26
+ ```
27
+
28
+ ### Client-Side
29
+
30
+ ```ts
31
+ import { getDevToolsRpcClient } from '@vitejs/devtools-kit/client'
32
+
33
+ const client = await getDevToolsRpcClient()
34
+ const state = await client.rpc.sharedState.get('my-plugin:state')
35
+
36
+ // Read
37
+ console.log(state.value())
38
+
39
+ // Subscribe
40
+ state.on('updated', (newState) => {
41
+ console.log('Updated:', newState)
42
+ })
43
+ ```
44
+
45
+ ## Type-Safe Shared State
46
+
47
+ ```ts
48
+ // src/types.ts
49
+ interface MyPluginState {
50
+ count: number
51
+ items: Array<{ id: string, name: string }>
52
+ settings: {
53
+ theme: 'light' | 'dark'
54
+ notifications: boolean
55
+ }
56
+ }
57
+
58
+ declare module '@vitejs/devtools-kit' {
59
+ interface DevToolsRpcSharedStates {
60
+ 'my-plugin:state': MyPluginState
61
+ }
62
+ }
63
+ ```
64
+
65
+ ## Vue Integration
66
+
67
+ ```ts
68
+ // composables/useSharedState.ts
69
+ import { getDevToolsRpcClient } from '@vitejs/devtools-kit/client'
70
+ import { onMounted, shallowRef } from 'vue'
71
+
72
+ export function useSharedState<T>(name: string) {
73
+ const state = shallowRef<T | null>(null)
74
+ const loading = shallowRef(true)
75
+
76
+ onMounted(async () => {
77
+ const client = await getDevToolsRpcClient()
78
+ const shared = await client.rpc.sharedState.get<T>(name)
79
+
80
+ state.value = shared.value()
81
+ loading.value = false
82
+
83
+ shared.on('updated', (newState) => {
84
+ state.value = newState
85
+ })
86
+ })
87
+
88
+ return { state, loading }
89
+ }
90
+
91
+ // Usage in component
92
+ const { state, loading } = useSharedState<MyPluginState>('my-plugin:state')
93
+ ```
94
+
95
+ ### Full Vue Component Example
96
+
97
+ ```vue
98
+ <script setup lang="ts">
99
+ import { getDevToolsRpcClient } from '@vitejs/devtools-kit/client'
100
+ import { onMounted, shallowRef } from 'vue'
101
+
102
+ interface PluginState {
103
+ count: number
104
+ items: string[]
105
+ }
106
+
107
+ const state = shallowRef<PluginState | null>(null)
108
+
109
+ onMounted(async () => {
110
+ const client = await getDevToolsRpcClient()
111
+ const shared = await client.rpc.sharedState.get<PluginState>('my-plugin:state')
112
+
113
+ state.value = shared.value()
114
+
115
+ shared.on('updated', (newState) => {
116
+ state.value = newState
117
+ })
118
+ })
119
+ </script>
120
+
121
+ <template>
122
+ <div v-if="state">
123
+ <p>Count: {{ state.count }}</p>
124
+ <ul>
125
+ <li v-for="item in state.items" :key="item">
126
+ {{ item }}
127
+ </li>
128
+ </ul>
129
+ </div>
130
+ </template>
131
+ ```
132
+
133
+ ## React Integration
134
+
135
+ ```tsx
136
+ import { getDevToolsRpcClient } from '@vitejs/devtools-kit/client'
137
+ import { useEffect, useState } from 'react'
138
+
139
+ function useSharedState<T>(name: string, fallback: T) {
140
+ const [state, setState] = useState<T>(fallback)
141
+ const [loading, setLoading] = useState(true)
142
+
143
+ useEffect(() => {
144
+ let mounted = true
145
+
146
+ async function init() {
147
+ const client = await getDevToolsRpcClient()
148
+ const shared = await client.rpc.sharedState.get<T>(name)
149
+
150
+ if (mounted) {
151
+ setState(shared.value() ?? fallback)
152
+ setLoading(false)
153
+
154
+ shared.on('updated', (newState) => {
155
+ if (mounted)
156
+ setState(newState)
157
+ })
158
+ }
159
+ }
160
+
161
+ init()
162
+ return () => {
163
+ mounted = false
164
+ }
165
+ }, [name])
166
+
167
+ return { state, loading }
168
+ }
169
+
170
+ // Usage
171
+ function MyComponent() {
172
+ const { state, loading } = useSharedState('my-plugin:state', { count: 0 })
173
+
174
+ if (loading)
175
+ return <div>Loading...</div>
176
+
177
+ return (
178
+ <div>
179
+ Count:
180
+ {state.count}
181
+ </div>
182
+ )
183
+ }
184
+ ```
185
+
186
+ ## Svelte Integration
187
+
188
+ ```svelte
189
+ <script lang="ts">
190
+ import { onMount } from 'svelte'
191
+ import { writable } from 'svelte/store'
192
+ import { getDevToolsRpcClient } from '@vitejs/devtools-kit/client'
193
+
194
+ interface PluginState {
195
+ count: number
196
+ }
197
+
198
+ const state = writable<PluginState>({ count: 0 })
199
+
200
+ onMount(async () => {
201
+ const client = await getDevToolsRpcClient()
202
+ const shared = await client.rpc.sharedState.get<PluginState>('my-plugin:state')
203
+
204
+ state.set(shared.value())
205
+
206
+ shared.on('updated', (newState) => {
207
+ state.set(newState)
208
+ })
209
+ })
210
+ </script>
211
+
212
+ <p>Count: {$state.count}</p>
213
+ ```
214
+
215
+ ## Best Practices
216
+
217
+ ### Batch Mutations
218
+
219
+ ```ts
220
+ // Good - single sync event
221
+ state.mutate((draft) => {
222
+ draft.count += 1
223
+ draft.lastUpdate = Date.now()
224
+ draft.items.push(newItem)
225
+ })
226
+
227
+ // Bad - multiple sync events
228
+ state.mutate((d) => {
229
+ d.count += 1
230
+ })
231
+ state.mutate((d) => {
232
+ d.lastUpdate = Date.now()
233
+ })
234
+ state.mutate((d) => {
235
+ d.items.push(newItem)
236
+ })
237
+ ```
238
+
239
+ ### Keep State Small
240
+
241
+ For large datasets, store IDs in shared state and fetch details via RPC:
242
+
243
+ <!-- eslint-skip -->
244
+ ```ts
245
+ // Shared state (small)
246
+ {
247
+ moduleIds: ['a', 'b', 'c'],
248
+ selectedId: 'a'
249
+ }
250
+
251
+ // Fetch full data via RPC when needed
252
+ const module = await rpc.call('my-plugin:get-module', state.selectedId)
253
+ ```
254
+
255
+ ### Serializable Data Only
256
+
257
+ <!-- eslint-skip -->
258
+ ```ts
259
+ // Bad - functions can't be serialized
260
+ { count: 0, increment: () => {} }
261
+
262
+ // Bad - circular references
263
+ const obj = { child: null }
264
+ obj.child = obj
265
+
266
+ // Good - plain data
267
+ { count: 0, items: [{ id: 1 }] }
268
+ ```
269
+
270
+ ### Real-Time Updates Example
271
+
272
+ ```ts
273
+ const plugin: Plugin = {
274
+ devtools: {
275
+ async setup(ctx) {
276
+ const state = await ctx.rpc.sharedState.get('my-plugin:state', {
277
+ initialValue: { modules: [], lastUpdate: 0 },
278
+ })
279
+
280
+ // Update state when Vite processes modules
281
+ ctx.viteServer?.watcher.on('change', (file) => {
282
+ state.mutate((draft) => {
283
+ draft.modules.push(file)
284
+ draft.lastUpdate = Date.now()
285
+ })
286
+ })
287
+ }
288
+ }
289
+ }
290
+ ```
package/dist/client.d.ts DELETED
@@ -1,17 +0,0 @@
1
- import { ConnectionMeta, DevToolsRpcClientFunctions, DevToolsRpcServerFunctions } from "./rpc-ls6mUIa2.js";
2
- import { WebSocketRpcClientOptions } from "@vitejs/devtools-rpc/presets/ws/client";
3
- import { BirpcOptions, BirpcReturn } from "birpc";
4
-
5
- //#region src/client/index.d.ts
6
- interface DevToolsRpcClientOptions {
7
- connectionMeta?: ConnectionMeta;
8
- baseURL?: string[];
9
- wsOptions?: Partial<WebSocketRpcClientOptions>;
10
- rpcOptions?: Partial<BirpcOptions<DevToolsRpcServerFunctions>>;
11
- }
12
- declare function getDevToolsRpcClient(options?: DevToolsRpcClientOptions): Promise<{
13
- connectionMeta: ConnectionMeta;
14
- rpc: BirpcReturn<DevToolsRpcServerFunctions, DevToolsRpcClientFunctions>;
15
- }>;
16
- //#endregion
17
- export { DevToolsRpcClientOptions, getDevToolsRpcClient };
package/dist/client.js DELETED
@@ -1,38 +0,0 @@
1
- import { createRpcClient } from "@vitejs/devtools-rpc";
2
- import { createWsRpcPreset } from "@vitejs/devtools-rpc/presets/ws/client";
3
-
4
- //#region src/client/index.ts
5
- function isNumeric(str) {
6
- if (str == null) return false;
7
- return `${+str}` === `${str}`;
8
- }
9
- async function getDevToolsRpcClient(options = {}) {
10
- const { baseURL = "/__vite_devtools__/api/" } = options;
11
- const urls = Array.isArray(baseURL) ? baseURL : [baseURL];
12
- let connectionMeta = options.connectionMeta;
13
- if (!connectionMeta) {
14
- const errors = [];
15
- for (const url$1 of urls) try {
16
- connectionMeta = await fetch(`${url$1}connection.json`).then((r) => r.json());
17
- break;
18
- } catch (e) {
19
- errors.push(e);
20
- }
21
- if (!connectionMeta) throw new Error(`Failed to get connection meta from ${urls.join(", ")}`, { cause: errors });
22
- }
23
- const url = isNumeric(connectionMeta.websocket) ? `${location.protocol.replace("http", "ws")}//${location.hostname}:${connectionMeta.websocket}` : connectionMeta.websocket;
24
- const rpc = createRpcClient({}, {
25
- preset: createWsRpcPreset({
26
- url,
27
- ...options.wsOptions
28
- }),
29
- ...options.rpcOptions
30
- });
31
- return {
32
- connectionMeta,
33
- rpc
34
- };
35
- }
36
-
37
- //#endregion
38
- export { getDevToolsRpcClient };
package/dist/index.d.ts DELETED
@@ -1,18 +0,0 @@
1
- import { BirpcFn, BirpcReturn, ConnectionMeta, DevToolsCapabilities, DevToolsDockEntry, DevToolsDockEntryBase, DevToolsDockHost, DevToolsNodeContext, DevToolsPluginOptions, DevToolsRpcClientFunctions, DevToolsRpcServerFunctions, DevToolsViewAction, DevToolsViewIframe, DevToolsViewWebComponent, EntriesToObject, RpcDefinitionsFilter, RpcDefinitionsToFunctions, RpcFunctionDefinition, RpcFunctionSetupResult, RpcFunctionType, RpcFunctionsHost, Thenable } from "./rpc-ls6mUIa2.js";
2
- import { Plugin } from "vite";
3
-
4
- //#region src/types/vite-augment.d.ts
5
- declare module 'vite' {
6
- interface Plugin {
7
- devtools?: DevToolsPluginOptions;
8
- }
9
- }
10
- interface PluginWithDevTools extends Plugin {
11
- devtools?: DevToolsPluginOptions;
12
- }
13
- //#endregion
14
- //#region src/utils/rpc.d.ts
15
- declare function defineRpcFunction<NAME extends string, TYPE extends RpcFunctionType, ARGS extends any[], RETURN = void>(definition: RpcFunctionDefinition<NAME, TYPE, ARGS, RETURN>): RpcFunctionDefinition<NAME, TYPE, ARGS, RETURN>;
16
- declare function getRpcHandler<NAME extends string, TYPE extends RpcFunctionType, ARGS extends any[], RETURN = void>(definition: RpcFunctionDefinition<NAME, TYPE, ARGS, RETURN>, context: DevToolsNodeContext): Promise<(...args: ARGS) => RETURN>;
17
- //#endregion
18
- export { BirpcFn, BirpcReturn, ConnectionMeta, DevToolsCapabilities, DevToolsDockEntry, DevToolsDockEntryBase, DevToolsDockHost, DevToolsNodeContext, DevToolsPluginOptions, DevToolsRpcClientFunctions, DevToolsRpcServerFunctions, DevToolsViewAction, DevToolsViewIframe, DevToolsViewWebComponent, EntriesToObject, PluginWithDevTools, RpcDefinitionsFilter, RpcDefinitionsToFunctions, RpcFunctionDefinition, RpcFunctionSetupResult, RpcFunctionType, RpcFunctionsHost, Thenable, defineRpcFunction, getRpcHandler };
package/dist/index.js DELETED
@@ -1,17 +0,0 @@
1
- //#region src/utils/rpc.ts
2
- function defineRpcFunction(definition) {
3
- return definition;
4
- }
5
- async function getRpcHandler(definition, context) {
6
- if (definition.handler) return definition.handler;
7
- if (definition.__resolved?.handler) return definition.__resolved.handler;
8
- definition.__promise ??= Promise.resolve(definition.setup(context)).then((r) => {
9
- definition.__resolved = r;
10
- definition.__promise = void 0;
11
- return r;
12
- });
13
- return (definition.__resolved ??= await definition.__promise).handler;
14
- }
15
-
16
- //#endregion
17
- export { defineRpcFunction, getRpcHandler };
@@ -1,118 +0,0 @@
1
- import { BirpcFn, BirpcReturn as BirpcReturn$1 } from "birpc";
2
- import { ResolvedConfig, ViteDevServer } from "vite";
3
-
4
- //#region src/types/rpc-augments.d.ts
5
- /**
6
- * To be extended
7
- */
8
- interface DevToolsRpcClientFunctions {}
9
- /**
10
- * To be extended
11
- */
12
- interface DevToolsRpcServerFunctions {}
13
- //#endregion
14
- //#region src/types/utils.d.ts
15
- type Thenable<T> = T | Promise<T>;
16
- type EntriesToObject<T extends readonly [string, any][]> = { [K in T[number] as K[0]]: K[1] };
17
- //#endregion
18
- //#region src/types/views.d.ts
19
- interface DevToolsDockHost {
20
- register: (entry: DevToolsDockEntry) => void;
21
- values: () => DevToolsDockEntry[];
22
- }
23
- interface DevToolsDockEntryBase {
24
- id: string;
25
- title: string;
26
- icon: string;
27
- }
28
- interface DevToolsViewIframe extends DevToolsDockEntryBase {
29
- type: 'iframe';
30
- url: string;
31
- /**
32
- * The id of the iframe, if multiple tabs is assigned with the same id, the iframe will be shared.
33
- *
34
- * When not provided, it would be treated as a unique frame.
35
- */
36
- frameId?: string;
37
- }
38
- interface DevToolsViewWebComponent extends DevToolsDockEntryBase {
39
- type: 'webcomponent';
40
- from: string;
41
- import: string;
42
- }
43
- interface DevToolsViewAction extends DevToolsDockEntryBase {
44
- type: 'action';
45
- importFrom: string;
46
- /**
47
- * @default 'default'
48
- */
49
- importName?: string;
50
- }
51
- type DevToolsDockEntry = DevToolsViewIframe | DevToolsViewWebComponent | DevToolsViewAction;
52
- //#endregion
53
- //#region src/types/vite-plugin.d.ts
54
- interface DevToolsCapabilities {
55
- rpc?: boolean;
56
- views?: boolean;
57
- }
58
- interface DevToolsPluginOptions {
59
- capabilities?: {
60
- dev?: DevToolsCapabilities | boolean;
61
- build?: DevToolsCapabilities | boolean;
62
- };
63
- setup: (context: DevToolsNodeContext) => void | Promise<void>;
64
- }
65
- interface DevToolsNodeContext {
66
- readonly cwd: string;
67
- readonly mode: 'dev' | 'build';
68
- readonly viteConfig: ResolvedConfig;
69
- readonly viteServer?: ViteDevServer;
70
- rpc: RpcFunctionsHost;
71
- docks: DevToolsDockHost;
72
- /**
73
- * Helper to host static files
74
- * - In `dev` mode, it will register middleware to `viteServer.middlewares` to host the static files
75
- * - In `build` mode, it will copy the static files to the dist directory
76
- */
77
- hostStatic: (baseUrl: string, distDir: string) => void;
78
- staticDirs: {
79
- baseUrl: string;
80
- distDir: string;
81
- }[];
82
- }
83
- interface ConnectionMeta {
84
- backend: 'websocket' | 'static';
85
- websocket?: number | string;
86
- }
87
- //#endregion
88
- //#region src/types/rpc.d.ts
89
- /**
90
- * Type of the RPC function,
91
- * - static: A function that returns a static data (can be cached and dumped)
92
- * - action: A function that performs an action (no data returned)
93
- * - query: A function that queries a resource
94
- */
95
- type RpcFunctionType = 'static' | 'action' | 'query';
96
- interface RpcFunctionsHost {
97
- context: DevToolsNodeContext;
98
- readonly functions: DevToolsRpcServerFunctions;
99
- readonly definitions: Map<string, RpcFunctionDefinition<string, any, any, any>>;
100
- register: (fn: RpcFunctionDefinition<string, any, any, any>) => void;
101
- }
102
- interface RpcFunctionSetupResult<ARGS extends any[], RETURN = void> {
103
- handler: (...args: ARGS) => RETURN;
104
- }
105
- interface RpcFunctionDefinition<NAME extends string, TYPE extends RpcFunctionType, ARGS extends any[] = [], RETURN = void> {
106
- name: NAME;
107
- type: TYPE;
108
- setup: (context: DevToolsNodeContext) => Thenable<RpcFunctionSetupResult<ARGS, RETURN>>;
109
- handler?: (...args: ARGS) => RETURN;
110
- __resolved?: RpcFunctionSetupResult<ARGS, RETURN>;
111
- __promise?: Thenable<RpcFunctionSetupResult<ARGS, RETURN>>;
112
- }
113
- type RpcDefinitionsToFunctions<T extends readonly RpcFunctionDefinition<any, any, any>[]> = EntriesToObject<{ [K in keyof T]: [T[K]['name'], Awaited<ReturnType<T[K]['setup']>>['handler']] }>;
114
- type RpcDefinitionsFilter<T extends readonly RpcFunctionDefinition<any, any, any>[], Type extends RpcFunctionType> = { [K in keyof T]: T[K] extends {
115
- type: Type;
116
- } ? T[K] : never };
117
- //#endregion
118
- export { type BirpcFn, type BirpcReturn$1 as BirpcReturn, ConnectionMeta, DevToolsCapabilities, DevToolsDockEntry, DevToolsDockEntryBase, DevToolsDockHost, DevToolsNodeContext, DevToolsPluginOptions, DevToolsRpcClientFunctions, DevToolsRpcServerFunctions, DevToolsViewAction, DevToolsViewIframe, DevToolsViewWebComponent, EntriesToObject, RpcDefinitionsFilter, RpcDefinitionsToFunctions, RpcFunctionDefinition, RpcFunctionSetupResult, RpcFunctionType, RpcFunctionsHost, Thenable };