-
-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy path[...pkg].get.ts
More file actions
53 lines (48 loc) · 1.69 KB
/
[...pkg].get.ts
File metadata and controls
53 lines (48 loc) · 1.69 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
import * as v from 'valibot'
import { PackageVersionQuerySchema } from '#shared/schemas/package'
import type { PackageFileTreeResponse } from '#shared/types'
import { CACHE_MAX_AGE_ONE_YEAR, ERROR_FILE_LIST_FETCH_FAILED } from '#shared/utils/constants'
/**
* Returns the file tree for a package version.
*
* URL patterns:
* - /api/registry/files/packageName/v/1.2.3 - required version
* - /api/registry/files/@scope/packageName/v/1.2.3 - scoped package
*/
export default defineBypassableCachedEventHandler(
async event => {
// Parse package name and version from URL segments
// Patterns: [pkg, 'v', version] or [@scope, pkg, 'v', version]
const pkgParamSegments = getRouterParam(event, 'pkg')?.split('/') ?? []
const { rawPackageName, rawVersion } = parsePackageParams(pkgParamSegments)
try {
const { packageName, version } = v.parse(PackageVersionQuerySchema, {
packageName: rawPackageName,
version: rawVersion,
})
const jsDelivrData = await fetchFileTree(packageName, version)
const tree = convertToFileTree(jsDelivrData.files)
return {
package: packageName,
version,
default: jsDelivrData.default ?? undefined,
tree,
} satisfies PackageFileTreeResponse
} catch (error: unknown) {
handleApiError(error, {
statusCode: 502,
message: ERROR_FILE_LIST_FETCH_FAILED,
})
}
},
{
// Files for a specific version never change - cache permanently
maxAge: CACHE_MAX_AGE_ONE_YEAR, // 1 year
swr: true,
bypassKey: 'files',
getKey: event => {
const pkg = getRouterParam(event, 'pkg') ?? ''
return `files:v1:${pkg.replace(/\/+$/, '').trim()}`
},
},
)