+
{{ $t('code.loading_tree') }}
diff --git a/app/pages/package-docs/[...path].vue b/app/pages/package-docs/[...path].vue
index 956c33d202..ec4575b069 100644
--- a/app/pages/package-docs/[...path].vue
+++ b/app/pages/package-docs/[...path].vue
@@ -1,6 +1,5 @@
',
+ )
+ writeFileSync(
+ resolve(dir, 'config.json'),
+ JSON.stringify({
+ routes: [
+ { src: '^/code(?:/(.*))?$', headers: { 'X-Robots-Tag': 'noindex' }, continue: true },
+ { handle: 'filesystem' },
+ isrRoute,
+ { src: '/(.*)', dest: '/__fallback' },
+ ],
+ }),
+ )
+ })
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true })
+ })
+
+ it('rewrites to the shell straight after the filesystem handler', () => {
+ addSpaShellRoutes(dir, '/_spa.html', ['/code/**', '/a/:name/v/**'])
+
+ const { routes } = readConfig()
+ const unfurl = [{ type: 'header', key: 'user-agent', value: UNFURL_USER_AGENT_PATTERN }]
+ expect(routes.slice(1, 6)).toEqual([
+ { handle: 'filesystem' },
+ { src: '^/code(?:/.*)?$', dest: '/__fallback', has: unfurl },
+ { src: '^/code(?:/.*)?$', dest: '/_spa.html' },
+ { src: '^/a/[^/]+/v(?:/.*)?$', dest: '/__fallback', has: unfurl },
+ { src: '^/a/[^/]+/v(?:/.*)?$', dest: '/_spa.html' },
+ ])
+ expect(routes[6]).toEqual(isrRoute)
+ })
+
+ it('sends link preview bots to the server renderer and everyone else to the shell', () => {
+ addSpaShellRoutes(dir, '/_spa.html', ['/code/**'])
+
+ const { routes } = readConfig() as {
+ routes: Array<{ dest?: string; has?: Array<{ value: string }> }>
+ }
+ const select = (userAgent: string) =>
+ routes
+ .slice(2, 4)
+ .find(
+ route => !route.has || route.has.every(c => new RegExp(`^${c.value}$`).test(userAgent)),
+ )?.dest
+
+ const unfurlers = [
+ 'Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)',
+ 'Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)',
+ 'Twitterbot/1.0',
+ 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)',
+ 'LinkedInBot/1.0 (compatible; Mozilla/5.0; Apache-HttpClient +http://www.linkedin.com)',
+ 'TelegramBot (like TwitterBot)',
+ 'WhatsApp/2.23.20.0 A',
+ 'http.rb/5.1.1 (Mastodon/4.2.0; +https://mastodon.social/)',
+ 'Mozilla/5.0 (compatible; Bluesky Cardyb/1.1; +mailto:support@bsky.app)',
+ 'Mozilla/5.0 (compatible; redditbot/1.0; +http://www.reddit.com/feedback)',
+ 'Mozilla/5.0 (Windows NT 6.1; WOW64) SkypeUriPreview Preview/0.5 skype-url-preview@microsoft.com',
+ 'Iframely/1.3.1 (+https://iframely.com/docs/about)',
+ 'Mozilla/5.0 (compatible; Embedly/0.2; +http://support.embed.ly/)',
+ ]
+ const others = [
+ 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
+ 'Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)',
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
+ ]
+ const destinations = (userAgents: string[]) =>
+ Object.fromEntries(userAgents.map(userAgent => [userAgent, select(userAgent)]))
+
+ expect(destinations(unfurlers)).toEqual(
+ Object.fromEntries(unfurlers.map(userAgent => [userAgent, '/__fallback'])),
+ )
+ expect(destinations(others)).toEqual(
+ Object.fromEntries(others.map(userAgent => [userAgent, '/_spa.html'])),
+ )
+ })
+
+ it('throws when the shell was server-rendered', () => {
+ writeFileSync(resolve(dir, 'static/_spa.html'), '')
+ expect(() => addSpaShellRoutes(dir, '/_spa.html', ['/code/**'])).toThrow(
+ /not a client-only shell/,
+ )
+ })
+
+ it('throws when the server renderer route is missing', () => {
+ writeFileSync(
+ resolve(dir, 'config.json'),
+ JSON.stringify({ routes: [{ handle: 'filesystem' }] }),
+ )
+ expect(() => addSpaShellRoutes(dir, '/_spa.html', ['/code/**'])).toThrow(
+ /could not find the route to \/__fallback/,
+ )
+ })
+})
diff --git a/test/unit/server/api/auth/atproto.spec.ts b/test/unit/server/api/auth/atproto.spec.ts
new file mode 100644
index 0000000000..496a2d4b36
--- /dev/null
+++ b/test/unit/server/api/auth/atproto.spec.ts
@@ -0,0 +1,153 @@
+import type * as AtprotoLex from '@atproto/lex'
+import type { H3Event } from 'h3'
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+
+const getCookieMock = vi.hoisted(() => vi.fn())
+const getQueryMock = vi.hoisted(() => vi.fn())
+const setCookieMock = vi.hoisted(() => vi.fn())
+const deleteCookieMock = vi.hoisted(() => vi.fn())
+const sendRedirectMock = vi.hoisted(() => vi.fn((_event: unknown, location: string) => location))
+const useServerSessionMock = vi.hoisted(() => vi.fn())
+const setSessionHintCookieMock = vi.hoisted(() => vi.fn())
+const xrpcSafeMock = vi.hoisted(() => vi.fn())
+
+vi.mock('h3', () => ({
+ createError: vi.fn((options: { status?: number; statusCode?: number; message?: string }) =>
+ Object.assign(new Error(options.message ?? 'error'), options),
+ ),
+ getCookie: getCookieMock,
+ getQuery: getQueryMock,
+ setCookie: setCookieMock,
+ deleteCookie: deleteCookieMock,
+ sendRedirect: sendRedirectMock,
+}))
+
+vi.mock('#oauth/config', () => ({
+ clientUri: 'https://npmx.dev',
+}))
+
+vi.mock('#server/utils/server-session', () => ({
+ useServerSession: useServerSessionMock,
+ setSessionHintCookie: setSessionHintCookieMock,
+}))
+
+vi.mock('#server/utils/error-handler', () => ({
+ handleApiError: vi.fn((error: unknown) => {
+ throw error
+ }),
+}))
+
+vi.mock('#server/utils/atproto/oauth', () => ({
+ scope: 'atproto',
+}))
+
+vi.mock('@atproto/lex', async importOriginal => {
+ const actual = await importOriginal
()
+ return {
+ ...actual,
+ Client: class {
+ did = 'did:plc:alice123'
+ xrpcSafe = xrpcSafeMock
+ get = vi.fn(async () => ({ value: {} }))
+ createRecord = vi.fn(async () => ({}))
+ },
+ }
+})
+
+vi.mock('@atproto/oauth-client-node', () => ({
+ OAuthCallbackError: class extends Error {
+ state?: string
+ },
+}))
+
+vi.stubGlobal('defineEventHandler', (fn: Function) => fn)
+vi.stubGlobal('useRuntimeConfig', () => ({
+ sessionPassword: 'test-session-password-32-chars-long',
+}))
+
+const handler = (await import('#server/api/auth/atproto.get')).default
+
+afterAll(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('atproto OAuth handler', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('does not create a server session or set the hint cookie when initiating login', async () => {
+ getQueryMock.mockReturnValue({ handle: 'alice.bsky.social', returnTo: '/package/vue' })
+ const event = {
+ path: '/api/auth/atproto?handle=alice.bsky.social',
+ context: {
+ oauthClient: {
+ authorize: vi.fn(async () => new URL('https://bsky.social/oauth/authorize')),
+ },
+ },
+ } as unknown as H3Event
+
+ await expect(handler(event)).resolves.toBe('https://bsky.social/oauth/authorize')
+ expect(useServerSessionMock).not.toHaveBeenCalled()
+ expect(setSessionHintCookieMock).not.toHaveBeenCalled()
+ })
+
+ it('sets the hint cookie after updating the server session on callback', async () => {
+ const update = vi.fn()
+ useServerSessionMock.mockResolvedValue({ update })
+ getQueryMock.mockReturnValue({ code: 'abc', state: 'state' })
+ getCookieMock.mockReturnValue('1')
+ xrpcSafeMock
+ .mockResolvedValueOnce({
+ success: true,
+ body: {
+ did: 'did:plc:alice123',
+ handle: 'alice.bsky.social',
+ pds: 'https://bsky.social',
+ },
+ })
+ .mockResolvedValueOnce({
+ success: true,
+ body: { value: { displayName: 'Alice' } },
+ })
+
+ const event = {
+ path: '/api/auth/atproto?code=abc',
+ context: {
+ oauthClient: {
+ callback: vi.fn(async () => ({
+ state: JSON.stringify({ data: { redirectPath: '/package/vue' }, id: 'req123' }),
+ session: { did: 'did:plc:alice123', signOut: vi.fn() },
+ })),
+ },
+ },
+ } as unknown as H3Event
+
+ await expect(handler(event)).resolves.toBe('/package/vue')
+ expect(update).toHaveBeenCalledTimes(1)
+ expect(setSessionHintCookieMock).toHaveBeenCalledWith(event)
+ })
+
+ it('does not set the hint cookie when callback fails', async () => {
+ const signOut = vi.fn()
+ getQueryMock.mockReturnValue({ code: 'abc', state: 'state' })
+ getCookieMock.mockReturnValue(undefined)
+
+ const event = {
+ path: '/api/auth/atproto?code=abc',
+ context: {
+ oauthClient: {
+ callback: vi.fn(async () => ({
+ state: JSON.stringify({ data: { redirectPath: '/' }, id: 'missing' }),
+ session: { did: 'did:plc:alice123', signOut },
+ })),
+ },
+ },
+ } as unknown as H3Event
+
+ await expect(handler(event)).rejects.toThrow(/Missing authentication state/)
+ expect(signOut).toHaveBeenCalledTimes(1)
+ expect(useServerSessionMock).not.toHaveBeenCalled()
+ expect(setSessionHintCookieMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/test/unit/server/api/auth/session.spec.ts b/test/unit/server/api/auth/session.spec.ts
new file mode 100644
index 0000000000..3068b44c60
--- /dev/null
+++ b/test/unit/server/api/auth/session.spec.ts
@@ -0,0 +1,212 @@
+import type { H3Event } from 'h3'
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { SESSION_HINT_COOKIE, SESSION_HINT_VALUE } from '#shared/utils/constants'
+
+const getCookieMock = vi.hoisted(() => vi.fn())
+const getHeaderMock = vi.hoisted(() => vi.fn())
+const setCookieMock = vi.hoisted(() => vi.fn())
+const deleteCookieMock = vi.hoisted(() => vi.fn())
+const useSessionMock = vi.hoisted(() => vi.fn())
+
+vi.mock('h3', () => ({
+ getCookie: getCookieMock,
+ getHeader: getHeaderMock,
+ setCookie: setCookieMock,
+ deleteCookie: deleteCookieMock,
+ useSession: useSessionMock,
+}))
+
+vi.mock('#oauth/config', () => ({
+ clientUri: 'https://npmx.dev',
+}))
+
+vi.mock('#server/utils/atproto/lock', () => ({
+ getOAuthLock: vi.fn(),
+}))
+
+vi.mock('#server/utils/atproto/storage', () => ({
+ useOAuthStorage: vi.fn(() => ({ stateStore: {}, sessionStore: {} })),
+}))
+
+vi.stubGlobal('defineEventHandler', (fn: Function) => fn)
+vi.stubGlobal('useRuntimeConfig', () => ({
+ sessionPassword: 'test-session-password-32-chars-long',
+}))
+vi.stubGlobal(
+ 'createError',
+ (options: { status?: number; statusCode?: number; message?: string }) =>
+ Object.assign(new Error(options.message ?? 'error'), options),
+)
+
+const sessionGetHandler = (await import('#server/api/auth/session.get')).default
+const sessionDeleteHandler = (await import('#server/api/auth/session.delete')).default
+
+const validPublicUser = {
+ did: 'did:plc:alice123',
+ handle: 'alice.bsky.social',
+ pds: 'https://bsky.social',
+}
+
+function createEvent(cookies: Record = {}, oauthRestore?: () => Promise) {
+ getCookieMock.mockImplementation((_event: unknown, name: string) => cookies[name])
+ getHeaderMock.mockReturnValue(undefined)
+ return {
+ context: {
+ oauthClient: {
+ restore: vi.fn(
+ oauthRestore ?? (async () => ({ did: validPublicUser.did, signOut: vi.fn() })),
+ ),
+ },
+ },
+ } as unknown as H3Event
+}
+
+afterAll(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('auth session endpoints', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('returns null without decrypting or setting cookies for anonymous requests', async () => {
+ const event = createEvent()
+
+ await expect(sessionGetHandler(event)).resolves.toBeNull()
+ expect(useSessionMock).not.toHaveBeenCalled()
+ expect(setCookieMock).not.toHaveBeenCalled()
+ expect(deleteCookieMock).not.toHaveBeenCalled()
+ })
+
+ it('clears a forged hint cookie without creating a server session', async () => {
+ const event = createEvent({ [SESSION_HINT_COOKIE]: SESSION_HINT_VALUE })
+
+ await expect(sessionGetHandler(event)).resolves.toBeNull()
+ expect(useSessionMock).not.toHaveBeenCalled()
+ expect(deleteCookieMock).toHaveBeenCalledWith(
+ event,
+ SESSION_HINT_COOKIE,
+ expect.objectContaining({ httpOnly: false, path: '/', sameSite: 'lax' }),
+ )
+ })
+
+ it('sets the hint cookie when migrating a logged-in session without a hint', async () => {
+ const event = createEvent({ h3: 'sealed-session' })
+ useSessionMock.mockResolvedValue({
+ data: { public: validPublicUser },
+ update: vi.fn(),
+ clear: vi.fn(),
+ })
+
+ await expect(sessionGetHandler(event)).resolves.toEqual(validPublicUser)
+ expect(setCookieMock).toHaveBeenCalledWith(
+ event,
+ SESSION_HINT_COOKIE,
+ SESSION_HINT_VALUE,
+ expect.objectContaining({ httpOnly: false, path: '/', sameSite: 'lax' }),
+ )
+ })
+
+ it('does not rewrite the hint cookie when already present on a valid session', async () => {
+ const event = createEvent({
+ h3: 'sealed-session',
+ [SESSION_HINT_COOKIE]: SESSION_HINT_VALUE,
+ })
+ useSessionMock.mockResolvedValue({
+ data: { public: validPublicUser },
+ update: vi.fn(),
+ clear: vi.fn(),
+ })
+
+ await expect(sessionGetHandler(event)).resolves.toEqual(validPublicUser)
+ expect(setCookieMock).not.toHaveBeenCalled()
+ })
+
+ it('clears both server session and hint cookie when server session has no public user', async () => {
+ const clear = vi.fn()
+ const event = createEvent({
+ h3: 'empty-sealed-session',
+ [SESSION_HINT_COOKIE]: SESSION_HINT_VALUE,
+ })
+ useSessionMock.mockResolvedValue({
+ data: {},
+ update: vi.fn(),
+ clear,
+ })
+
+ await expect(sessionGetHandler(event)).resolves.toBeNull()
+ expect(clear).toHaveBeenCalledTimes(1)
+ expect(deleteCookieMock).toHaveBeenCalledWith(
+ event,
+ SESSION_HINT_COOKIE,
+ expect.objectContaining({ httpOnly: false, path: '/', sameSite: 'lax' }),
+ )
+ })
+
+ it('clears both server session and hint cookie and throws 401 when oauth restore fails', async () => {
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const clear = vi.fn()
+ const event = createEvent(
+ {
+ h3: 'stale-sealed-session',
+ [SESSION_HINT_COOKIE]: SESSION_HINT_VALUE,
+ },
+ async () => {
+ throw new Error('session expired')
+ },
+ )
+ useSessionMock.mockResolvedValue({
+ data: { public: validPublicUser },
+ update: vi.fn(),
+ clear,
+ })
+
+ await expect(sessionGetHandler(event)).rejects.toMatchObject({ status: 401 })
+ expect(clear).toHaveBeenCalledTimes(1)
+ expect(deleteCookieMock).toHaveBeenCalledWith(
+ event,
+ SESSION_HINT_COOKIE,
+ expect.objectContaining({ httpOnly: false, path: '/', sameSite: 'lax' }),
+ )
+ consoleErrorSpy.mockRestore()
+ })
+
+ it('signs out oauth and clears both cookies on DELETE /api/auth/session', async () => {
+ const signOut = vi.fn()
+ const clear = vi.fn()
+ const event = createEvent(
+ {
+ h3: 'sealed-session',
+ [SESSION_HINT_COOKIE]: SESSION_HINT_VALUE,
+ },
+ async () => ({ did: validPublicUser.did, signOut }),
+ )
+ useSessionMock.mockResolvedValue({
+ data: { public: validPublicUser },
+ update: vi.fn(),
+ clear,
+ })
+
+ await expect(sessionDeleteHandler(event)).resolves.toBe('Session cleared')
+ expect(signOut).toHaveBeenCalledTimes(1)
+ expect(clear).toHaveBeenCalledTimes(1)
+ expect(deleteCookieMock).toHaveBeenCalledWith(
+ event,
+ SESSION_HINT_COOKIE,
+ expect.objectContaining({ httpOnly: false, path: '/', sameSite: 'lax' }),
+ )
+ })
+
+ it('clears the hint cookie without decrypting when DELETE is called without h3 cookie', async () => {
+ const event = createEvent({ [SESSION_HINT_COOKIE]: SESSION_HINT_VALUE })
+
+ await expect(sessionDeleteHandler(event)).resolves.toBe('Session cleared')
+ expect(useSessionMock).not.toHaveBeenCalled()
+ expect(deleteCookieMock).toHaveBeenCalledWith(
+ event,
+ SESSION_HINT_COOKIE,
+ expect.objectContaining({ httpOnly: false, path: '/', sameSite: 'lax' }),
+ )
+ })
+})
diff --git a/test/unit/server/api/social/likes.spec.ts b/test/unit/server/api/social/likes.spec.ts
new file mode 100644
index 0000000000..878aeec4d6
--- /dev/null
+++ b/test/unit/server/api/social/likes.spec.ts
@@ -0,0 +1,202 @@
+import type { H3Event } from 'h3'
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { parsePackageParams } from '#server/utils/parse-package-params'
+
+const setResponseHeaderMock = vi.hoisted(() => vi.fn())
+const getCookieMock = vi.hoisted(() => vi.fn())
+const getHeaderMock = vi.hoisted(() => vi.fn())
+const setCookieMock = vi.hoisted(() => vi.fn())
+const deleteCookieMock = vi.hoisted(() => vi.fn())
+const useSessionMock = vi.hoisted(() => vi.fn())
+
+const getTotalLikesMock = vi.hoisted(() => vi.fn())
+const getLikesMock = vi.hoisted(() => vi.fn())
+const getTopLikedRankMock = vi.hoisted(() => vi.fn())
+
+let routerParam: string | undefined
+
+vi.mock('h3', () => ({
+ setResponseHeader: setResponseHeaderMock,
+ getCookie: getCookieMock,
+ getHeader: getHeaderMock,
+ setCookie: setCookieMock,
+ deleteCookie: deleteCookieMock,
+ useSession: useSessionMock,
+}))
+
+vi.mock('#oauth/config', () => ({
+ clientUri: 'https://npmx.dev',
+}))
+
+vi.mock('#server/utils/atproto/lock', () => ({
+ getOAuthLock: vi.fn(),
+}))
+
+vi.mock('#server/utils/atproto/storage', () => ({
+ useOAuthStorage: vi.fn(() => ({ stateStore: {}, sessionStore: {} })),
+}))
+
+vi.mock('#server/utils/likes-leaderboard', () => ({
+ getTopLikedRank: getTopLikedRankMock,
+}))
+
+vi.stubGlobal('defineEventHandler', (fn: Function) => fn)
+vi.stubGlobal('getRouterParam', () => routerParam)
+vi.stubGlobal('parsePackageParams', parsePackageParams)
+vi.stubGlobal('useRuntimeConfig', () => ({
+ sessionPassword: 'test-session-password-32-chars-long',
+}))
+vi.stubGlobal(
+ 'createError',
+ (options: { status?: number; statusCode?: number; message?: string }) =>
+ Object.assign(new Error(options.message ?? 'error'), options),
+)
+vi.stubGlobal(
+ 'handleApiError',
+ (error: unknown, fallback: { statusCode: number; message: string }) => {
+ if (error && typeof error === 'object' && ('status' in error || 'statusCode' in error)) {
+ throw error
+ }
+ throw Object.assign(new Error(fallback.message), fallback)
+ },
+)
+vi.stubGlobal(
+ 'PackageLikesUtils',
+ class {
+ getTotalLikes = getTotalLikesMock
+ getLikes = getLikesMock
+ },
+)
+
+const { eventHandlerWithOAuthSession } = await import('#server/utils/atproto/oauth')
+vi.stubGlobal('eventHandlerWithOAuthSession', eventHandlerWithOAuthSession)
+
+const publicLikesHandler = (await import('#server/api/social/likes/[...pkg].get')).default
+const likeStatusHandler = (await import('#server/api/social/like-status/[...pkg].get')).default
+
+function createEvent(cookies: Record = {}, did?: string) {
+ getCookieMock.mockImplementation((_event: unknown, name: string) => cookies[name])
+ getHeaderMock.mockReturnValue(undefined)
+ return {
+ context: {
+ oauthClient: {
+ restore: vi.fn(async () => (did ? { did } : undefined)),
+ },
+ },
+ } as unknown as H3Event
+}
+
+afterAll(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('GET /api/social/likes/[...pkg]', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ routerParam = undefined
+ getTotalLikesMock.mockResolvedValue(42)
+ getTopLikedRankMock.mockResolvedValue(3)
+ })
+
+ it('returns only public fields and sets CDN cache headers without reading cookies', async () => {
+ routerParam = 'vue'
+ const event = createEvent({ h3: 'sealed-session' })
+
+ const result = await publicLikesHandler(event)
+
+ expect(result).toEqual({
+ totalLikes: 42,
+ topLikedRank: 3,
+ })
+ expect('userHasLiked' in result).toBe(false)
+ expect(getTotalLikesMock).toHaveBeenCalledWith('vue')
+ expect(getLikesMock).not.toHaveBeenCalled()
+ expect(getCookieMock).not.toHaveBeenCalled()
+ expect(useSessionMock).not.toHaveBeenCalled()
+ expect(setCookieMock).not.toHaveBeenCalled()
+ expect(setResponseHeaderMock).toHaveBeenCalledTimes(1)
+ expect(setResponseHeaderMock).toHaveBeenCalledWith(
+ event,
+ 'Cache-Control',
+ 'public, max-age=0, s-maxage=60, stale-while-revalidate=300',
+ )
+ })
+
+ it('handles scoped package names', async () => {
+ routerParam = '@nuxt/ui'
+ const event = createEvent()
+
+ const result = await publicLikesHandler(event)
+
+ expect(getTotalLikesMock).toHaveBeenCalledWith('@nuxt/ui')
+ expect(result).toEqual({ totalLikes: 42, topLikedRank: 3 })
+ })
+
+ it('throws 400 and does not set cache headers when package name is missing', async () => {
+ routerParam = undefined
+ const event = createEvent()
+
+ await expect(publicLikesHandler(event)).rejects.toMatchObject({ status: 400 })
+ expect(setResponseHeaderMock).not.toHaveBeenCalled()
+ })
+
+ it('does not set cache headers when upstream fails', async () => {
+ routerParam = 'vue'
+ getTotalLikesMock.mockRejectedValueOnce(new Error('constellation down'))
+ const event = createEvent()
+
+ await expect(publicLikesHandler(event)).rejects.toMatchObject({ statusCode: 502 })
+ expect(setResponseHeaderMock).not.toHaveBeenCalled()
+ })
+})
+
+describe('GET /api/social/like-status/[...pkg]', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ routerParam = undefined
+ getLikesMock.mockResolvedValue({
+ totalLikes: 43,
+ userHasLiked: true,
+ topLikedRank: null,
+ })
+ })
+
+ it('sets private no-store and returns userHasLiked false without session', async () => {
+ routerParam = 'vue'
+ const event = createEvent()
+
+ const result = await likeStatusHandler(event)
+
+ expect(result).toEqual({ userHasLiked: false })
+ expect(getLikesMock).not.toHaveBeenCalled()
+ expect(useSessionMock).not.toHaveBeenCalled()
+ expect(setResponseHeaderMock).toHaveBeenCalledWith(event, 'Cache-Control', 'private, no-store')
+ })
+
+ it('returns userHasLiked and fresh totalLikes for an authenticated user', async () => {
+ routerParam = '@nuxt/ui'
+ const did = 'did:plc:alice123'
+ const event = createEvent({ h3: 'sealed-session' }, did)
+ useSessionMock.mockResolvedValue({
+ data: { public: { did, handle: 'alice.bsky.social', pds: 'https://bsky.social' } },
+ clear: vi.fn(),
+ })
+
+ const result = await likeStatusHandler(event)
+
+ expect(getLikesMock).toHaveBeenCalledWith('@nuxt/ui', did)
+ expect(result).toEqual({
+ userHasLiked: true,
+ totalLikes: 43,
+ })
+ expect(setResponseHeaderMock).toHaveBeenCalledWith(event, 'Cache-Control', 'private, no-store')
+ })
+
+ it('throws 400 when package name is missing', async () => {
+ routerParam = undefined
+ const event = createEvent()
+
+ await expect(likeStatusHandler(event)).rejects.toMatchObject({ status: 400 })
+ expect(setResponseHeaderMock).toHaveBeenCalledWith(event, 'Cache-Control', 'private, no-store')
+ })
+})
diff --git a/test/unit/server/utils/dependency-analysis.spec.ts b/test/unit/server/utils/dependency-analysis.spec.ts
index ca653b88a6..caaf50cb5f 100644
--- a/test/unit/server/utils/dependency-analysis.spec.ts
+++ b/test/unit/server/utils/dependency-analysis.spec.ts
@@ -63,6 +63,97 @@ function mockNuxt(vulns: Array & { id: string }>) {
)
}
+interface OsvBatchQuery {
+ package: { name: string; ecosystem: string }
+ version: string
+ page_token?: string
+}
+
+function packageNames(count: number): string[] {
+ return Array.from({ length: count }, (_, i) => `pkg-${i}`)
+}
+
+function resolvedPackages(names: string[]) {
+ return new Map(
+ names.map(name => [
+ `${name}@1.0.0`,
+ {
+ name,
+ version: '1.0.0',
+ size: 100,
+ optional: false,
+ depth: 'transitive' as const,
+ path: ['root@1.0.0', `${name}@1.0.0`],
+ tarballUrl: `https://example.com/${name}-1.0.0.tgz`,
+ },
+ ]),
+ )
+}
+
+function batchQueries(options?: { body?: unknown }): OsvBatchQuery[] {
+ return (options?.body as { queries: OsvBatchQuery[] } | undefined)?.queries ?? []
+}
+
+interface OsvBatchPage {
+ results: Array<{ vulns?: Array<{ id: string; modified: string }>; next_page_token?: string }>
+}
+
+function mockPaginatedOsv(pages: OsvBatchPage[]): OsvBatchQuery[][] {
+ const calls: OsvBatchQuery[][] = []
+ $fetchMock.mockImplementation(async (url: string, request?: { body?: unknown }) => {
+ if (url === 'https://api.osv.dev/v1/query') {
+ const body = request?.body as { package: { name: string } }
+ return {
+ vulns: [
+ {
+ id: `GHSA-${body.package.name}`,
+ summary: 'A vulnerability',
+ database_specific: { severity: 'MEDIUM' },
+ },
+ ],
+ }
+ }
+ calls.push(batchQueries(request))
+ return pages[calls.length - 1] ?? { results: [] }
+ })
+ return calls
+}
+
+function mockBatchedOsv(
+ vulnerable: Set,
+ options: { failChunk?: (call: number) => boolean } = {},
+): OsvBatchQuery[][] {
+ const calls: OsvBatchQuery[][] = []
+ $fetchMock.mockImplementation(async (url: string, request?: { body?: unknown }) => {
+ if (url === 'https://api.osv.dev/v1/querybatch') {
+ const queries = batchQueries(request)
+ calls.push(queries)
+ if (options.failChunk?.(calls.length)) throw new Error('OSV batch chunk failed')
+ return {
+ results: queries.map(query =>
+ vulnerable.has(query.package.name)
+ ? { vulns: [{ id: `GHSA-${query.package.name}`, modified: '2024-01-01' }] }
+ : { vulns: [] },
+ ),
+ }
+ }
+ if (url === 'https://api.osv.dev/v1/query') {
+ const body = request?.body as { package: { name: string } }
+ return {
+ vulns: [
+ {
+ id: `GHSA-${body.package.name}`,
+ summary: 'A vulnerability',
+ database_specific: { severity: 'HIGH' },
+ },
+ ],
+ }
+ }
+ throw new Error(`Unexpected fetch to ${url}`)
+ })
+ return calls
+}
+
describe('dependency-analysis', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -1056,4 +1147,173 @@ describe('dependency-analysis', () => {
expect(result.totalPackages).toBe(3)
})
})
+
+ describe('OSV batch chunking', () => {
+ it('sends a single request when the tree is under the limit', async () => {
+ const names = packageNames(10)
+ vi.mocked(resolveDependencyTree).mockResolvedValue(resolvedPackages(names))
+ const calls = mockBatchedOsv(new Set(['pkg-3']))
+
+ const result = await analyzeDependencyTree('root', '1.0.0')
+
+ expect(calls).toHaveLength(1)
+ expect(calls[0]).toHaveLength(10)
+ expect(result.vulnerablePackages.map(pkg => pkg.name)).toEqual(['pkg-3'])
+ expect(result.failedQueries).toBe(0)
+ })
+
+ it('sends a single request at the limit', async () => {
+ const names = packageNames(1000)
+ vi.mocked(resolveDependencyTree).mockResolvedValue(resolvedPackages(names))
+ const calls = mockBatchedOsv(new Set(['pkg-999']))
+
+ const result = await analyzeDependencyTree('root', '1.0.0')
+
+ expect(calls).toHaveLength(1)
+ expect(calls[0]).toHaveLength(1000)
+ expect(result.vulnerablePackages.map(pkg => pkg.name)).toEqual(['pkg-999'])
+ expect(result.failedQueries).toBe(0)
+ })
+
+ it('chunks trees over the limit and merges results in order', async () => {
+ const names = packageNames(1653)
+ vi.mocked(resolveDependencyTree).mockResolvedValue(resolvedPackages(names))
+ const calls = mockBatchedOsv(new Set(['pkg-0', 'pkg-1000', 'pkg-1652']))
+
+ const result = await analyzeDependencyTree('root', '1.0.0')
+
+ expect(calls.map(queries => queries.length)).toEqual([1000, 653])
+ expect(calls[1]?.[0]?.package.name).toBe('pkg-1000')
+ expect(result.totalPackages).toBe(1653)
+ expect(result.failedQueries).toBe(0)
+ expect(result.vulnerablePackages.map(pkg => pkg.name)).toEqual([
+ 'pkg-0',
+ 'pkg-1000',
+ 'pkg-1652',
+ ])
+ })
+
+ it('keeps results from successful chunks when one chunk fails', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ const names = packageNames(1200)
+ vi.mocked(resolveDependencyTree).mockResolvedValue(resolvedPackages(names))
+ const calls = mockBatchedOsv(new Set(['pkg-3', 'pkg-1003']), {
+ failChunk: call => call === 1,
+ })
+
+ const result = await analyzeDependencyTree('root', '1.0.0')
+
+ expect(calls).toHaveLength(2)
+ expect(result.totalPackages).toBe(1200)
+ expect(result.failedQueries).toBe(1000)
+ expect(result.vulnerablePackages.map(pkg => pkg.name)).toEqual(['pkg-1003'])
+ })
+
+ it('keeps indices found before a continuation request fails', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ vi.mocked(resolveDependencyTree).mockResolvedValue(resolvedPackages(['a', 'b']))
+ const calls: OsvBatchQuery[][] = []
+ $fetchMock.mockImplementation(async (url: string, request?: { body?: unknown }) => {
+ if (url === 'https://api.osv.dev/v1/query') {
+ return {
+ vulns: [
+ {
+ id: 'GHSA-a',
+ summary: 'A vulnerability',
+ database_specific: { severity: 'MEDIUM' },
+ },
+ ],
+ }
+ }
+ calls.push(batchQueries(request))
+ if (calls.length === 1) {
+ return {
+ results: [
+ { vulns: [{ id: 'GHSA-a', modified: '2024-01-01' }] },
+ { vulns: [], next_page_token: 'page-2' },
+ ],
+ }
+ }
+ throw new Error('OSV batch chunk failed')
+ })
+
+ const result = await analyzeDependencyTree('root', '1.0.0')
+
+ expect(calls).toHaveLength(2)
+ expect(result.failedQueries).toBe(1)
+ expect(result.vulnerablePackages.map(pkg => pkg.name)).toEqual(['a'])
+ })
+
+ it('follows per-query pagination tokens across several pages', async () => {
+ vi.mocked(resolveDependencyTree).mockResolvedValue(resolvedPackages(['a', 'b']))
+ const calls = mockPaginatedOsv([
+ { results: [{ vulns: [] }, { vulns: [], next_page_token: 'page-2' }] },
+ { results: [{ vulns: [], next_page_token: 'page-3' }] },
+ { results: [{ vulns: [{ id: 'GHSA-b', modified: '2024-01-02' }] }] },
+ ])
+
+ const result = await analyzeDependencyTree('root', '1.0.0')
+
+ expect(calls).toHaveLength(3)
+ expect(calls[1]).toHaveLength(1)
+ expect(calls[1]?.[0]?.package.name).toBe('b')
+ expect(calls[1]?.[0]?.page_token).toBe('page-2')
+ expect(calls[1]?.[0]?.version).toBe('1.0.0')
+ expect(calls[2]).toHaveLength(1)
+ expect(calls[2]?.[0]?.package.name).toBe('b')
+ expect(calls[2]?.[0]?.page_token).toBe('page-3')
+ expect(result.vulnerablePackages.map(pkg => pkg.name)).toEqual(['b'])
+ })
+
+ it('does not duplicate packages whose vulnerabilities span pages', async () => {
+ vi.mocked(resolveDependencyTree).mockResolvedValue(resolvedPackages(['a', 'b']))
+ const calls = mockPaginatedOsv([
+ {
+ results: [
+ { vulns: [{ id: 'GHSA-a', modified: '2024-01-01' }], next_page_token: 'page-2' },
+ { vulns: [] },
+ ],
+ },
+ { results: [{ vulns: [{ id: 'GHSA-a-2', modified: '2024-01-02' }] }] },
+ ])
+
+ const result = await analyzeDependencyTree('root', '1.0.0')
+
+ expect(calls).toHaveLength(2)
+ expect(result.vulnerablePackages.map(pkg => pkg.name)).toEqual(['a'])
+ })
+
+ it('stops paginating after the page cap', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ vi.mocked(resolveDependencyTree).mockResolvedValue(resolvedPackages(['a']))
+ const calls: OsvBatchQuery[][] = []
+ $fetchMock.mockImplementation(async (url: string, request?: { body?: unknown }) => {
+ if (url === 'https://api.osv.dev/v1/querybatch') {
+ calls.push(batchQueries(request))
+ return {
+ results: [
+ {
+ vulns: [{ id: 'GHSA-a', modified: '2024-01-01' }],
+ next_page_token: 'another-page',
+ },
+ ],
+ }
+ }
+ return {
+ vulns: [
+ { id: 'GHSA-a', summary: 'A vulnerability', database_specific: { severity: 'MEDIUM' } },
+ ],
+ }
+ })
+
+ const result = await analyzeDependencyTree('root', '1.0.0')
+
+ expect(calls).toHaveLength(5)
+ expect(result.vulnerablePackages.map(pkg => pkg.name)).toEqual(['a'])
+ expect(result.failedQueries).toBe(0)
+ })
+ })
})
diff --git a/test/unit/server/utils/file-tree.spec.ts b/test/unit/server/utils/file-tree.spec.ts
index f64a43fb9d..9290a2a303 100644
--- a/test/unit/server/utils/file-tree.spec.ts
+++ b/test/unit/server/utils/file-tree.spec.ts
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from 'vite-plus/test'
import type { JsDelivrFileNode, PackageFileTree } from '#shared/types'
-import { convertToFileTree, fetchFileTree, getPackageFileTree } from '#server/utils/file-tree'
+import {
+ convertToFileTree,
+ fetchFileTree,
+ getPackageFileTree,
+ withoutFileHashes,
+} from '#server/utils/file-tree'
const getChildren = (node?: PackageFileTree): PackageFileTree[] => node?.children ?? []
@@ -115,6 +120,30 @@ describe('convertToFileTree', () => {
})
})
+describe('withoutFileHashes', () => {
+ it('removes hashes at every depth and keeps everything else', () => {
+ const tree = convertToFileTree([
+ { type: 'file', name: 'index.js', hash: 'a', size: 1 },
+ {
+ type: 'directory',
+ name: 'dist',
+ files: [{ type: 'file', name: 'index.mjs', hash: 'b', size: 2 }],
+ },
+ ])
+
+ expect(withoutFileHashes(tree)).toEqual([
+ {
+ name: 'dist',
+ path: 'dist',
+ type: 'directory',
+ size: 2,
+ children: [{ name: 'index.mjs', path: 'dist/index.mjs', type: 'file', size: 2 }],
+ },
+ { name: 'index.js', path: 'index.js', type: 'file', size: 1 },
+ ])
+ })
+})
+
describe('fetchFileTree', () => {
it('returns parsed json when response is ok', async () => {
const body = {
diff --git a/test/unit/server/utils/likes-cache.spec.ts b/test/unit/server/utils/likes-cache.spec.ts
new file mode 100644
index 0000000000..2803a65ad3
--- /dev/null
+++ b/test/unit/server/utils/likes-cache.spec.ts
@@ -0,0 +1,116 @@
+import type { Redis } from '@upstash/redis'
+import type { ConstellationLike } from '#server/utils/atproto/utils/likes'
+import { afterAll, describe, expect, it, vi } from 'vite-plus/test'
+import { RedisCacheAdapter } from '#server/utils/cache/redis'
+
+vi.stubGlobal('CACHE_MAX_AGE_ONE_MINUTE', 60)
+vi.stubGlobal('PACKAGE_SUBJECT_REF', (pkg: string) => `https://npmx.dev/package/${pkg}`)
+vi.stubGlobal('getCacheAdapter', vi.fn())
+vi.stubGlobal('Constellation', vi.fn())
+
+const { PackageLikesUtils } = await import('#server/utils/atproto/utils/likes')
+
+function createMemoryCache(): CacheAdapter {
+ const store = new Map()
+ return {
+ get: async (key: string) => store.get(key) as T | undefined,
+ set: async (key: string, value: T) => {
+ store.set(key, value)
+ },
+ delete: async (key: string) => {
+ store.delete(key)
+ },
+ }
+}
+
+function createMockConstellation(total = 0, userTotal = 0): ConstellationLike {
+ return {
+ getLinksDistinctDids: vi.fn(async () => ({
+ data: { total, linking_dids: [] },
+ isStale: false,
+ cachedAt: null,
+ })) as unknown as ConstellationLike['getLinksDistinctDids'],
+ getBackLinks: vi.fn(async () => ({
+ data: { total: userTotal, records: [] },
+ isStale: false,
+ cachedAt: null,
+ })) as unknown as ConstellationLike['getBackLinks'],
+ }
+}
+
+afterAll(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('PackageLikesUtils caching', () => {
+ it('caches zero total likes without re-querying constellation', async () => {
+ const cache = createMemoryCache()
+ const constellation = createMockConstellation(0, 0)
+ const utils = new PackageLikesUtils({ cache, constellation })
+
+ expect(await utils.getTotalLikes('zero-likes-pkg')).toBe(0)
+ expect(await utils.getTotalLikes('zero-likes-pkg')).toBe(0)
+ expect(constellation.getLinksDistinctDids).toHaveBeenCalledTimes(1)
+ })
+
+ it('caches false userHasLiked and zero totalLikes in getLikes', async () => {
+ const cache = createMemoryCache()
+ const constellation = createMockConstellation(0, 0)
+ const utils = new PackageLikesUtils({ cache, constellation })
+
+ const first = await utils.getLikes('zero-likes-pkg', 'did:plc:alice')
+ const second = await utils.getLikes('zero-likes-pkg', 'did:plc:alice')
+
+ expect(first).toEqual({ totalLikes: 0, userHasLiked: false, topLikedRank: null })
+ expect(second).toEqual({ totalLikes: 0, userHasLiked: false, topLikedRank: null })
+ expect(constellation.getLinksDistinctDids).toHaveBeenCalledTimes(1)
+ expect(constellation.getBackLinks).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps cached count consistent across like and unlike down to zero', async () => {
+ const cache = createMemoryCache()
+ const constellation = createMockConstellation(0, 0)
+ const utils = new PackageLikesUtils({ cache, constellation })
+
+ expect(await utils.getTotalLikes('fresh-pkg')).toBe(0)
+
+ const liked = await utils.likeAPackageAndReturnLikes(
+ 'fresh-pkg',
+ 'did:plc:alice',
+ 'at://did:plc:alice/dev.npmx.feed.like/3k2abc',
+ )
+ expect(liked).toEqual({ totalLikes: 1, userHasLiked: true, topLikedRank: null })
+ expect(await utils.getLikes('fresh-pkg', 'did:plc:alice')).toEqual({
+ totalLikes: 1,
+ userHasLiked: true,
+ topLikedRank: null,
+ })
+
+ const unliked = await utils.unlikeAPackageAndReturnLikes('fresh-pkg', 'did:plc:alice')
+ expect(unliked).toEqual({ totalLikes: 0, userHasLiked: false, topLikedRank: null })
+ expect(await utils.getLikes('fresh-pkg', 'did:plc:alice')).toEqual({
+ totalLikes: 0,
+ userHasLiked: false,
+ topLikedRank: null,
+ })
+ expect(constellation.getLinksDistinctDids).toHaveBeenCalledTimes(1)
+ expect(constellation.getBackLinks).not.toHaveBeenCalled()
+ })
+})
+
+describe('RedisCacheAdapter', () => {
+ it('returns cached falsy values (0 and false) and undefined only for null', async () => {
+ const getMock = vi.fn()
+ const redis = { get: getMock } as unknown as Redis
+ const adapter = new RedisCacheAdapter(redis, 'generic')
+
+ getMock.mockResolvedValueOnce(0)
+ await expect(adapter.get('zero')).resolves.toBe(0)
+
+ getMock.mockResolvedValueOnce(false)
+ await expect(adapter.get('false')).resolves.toBe(false)
+
+ getMock.mockResolvedValueOnce(null)
+ await expect(adapter.get('missing')).resolves.toBeUndefined()
+ })
+})
diff --git a/test/unit/server/utils/server-session.spec.ts b/test/unit/server/utils/server-session.spec.ts
new file mode 100644
index 0000000000..f3d548de80
--- /dev/null
+++ b/test/unit/server/utils/server-session.spec.ts
@@ -0,0 +1,89 @@
+import type { AddressInfo } from 'node:net'
+import { createServer } from 'node:http'
+import { createApp, eventHandler, toNodeListener } from 'h3'
+import { afterAll, describe, expect, it, vi } from 'vite-plus/test'
+import {
+ clearSessionHintCookie,
+ hasServerSessionCookie,
+ setSessionHintCookie,
+ useServerSession,
+} from '#server/utils/server-session'
+import { CACHE_MAX_AGE_ONE_DAY, SESSION_HINT_COOKIE } from '#shared/utils/constants'
+
+vi.stubGlobal('useRuntimeConfig', () => ({
+ sessionPassword: 'test-session-password-32-chars-long',
+}))
+
+afterAll(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('server-session', () => {
+ it('round-trips sealed session and hint cookies and clears both on logout', async () => {
+ const user = {
+ did: 'did:plc:alice123',
+ handle: 'alice.bsky.social',
+ pds: 'https://bsky.social',
+ }
+
+ const app = createApp().use(
+ eventHandler(async event => {
+ if (event.path === '/login') {
+ const session = await useServerSession(event)
+ await session.update({ public: user })
+ setSessionHintCookie(event)
+ return 'ok'
+ }
+ if (!hasServerSessionCookie(event)) return null
+ const session = await useServerSession(event)
+ if (event.path === '/logout') {
+ await session.clear()
+ clearSessionHintCookie(event)
+ return 'ok'
+ }
+ return session.data.public ?? null
+ }),
+ )
+
+ const server = createServer(toNodeListener(app))
+ try {
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
+ const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
+
+ const anonymous = await fetch(origin)
+ expect(anonymous.status).toBe(204)
+ expect(anonymous.headers.getSetCookie()).toEqual([])
+
+ const login = await fetch(`${origin}/login`)
+ const cookies = login.headers.getSetCookie()
+ const hint = cookies.find(value => value.startsWith(`${SESSION_HINT_COOKIE}=`))
+ const sessionCookie = cookies.find(value => value.startsWith('h3='))
+
+ expect(hint).toBeDefined()
+ expect(hint).toContain(`${SESSION_HINT_COOKIE}=1`)
+ expect(hint).toContain(`Max-Age=${CACHE_MAX_AGE_ONE_DAY * 179}`)
+ expect(hint).toMatch(/Path=\//i)
+ expect(hint).toMatch(/SameSite=Lax/i)
+ expect(hint).not.toMatch(/HttpOnly/i)
+ expect(sessionCookie).toBeDefined()
+ expect(sessionCookie).toMatch(/HttpOnly/i)
+
+ const cookieHeader = cookies.map(value => value.split(';')[0]).join('; ')
+ const restored = await fetch(origin, { headers: { cookie: cookieHeader } })
+ expect(await restored.json()).toEqual(user)
+
+ const logout = await fetch(`${origin}/logout`, { headers: { cookie: cookieHeader } })
+ const deletions = logout.headers.getSetCookie()
+ expect(
+ deletions.some(
+ value => value.startsWith(`${SESSION_HINT_COOKIE}=;`) && /Max-Age=0/i.test(value),
+ ),
+ ).toBe(true)
+ expect(deletions.some(value => value.startsWith('h3=;'))).toBe(true)
+ } finally {
+ await new Promise((resolve, reject) =>
+ server.close(error => (error ? reject(error) : resolve())),
+ )
+ }
+ })
+})
diff --git a/test/unit/shared/utils/unfurl.spec.ts b/test/unit/shared/utils/unfurl.spec.ts
new file mode 100644
index 0000000000..18a1da4fa2
--- /dev/null
+++ b/test/unit/shared/utils/unfurl.spec.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vite-plus/test'
+import { isUnfurlUserAgent } from '#shared/utils/unfurl'
+
+describe('isUnfurlUserAgent', () => {
+ it.each([
+ 'Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)',
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 MicrosoftPreview/2.0',
+ 'Mozilla/5.0 (compatible; embedly/0.2; +http://support.embed.ly/)',
+ ])('matches %s', userAgent => {
+ expect(isUnfurlUserAgent(userAgent)).toBe(true)
+ })
+
+ it.each([
+ undefined,
+ '',
+ 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/140.0.0.0',
+ ])('does not match %s', userAgent => {
+ expect(isUnfurlUserAgent(userAgent)).toBe(false)
+ })
+})
diff --git a/test/unit/uno-preset-a11y.spec.ts b/test/unit/uno-preset-a11y.spec.ts
index ffa78c213c..d054193df0 100644
--- a/test/unit/uno-preset-a11y.spec.ts
+++ b/test/unit/uno-preset-a11y.spec.ts
@@ -24,17 +24,17 @@ describe('uno-preset-a11y', () => {
)
expect(css).toMatchInlineSnapshot(`
- "/* layer: theme */
- :root, :host { --font-sans: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"; --font-mono: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; --default-font-family: var(--font-sans); --default-monoFont-family: var(--font-mono); }
- /* layer: base */
- *, ::after, ::before, ::backdrop, ::file-selector-button { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; } html, :host { line-height: 1.5; -webkit-text-size-adjust: 100%; tab-size: 4; font-family: var( --default-font-family, ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji' ); font-feature-settings: var(--default-font-featureSettings, normal); font-variation-settings: var(--default-font-variationSettings, normal); -webkit-tap-highlight-color: transparent; } hr { height: 0; color: inherit; border-top-width: 1px; } abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } a { color: inherit; -webkit-text-decoration: inherit; text-decoration: inherit; } b, strong { font-weight: bolder; } code, kbd, samp, pre { font-family: var( --default-monoFont-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace ); font-feature-settings: var(--default-monoFont-featureSettings, normal); font-variation-settings: var(--default-monoFont-variationSettings, normal); font-size: 1em; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } table { text-indent: 0; border-color: inherit; border-collapse: collapse; } :-moz-focusring { outline: auto; } progress { vertical-align: baseline; } summary { display: list-item; } ol, ul, menu { list-style: none; } img, svg, video, canvas, audio, iframe, embed, object { display: block; vertical-align: middle; } img, video { max-width: 100%; height: auto; } button, input, select, optgroup, textarea, ::file-selector-button { font: inherit; font-feature-settings: inherit; font-variation-settings: inherit; letter-spacing: inherit; color: inherit; border-radius: 0; background-color: transparent; opacity: 1; } :where(select:is([multiple], [size])) optgroup { font-weight: bolder; } :where(select:is([multiple], [size])) optgroup option { padding-inline-start: 20px; } ::file-selector-button { margin-inline-end: 4px; } ::placeholder { opacity: 1; } @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) { ::placeholder { color: color-mix(in oklab, currentcolor 50%, transparent); } } textarea { resize: vertical; } ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-date-and-time-value { min-height: 1lh; text-align: inherit; } ::-webkit-datetime-edit { display: inline-flex; } ::-webkit-datetime-edit-fields-wrapper { padding: 0; } ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field { padding-block: 0; } ::-webkit-calendar-picker-indicator { line-height: 1; } :-moz-ui-invalid { box-shadow: none; } button, input:where([type='button'], [type='reset'], [type='submit']), ::file-selector-button { appearance: button; } ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } [hidden]:where(:not([hidden~='until-found'])) { display: none !important; }
- /* layer: default */
- .text-\\[10px\\]{font-size:10px;}
- .text-\\[11px\\]{font-size:11px;}
- .text-\\[12px\\]{font-size:12px;}
- .text-\\[8px\\]{font-size:8px;}
- .text-\\[9px\\]{font-size:9px;}
- .text-\\[1\\.5em\\]{font-size:1.5em;}"
+ "/* layer: theme */
+ :root, :host { --font-sans: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"; --font-mono: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; --default-font-family: var(--font-sans); --default-monoFont-family: var(--font-mono); }
+ /* layer: base */
+ *, ::after, ::before, ::backdrop, ::file-selector-button { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; } html, :host { line-height: 1.5; -webkit-text-size-adjust: 100%; tab-size: 4; font-family: var( --default-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', 'Noto Sans', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji' ); font-feature-settings: var(--default-font-featureSettings, normal); font-variation-settings: var(--default-font-variationSettings, normal); -webkit-tap-highlight-color: transparent; } hr { height: 0; color: inherit; border-top-width: 1px; } abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } a { color: inherit; -webkit-text-decoration: inherit; text-decoration: inherit; } b, strong { font-weight: bolder; } code, kbd, samp, pre { font-family: var( --default-monoFont-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace ); font-feature-settings: var(--default-monoFont-featureSettings, normal); font-variation-settings: var(--default-monoFont-variationSettings, normal); font-size: 1em; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } table { text-indent: 0; border-color: inherit; border-collapse: collapse; } :-moz-focusring:where(:not(iframe)) { outline: auto; } progress { vertical-align: baseline; } summary { display: list-item; } ol, ul, menu { list-style: none; } img, svg, video, canvas, audio, iframe, embed, object { display: block; vertical-align: middle; } img, video { max-width: 100%; height: auto; } button, input, select, optgroup, textarea, ::file-selector-button { font: inherit; font-feature-settings: inherit; font-variation-settings: inherit; letter-spacing: inherit; color: inherit; border-radius: 0; background-color: transparent; opacity: 1; } :where(select:is([multiple], [size])) optgroup { font-weight: bolder; } :where(select:is([multiple], [size])) optgroup option { padding-inline-start: 20px; } ::file-selector-button { margin-inline-end: 4px; } ::placeholder { opacity: 1; } @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) { ::placeholder { color: color-mix(in oklab, currentcolor 50%, transparent); } } textarea { resize: vertical; } ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-date-and-time-value { min-height: 1lh; text-align: inherit; } ::-webkit-datetime-edit { display: inline-flex; } ::-webkit-datetime-edit-fields-wrapper { padding: 0; } ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field { padding-block: 0; } ::-webkit-calendar-picker-indicator { line-height: 1; } :-moz-ui-invalid { box-shadow: none; } button, input:where([type='button'], [type='reset'], [type='submit']), ::file-selector-button { appearance: button; } ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } [hidden]:where(:not([hidden~='until-found'])) { display: none !important; }
+ /* layer: default */
+ .text-\\[10px\\]{font-size:10px;}
+ .text-\\[11px\\]{font-size:11px;}
+ .text-\\[12px\\]{font-size:12px;}
+ .text-\\[8px\\]{font-size:8px;}
+ .text-\\[9px\\]{font-size:9px;}
+ .text-\\[1\\.5em\\]{font-size:1.5em;}"
`)
const warnings = warnSpy.mock.calls.flat()
@@ -63,14 +63,14 @@ describe('uno-preset-a11y', () => {
const { css } = await uno.generate('text-[11px] text-[12px] text-[1.5em]')
expect(css).toMatchInlineSnapshot(`
- "/* layer: theme */
- :root, :host { --font-sans: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"; --font-mono: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; --default-font-family: var(--font-sans); --default-monoFont-family: var(--font-mono); }
- /* layer: base */
- *, ::after, ::before, ::backdrop, ::file-selector-button { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; } html, :host { line-height: 1.5; -webkit-text-size-adjust: 100%; tab-size: 4; font-family: var( --default-font-family, ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji' ); font-feature-settings: var(--default-font-featureSettings, normal); font-variation-settings: var(--default-font-variationSettings, normal); -webkit-tap-highlight-color: transparent; } hr { height: 0; color: inherit; border-top-width: 1px; } abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } a { color: inherit; -webkit-text-decoration: inherit; text-decoration: inherit; } b, strong { font-weight: bolder; } code, kbd, samp, pre { font-family: var( --default-monoFont-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace ); font-feature-settings: var(--default-monoFont-featureSettings, normal); font-variation-settings: var(--default-monoFont-variationSettings, normal); font-size: 1em; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } table { text-indent: 0; border-color: inherit; border-collapse: collapse; } :-moz-focusring { outline: auto; } progress { vertical-align: baseline; } summary { display: list-item; } ol, ul, menu { list-style: none; } img, svg, video, canvas, audio, iframe, embed, object { display: block; vertical-align: middle; } img, video { max-width: 100%; height: auto; } button, input, select, optgroup, textarea, ::file-selector-button { font: inherit; font-feature-settings: inherit; font-variation-settings: inherit; letter-spacing: inherit; color: inherit; border-radius: 0; background-color: transparent; opacity: 1; } :where(select:is([multiple], [size])) optgroup { font-weight: bolder; } :where(select:is([multiple], [size])) optgroup option { padding-inline-start: 20px; } ::file-selector-button { margin-inline-end: 4px; } ::placeholder { opacity: 1; } @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) { ::placeholder { color: color-mix(in oklab, currentcolor 50%, transparent); } } textarea { resize: vertical; } ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-date-and-time-value { min-height: 1lh; text-align: inherit; } ::-webkit-datetime-edit { display: inline-flex; } ::-webkit-datetime-edit-fields-wrapper { padding: 0; } ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field { padding-block: 0; } ::-webkit-calendar-picker-indicator { line-height: 1; } :-moz-ui-invalid { box-shadow: none; } button, input:where([type='button'], [type='reset'], [type='submit']), ::file-selector-button { appearance: button; } ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } [hidden]:where(:not([hidden~='until-found'])) { display: none !important; }
- /* layer: default */
- .text-\\[11px\\]{font-size:11px;}
- .text-\\[12px\\]{font-size:12px;}
- .text-\\[1\\.5em\\]{font-size:1.5em;}"
+ "/* layer: theme */
+ :root, :host { --font-sans: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"; --font-mono: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; --default-font-family: var(--font-sans); --default-monoFont-family: var(--font-mono); }
+ /* layer: base */
+ *, ::after, ::before, ::backdrop, ::file-selector-button { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; } html, :host { line-height: 1.5; -webkit-text-size-adjust: 100%; tab-size: 4; font-family: var( --default-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', 'Noto Sans', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji' ); font-feature-settings: var(--default-font-featureSettings, normal); font-variation-settings: var(--default-font-variationSettings, normal); -webkit-tap-highlight-color: transparent; } hr { height: 0; color: inherit; border-top-width: 1px; } abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } a { color: inherit; -webkit-text-decoration: inherit; text-decoration: inherit; } b, strong { font-weight: bolder; } code, kbd, samp, pre { font-family: var( --default-monoFont-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace ); font-feature-settings: var(--default-monoFont-featureSettings, normal); font-variation-settings: var(--default-monoFont-variationSettings, normal); font-size: 1em; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } table { text-indent: 0; border-color: inherit; border-collapse: collapse; } :-moz-focusring:where(:not(iframe)) { outline: auto; } progress { vertical-align: baseline; } summary { display: list-item; } ol, ul, menu { list-style: none; } img, svg, video, canvas, audio, iframe, embed, object { display: block; vertical-align: middle; } img, video { max-width: 100%; height: auto; } button, input, select, optgroup, textarea, ::file-selector-button { font: inherit; font-feature-settings: inherit; font-variation-settings: inherit; letter-spacing: inherit; color: inherit; border-radius: 0; background-color: transparent; opacity: 1; } :where(select:is([multiple], [size])) optgroup { font-weight: bolder; } :where(select:is([multiple], [size])) optgroup option { padding-inline-start: 20px; } ::file-selector-button { margin-inline-end: 4px; } ::placeholder { opacity: 1; } @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) { ::placeholder { color: color-mix(in oklab, currentcolor 50%, transparent); } } textarea { resize: vertical; } ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-date-and-time-value { min-height: 1lh; text-align: inherit; } ::-webkit-datetime-edit { display: inline-flex; } ::-webkit-datetime-edit-fields-wrapper { padding: 0; } ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field { padding-block: 0; } ::-webkit-calendar-picker-indicator { line-height: 1; } :-moz-ui-invalid { box-shadow: none; } button, input:where([type='button'], [type='reset'], [type='submit']), ::file-selector-button { appearance: button; } ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } [hidden]:where(:not([hidden~='until-found'])) { display: none !important; }
+ /* layer: default */
+ .text-\\[11px\\]{font-size:11px;}
+ .text-\\[12px\\]{font-size:12px;}
+ .text-\\[1\\.5em\\]{font-size:1.5em;}"
`)
expect(warnSpy).not.toHaveBeenCalled()
diff --git a/test/unit/uno-preset-rtl.spec.ts b/test/unit/uno-preset-rtl.spec.ts
index eb97c19946..f830d58746 100644
--- a/test/unit/uno-preset-rtl.spec.ts
+++ b/test/unit/uno-preset-rtl.spec.ts
@@ -24,29 +24,29 @@ describe('uno-preset-rtl', () => {
)
expect(css).toMatchInlineSnapshot(`
- "/* layer: theme */
- :root, :host { --spacing: 0.25rem; --font-sans: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"; --font-mono: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; --default-font-family: var(--font-sans); --default-monoFont-family: var(--font-mono); }
- /* layer: base */
- *, ::after, ::before, ::backdrop, ::file-selector-button { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; } html, :host { line-height: 1.5; -webkit-text-size-adjust: 100%; tab-size: 4; font-family: var( --default-font-family, ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji' ); font-feature-settings: var(--default-font-featureSettings, normal); font-variation-settings: var(--default-font-variationSettings, normal); -webkit-tap-highlight-color: transparent; } hr { height: 0; color: inherit; border-top-width: 1px; } abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } a { color: inherit; -webkit-text-decoration: inherit; text-decoration: inherit; } b, strong { font-weight: bolder; } code, kbd, samp, pre { font-family: var( --default-monoFont-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace ); font-feature-settings: var(--default-monoFont-featureSettings, normal); font-variation-settings: var(--default-monoFont-variationSettings, normal); font-size: 1em; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } table { text-indent: 0; border-color: inherit; border-collapse: collapse; } :-moz-focusring { outline: auto; } progress { vertical-align: baseline; } summary { display: list-item; } ol, ul, menu { list-style: none; } img, svg, video, canvas, audio, iframe, embed, object { display: block; vertical-align: middle; } img, video { max-width: 100%; height: auto; } button, input, select, optgroup, textarea, ::file-selector-button { font: inherit; font-feature-settings: inherit; font-variation-settings: inherit; letter-spacing: inherit; color: inherit; border-radius: 0; background-color: transparent; opacity: 1; } :where(select:is([multiple], [size])) optgroup { font-weight: bolder; } :where(select:is([multiple], [size])) optgroup option { padding-inline-start: 20px; } ::file-selector-button { margin-inline-end: 4px; } ::placeholder { opacity: 1; } @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) { ::placeholder { color: color-mix(in oklab, currentcolor 50%, transparent); } } textarea { resize: vertical; } ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-date-and-time-value { min-height: 1lh; text-align: inherit; } ::-webkit-datetime-edit { display: inline-flex; } ::-webkit-datetime-edit-fields-wrapper { padding: 0; } ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field { padding-block: 0; } ::-webkit-calendar-picker-indicator { line-height: 1; } :-moz-ui-invalid { box-shadow: none; } button, input:where([type='button'], [type='reset'], [type='submit']), ::file-selector-button { appearance: button; } ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } [hidden]:where(:not([hidden~='until-found'])) { display: none !important; }
- /* layer: shortcuts */
- .text-left{text-align:start;--x-rtl-start:"text-left -> text-start";}
- .text-right{text-align:end;--x-rtl-end:"text-right -> text-end";}
- .hover\\:text-right:hover{text-align:end;--x-rtl-end:"hover:text-right -> hover:text-end";}
- /* layer: default */
- .pl-1{padding-inline-start:calc(var(--spacing) * 1);}
- .pr-1{padding-inline-end:calc(var(--spacing) * 1);}
- .ml-1{margin-inline-start:calc(var(--spacing) * 1);}
- .mr-1{margin-inline-end:calc(var(--spacing) * 1);}
- .left-0{inset-inline-start:calc(var(--spacing) * 0);}
- .position-left-4{inset-inline-start:calc(var(--spacing) * 4);}
- .right-0{inset-inline-end:calc(var(--spacing) * 0);}
- .rounded-l{border-end-start-radius:0.25rem;border-start-start-radius:0.25rem;}
- .rounded-r{border-start-end-radius:0.25rem;border-end-end-radius:0.25rem;}
- .border-l{border-inline-start-width:1px;}
- .border-r{border-inline-end-width:1px;}
- @media (min-width: 40rem){
- .sm\\:pl-2{padding-inline-start:calc(var(--spacing) * 2);}
- }"
+ "/* layer: theme */
+ :root, :host { --spacing: 0.25rem; --font-sans: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"; --font-mono: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; --default-font-family: var(--font-sans); --default-monoFont-family: var(--font-mono); }
+ /* layer: base */
+ *, ::after, ::before, ::backdrop, ::file-selector-button { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; } html, :host { line-height: 1.5; -webkit-text-size-adjust: 100%; tab-size: 4; font-family: var( --default-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', 'Noto Sans', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji' ); font-feature-settings: var(--default-font-featureSettings, normal); font-variation-settings: var(--default-font-variationSettings, normal); -webkit-tap-highlight-color: transparent; } hr { height: 0; color: inherit; border-top-width: 1px; } abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } a { color: inherit; -webkit-text-decoration: inherit; text-decoration: inherit; } b, strong { font-weight: bolder; } code, kbd, samp, pre { font-family: var( --default-monoFont-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace ); font-feature-settings: var(--default-monoFont-featureSettings, normal); font-variation-settings: var(--default-monoFont-variationSettings, normal); font-size: 1em; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } table { text-indent: 0; border-color: inherit; border-collapse: collapse; } :-moz-focusring:where(:not(iframe)) { outline: auto; } progress { vertical-align: baseline; } summary { display: list-item; } ol, ul, menu { list-style: none; } img, svg, video, canvas, audio, iframe, embed, object { display: block; vertical-align: middle; } img, video { max-width: 100%; height: auto; } button, input, select, optgroup, textarea, ::file-selector-button { font: inherit; font-feature-settings: inherit; font-variation-settings: inherit; letter-spacing: inherit; color: inherit; border-radius: 0; background-color: transparent; opacity: 1; } :where(select:is([multiple], [size])) optgroup { font-weight: bolder; } :where(select:is([multiple], [size])) optgroup option { padding-inline-start: 20px; } ::file-selector-button { margin-inline-end: 4px; } ::placeholder { opacity: 1; } @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) { ::placeholder { color: color-mix(in oklab, currentcolor 50%, transparent); } } textarea { resize: vertical; } ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-date-and-time-value { min-height: 1lh; text-align: inherit; } ::-webkit-datetime-edit { display: inline-flex; } ::-webkit-datetime-edit-fields-wrapper { padding: 0; } ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field { padding-block: 0; } ::-webkit-calendar-picker-indicator { line-height: 1; } :-moz-ui-invalid { box-shadow: none; } button, input:where([type='button'], [type='reset'], [type='submit']), ::file-selector-button { appearance: button; } ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } [hidden]:where(:not([hidden~='until-found'])) { display: none !important; }
+ /* layer: shortcuts */
+ .text-left{text-align:start;--x-rtl-start:"text-left -> text-start";}
+ .text-right{text-align:end;--x-rtl-end:"text-right -> text-end";}
+ .hover\\:text-right:hover{text-align:end;--x-rtl-end:"hover:text-right -> hover:text-end";}
+ /* layer: default */
+ .pl-1{padding-inline-start:calc(var(--spacing) * 1);}
+ .pr-1{padding-inline-end:calc(var(--spacing) * 1);}
+ .ml-1{margin-inline-start:calc(var(--spacing) * 1);}
+ .mr-1{margin-inline-end:calc(var(--spacing) * 1);}
+ .left-0{inset-inline-start:calc(var(--spacing) * 0);}
+ .position-left-4{inset-inline-start:calc(var(--spacing) * 4);}
+ .right-0{inset-inline-end:calc(var(--spacing) * 0);}
+ .rounded-l{border-end-start-radius:0.25rem;border-start-start-radius:0.25rem;}
+ .rounded-r{border-start-end-radius:0.25rem;border-end-end-radius:0.25rem;}
+ .border-l{border-inline-start-width:1px;}
+ .border-r{border-inline-end-width:1px;}
+ @media (min-width: 40rem){
+ .sm\\:pl-2{padding-inline-start:calc(var(--spacing) * 2);}
+ }"
`)
const warnings = warnSpy.mock.calls.flat()
@@ -81,28 +81,28 @@ describe('uno-preset-rtl', () => {
)
expect(css).toMatchInlineSnapshot(`
- "/* layer: theme */
- :root, :host { --font-sans: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"; --font-mono: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; --default-font-family: var(--font-sans); --default-monoFont-family: var(--font-mono); }
- /* layer: base */
- *, ::after, ::before, ::backdrop, ::file-selector-button { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; } html, :host { line-height: 1.5; -webkit-text-size-adjust: 100%; tab-size: 4; font-family: var( --default-font-family, ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji' ); font-feature-settings: var(--default-font-featureSettings, normal); font-variation-settings: var(--default-font-variationSettings, normal); -webkit-tap-highlight-color: transparent; } hr { height: 0; color: inherit; border-top-width: 1px; } abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } a { color: inherit; -webkit-text-decoration: inherit; text-decoration: inherit; } b, strong { font-weight: bolder; } code, kbd, samp, pre { font-family: var( --default-monoFont-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace ); font-feature-settings: var(--default-monoFont-featureSettings, normal); font-variation-settings: var(--default-monoFont-variationSettings, normal); font-size: 1em; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } table { text-indent: 0; border-color: inherit; border-collapse: collapse; } :-moz-focusring { outline: auto; } progress { vertical-align: baseline; } summary { display: list-item; } ol, ul, menu { list-style: none; } img, svg, video, canvas, audio, iframe, embed, object { display: block; vertical-align: middle; } img, video { max-width: 100%; height: auto; } button, input, select, optgroup, textarea, ::file-selector-button { font: inherit; font-feature-settings: inherit; font-variation-settings: inherit; letter-spacing: inherit; color: inherit; border-radius: 0; background-color: transparent; opacity: 1; } :where(select:is([multiple], [size])) optgroup { font-weight: bolder; } :where(select:is([multiple], [size])) optgroup option { padding-inline-start: 20px; } ::file-selector-button { margin-inline-end: 4px; } ::placeholder { opacity: 1; } @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) { ::placeholder { color: color-mix(in oklab, currentcolor 50%, transparent); } } textarea { resize: vertical; } ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-date-and-time-value { min-height: 1lh; text-align: inherit; } ::-webkit-datetime-edit { display: inline-flex; } ::-webkit-datetime-edit-fields-wrapper { padding: 0; } ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field { padding-block: 0; } ::-webkit-calendar-picker-indicator { line-height: 1; } :-moz-ui-invalid { box-shadow: none; } button, input:where([type='button'], [type='reset'], [type='submit']), ::file-selector-button { appearance: button; } ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } [hidden]:where(:not([hidden~='until-found'])) { display: none !important; }
- /* layer: default */
- .force-pl-1{padding-left:0.25rem;}
- .force-pr-1{padding-right:0.25rem;}
- .force-ml-1{margin-left:0.25rem;}
- .force-mr-1{margin-right:0.25rem;}
- .force-left-0{left:0;}
- .force-position-left-4{left:1rem;}
- .force-right-0{right:0;}
- .force-text-left{text-align:left;}
- .force-text-right{text-align:right;}
- .hover\\:force-text-right:hover{text-align:right;}
- .force-rounded-l{border-top-left-radius:0.25rem;border-bottom-left-radius:0.25rem;}
- .force-rounded-r{border-top-right-radius:0.25rem;border-bottom-right-radius:0.25rem;}
- .force-border-l{border-left-width:1px;}
- .force-border-r{border-right-width:1px;}
- @media (min-width: 40rem){
- .sm\\:force-pl-2{padding-left:0.5rem;}
- }"
+ "/* layer: theme */
+ :root, :host { --font-sans: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"; --font-mono: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; --default-font-family: var(--font-sans); --default-monoFont-family: var(--font-mono); }
+ /* layer: base */
+ *, ::after, ::before, ::backdrop, ::file-selector-button { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; } html, :host { line-height: 1.5; -webkit-text-size-adjust: 100%; tab-size: 4; font-family: var( --default-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', 'Noto Sans', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji' ); font-feature-settings: var(--default-font-featureSettings, normal); font-variation-settings: var(--default-font-variationSettings, normal); -webkit-tap-highlight-color: transparent; } hr { height: 0; color: inherit; border-top-width: 1px; } abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } a { color: inherit; -webkit-text-decoration: inherit; text-decoration: inherit; } b, strong { font-weight: bolder; } code, kbd, samp, pre { font-family: var( --default-monoFont-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace ); font-feature-settings: var(--default-monoFont-featureSettings, normal); font-variation-settings: var(--default-monoFont-variationSettings, normal); font-size: 1em; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } table { text-indent: 0; border-color: inherit; border-collapse: collapse; } :-moz-focusring:where(:not(iframe)) { outline: auto; } progress { vertical-align: baseline; } summary { display: list-item; } ol, ul, menu { list-style: none; } img, svg, video, canvas, audio, iframe, embed, object { display: block; vertical-align: middle; } img, video { max-width: 100%; height: auto; } button, input, select, optgroup, textarea, ::file-selector-button { font: inherit; font-feature-settings: inherit; font-variation-settings: inherit; letter-spacing: inherit; color: inherit; border-radius: 0; background-color: transparent; opacity: 1; } :where(select:is([multiple], [size])) optgroup { font-weight: bolder; } :where(select:is([multiple], [size])) optgroup option { padding-inline-start: 20px; } ::file-selector-button { margin-inline-end: 4px; } ::placeholder { opacity: 1; } @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) { ::placeholder { color: color-mix(in oklab, currentcolor 50%, transparent); } } textarea { resize: vertical; } ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-date-and-time-value { min-height: 1lh; text-align: inherit; } ::-webkit-datetime-edit { display: inline-flex; } ::-webkit-datetime-edit-fields-wrapper { padding: 0; } ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field { padding-block: 0; } ::-webkit-calendar-picker-indicator { line-height: 1; } :-moz-ui-invalid { box-shadow: none; } button, input:where([type='button'], [type='reset'], [type='submit']), ::file-selector-button { appearance: button; } ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } [hidden]:where(:not([hidden~='until-found'])) { display: none !important; }
+ /* layer: default */
+ .force-pl-1{padding-left:0.25rem;}
+ .force-pr-1{padding-right:0.25rem;}
+ .force-ml-1{margin-left:0.25rem;}
+ .force-mr-1{margin-right:0.25rem;}
+ .force-left-0{left:0;}
+ .force-position-left-4{left:1rem;}
+ .force-right-0{right:0;}
+ .force-text-left{text-align:left;}
+ .force-text-right{text-align:right;}
+ .hover\\:force-text-right:hover{text-align:right;}
+ .force-rounded-l{border-top-left-radius:0.25rem;border-bottom-left-radius:0.25rem;}
+ .force-rounded-r{border-top-right-radius:0.25rem;border-bottom-right-radius:0.25rem;}
+ .force-border-l{border-left-width:1px;}
+ .force-border-r{border-right-width:1px;}
+ @media (min-width: 40rem){
+ .sm\\:force-pl-2{padding-left:0.5rem;}
+ }"
`)
const warnings = warnSpy.mock.calls.flat()
diff --git a/uno.config.ts b/uno.config.ts
index dc73136a78..ef17a19781 100644
--- a/uno.config.ts
+++ b/uno.config.ts
@@ -24,7 +24,7 @@ export default defineConfig({
'**/OgImage/*.takumi.vue',
],
include: [
- /\.(vue|mdx|html)($|\?)/,
+ /\.(vue|md|mdx|html)($|\?)/,
// git provider icons composable
'**/composables/useProviderIcon.ts',
// Shared chart annotator icon classes
diff --git a/uno.theme.ts b/uno.theme.ts
index 0814d100fc..02fa988adb 100644
--- a/uno.theme.ts
+++ b/uno.theme.ts
@@ -7,6 +7,9 @@ export const theme = {
sans: "'Geist', 'IBM Plex Sans Arabic', system-ui, -apple-system, sans-serif",
noodle: "'Baloo 2', sans-serif",
},
+ container: {
+ prose: '44.6875rem', // 65ch in Geist at 16px
+ },
text: {
'2xs': { fontSize: '0.6875rem' }, // 11px
'3xs': { fontSize: '0.625rem' }, // 10px
diff --git a/vercel.json b/vercel.json
index 351f0d4bf9..9cf5edbee1 100644
--- a/vercel.json
+++ b/vercel.json
@@ -101,6 +101,26 @@
}
],
"destination": "https://main.npmx.dev/translation-status"
+ },
+ {
+ "source": "/blog/og/release-0_8.png",
+ "destination": "/blog/assets/release/0.8/og.png",
+ "permanent": true
+ },
+ {
+ "source": "/blog/og/release-crystal-chronicle.png",
+ "destination": "/blog/assets/release/crystal-chronicle/og.png",
+ "permanent": true
+ },
+ {
+ "source": "/blog/og/release-rainbow-comet.png",
+ "destination": "/blog/assets/release/rainbow-comet/og.png",
+ "permanent": true
+ },
+ {
+ "source": "/blog/og/release-photon-genesis.png",
+ "destination": "/blog/assets/release/photon-genesis/og.png",
+ "permanent": true
}
]
}
diff --git a/vite.config.ts b/vite.config.ts
index 404d364bff..ac2755b567 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -6,25 +6,35 @@ import { createRequire } from 'node:module'
const rootDir = import.meta.dirname
/**
- * Nuxt >= 4.5 auto-imports `$fetch` from a generated `fetch.mjs`, which copies
- * `globalThis.$fetch` into a module-scoped binding at import time. Component tests replace the
- * global with `vi.stubGlobal('$fetch', ...)` after the Nuxt app has been imported, so the binding
- * has to resolve the global on every call for those stubs to be visible to application code.
+ * The generated `#build/fetch` module binds `$fetch` to a module-scoped copy of `globalThis.$fetch`
+ * at import time. Component tests replace the global with `vi.stubGlobal('$fetch', ...)` after the
+ * Nuxt app has been imported, so the binding has to resolve the global on every call.
*/
function liveDollarFetch() {
- const SNAPSHOT_RE = /export const \$fetch = globalThis\.\$fetch/
- return {
- name: 'npmx:test:live-dollar-fetch',
- transform(code: string, id: string) {
- if (!id.startsWith('virtual:nuxt:') || !SNAPSHOT_RE.test(code)) return
- return code.replace(
- SNAPSHOT_RE,
- `export const $fetch = new Proxy(function () {}, {
+ const CLIENT_BINDING_RE =
+ /export const \$fetch = \/\*#__PURE__\*\/ \(\(\) => globalThis\.\$fetch \|\|= _\$fetch\.create\(\{ baseURL: baseURL\(\) \}\)\)\(\)/
+ const SERVER_BINDING_RE = /export const \$fetch = globalThis\.\$fetch/
+ const RESOLVE_GLOBAL = `new Proxy(function () {}, {
apply: (_target, _thisArg, args) => globalThis.$fetch(...args),
get: (_target, property) => Reflect.get(globalThis.$fetch, property),
has: (_target, property) => Reflect.has(globalThis.$fetch, property),
-})`,
- )
+})`
+ return {
+ name: 'npmx:test:live-dollar-fetch',
+ transform(code: string, id: string) {
+ if (!id.startsWith('virtual:nuxt:')) return
+ if (CLIENT_BINDING_RE.test(code)) {
+ return code.replace(
+ CLIENT_BINDING_RE,
+ `export const $fetch = /*#__PURE__*/ (() => {
+ globalThis.$fetch ||= _$fetch.create({ baseURL: baseURL() })
+ return ${RESOLVE_GLOBAL}
+})()`,
+ )
+ }
+ if (SERVER_BINDING_RE.test(code)) {
+ return code.replace(SERVER_BINDING_RE, `export const $fetch = ${RESOLVE_GLOBAL}`)
+ }
},
}
}