-
Notifications
You must be signed in to change notification settings - Fork 153
/
npm.ts
72 lines (55 loc) · 1.79 KB
/
npm.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import semver from 'semver'
import type { NpmCommandOptions } from '../../src/types'
export type PackageUpdateState = 'idle' | 'running' | 'updated'
const map = new Map<string, any>()
export function usePackageUpdate(name: string, options?: NpmCommandOptions): ReturnType<typeof getPackageUpdate> {
const key = name
if (!map.has(key))
map.set(key, getPackageUpdate(name, options))
return map.get(key)
}
export function useNuxtVersion() {
return useAsyncData('npm:check:nuxt', () => rpc.checkForUpdateFor('nuxt')).data
}
export function satisfyNuxtVersion(range: string) {
const nuxt = useNuxtVersion()
if (!nuxt?.value?.current)
return false
return semver.satisfies(nuxt.value.current, range)
}
function getPackageUpdate(name: string, options?: NpmCommandOptions) {
const nuxt = useNuxtApp()
const info = useAsyncData(`npm:check:${name}`, () => rpc.checkForUpdateFor(name)).data
const state = ref<PackageUpdateState>('idle')
const processId = ref<string | undefined>()
// @ts-expect-error missing hooks type
nuxt.hook('devtools:terminal:exit', ({ id, code }) => {
if (id !== processId || !processId)
return
state.value = code === 0 ? 'updated' : 'idle'
})
async function update(confirm: (command: string) => Promise<boolean>) {
if (state.value !== 'idle')
return
const command = await rpc.getNpmCommand('update', name, options)
if (!command)
return
if (!await confirm(command.join(' ')))
return
state.value = 'running'
processId.value = (await rpc.runNpmCommand('update', name, options))?.processId
return processId.value
}
async function restart() {
if (state.value !== 'updated')
return
await rpc.restartNuxt()
}
return {
info,
state,
update,
restart,
processId,
}
}