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
9 changes: 9 additions & 0 deletions app/composables/usePageCacheControl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* Give this page's HTML a CDN cache header. Only applied on the server, and only when the page
* renders, so pages that end up on an error never leave a cacheable response behind.
*/
export function usePageCacheControl(cacheControl: string | undefined) {
if (import.meta.server && cacheControl) {
useResponseHeader('cache-control').value = cacheControl
}
}
5 changes: 5 additions & 0 deletions app/error.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ const props = defineProps<{
error: NuxtError
}>()

// a page can set a cdn cache header before it fails
if (import.meta.server) {
useResponseHeader('cache-control').value = 'no-store'
}

const status = computed(() => props.error.status || 500)
const statusText = computed(() => {
if (props.error.statusText) return props.error.statusText
Expand Down
3 changes: 3 additions & 0 deletions app/pages/compare.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ import { useRouteQuery } from '@vueuse/router'
import FacetBarChart from '~/components/Compare/FacetBarChart.vue'
import type { CommandPaletteContextCommandInput } from '~/types/command-palette'
import FacetScatterChart from '~/components/Compare/FacetScatterChart.vue'
import { CACHE_CONTROL_PAGE_HOUR } from '#shared/utils/constants'

definePageMeta({
name: 'compare',
preserveScrollOnQuery: true,
})

usePageCacheControl(CACHE_CONTROL_PAGE_HOUR)

const { locale } = useI18n()
const { copied, copy } = useClipboard({ copiedDuring: 2000 })

Expand Down
10 changes: 10 additions & 0 deletions app/pages/diff/[[org]]/[packageName]/v/[versionRange].vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<script setup lang="ts">
import type { RouteLocationRaw } from 'vue-router'
import { CACHE_CONTROL_PAGE_DAY, CACHE_CONTROL_PAGE_TAG } from '#shared/utils/constants'
import { isExactVersion } from '#shared/utils/npm'

definePageMeta({
name: 'diff',
Expand All @@ -26,6 +28,14 @@ const versionRange = computed(() => {
const fromVersion = computed(() => versionRange.value?.from ?? '')
const toVersion = computed(() => versionRange.value?.to ?? '')

if (fromVersion.value && toVersion.value) {
usePageCacheControl(
isExactVersion(fromVersion.value) && isExactVersion(toVersion.value)
? CACHE_CONTROL_PAGE_DAY
: CACHE_CONTROL_PAGE_TAG,
)
}

const router = useRouter()
const { data: pkg } = usePackage(packageName)
const { versions: commandPaletteVersions, ensureLoaded: ensureCommandPaletteVersionsLoaded } =
Expand Down
3 changes: 3 additions & 0 deletions app/pages/org/[org].vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
serializeVisibleColumns,
} from '#shared/types/preferences'
import { normalizeSearchParam } from '#shared/utils/url'
import { CACHE_CONTROL_PAGE_HOUR } from '#shared/utils/constants'
import { debounce } from 'perfect-debounce'

definePageMeta({
Expand All @@ -28,6 +29,8 @@

const orgName = computed(() => route.params.org.toLowerCase())

usePageCacheControl(CACHE_CONTROL_PAGE_HOUR)

const { isConnected } = useConnector()

// Fetch all packages in this org using the org packages API (lazy to not block navigation)
Expand Down Expand Up @@ -104,7 +107,7 @@
resetColumns()
return
}
columnOverride.value = DEFAULT_COLUMNS.map(col => ({ ...col }))

Check warning on line 110 in app/pages/org/[org].vue

View workflow job for this annotation

GitHub Actions / 🤖 Autofix code

oxc(no-map-spread)

app/pages/org/[org].vue:110:42: Spreading to modify object properties in `map` calls is inefficient

Check warning on line 110 in app/pages/org/[org].vue

View workflow job for this annotation

GitHub Actions / 🔠 Lint project

oxc(no-map-spread)

app/pages/org/[org].vue:110:42: Spreading to modify object properties in `map` calls is inefficient
}

// Structured filters and sorting
Expand Down Expand Up @@ -200,7 +203,7 @@
// serialize so visibility toggles (same array ref) still trigger
() => serializeVisibleColumns(viewColumns.value),
] as const,
([text, keywords, sort, scope, downloads, security, updated]) => {

Check warning on line 206 in app/pages/org/[org].vue

View workflow job for this annotation

GitHub Actions / 🤖 Autofix code

eslint(no-shadow)

app/pages/org/[org].vue:206:45: 'security' is already declared in the upper scope.

Check warning on line 206 in app/pages/org/[org].vue

View workflow job for this annotation

GitHub Actions / 🔠 Lint project

eslint(no-shadow)

app/pages/org/[org].vue:206:45: 'security' is already declared in the upper scope.
const filter = [text, ...keywords.map(keyword => `keyword:${keyword}`)]
.filter(Boolean)
.join(' ')
Expand Down
7 changes: 7 additions & 0 deletions app/pages/package-stats/[[org]]/[packageName].vue
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
<script setup lang="ts">
import { CACHE_CONTROL_PAGE_HOUR, CACHE_CONTROL_PAGE_TAG } from '#shared/utils/constants'
import { isExactVersion } from '#shared/utils/npm'

definePageMeta({
name: 'stats',
path: '/package-stats/:org?/:packageName/v/:version',
Expand All @@ -14,6 +17,10 @@ const packageName = computed(() =>
)
const version = computed(() => route.params.version)

usePageCacheControl(
isExactVersion(version.value) ? CACHE_CONTROL_PAGE_HOUR : CACHE_CONTROL_PAGE_TAG,
)

const { data: pkg } = usePackage(packageName, version)
const { versions: commandPaletteVersions, ensureLoaded: ensureCommandPaletteVersionsLoaded } =
useCommandPalettePackageVersions(packageName)
Expand Down
6 changes: 6 additions & 0 deletions app/pages/package-timeline/[[org]]/[packageName].vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import type {
} from '~~/server/api/registry/timeline/[...pkg].get'
import type { TimelineSizeResponse } from '~~/server/api/registry/timeline/sizes/[...pkg].get'
import type { TimelineSizeCacheValue } from '~/utils/charts'
import { CACHE_CONTROL_PAGE_HOUR, CACHE_CONTROL_PAGE_TAG } from '#shared/utils/constants'
import { isExactVersion } from '#shared/utils/npm'

definePageMeta({
name: 'timeline',
Expand All @@ -24,6 +26,10 @@ const packageName = computed(() =>
)
const version = computed(() => route.params.version)

usePageCacheControl(
isExactVersion(version.value) ? CACHE_CONTROL_PAGE_HOUR : CACHE_CONTROL_PAGE_TAG,
)

const { data: pkg } = usePackage(packageName, version)
const { versions: commandPaletteVersions, ensureLoaded: ensureCommandPaletteVersionsLoaded } =
useCommandPalettePackageVersions(packageName)
Expand Down
9 changes: 8 additions & 1 deletion app/pages/package/[[org]]/[name].vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { assertValidPackageName } from '#shared/utils/npm'
import { CACHE_CONTROL_PAGE_DAY, CACHE_CONTROL_PAGE_TAG } from '#shared/utils/constants'
import { assertValidPackageName, isExactVersion } from '#shared/utils/npm'
import { getDependencyCount } from '~/utils/npm/dependency-count'

const readmeHeader = useTemplateRef('readmeHeader')
Expand Down Expand Up @@ -30,6 +31,12 @@ onMounted(() => {

const { packageName, requestedVersion } = usePackageRoute()

if (requestedVersion.value) {
usePageCacheControl(
isExactVersion(requestedVersion.value) ? CACHE_CONTROL_PAGE_DAY : CACHE_CONTROL_PAGE_TAG,
)
}

const { data: resolvedVersion, status: resolvedStatus } = await useResolvedVersion(
packageName,
requestedVersion,
Expand Down
9 changes: 9 additions & 0 deletions modules/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { provider } from 'std-env'
// Storage key for fetch cache - must match shared/utils/fetch-cache-config.ts
const FETCH_CACHE_STORAGE_BASE = 'fetch-cache'

const MB = 1024 * 1024

export default defineNuxtModule({
meta: {
name: 'vercel-cache',
Expand Down Expand Up @@ -37,6 +39,13 @@ export default defineNuxtModule({
...nitroConfig.storage[FETCH_CACHE_STORAGE_BASE],
driver: 'vercel-runtime-cache',
}
} else {
// function filesystems are read-only
nitroConfig.storage[FETCH_CACHE_STORAGE_BASE] = {
driver: 'lru-cache',
max: 5_000,
maxSize: 32 * MB,
}
}

const env = process.env.VERCEL_ENV
Expand Down
4 changes: 0 additions & 4 deletions modules/isr-fallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,8 @@ export default defineNuxtModule({
for (const path of [
'package',
'package/[name]',
'package/[name]/v',
'package/[name]/v/[version]',
'package/[org]',
'package/[org]/[name]',
'package/[org]/[name]/v',
'package/[org]/[name]/v/[version]',
'',
]) {
const outputPath = resolve(nitro.options.output.serverDir, '..', path, htmlFallback)
Expand Down
57 changes: 57 additions & 0 deletions modules/runtime/server/cache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import process from 'node:process'
import type { CachedFetchResult } from '#shared/utils/fetch-cache-config'
import { isExactVersion } from '#shared/utils/npm'
import { parsePackageSpec } from '#shared/utils/parse-package-param'
import { createFetch } from 'ofetch'

Expand Down Expand Up @@ -32,6 +33,7 @@ const FIXTURE_PATHS = {
githubContributors: 'github:contributors.json',
githubContributorsStats: 'github:contributors-stats.json',
jsdelivr: 'jsdelivr',
jsdelivrCdn: 'jsdelivr-cdn',
unghReleases: 'ungh:releases',
} as const

Expand Down Expand Up @@ -650,6 +652,56 @@ async function handleJsdelivrDataApi(
}
}

/**

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Side note: I wish we could move all this test-only code out of this file. It always makes me do a double-take when reviewing PRs!

* File contents are served from `test/fixtures/jsdelivr-cdn/<name>@<version>/<path>`.
* A dist-tag or partial version resolves to the version of the jsDelivr data fixture,
* and anything without a fixture is a 404 so tests can cover the missing-file path.
*/
async function handleJsdelivrCdnFile(
url: string,
storage: ReturnType<typeof useStorage>,
): Promise<Response | null> {
const urlObj = URL.parse(url)
if (urlObj?.host !== 'cdn.jsdelivr.net') return null

const specMatch = decodeURIComponent(urlObj.pathname).match(
/^\/npm\/((?:@[^/]+\/)?[^/@]+)@([^/]+)\/(.+)$/,
)
if (!specMatch?.[1] || !specMatch[2] || !specMatch[3]) {
return new Response(null, { status: 404 })
}

const [, name, requestedVersion, filePath] = specMatch

const read = (version: string) =>
storage
.getItemRaw<string>(
`${FIXTURE_PATHS.jsdelivrCdn}:${name}@${version}/${filePath}`.replace(/\//g, ':'),
)
.catch(() => null)

let content = await read(requestedVersion)
if (content === null && !isExactVersion(requestedVersion)) {
const published = await storage
.getItem<{ version?: string }>(getFixturePath('jsdelivr', name))
.catch(() => null)
if (published?.version) {
content = await read(published.version)
}
}

if (content === null) {
if (VERBOSE) process.stdout.write(`[test-fixtures] jsDelivr CDN (missing): ${url}\n`)
return new Response(null, { status: 404 })
}

if (VERBOSE) process.stdout.write(`[test-fixtures] jsDelivr CDN: ${url}\n`)
return new Response(content, {
status: 200,
headers: { 'content-type': filePath.endsWith('.json') ? 'application/json' : 'text/plain' },
})
}

/**
* Shared fixture-backed fetch implementation.
* This is used by both cachedFetch and the global $fetch override.
Expand Down Expand Up @@ -955,6 +1007,11 @@ export default defineNitroPlugin(nitroApp => {
return await handleEsmShFetch(urlStr, init, storage)
}

const jsdelivrCdnFile = await handleJsdelivrCdnFile(urlStr, storage)
if (jsdelivrCdnFile) {
return jsdelivrCdnFile
}

try {
const res = await fetchFromFixtures(urlStr, storage)
if (res.data) {
Expand Down
Loading
Loading