Skip to content
Merged
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
53 changes: 53 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,59 @@ The connector will check your npm authentication, generate a connection token, a
- We care about good types – never cast things to `any` 💪
- Validate rather than just assert

### Server API patterns

#### Input validation with Valibot

Use Valibot schemas from `#shared/schemas/` to validate API inputs. This ensures type safety and provides consistent error messages:

```typescript
import * as v from 'valibot'
import { PackageRouteParamsSchema } from '#shared/schemas/package'

// In your handler:
const { packageName, version } = v.parse(PackageRouteParamsSchema, {
packageName: rawPackageName,
version: rawVersion,
})
```

#### Error handling with `handleApiError`

Use the `handleApiError` utility for consistent error handling in API routes. It re-throws H3 errors (like 404s) and wraps other errors with a fallback message:

```typescript
import { ERROR_NPM_FETCH_FAILED } from '#shared/utils/constants'

try {
// API logic...
} catch (error: unknown) {
handleApiError(error, {
statusCode: 502,
message: ERROR_NPM_FETCH_FAILED,
})
}
```

#### URL parameter parsing with `parsePackageParams`

Use `parsePackageParams` to extract package name and version from URL segments:

```typescript
const pkgParamSegments = getRouterParam(event, 'pkg')?.split('/') ?? []
const { rawPackageName, rawVersion } = parsePackageParams(pkgParamSegments)
```

This handles patterns like `/pkg`, `/pkg/v/1.0.0`, `/@scope/pkg`, and `/@scope/pkg/v/1.0.0`.

#### Constants

Define error messages and other string constants in `#shared/utils/constants.ts` to ensure consistency across the codebase:

```typescript
export const ERROR_NPM_FETCH_FAILED = 'Failed to fetch package from npm registry.'
```

### Import order

1. Type imports first (`import type { ... }`)
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"shiki": "^3.21.0",
"ufo": "^1.6.3",
"unplugin-vue-router": "^0.19.2",
"valibot": "^1.2.0",
"validate-npm-package-name": "^7.0.2",
"virtua": "^0.48.3",
"vue": "3.5.27",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 18 additions & 7 deletions server/api/jsr/[...pkg].get.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import * as v from 'valibot'
import { PackageNameSchema } from '#shared/schemas/package'
import { CACHE_MAX_AGE_ONE_HOUR, ERROR_JSR_FETCH_FAILED } from '#shared/utils/constants'
import type { JsrPackageInfo } from '#shared/types/jsr'

/**
Expand All @@ -11,17 +14,25 @@ import type { JsrPackageInfo } from '#shared/types/jsr'
export default defineCachedEventHandler<Promise<JsrPackageInfo>>(
async event => {
const pkgPath = getRouterParam(event, 'pkg')
if (!pkgPath) {
throw createError({ statusCode: 400, message: 'Package name is required' })
}
assertValidPackageName(pkgPath)

return await fetchJsrPackageInfo(pkgPath)
try {
const packageName = v.parse(PackageNameSchema, pkgPath)

return await fetchJsrPackageInfo(packageName)
} catch (error: unknown) {
handleApiError(error, {
statusCode: 502,
message: ERROR_JSR_FETCH_FAILED,
})
}
},
{
maxAge: 60 * 60, // 1 hour
maxAge: CACHE_MAX_AGE_ONE_HOUR,
swr: true,
name: 'api-jsr-package',
getKey: event => getRouterParam(event, 'pkg') ?? '',
getKey: event => {
const pkg = getRouterParam(event, 'pkg') ?? ''
return `jsr:v1:${pkg.replace(/\/+$/, '').trim()}`
},
},
)
32 changes: 18 additions & 14 deletions server/api/registry/[...pkg].get.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
import * as v from 'valibot'
import { PackageNameSchema } from '#shared/schemas/package'
import { CACHE_MAX_AGE_ONE_HOUR, ERROR_NPM_FETCH_FAILED } from '#shared/utils/constants'

export default defineCachedEventHandler(
async event => {
const pkg = getRouterParam(event, 'pkg')
if (!pkg) {
throw createError({ statusCode: 400, message: 'Package name is required' })
}
try {
const pkg = getRouterParam(event, 'pkg')

assertValidPackageName(pkg)
const packageName = v.parse(PackageNameSchema, pkg)

try {
return await fetchNpmPackage(pkg)
} catch (error) {
if (error && typeof error === 'object' && 'statusCode' in error) {
throw error
}
throw createError({ statusCode: 502, message: 'Failed to fetch package from npm registry' })
return await fetchNpmPackage(packageName)
} catch (error: unknown) {
handleApiError(error, {
statusCode: 502,
message: ERROR_NPM_FETCH_FAILED,
})
}
},
{
maxAge: 60 * 60, // 1 hour
maxAge: CACHE_MAX_AGE_ONE_HOUR,
swr: true,
getKey: event => getRouterParam(event, 'pkg') ?? '',
getKey: event => {
const pkg = getRouterParam(event, 'pkg') ?? ''
return `packument:v1:${pkg.replace(/\/+$/, '').trim()}`
},
},
)
51 changes: 24 additions & 27 deletions server/api/registry/analysis/[...pkg].get.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,31 @@
import * as v from 'valibot'
import { PackageRouteParamsSchema } from '#shared/schemas/package'
import type { PackageAnalysis, ExtendedPackageJson } from '#shared/utils/package-analysis'
import {
analyzePackage,
getTypesPackageName,
hasBuiltInTypes,
} from '#shared/utils/package-analysis'

const NPM_REGISTRY = 'https://registry.npmjs.org'
import {
NPM_REGISTRY,
CACHE_MAX_AGE_ONE_DAY,
ERROR_PACKAGE_ANALYSIS_FAILED,
} from '#shared/utils/constants'

export default defineCachedEventHandler(
async event => {
const pkgParam = getRouterParam(event, 'pkg')
if (!pkgParam) {
throw createError({ statusCode: 400, message: 'Package name is required' })
}

// Parse package name and optional version from path
// e.g., "vue" or "vue/v/3.4.0" or "@nuxt/kit" or "@nuxt/kit/v/1.0.0"
const segments = pkgParam.split('/')
let packageName: string
let version: string | undefined
const pkgParamSegments = getRouterParam(event, 'pkg')?.split('/') ?? []

const vIndex = segments.indexOf('v')
if (vIndex !== -1 && vIndex < segments.length - 1) {
packageName = segments.slice(0, vIndex).join('/')
version = segments.slice(vIndex + 1).join('/')
} else {
packageName = segments.join('/')
}
const { rawPackageName, rawVersion } = parsePackageParams(pkgParamSegments)

try {
const { packageName, version } = v.parse(PackageRouteParamsSchema, {
packageName: rawPackageName,
version: rawVersion,
})

// Fetch package data
const encodedName = encodePackageName(packageName)
const versionSuffix = version ? `/${version}` : '/latest'
Expand All @@ -39,8 +36,8 @@ export default defineCachedEventHandler(
// Only check for @types package if the package doesn't ship its own types
let typesPackageExists = false
if (!hasBuiltInTypes(pkg)) {
const typesPackageName = getTypesPackageName(packageName)
typesPackageExists = await checkPackageExists(typesPackageName)
const typesPkgName = getTypesPackageName(packageName)
typesPackageExists = await checkPackageExists(typesPkgName)
}

const analysis = analyzePackage(pkg, { typesPackageExists })
Expand All @@ -50,20 +47,20 @@ export default defineCachedEventHandler(
version: pkg.version ?? version ?? 'latest',
...analysis,
} satisfies PackageAnalysisResponse
} catch (error) {
if (error && typeof error === 'object' && 'statusCode' in error) {
throw error
}
throw createError({
} catch (error: unknown) {
handleApiError(error, {
statusCode: 502,
message: 'Failed to analyze package',
message: ERROR_PACKAGE_ANALYSIS_FAILED,
})
}
},
{
maxAge: 60 * 60 * 24, // 24 hours - analysis rarely changes
maxAge: CACHE_MAX_AGE_ONE_DAY, // 24 hours - analysis rarely changes
swr: true,
getKey: event => getRouterParam(event, 'pkg') ?? '',
getKey: event => {
const pkg = getRouterParam(event, 'pkg') ?? ''
return `analysis:v1:${pkg.replace(/\/+$/, '').trim()}`
},
},
)

Expand Down
70 changes: 39 additions & 31 deletions server/api/registry/file/[...pkg].get.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import * as v from 'valibot'
import { PackageFileQuerySchema } from '#shared/schemas/package'
import {
CACHE_MAX_AGE_ONE_YEAR,
ERROR_PACKAGE_VERSION_AND_FILE_FAILED,
} from '#shared/utils/constants'

const CACHE_VERSION = 2

// Maximum file size to fetch and highlight (500KB)
Expand Down Expand Up @@ -50,7 +57,10 @@ async function fetchFileContent(
if (response.status === 404) {
throw createError({ statusCode: 404, message: 'File not found' })
}
throw createError({ statusCode: 502, message: 'Failed to fetch file from jsDelivr' })
throw createError({
statusCode: 502,
message: 'Failed to fetch file from jsDelivr',
})
}

// Check content-length header if available
Expand Down Expand Up @@ -84,38 +94,33 @@ async function fetchFileContent(
*/
export default defineCachedEventHandler(
async event => {
const segments = getRouterParam(event, 'pkg')?.split('/') ?? []
if (segments.length === 0) {
throw createError({
statusCode: 400,
message: 'Package name, version, and file path are required',
})
}

// Parse: [pkg, 'v', version, ...filePath] or [@scope, pkg, 'v', version, ...filePath]
const vIndex = segments.indexOf('v')
if (vIndex === -1 || vIndex >= segments.length - 2) {
throw createError({ statusCode: 400, message: 'Version and file path are required' })
}
const pkgParamSegments = getRouterParam(event, 'pkg')?.split('/') ?? []

const packageName = segments.slice(0, vIndex).join('/')
// Find where version ends (next segment after 'v') and file path begins
// Version could be like "1.2.3" or "1.2.3-beta.1"
const versionAndPath = segments.slice(vIndex + 1)
const { rawPackageName, rawVersion: fullPathAfterV } = parsePackageParams(pkgParamSegments)

// The version is the first segment after 'v', and everything else is the file path
const version = versionAndPath[0]
const filePath = versionAndPath.slice(1).join('/')
// Since version AND path route are required, we split the remainder
// fullPathAfterV => "1.2.3/dist/index.mjs"
const versionSegments = fullPathAfterV?.split('/') ?? []

if (!packageName || !version || !filePath) {
if (versionSegments.length < 2) {
throw createError({
statusCode: 400,
message: 'Package name, version, and file path are required',
message: ERROR_PACKAGE_VERSION_AND_FILE_FAILED,
})
}
assertValidPackageName(packageName)

// The version is the first segment after 'v', and everything else is the file path
const rawVersion = versionSegments[0]
const rawFilePath = versionSegments.slice(1).join('/')

try {
const { packageName, version, filePath } = v.parse(PackageFileQuerySchema, {
packageName: rawPackageName,
version: rawVersion,
filePath: rawFilePath,
})

const content = await fetchFileContent(packageName, version, filePath)
const language = getLanguageFromPath(filePath)

Expand Down Expand Up @@ -156,7 +161,10 @@ export default defineCachedEventHandler(
}
}

const html = await highlightCode(content, language, { dependencies, resolveRelative })
const html = await highlightCode(content, language, {
dependencies,
resolveRelative,
})

return {
package: packageName,
Expand All @@ -167,19 +175,19 @@ export default defineCachedEventHandler(
html,
lines: content.split('\n').length,
}
} catch (error) {
if (error && typeof error === 'object' && 'statusCode' in error) {
throw error
}
throw createError({ statusCode: 502, message: 'Failed to fetch file content' })
} catch (error: unknown) {
handleApiError(error, {
statusCode: 502,
message: 'Failed to fetch file content',
})
}
},
{
// File content for a specific version never changes - cache permanently
maxAge: 60 * 60 * 24 * 365, // 1 year
maxAge: CACHE_MAX_AGE_ONE_YEAR, // 1 year
getKey: event => {
const pkg = getRouterParam(event, 'pkg') ?? ''
return `file:v${CACHE_VERSION}:${pkg}`
return `file:v${CACHE_VERSION}:${pkg.replace(/\/+$/, '').trim()}`
},
},
)
Loading