-
-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathuseLicenseChanges.ts
More file actions
80 lines (70 loc) · 2.26 KB
/
useLicenseChanges.ts
File metadata and controls
80 lines (70 loc) · 2.26 KB
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
73
74
75
76
77
78
79
80
import type { MaybeRefOrGetter } from 'vue'
import { toValue } from 'vue'
export interface LicenseChange {
from: string
to: string
version: string
}
export interface LicenseChangesResult {
changes: LicenseChange[]
}
// Type definitions for npm registry response
interface NpmRegistryVersion {
version: string
license?: string
}
// for registry responses of $fetch function, the type includes the key versions as well as many others too.
interface NpmRegistryResponse {
versions: Record<
string,
{
version: string
license?: string
}
>
}
/**
* Composable to detect license changes across all versions of a package
*/
export function useLicenseChanges(packageName: MaybeRefOrGetter<string | null | undefined>) {
return useAsyncData<LicenseChangesResult>(
() => `license-changes:${toValue(packageName)}`,
async () => {
const name = toValue(packageName)
if (!name) return { changes: [] }
// Fetch full package metadata from npm registry
const url = `https://registry.npmjs.org/${name}`
const data = await $fetch<NpmRegistryResponse>(url)
const changes: LicenseChange[] = []
let prevLicense: string | undefined = undefined
// `data.versions` is an object with version keys
const versions = Object.values(data.versions) as NpmRegistryVersion[]
// Sort versions ascending to compare chronologically
versions.sort((a, b) => {
const parse = (v: string) => v.split('.').map(Number)
const [aMajor, aMinor, aPatch] = parse(a.version as string)
const [bMajor, bMinor, bPatch] = parse(b.version as string)
if (aMajor !== bMajor) return aMajor! - bMajor!
if (aMinor !== bMinor) return aMinor! - bMinor!
return aPatch! - bPatch!
})
// Detect license changes
for (const version of versions) {
const license = (version.license as string) ?? 'UNKNOWN'
if (prevLicense && license !== prevLicense) {
changes.push({
from: prevLicense,
to: license,
version: version.version as string,
})
}
prevLicense = license
}
return { changes }
},
{
default: () => ({ changes: [] }),
watch: [() => toValue(packageName)],
},
)
}