forked from npmx-dev/npmx.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseVersionDistribution.ts
More file actions
188 lines (164 loc) · 5.18 KB
/
useVersionDistribution.ts
File metadata and controls
188 lines (164 loc) · 5.18 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import type {
VersionDistributionResponse,
VersionGroupDownloads,
VersionGroupingMode,
} from '#shared/types/version-downloads'
import type { MaybeRefOrGetter } from 'vue'
import { toValue } from 'vue'
interface ChartDataItem {
name: string
downloads: number
}
/**
* Composable for managing version download distribution data and state.
*
* Fetches version download statistics from the API, manages grouping/filtering state,
* and formats data for chart visualization.
*
* @param packageName - The package name to fetch version downloads for
* @returns Reactive state and computed chart data
*/
export function useVersionDistribution(packageName: MaybeRefOrGetter<string>) {
const groupingMode = useRouteQuery<VersionGroupingMode>('grouping', 'major', {
transform: (v: string) => (v === 'minor' ? 'minor' : 'major'),
mode: 'replace',
})
const showRecentOnly = useBooleanRouteQuery('recent', false)
const showLowUsageVersions = useBooleanRouteQuery('lowUsage', false)
const pending = ref(false)
const error = ref<Error | null>(null)
const data = ref<VersionDistributionResponse | null>(null)
/**
* Fetches version download distribution from the API
*/
async function fetchDistribution() {
const pkgName = toValue(packageName)
if (!pkgName) {
data.value = null
return
}
pending.value = true
error.value = null
try {
const mode = groupingMode.value
const response = await $fetch<VersionDistributionResponse>(
`/api/registry/downloads/${encodeURIComponent(pkgName)}/versions`,
{
query: {
mode,
filterOldVersions: showRecentOnly.value ? 'true' : 'false',
filterThreshold: showLowUsageVersions.value ? '0' : '1',
},
cache: 'default', // Don't force-cache since query params change frequently
},
)
data.value = response
} catch (err) {
error.value = err instanceof Error ? err : new Error('Failed to fetch version distribution')
data.value = null
} finally {
pending.value = false
}
}
/**
* Applies filtering to version groups based on current filter settings
* Sorts groups from oldest to newest version
*/
const filteredGroups = computed<VersionGroupDownloads[]>(() => {
if (!data.value) return []
let groups = data.value.groups
// Filter using server-provided recent versions list
if (showRecentOnly.value && data.value.recentVersions) {
const recentVersionsSet = new Set(data.value.recentVersions)
groups = groups.filter(group => {
return group.versions.some(v => {
// Check exact version match
if (recentVersionsSet.has(v.version)) return true
// Also check base version (strip prerelease suffix)
if (v.version.includes('-')) {
const baseVersion = v.version.split('-')[0]
if (baseVersion && recentVersionsSet.has(baseVersion)) return true
}
return false
})
})
}
// Sort groups from oldest to newest by parsing version numbers
return groups.slice().sort((a, b) => {
// Extract version numbers from groupKey (e.g., "1.x" or "1.2.x")
const aParts = a.groupKey.replace(/\.x$/, '').split('.').map(Number)
const bParts = b.groupKey.replace(/\.x$/, '').split('.').map(Number)
for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
const aPart = aParts[i] ?? 0
const bPart = bParts[i] ?? 0
if (aPart !== bPart) {
return aPart - bPart
}
}
return 0
})
})
const chartDataset = computed<ChartDataItem[]>(() => {
const groups = filteredGroups.value
if (!groups.length) return []
return groups.map(group => ({
name: group.label,
downloads: group.downloads,
}))
})
const totalDownloads = computed(() => {
const groups = filteredGroups.value
if (!groups || !groups.length) return 0
return groups.reduce((sum, group) => sum + group.downloads, 0)
})
const hasData = computed(() => {
return data.value !== null && filteredGroups.value.length > 0
})
// Refetch when filter changes - no immediate since we already have data
watch(showRecentOnly, () => {
fetchDistribution()
})
watch(showLowUsageVersions, () => {
fetchDistribution()
})
// Refetch when grouping mode changes - immediate to load initial data
watch(
groupingMode,
() => {
fetchDistribution()
},
{ immediate: true },
)
// Refetch when package name changes - not immediate since parent component controls initialization
watch(
() => toValue(packageName),
() => {
fetchDistribution()
},
{ immediate: false },
)
return {
// State
groupingMode,
showRecentOnly,
showLowUsageVersions,
pending,
error,
// Computed
filteredGroups,
chartDataset,
totalDownloads,
hasData,
// Methods
fetchDistribution,
}
}
function useBooleanRouteQuery(key: string, defaultValue = false) {
return useRouteQuery(key, defaultValue ? 'true' : 'false', {
transform: {
get: (v: string) => v === 'true',
set: (v: boolean) => (v ? 'true' : 'false'),
},
mode: 'replace',
})
}