Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion packages/devtools-kit/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export default defineBuildConfig({
'nitro',
'nitro/types',
'unimport',
'unstorage',
'ofetch',
'vue',
'vue-router',
Expand Down
3 changes: 3 additions & 0 deletions packages/devtools-kit/src/_types/common.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/** Mirrors unstorage's `StorageValue`, declared locally to avoid a dependency on either unstorage major. */
export type StorageValue = null | string | number | boolean | object

export type TabCategory
= | 'pinned'
| 'app'
Expand Down
2 changes: 1 addition & 1 deletion packages/devtools-kit/src/_types/rpc.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Component, NuxtApp, NuxtLayout, NuxtOptions, NuxtPage } from 'nuxt/schema'
import type { StorageValue } from 'unstorage'
import type { ResolvedConfig } from 'vite'
import type { AnalyzeBuildsInfo } from './analyze-build'
import type { StorageValue } from './common'
import type { ModuleCustomTab } from './custom-tabs'
import type { AssetEntry, AssetInfo, AutoImportsWithMetadata, ComponentRelationship, HookInfo, ImageMeta, NpmCommandOptions, NpmCommandType, PackageUpdateInfo, ScannedNitroTasks, ServerRouteInfo } from './integrations'
import type { AnyNitro, AnyStorageMounts } from './nitro-compat'
Expand Down
1 change: 0 additions & 1 deletion packages/devtools/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export default defineBuildConfig({
// Type only
'vue',
'vue-router',
'unstorage',
'nitropack',
'vite-plugin-vue-tracer',
],
Expand Down
1 change: 0 additions & 1 deletion packages/devtools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@
"structured-clone-es": "catalog:frontend",
"tinyexec": "catalog:prod",
"tinyglobby": "catalog:prod",
"unstorage": "catalog:prod",
"verkit": "catalog:prod",
"vite-plugin-vue-tracer": "catalog:prod",
"ws": "catalog:prod"
Expand Down
118 changes: 118 additions & 0 deletions packages/devtools/src/runtime/nitro/storage-bridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
export const DEVTOOLS_STORAGE_ROUTE = '/__nuxt_devtools__/storage'

/**
* Mounts Nitro adds for its own bookkeeping.
*/
export const IGNORE_STORAGE_MOUNTS = ['root', 'build', 'src', 'cache', 'assets']

export function shouldIgnoreStorageKey(key: string) {
return IGNORE_STORAGE_MOUNTS.includes(key.split(':')[0]!)
}

export type StorageBridgeMethod = 'getKeys' | 'getItem' | 'setItem' | 'removeItem' | 'pullWatchEvents'

export interface StorageBridgeRequest {
token: string
method: StorageBridgeMethod
args?: unknown[]
}

export interface StorageBridgeWatchEvent {
event: 'update' | 'remove'
key: string
}

export interface StorageBridgeWatchBatch {
instance: string
cursor: number
events: StorageBridgeWatchEvent[]
}

/**
* Structural subset of unstorage's `Storage` shared by the v1 instance Nitro v2
* bundles and the v2 instance Nitro v3 bundles, so the bridge works against
* whichever `useStorage()` returns without importing either version.
*/
export interface StorageBridgeStorage {
getKeys: (base?: string) => Promise<string[]>
getItem: (key: string) => Promise<unknown>
setItem: (key: string, value: any) => Promise<void>
removeItem: (key: string) => Promise<void>
getMounts?: () => Array<{
base: string
driver: {
watch?: (callback: (event: 'update' | 'remove', key: string) => void) => Promise<unknown> | unknown
}
}>
}

const MAX_BUFFERED_EVENTS = 500

interface WatchState {
instance: string
events: Array<StorageBridgeWatchEvent & { id: number }>
nextId: number
}

let watchState: WatchState | undefined

async function ensureWatcher(storage: StorageBridgeStorage): Promise<WatchState> {
if (watchState)
return watchState
const state: WatchState = {
instance: Math.random().toString(36).slice(2),
events: [],
nextId: 1,
}
watchState = state

const mounts = storage.getMounts?.() ?? []
await Promise.all(mounts.map(async ({ base, driver }) => {
if (!driver?.watch || shouldIgnoreStorageKey(base))
return
try {
await driver.watch((event, key) => {
state.events.push({ id: state.nextId++, event, key: base + key })
if (state.events.length > MAX_BUFFERED_EVENTS)
state.events.splice(0, state.events.length - MAX_BUFFERED_EVENTS)
})
}
catch {
// Some drivers don't support watching; polling clients see no events for them.
}
}))

return state
}

export async function handleStorageBridgeRequest(storage: StorageBridgeStorage, body: StorageBridgeRequest | undefined, token: string) {
if (!token || !body || body.token !== token)
throw new Error('[nuxt-devtools] Invalid storage bridge token')

const args = body.args ?? []
switch (body.method) {
case 'getKeys':
return { result: await storage.getKeys(args[0] as string | undefined) }
case 'getItem':
return { result: await storage.getItem(args[0] as string) }
case 'setItem':
return { result: await storage.setItem(args[0] as string, args[1]) }
case 'removeItem':
return { result: await storage.removeItem(args[0] as string) }
case 'pullWatchEvents': {
const state = await ensureWatcher(storage)
const [instance, cursor] = args as [string | undefined, number | undefined]
const events = instance === state.instance
? state.events.filter(e => e.id > (cursor ?? 0))
: []
const batch: StorageBridgeWatchBatch = {
instance: state.instance,
cursor: state.events.at(-1)?.id ?? 0,
events: events.map(({ event, key }) => ({ event, key })),
}
return { result: batch }
}
default:
throw new Error(`[nuxt-devtools] Unknown storage bridge method "${(body as StorageBridgeRequest).method}"`)
}
}
9 changes: 9 additions & 0 deletions packages/devtools/src/runtime/nitro/storage-handler-v2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { defineEventHandler, readBody } from 'h3'
import { useStorage } from 'nitropack/runtime'
// @ts-expect-error virtual module injected by @nuxt/devtools
import { token } from '#nuxt-devtools-storage'
import { handleStorageBridgeRequest } from './storage-bridge'

export default defineEventHandler(async (event) => {
return handleStorageBridgeRequest(useStorage(), await readBody(event), token)
})
9 changes: 9 additions & 0 deletions packages/devtools/src/runtime/nitro/storage-handler-v3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { defineEventHandler, readBody } from 'nitro/h3'
import { useStorage } from 'nitro/storage'
// @ts-expect-error virtual module injected by @nuxt/devtools
import { token } from '#nuxt-devtools-storage'
import { handleStorageBridgeRequest } from './storage-bridge'

export default defineEventHandler(async (event) => {
return handleStorageBridgeRequest(useStorage(), await readBody(event), token)
})
19 changes: 0 additions & 19 deletions packages/devtools/src/server-rpc/storage-watch.ts

This file was deleted.

Loading
Loading