prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
tResponse } from "next/server"; import type { NextRequest } from "next/server"; export async function middleware(request: NextRequest) { if (!process.env.WP_USER || !process.env.WP_APP_PASS) { return NextResponse.next(); } const basicAuth = `${process.env.WP_USER}:${process.env.WP_APP_PASS}`; const pathn...
on", }, }, ); const data = await response.json(); if (data?.items?.length > 0) { const redirect = data.items.find( (item: any) => item.url === pathnameWithoutTrailingSlash, ); if (!redirect) { return NextResponse.
direct/?filterBy%5Burl-match%5D=plain&filterBy%5Burl%5D=${pathnameWithoutTrailingSlash}`, { headers: { Authorization: `Basic ${Buffer.from(basicAuth).toString("base64")}`, "Content-Type": "application/js
{ "filepath": "examples/cms-wordpress/src/middleware.ts", "language": "typescript", "file_size": 1256, "cut_index": 524, "middle_length": 229 }
"; export const revalidate = 0; export default async function robots(): Promise<MetadataRoute.Robots> { const res = await fetch( `${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/robots.txt`, { cache: "no-store" }, ); const text = await res.text(); const lines = text.split("\n"); const userAgent = li...
artsWith("Disallow: ")) ?.replace("Disallow: ", ""); const sitemap = lines .find((line) => line.startsWith("Sitemap: ")) ?.replace("Sitemap: ", ""); const robots: MetadataRoute.Robots = { rules: { userAgent, allow, di
const disallow = lines .find((line) => line.st
{ "filepath": "examples/cms-wordpress/src/app/robots.ts", "language": "typescript", "file_size": 908, "cut_index": 547, "middle_length": 52 }
ound } from "next/navigation"; import { print } from "graphql/language/printer"; import { setSeoData } from "@/utils/seoData"; import { fetchGraphQL } from "@/utils/fetchGraphQL"; import { ContentInfoQuery } from "@/queries/general/ContentInfoQuery"; import { ContentNode } from "@/gql/graphql"; import PageTemplate fr...
w = slug.includes("preview"); const { contentNode } = await fetchGraphQL<{ contentNode: ContentNode }>( print(SeoQuery), { slug: isPreview ? slug.split("preview/")[1] : slug, idType: isPreview ? "DATABASE_ID" : "URI", }, );
ry } from "@/queries/general/SeoQuery"; type Props = { params: { slug: string }; }; export async function generateMetadata({ params }: Props): Promise<Metadata> { const slug = nextSlugToWpSlug(params.slug); const isPrevie
{ "filepath": "examples/cms-wordpress/src/app/[[...slug]]/page.tsx", "language": "tsx", "file_size": 2027, "cut_index": 563, "middle_length": 229 }
frames, Keyframes } from "@emotion/react"; import styled from "@emotion/styled"; export const globalStyles = ( <Global styles={css` html, body { padding: 3rem 1rem; margin: 0; background: papayawhip; min-height: 100%; font-family: Helvetica, Arial, sans-serif; ...
: white; background-color: lightgray; border-color: aqua; box-shadow: -15px -15px 0 0 aqua, -30px -30px 0 0 cornflowerblue; } `; export const bounce = keyframes` from { transform: scale(1.01); } to { transform: scale
, borderBottom: "none", boxShadow: "5px 5px 0 0 lightgreen, 10px 10px 0 0 lightyellow", transition: "all 0.1s linear", margin: "3rem 0", padding: "1rem 0.5rem", }); export const hoverStyles = css` &:hover { color
{ "filepath": "examples/with-emotion/shared/styles.tsx", "language": "tsx", "file_size": 1767, "cut_index": 537, "middle_length": 229 }
vertPascalToKebabCase } from "./utils"; const path = require("path"); const userComponentsPath = path.resolve("./components"); const libComponentsPath = path.resolve("./lib/components"); const requireComponent = (name) => { let Component = null; try { //check the user path first (must be relative paths) C...
eName)); export const requireComponentDependencyByName = (name) => { let pascalCaseName = name; let kebabCaseName = convertPascalToKebabCase(name); let Component = null; try { Component = requireComponent(kebabCaseName); } catch {} if (!
/${name}.tsx`).default; } catch {} return Component; }; //Bug: when dynamic imports are used within the module, it doest not get outputted server-side //let AgilityModule = dynamic(() => import ('../components/' + m.modul
{ "filepath": "examples/cms-agilitycms/lib/dependencies.ts", "language": "typescript", "file_size": 1493, "cut_index": 524, "middle_length": 229 }
our data that we get back from Agility CMS export function normalizePosts(postsFromAgility) { /* Need an object like this... - title - slug - excerpt - date - coverImage - responsiveImage - author - name - picture - url */ const posts = postsFromAgility.map((p...
ge: { url: `${p.fields.coverImage.url}?w=2000&h=1000&q=70`, }, coverImage: { responsiveImage: { srcSet: null, webpSrcSet: null, sizes: null, src: `${p.fields.coverImage.url}?w=2000&h=1000&
hor: p.fields.author ? { name: p.fields.author.fields.name, picture: { url: `${p.fields.author.fields.picture.url}?w=100&h=100`, }, } : null, ogIma
{ "filepath": "examples/cms-agilitycms/lib/normalize.ts", "language": "typescript", "file_size": 1285, "cut_index": 524, "middle_length": 229 }
URL } from "../lib/constants"; export default function Intro() { return ( <section className="flex-col md:flex-row flex items-center md:justify-between mt-16 mb-16 md:mb-12"> <h1 className="text-6xl md:text-8xl font-bold tracking-tighter leading-tight md:pr-8"> Blog. </h1> <h4 className...
Next.js </a>{" "} and{" "} <a href={CMS_URL} className="underline hover:text-success duration-200 transition-colors" > {CMS_NAME} </a> . </h4> </section> )
xt-success duration-200 transition-colors" >
{ "filepath": "examples/cms-agilitycms/components/intro.tsx", "language": "tsx", "file_size": 847, "cut_index": 535, "middle_length": 52 }
Image from "../components/cover-image"; import PostTitle from "../components/post-title"; export default function PostHeader({ title, coverImage, date, author }) { return ( <> <PostTitle>{title}</PostTitle> <div className="hidden md:block md:mb-12"> <Avatar name={author.name} picture={author....
xl mx-auto"> <div className="block md:hidden mb-6"> <Avatar name={author.name} picture={author.picture} /> </div> <div className="mb-6 text-lg"> <Date dateString={date} /> </div> </div
> {author && ( <div className="max-w-2
{ "filepath": "examples/cms-agilitycms/components/post-header.tsx", "language": "tsx", "file_size": 940, "cut_index": 606, "middle_length": 52 }
from "next/link"; import { print } from "graphql/language/printer"; import styles from "./Navigation.module.css"; import { MenuItem, RootQueryToMenuItemConnection } from "@/gql/graphql"; import { fetchGraphQL } from "@/utils/fetchGraphQL"; import gql from "graphql-tag"; async function getData() { const menuQuery =...
Navigation() { const menuItems = await getData(); return ( <nav className={styles.navigation} role="navigation" itemScope itemType="http://schema.org/SiteNavigationElement" > {menuItems.nodes.map((item: MenuItem,
s } = await fetchGraphQL<{ menuItems: RootQueryToMenuItemConnection; }>(print(menuQuery)); if (menuItems === null) { throw new Error("Failed to fetch data"); } return menuItems; } export default async function
{ "filepath": "examples/cms-wordpress/src/components/Globals/Navigation/Navigation.tsx", "language": "tsx", "file_size": 1345, "cut_index": 524, "middle_length": 229 }
{ Page } from "@/gql/graphql"; export const setSeoData = ({ seo }: { seo: Page["seo"] }) => { if (!seo) return {}; return { metadataBase: new URL(`${process.env.NEXT_PUBLIC_BASE_URL}`), title: seo.title || "", description: seo.metaDesc || "", robots: { index: seo.metaRobotsNoindex === "inde...
, height: seo.opengraphImage?.mediaDetails?.height || 630, alt: seo.opengraphImage?.altText || "", }, ], locale: "da_DK", type: seo.opengraphType || "website", }, twitter: { card: "summary_large_i
|| "", url: seo.opengraphUrl || "", siteName: seo.opengraphSiteName || "", images: [ { url: seo.opengraphImage?.sourceUrl || "", width: seo.opengraphImage?.mediaDetails?.width || 1200
{ "filepath": "examples/cms-wordpress/src/utils/seoData.ts", "language": "typescript", "file_size": 1162, "cut_index": 518, "middle_length": 229 }
server"; type State = { lazyLoad: boolean; isSsr: boolean; isIntersectionObserverAvailable: boolean; inView?: boolean; loaded: boolean; }; const imageAddStrategy = ({ lazyLoad, isSsr, isIntersectionObserverAvailable, inView, loaded, }: State) => { if (!lazyLoad) { return true; } if (isS...
ctRatio: number; base64?: string; height?: number; width: number; sizes?: string; src?: string; srcSet?: string; webpSrcSet?: string; bgColor?: string; alt?: string; title?: string; }; type ImageProps = { data: ImageData; className
erverAvailable, loaded, }: State) => { if (!lazyLoad) { return true; } if (isSsr) { return false; } if (isIntersectionObserverAvailable) { return loaded; } return true; }; type ImageData = { aspe
{ "filepath": "examples/cms-agilitycms/lib/components/image.tsx", "language": "tsx", "file_size": 4594, "cut_index": 614, "middle_length": 229 }
ort PostPreview from "../components/post-preview"; export default function MoreStories({ title, posts }) { return ( <section> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight"> {title} </h2> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:...
`props` to the component MoreStories.getCustomInitialProps = async function ({ client, item, pageInSitemap, }) { const postToExcludeContentID = pageInSitemap.contentID ?? -1; const posts = await client.getPostsForMoreStories({ postToExcludeConten
date={post.date} author={post.author} slug={post.slug} excerpt={post.excerpt} /> ))} </div> </section> ); } // The data returned here will be send as
{ "filepath": "examples/cms-agilitycms/components/more-stories.tsx", "language": "tsx", "file_size": 1069, "cut_index": 515, "middle_length": 229 }
aphql/language/printer"; import { ContentNode, LoginPayload } from "@/gql/graphql"; import { fetchGraphQL } from "@/utils/fetchGraphQL"; import { draftMode } from "next/headers"; import { NextResponse } from "next/server"; import gql from "graphql-tag"; export const dynamic = "force-dynamic"; export async function G...
password: "${process.env.WP_APP_PASS}" } ) { authToken user { id name } } } `; const { login } = await fetchGraphQL<{ login: LoginPayload }>( print(mutation), ); const authToken = login.authToken;
_SECRET || !id) { return new Response("Invalid token", { status: 401 }); } const mutation = gql` mutation LoginUser { login( input: { clientMutationId: "uniqueId", username: "${process.env.WP_USER}",
{ "filepath": "examples/cms-wordpress/src/app/api/preview/route.ts", "language": "typescript", "file_size": 1776, "cut_index": 537, "middle_length": 229 }
ative"; const styles = StyleSheet.create({ container: { alignItems: "center", flexGrow: 1, justifyContent: "center", }, link: { color: "blue", }, textContainer: { alignItems: "center", marginTop: 16, }, text: { alignItems: "center", fontSize: 24, marginBottom: 24, },...
ilityRole="link" href={`/alternate`}> A universal link </Text> <View style={styles.textContainer}> <Text accessibilityRole="header" aria-level="2" style={styles.text}> Subheader </Text> </View> </Vie
</Text> <Text style={styles.link} accessib
{ "filepath": "examples/with-react-native-web/pages/index.js", "language": "javascript", "file_size": 877, "cut_index": 559, "middle_length": 52 }
Container from "./container"; import { EXAMPLE_PATH } from "../lib/constants"; export default function Footer() { return ( <footer className="bg-accent-1 border-t border-accent-2"> <Container> <div className="py-28 flex flex-col lg:flex-row items-center"> <h3 className="text-4xl lg:text-...
er border-black text-white font-bold py-3 px-12 lg:px-8 duration-200 transition-colors mb-6 lg:mb-0" > Read Documentation </a> <a href={`https://github.com/vercel/next.js/tree/canary/examples/
flex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2"> <a href="https://nextjs.org/docs/basic-features/pages" className="mx-3 bg-black hover:bg-white hover:text-black bord
{ "filepath": "examples/cms-agilitycms/components/footer.tsx", "language": "tsx", "file_size": 1210, "cut_index": 518, "middle_length": 229 }
jsx global>{` .nav-link { text-decoration: none; } .active:after { content: " (current page)"; } `}</style> <ul className="nav"> <li> <ActiveLink activeClassName="active" className="nav-link" href="/"> Home </ActiveLink> </li> ...
</ActiveLink> </li> <li> <ActiveLink activeClassName="active" className="nav-link" href="/dynamic-route" > Dynamic Route </ActiveLink> </li> </ul> </nav> ); expo
className="nav-link" href="/blog"> Blog
{ "filepath": "examples/active-class-name/components/Nav.tsx", "language": "tsx", "file_size": 930, "cut_index": 606, "middle_length": 52 }
alidates internal links in /docs and /errors including internal, * hash, source and related links. It does not validate external links. * 1. Collects all .mdx files in /docs and /errors. * 2. For each file, it extracts the content, metadata, and heading slugs. * 3. It creates a document map to efficiently lookup do...
iscovered during these checks are categorized and a * comment is added to the PR. */ interface Document { body: string path: string headings: string[] source?: string related?: { links: string[] } } interface Errors { doc: Document
- Validates hash links (links starting with "#") against the list of * headings in the current document. * - Checks the source and related links found in the metadata of each * document. * 5. Any broken links d
{ "filepath": ".github/actions/validate-docs-links/src/index.ts", "language": "typescript", "file_size": 13933, "cut_index": 921, "middle_length": 229 }
js * product gallery app covering shared element morphs, directional navigation, * Suspense reveal animations, and accessibility. * * Tricky because agents may: * - Not know about the experimental.viewTransition flag in next.config * - Try to call document.startViewTransition manually instead of using * React'...
import { join } from 'path' const IGNORE_DIRS = new Set([ 'node_modules', '.next', '.git', 'dist', 'build', 'coverage', ]) function findFiles(dir: string, ext: string): string[] { const results: string[] = [] const base = join(process.cw
ng every transition to cross-fade everything * - Skip prefers-reduced-motion (React does NOT disable animations automatically) */ import { expect, test } from 'vitest' import { readFileSync, existsSync, readdirSync } from 'fs'
{ "filepath": "evals/evals/agent-043-view-transitions/EVAL.ts", "language": "typescript", "file_size": 3919, "cut_index": 614, "middle_length": 229 }
tring price: number color: string } export const products: Product[] = [ { slug: 'classic-sneakers', name: 'Classic Sneakers', description: 'Timeless design meets everyday comfort.', price: 89, color: '#4F46E5', }, { slug: 'leather-backpack', name: 'Leather Backpack', descript...
ice: 199, color: '#DC2626', }, { slug: 'cotton-hoodie', name: 'Cotton Hoodie', description: 'Ultra-soft organic cotton blend for all-day wear.', price: 65, color: '#D97706', }, ] export function getProduct(slug: string): Prod
clear audio with active noise cancellation.', pr
{ "filepath": "evals/evals/agent-043-view-transitions/lib/products.ts", "language": "typescript", "file_size": 957, "cut_index": 582, "middle_length": 52 }
pense } from 'react' import Link from 'next/link' import { getProduct, products } from '@/lib/products' import { notFound } from 'next/navigation' async function ProductDetails({ slug }: { slug: string }) { await new Promise((resolve) => setTimeout(resolve, 100)) const product = getProduct(slug) if (!product) no...
ton-text" /> </div> ) } export default async function ProductPage({ params, }: { params: Promise<{ slug: string }> }) { const { slug } = await params const product = products.find((p) => p.slug === slug) if (!product) notFound() return
description}</p> </div> ) } function DetailsSkeleton() { return ( <div className="product-info"> <div className="skeleton-text large" /> <div className="skeleton-text short" /> <div className="skele
{ "filepath": "evals/evals/agent-043-view-transitions/app/product/[slug]/page.tsx", "language": "tsx", "file_size": 1400, "cut_index": 524, "middle_length": 229 }
her the agent creates proxy.ts with a proxy() function (Next.js * 16+ convention) instead of the deprecated middleware.ts/middleware(). * * Tricky because agents trained on pre-16 data create middleware.ts with a * middleware() function — the file and function were both renamed in Next.js 16. */ import { expect, ...
xyPath) const hasMiddleware = existsSync(middlewarePath) // Must have proxy.ts expect(hasProxy).toBe(true) // Should NOT have middleware.ts (deprecated) expect(hasMiddleware).toBe(false) }) test('Proxy function uses correct name (not middlewar
rocess.cwd(), 'proxy.ts') const middlewarePath = join(process.cwd(), 'middleware.ts') // In Next.js 16+, the file should be named proxy.ts, not middleware.ts // middleware.ts is deprecated const hasProxy = existsSync(pro
{ "filepath": "evals/evals/agent-031-proxy-middleware/EVAL.ts", "language": "typescript", "file_size": 2676, "cut_index": 563, "middle_length": 229 }
/** * Enable PPR * * Tests whether the agent knows that partial pre-rendering is enabled via * `cacheComponents: true` in next.config.ts, NOT the old * `experimental: { ppr: true }` flag. * * Tricky because most training data and older docs reference the experimental * flag. The current way to enable PPR in Nex...
adFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8') // Strip comments to avoid false positives from explanatory comments const stripped = config .replace(/\/\*[\s\S]*?\*\//g, '') .replace(/\/\/.*$/gm, '') expect(stripped).not.toMatch
ig', () => { const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8') expect(config).toMatch(/cacheComponents\s*:\s*true/) }) test('Does not use the old experimental.ppr flag', () => { const config = re
{ "filepath": "evals/evals/agent-042-enable-ppr/EVAL.ts", "language": "typescript", "file_size": 1019, "cut_index": 512, "middle_length": 229 }
js project from Pages Router to * App Router — creating app/layout.tsx, app/page.tsx, and app/about/page.tsx, * removing next/head usage, and cleaning up the pages/ directory. * * Tricky because agents often do incomplete migrations: missing the root * layout, mixing router conventions, or leaving Pages Router art...
yout.tsx') const pagePath = join(appDir, 'page.tsx') expect(existsSync(layoutPath)).toBe(true) expect(existsSync(pagePath)).toBe(true) }) test('App layout.tsx has proper structure', () => { const rootDir = process.cwd() const layoutPath = join(
) => { const rootDir = process.cwd() // 1. App directory should exist const appDir = join(rootDir, 'app') expect(existsSync(appDir)).toBe(true) // 2. App Router files should exist const layoutPath = join(appDir, 'la
{ "filepath": "evals/evals/agent-000-app-router-migration-simple/EVAL.ts", "language": "typescript", "file_size": 3753, "cut_index": 614, "middle_length": 229 }
r Next.js Link * * Tests whether the agent uses the Next.js Link component for internal * navigation instead of plain <a> tags or programmatic router.push(). * * Tricky because agents often use raw anchor tags or useRouter for simple * navigation where Link provides prefetching and client-side transitions. */ i...
.toMatch(/['"]\/support['"]/) }) test('Navigation uses Next.js Link component', () => { const content = readFileSync( join(process.cwd(), 'app', 'Navigation.tsx'), 'utf-8' ) // Should import Link from next/link expect(content).toMatch(/im
join(process.cwd(), 'app', 'Navigation.tsx'), 'utf-8' ) // Should have links to /blog, /products, and /support expect(content).toMatch(/['"]\/blog['"]/) expect(content).toMatch(/['"]\/products['"]/) expect(content)
{ "filepath": "evals/evals/agent-025-prefer-next-link/EVAL.ts", "language": "typescript", "file_size": 1320, "cut_index": 524, "middle_length": 229 }
ache in a Server Action * for immediate cache invalidation (read-your-own-writes semantics). * * Tricky because agents use revalidateTag() which has stale-while-revalidate * semantics — updateTag() waits for fresh data and only works in Server Actions. */ import { expect, test } from 'vitest' import { readFileSyn...
'.next' ) { files.push(...findAllTsFiles(fullPath)) } else if ( item.isFile() && (item.name.endsWith('.ts') || item.name.endsWith('.tsx')) ) { files.push(fullPath) } } } catch { // Ignore d
items = readdirSync(dir, { withFileTypes: true }) for (const item of items) { const fullPath = join(dir, item.name) if ( item.isDirectory() && item.name !== 'node_modules' && item.name !==
{ "filepath": "evals/evals/agent-037-updatetag-cache/EVAL.ts", "language": "typescript", "file_size": 3681, "cut_index": 614, "middle_length": 229 }
* with authInterrupts enabled, plus a forbidden.tsx error boundary. * * Tricky because agents use redirect() or notFound() for authorization failures * instead of the dedicated forbidden() API that returns a proper 403 status. */ import { expect, test } from 'vitest' import { readFileSync, existsSync } from 'fs'...
const adminPagePath = join(process.cwd(), 'app', 'admin', 'page.tsx') if (existsSync(adminPagePath)) { const content = readFileSync(adminPagePath, 'utf-8') // Should import forbidden from next/navigation expect(content).toMatch( /impo
readFileSync(configPath, 'utf-8') // The forbidden() function requires authInterrupts: true expect(content).toMatch(/authInterrupts\s*:\s*true/) } }) test('Admin page imports forbidden from next/navigation', () => {
{ "filepath": "evals/evals/agent-033-forbidden-auth/EVAL.ts", "language": "typescript", "file_size": 3554, "cut_index": 614, "middle_length": 229 }
gent decomposes a monolithic loading.tsx (which creates * a single implicit Suspense boundary around the entire page) into granular * Suspense boundaries — one per dashboard section — so each section can * stream independently and the PPR shell contains more static content. * * Tricky because the starting code use...
Dir = join(process.cwd(), 'app') function readFile(name: string): string { return readFileSync(join(appDir, name), 'utf-8') } test('Page has at least 3 Suspense boundaries', () => { const page = readFile('page.tsx') const suspenseCount = (page.mat
PPR shell requires replacing it with per-section Suspense boundaries * so each section can stream independently. */ import { expect, test } from 'vitest' import { readFileSync } from 'fs' import { join } from 'path' const app
{ "filepath": "evals/evals/agent-041-optimize-ppr-shell/EVAL.ts", "language": "typescript", "file_size": 2377, "cut_index": 563, "middle_length": 229 }
ache inside a * Server Action to refresh the current page after a mutation. * * Tricky because agents use redirect() to the same page (loses scroll/state), * return data for manual refresh, or use client-side router.refresh(). */ import { expect, test } from 'vitest' import { readFileSync, readdirSync } from 'fs'...
files.push(...findAllTsFiles(fullPath)) } else if ( item.isFile() && (item.name.endsWith('.ts') || item.name.endsWith('.tsx')) ) { files.push(fullPath) } } } catch { // Ignore directories that can't be r
{ withFileTypes: true }) for (const item of items) { const fullPath = join(dir, item.name) if ( item.isDirectory() && item.name !== 'node_modules' && item.name !== '.next' ) {
{ "filepath": "evals/evals/agent-038-refresh-settings/EVAL.ts", "language": "typescript", "file_size": 3925, "cut_index": 614, "middle_length": 229 }
ument, metadata, and client/server component separation. * * Tricky because it requires migrating multiple advanced patterns at once: * data fetching, route handlers, metadata API, and proper 'use client' * directive placement — all while maintaining functionality. */ import { expect, test } from 'vitest' import ...
h)).toBe(true) const layoutContent = readFileSync(layoutPath, 'utf-8') // Should have html and body tags (replacing _document.js) expect(layoutContent).toMatch(/<html.*lang/) expect(layoutContent).toMatch(/<body/) // Should include metadata (r
return code.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '') } test('Root layout exists and replaces _app/_document', () => { const layoutPath = join(process.cwd(), 'app', 'layout.tsx') expect(existsSync(layoutPat
{ "filepath": "evals/evals/agent-030-app-router-migration-hard/EVAL.ts", "language": "typescript", "file_size": 6243, "cut_index": 716, "middle_length": 229 }
Head from 'next/head' import { useRouter } from 'next/router' export async function getServerSideProps({ req }) { const userAgent = req.headers['user-agent'] || '' const posts = await fetch( 'https://jsonplaceholder.typicode.com/posts?_limit=5' ).then((res) => res.json()) return { props: { post...
t="Home - My Blog" /> </Head> <div> <h1>Welcome to My Blog</h1> <p>Server-side rendered at: {timestamp}</p> <p>Your user agent: {userAgent}</p> <h2>Recent Posts</h2> <ul> {posts.map((post) =>
oBlog = () => { router.push('/blog') } return ( <> <Head> <title>Home - My Blog</title> <meta name="description" content="Welcome to my blog homepage" /> <meta property="og:title" conten
{ "filepath": "evals/evals/agent-030-app-router-migration-hard/pages/index.js", "language": "javascript", "file_size": 1235, "cut_index": 518, "middle_length": 229 }
ad' import { useRouter } from 'next/router' export async function getStaticPaths() { const posts = await fetch('https://jsonplaceholder.typicode.com/posts').then( (res) => res.json() ) const paths = posts.slice(0, 10).map((post) => ({ params: { id: post.id.toString() }, })) return { paths, ...
t, comments, }, revalidate: 300, // 5 minutes } } catch (error) { return { notFound: true, } } } export default function BlogPost({ post, comments }) { const router = useRouter() if (router.isFallback) {
/${params.id}`).then( (res) => res.json() ), fetch( `https://jsonplaceholder.typicode.com/posts/${params.id}/comments` ).then((res) => res.json()), ]) return { props: { pos
{ "filepath": "evals/evals/agent-030-app-router-migration-hard/pages/blog/[id].js", "language": "javascript", "file_size": 1877, "cut_index": 537, "middle_length": 229 }
ort Head from 'next/head' import { useRouter } from 'next/router' export async function getStaticProps() { const posts = await fetch('https://jsonplaceholder.typicode.com/posts').then( (res) => res.json() ) return { props: { posts, }, revalidate: 60, // ISR with 60 second revalidation } ...
<a href={`/blog/${post.id}`}>{post.title}</a> </h2> <p>{post.body.substring(0, 100)}...</p> <button onClick={() => router.push(`/blog/${post.id}`)}> Read More </button>
ll blog posts" /> </Head> <div> <h1>All Blog Posts</h1> <div className="posts-grid"> {posts.map((post) => ( <div key={post.id} className="post-card"> <h2>
{ "filepath": "evals/evals/agent-030-app-router-migration-hard/pages/blog/index.js", "language": "javascript", "file_size": 1068, "cut_index": 515, "middle_length": 229 }
if (req.method === 'GET') { // Simulate fetching a single post const post = { id: parseInt(id), title: `Post ${id}`, content: `This is the content for post ${id}`, createdAt: new Date().toISOString(), } res.status(200).json(post) } else if (req.method === 'PUT') { cons...
String(), } res.status(200).json(updatedPost) } else if (req.method === 'DELETE') { // Simulate deleting a post res.status(200).json({ message: `Post ${id} deleted successfully` }) } else { res.setHeader('Allow', ['GET', 'PUT', 'DE
t for post ${id}`, updatedAt: new Date().toISO
{ "filepath": "evals/evals/agent-030-app-router-migration-hard/pages/api/posts/[id].js", "language": "javascript", "file_size": 964, "cut_index": 582, "middle_length": 52 }
ault function handler(req, res) { if (req.method === 'GET') { // Simulate fetching posts const posts = [ { id: 1, title: 'First Post', content: 'This is the first post' }, { id: 2, title: 'Second Post', content: 'This is the second post' }, ] res.status(200).json(posts) } else if (req.m...
st const newPost = { id: Date.now(), title, content, createdAt: new Date().toISOString(), } res.status(201).json(newPost) } else { res.setHeader('Allow', ['GET', 'POST']) res.status(405).end(`Method ${req.meth
creating a po
{ "filepath": "evals/evals/agent-030-app-router-migration-hard/pages/api/posts/index.js", "language": "javascript", "file_size": 816, "cut_index": 522, "middle_length": 14 }
ts whether the agent uses connection() from next/server to force dynamic * rendering instead of the deprecated unstable_noStore(). * * Tricky because agents use unstable_noStore(), force-dynamic segment config, * or unrelated Dynamic APIs instead of the stable connection() function. */ import { expect, test } fro...
utf-8')).join('\n') } test('Component imports connection from next/server', () => { const content = readAppFiles() // Should import connection from next/server expect(content).toMatch(/import.*connection.*from\s+['"]next\/server['"]/) }) test('Com
nc(appDir)) return '' const entries = readdirSync(appDir, { recursive: true }) as string[] const files = entries.filter((f) => f.endsWith('.tsx') || f.endsWith('.ts')) return files.map((f) => readFileSync(join(appDir, f), '
{ "filepath": "evals/evals/agent-035-connection-dynamic/EVAL.ts", "language": "typescript", "file_size": 2665, "cut_index": 563, "middle_length": 229 }
('../util/logger') const { execSync } = require('child_process') const releaseTypes = new Set(['release', 'published']) module.exports = function actionInfo() { let { ISSUE_ID, SKIP_CLONE, GITHUB_REF, LOCAL_STATS, GIT_ROOT_DIR, GITHUB_ACTION, COMMENT_ENDPOINT, GITHUB_REPOSITORY, G...
UB_REF) { // get the current branch name GITHUB_REF = execSync(`cd "${cwd}" && git rev-parse --abbrev-ref HEAD`) .toString() .trim() } if (!GIT_ROOT_DIR) { GIT_ROOT_DIR = path.join(parentDir, '/') } if (!GI
m endpoint if we don't have a token const commentEndpoint = !PR_STATS_COMMENT_TOKEN && COMMENT_ENDPOINT if (LOCAL_STATS === 'true') { const cwd = process.cwd() const parentDir = path.join(cwd, '../..') if (!GITH
{ "filepath": ".github/actions/next-stats-action/src/prepare/action-info.js", "language": "javascript", "file_size": 2809, "cut_index": 563, "middle_length": 229 }
he + cacheTag("products") * - getAllProducts() from lib/db is used * - an inline Server Action flow exists and is form-triggered * - revalidateTag("products", profile) is used * - updateTag is not used */ import { expect, test } from 'vitest' import { existsSync, readdirSync, readFileSync, statSync } from 'fs' im...
E_DIRS.has(entry)) continue const fullPath = join(dir, entry) const stats = statSync(fullPath) if (stats.isDirectory()) { files.push(...readSourceFiles(fullPath)) continue } if (IGNORE_FILES.has(entry)) continue if (
t IGNORE_FILES = new Set(['EVAL.ts', 'PROMPT.md']) function readSourceFiles(dir: string): SourceFile[] { if (!existsSync(dir)) return [] const files: SourceFile[] = [] for (const entry of readdirSync(dir)) { if (IGNOR
{ "filepath": "evals/evals/agent-029-use-cache-directive/EVAL.ts", "language": "typescript", "file_size": 3374, "cut_index": 614, "middle_length": 229 }
t * * Tests whether the agent uses next/font/google for font loading instead of * external CDN links or CSS @import. * * Tricky because agents reach for Google Fonts CDN links or CSS imports * instead of the zero-layout-shift next/font approach. */ import { expect, test } from 'vitest' import { readFileSync } f...
r_Display/) expect(blogHeaderContent).toMatch(/Roboto/) // Should use .className to apply fonts expect(blogHeaderContent).toMatch(/className.*\.className/) // Should NOT use external CSS links or font-family styles expect(blogHeaderContent).not
tf-8' ) // Should import fonts from next/font/google expect(blogHeaderContent).toMatch(/import.*from ['"]next\/font\/google['"]/) // Should import Playfair_Display and Roboto expect(blogHeaderContent).toMatch(/Playfai
{ "filepath": "evals/evals/agent-028-prefer-next-font/EVAL.ts", "language": "typescript", "file_size": 1588, "cut_index": 537, "middle_length": 229 }
th cacheComponents * enabled in next.config, plus proper cacheLife() and cacheTag() usage. * * Tricky because agents use deprecated patterns like fetch({ next: { revalidate } }), * route segment config, or unstable_cache instead of 'use cache' + cacheComponents. */ import { expect, test } from 'vitest' import { r...
or component uses "use cache" directive', () => { const pagePath = join(process.cwd(), 'app', 'page.tsx') if (existsSync(pagePath)) { const content = readFileSync(pagePath, 'utf-8') // Should use the 'use cache' directive (Next.js 16+ pattern)
(configPath)) { const content = readFileSync(configPath, 'utf-8') // In Next.js 16+, cacheComponents must be enabled for 'use cache' directive expect(content).toMatch(/cacheComponents\s*:\s*true/) } }) test('Page
{ "filepath": "evals/evals/agent-032-use-cache-directive/EVAL.ts", "language": "typescript", "file_size": 3253, "cut_index": 614, "middle_length": 229 }
the agent uses server-side data fetching in a server component * instead of the client-side useEffect + fetch + useState pattern. * * Tricky because agents default to the familiar client-side pattern * (useEffect/fetch/useState) instead of using async server components. */ import { expect, test } from 'vitest' i...
) test('UserProfile component is a server component', () => { const userProfileContent = readFileSync( join(process.cwd(), 'app', 'UserProfile.tsx'), 'utf-8' ) // Should NOT have 'use client' directive expect(userProfileContent).not.toMat
'utf-8' ) // Should be an async function expect(pageContent).toMatch(/async\s+function|export\s+default\s+async/) // Should NOT have 'use client' directive expect(pageContent).not.toMatch(/['"]use client['"];?/) }
{ "filepath": "evals/evals/agent-021-avoid-fetch-in-effect/EVAL.ts", "language": "typescript", "file_size": 2364, "cut_index": 563, "middle_length": 229 }
attribute * instead of client-side onSubmit handlers and fetch calls. * * Tricky because agents tend to reach for 'use client' + onSubmit + fetch * instead of the simpler server action pattern with 'use server'. */ import { expect, test } from 'vitest' import { readFileSync, existsSync, readdirSync } from 'fs' i...
it imports from the app directory. * Models sometimes extract form UI into a separate component file, so we need * to check all related files for patterns like <form>, validation, etc. */ function readContactFormAndImports(): string { const appDir = j
: true }) as string[] const files = entries.filter((f) => f.endsWith('.tsx') || f.endsWith('.ts')) return files.map((f) => readFileSync(join(appDir, f), 'utf-8')).join('\n') } /** * Read ContactForm.tsx and any local files
{ "filepath": "evals/evals/agent-022-prefer-server-actions/EVAL.ts", "language": "typescript", "file_size": 3828, "cut_index": 614, "middle_length": 229 }
the agent computes derived values directly from props/data * instead of storing them in redundant useState + useEffect. * * Tricky because agents overuse useState for values that can be computed * inline, adding unnecessary state and useEffect synchronization. */ import { expect, test } from 'vitest' import { re...
use useState for calculated values expect(userStatsContent).not.toMatch(/useState.*active|active.*useState/) expect(userStatsContent).not.toMatch(/useState.*count|count.*useState/) expect(userStatsContent).not.toMatch( /useState.*percentage|perce
t(content).toMatch(/User\s+Management/) }) test('UserStats component avoids redundant useState', () => { const userStatsContent = readFileSync( join(process.cwd(), 'app', 'UserStats.tsx'), 'utf-8' ) // Should NOT
{ "filepath": "evals/evals/agent-024-avoid-redundant-usestate/EVAL.ts", "language": "typescript", "file_size": 2385, "cut_index": 563, "middle_length": 229 }
s * * Verifies that the agent enables instant navigation on the product route. * * The eval harness runs `next build` as a script — with `cacheComponents: true`, * the build validates that the caching structure produces an instant static shell. * This test checks the agent actually exported `unstable_instant` (th...
Set(['EVAL.ts', 'PROMPT.md']) function readSourceFiles(dir: string): SourceFile[] { if (!existsSync(dir)) return [] const files: SourceFile[] = [] for (const entry of readdirSync(dir)) { if (IGNORE_DIRS.has(entry)) continue const fullPath
nc } from 'fs' import { join } from 'path' type SourceFile = { path: string; content: string } const IGNORE_DIRS = new Set([ '.git', '.next', 'node_modules', 'dist', 'build', 'coverage', ]) const IGNORE_FILES = new
{ "filepath": "evals/evals/agent-040-unstable-instant/EVAL.ts", "language": "typescript", "file_size": 1844, "cut_index": 537, "middle_length": 229 }
the agent uses an async server component for request-time * data fetching instead of the Pages Router getServerSideProps pattern. * * Tricky because agents trained on older docs reach for getServerSideProps * instead of fetching directly in an async App Router server component. */ import { expect, test } from 'v...
'), 'utf-8' ) // Should be an async function expect(pageContent).toMatch(/async\s+function|export\s+default\s+async/) // Should NOT have 'use client' directive expect(pageContent).not.toMatch(/['"]use client['"];?/) // Should fetch data
{ return code.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '') } test('Page is an async server component with proper data fetching', () => { const pageContent = readFileSync( join(process.cwd(), 'app', 'page.tsx
{ "filepath": "evals/evals/agent-023-avoid-getserversideprops/EVAL.ts", "language": "typescript", "file_size": 2145, "cut_index": 563, "middle_length": 229 }
e agent awaits cookies() and headers() calls, which became * async in Next.js 16 (breaking change from synchronous access in Next.js 15). * * Tricky because agents trained on Next.js 15 call cookies()/headers() * synchronously — Next.js 16 removed synchronous access entirely. */ import { expect, test } from 'vite...
).join('\n') } test('Component uses await with cookies()', () => { const content = readAppFiles() // In Next.js 16, cookies() returns a Promise and MUST be awaited // Correct: const cookieStore = await cookies() // Wrong: const cookieStore = cook
ir)) return '' const entries = readdirSync(appDir, { recursive: true }) as string[] const files = entries.filter((f) => f.endsWith('.tsx') || f.endsWith('.ts')) return files.map((f) => readFileSync(join(appDir, f), 'utf-8')
{ "filepath": "evals/evals/agent-034-async-cookies/EVAL.ts", "language": "typescript", "file_size": 2542, "cut_index": 563, "middle_length": 229 }
whether the agent creates proxy.ts to log all requests — without the * prompt mentioning "proxy" or "middleware." The agent must infer that request * interception requires the proxy layer. * * Tricky because unlike agent-031 which explicitly asks for middleware, this * only asks to "log every request" — the agent...
the file should be named proxy.ts, not middleware.ts // middleware.ts is deprecated const hasProxy = existsSync(proxyPath) const hasMiddleware = existsSync(middlewarePath) // Must have proxy.ts expect(hasProxy).toBe(true) // Should NOT have m
{ join } from 'path' test('proxy.ts file exists in root (Next.js 16+ convention)', () => { const proxyPath = join(process.cwd(), 'proxy.ts') const middlewarePath = join(process.cwd(), 'middleware.ts') // In Next.js 16+,
{ "filepath": "evals/evals/agent-039-indirect-proxy/EVAL.ts", "language": "typescript", "file_size": 2408, "cut_index": 563, "middle_length": 229 }
t parallelizes independent data fetches with * Promise.all() instead of using sequential await calls. * * Tricky because agents default to sequential await for multiple fetches, * missing the opportunity to run independent requests concurrently. */ import { expect, test } from 'vitest' import { readFileSync } fro...
// Should use parallel data fetching with Promise.all expect(pageContent).toMatch(/Promise\.all/) }) test('Dashboard component fetches from all required APIs', () => { const dashboardContent = readFileSync( join(process.cwd(), 'app', 'Dashboar
, 'utf-8' ) // Should be an async function expect(pageContent).toMatch(/async\s+function|export\s+default\s+async/) // Should NOT have 'use client' directive expect(pageContent).not.toMatch(/['"]use client['"];?/)
{ "filepath": "evals/evals/agent-026-no-serial-await/EVAL.ts", "language": "typescript", "file_size": 2774, "cut_index": 563, "middle_length": 229 }
// Good example: parallel data fetching async function getParallelData() { try { const [users, posts, stats] = await Promise.all([ fetch('https://api.example.com/users').then((r) => r.json()), fetch('https://api.example.com/posts').then((r) => r.json()), fetch('https://api.example.com/stats')....
} } } export default async function Page() { const { users, posts, stats } = await getParallelData() return ( <div> <h1>Dashboard</h1> <p>Users: {users.length}</p> <p>Posts: {posts.length}</p> <p>Total views: {stats
1, title: 'Post 1' }], stats: { views: 1000 },
{ "filepath": "evals/evals/agent-026-no-serial-await/app/page.tsx", "language": "tsx", "file_size": 905, "cut_index": 547, "middle_length": 52 }
r Next.js Image * * Tests whether the agent uses the Next.js Image component from next/image * instead of plain HTML <img> tags. * * Tricky because agents default to <img> tags, missing Next.js automatic * image optimization, lazy loading, and responsive sizing. */ import { expect, test } from 'vitest' import {...
h(/<Image/) // Should NOT use img tags for product images expect(galleryContent).not.toMatch(/<img/) }) test('ProductGallery has required image props', () => { const galleryContent = readFileSync( join(process.cwd(), 'app', 'ProductGallery.tsx'
tGallery.tsx'), 'utf-8' ) // Should import Image from next/image expect(galleryContent).toMatch(/import.*Image.*from ['"]next\/image['"]/) // Should use Image components, not img tags expect(galleryContent).toMatc
{ "filepath": "evals/evals/agent-027-prefer-next-image/EVAL.ts", "language": "typescript", "file_size": 1385, "cut_index": 524, "middle_length": 229 }
"./types"; export const handlers = [ http.get("https://my.backend/book", () => { const book: Book = { title: "Lord of the Rings", imageUrl: "/book-cover.jpg", description: "The Lord of the Rings is an epic high-fantasy novel written by English author and scholar J. R. R. Tolkien.", ...
no absolute hesitation, my most favored and adored book by‑far. The trilogy is wonderful‑ and I really consider this a legendary fantasy series. It will always keep you at the edge of your seat‑ and the characters you will grow and fall in love with!",
Maverick", text: "Lord of The Rings, is with
{ "filepath": "examples/with-msw/mocks/handlers.ts", "language": "typescript", "file_size": 958, "cut_index": 582, "middle_length": 52 }
ct-dropdown-menu"; function RightSlot({ children }) { return ( <div className="ml-auto pl-4 text-gray-500 group-hover:text-gray-200"> {children} </div> ); } function DropdownMenuItem({ children, ...props }) { return ( <DropdownMenu.Item {...props} className={ "group bg-whit...
rounded flex items-center h-6 px-1 pl-6 relative select-none" > {children} </DropdownMenu.CheckboxItem> ); } function DropdownMenuItemIndicator({ children, ...props }) { return ( <DropdownMenu.ItemIndicator {...props} cl
</DropdownMenu.Item> ); } function DropdownMenuCheckboxItem({ children, ...props }) { return ( <DropdownMenu.CheckboxItem {...props} className="group bg-white hover:bg-gray-700 hover:text-gray-200 text-xs
{ "filepath": "examples/radix-ui/app/page.tsx", "language": "tsx", "file_size": 5666, "cut_index": 716, "middle_length": 229 }
tton: { button: "_2Agdx", rippleWrapper: "_3AVBi", squared: "_2GH_L", icon: "_3aBSX", solid: "_1ZxqC", raised: "_221ic _2Agdx _2GH_L _1ZxqC", flat: "_1jWAQ _2Agdx _2GH_L", floating: "_3IRMZ _2Agdx _1ZxqC", mini: "_2DCN-", toggle: "hC5Z2 _2Agdx", primary: "_3tTAW", accent:...
"_2DDdC", dialog: "_3fCV6", button: "_2hL6u", calendar: "_1X9ls", prev: "Nv9Bc", next: "_3iPkS", title: "_2ESpD", years: "zEdgW", active: "_1pjXb", week: "PcByv", days: "_1qh3T", day: "_2qF_L", month: "_1hSm5
RTDatePicker: { input: "_2ISvI", disabled: "Cf3yF", inputElement: "x7MhN", header: "_2vLUd", year: "_1VWY-", date: "_3K2Ws", calendarWrapper: "_1t-4v", yearsDisplay: "_2OzvT", monthsDisplay:
{ "filepath": "examples/with-react-toolbox/theme.js", "language": "javascript", "file_size": 1964, "cut_index": 537, "middle_length": 229 }
client"; import { useActionState } from "react"; import { useFormStatus } from "react-dom"; import { createTodo } from "@/app/actions"; const initialState = { message: "", }; function SubmitButton() { const { pending } = useFormStatus(); return ( <button type="submit" aria-disabled={pending}> Add ...
orm action={formAction}> <label htmlFor="todo">Enter Task</label> <input type="text" id="todo" name="todo" required /> <SubmitButton /> <p aria-live="polite" className="sr-only" role="status"> {state?.message} </p>
eturn ( <f
{ "filepath": "examples/next-forms/app/add-form.tsx", "language": "tsx", "file_size": 803, "cut_index": 517, "middle_length": 14 }
ons/core' import { context, getOctokit } from '@actions/github' import { WebClient } from '@slack/web-api' import { BlockCollection, Divider, Section } from 'slack-block-builder' import { formattedDate, ninetyDaysAgo } from '../lib/util.mjs' async function run() { try { if (!process.env.GITHUB_TOKEN) throw new T...
${repo} -is:draft is:pr is:open created:>=${ninetyDaysAgo()}`, sort: 'reactions', }) if (prs.items.length > 0) { let text = '' let count = 0 prs.items.forEach((pr, i) => { if (pr.reactions) { if (pr.react
= new WebClient(process.env.SLACK_TOKEN) const { owner, repo } = context.repo const { data: prs } = await octoClient.rest.search.issuesAndPullRequests({ order: 'desc', per_page: 15, q: `repo:${owner}/
{ "filepath": ".github/actions/next-repo-actions/src/popular-prs.ts", "language": "typescript", "file_size": 2137, "cut_index": 563, "middle_length": 229 }
{ info, setFailed } from '@actions/core' import { context, getOctokit } from '@actions/github' async function main() { if (!process.env.GITHUB_TOKEN) throw new TypeError('GITHUB_TOKEN not set') const octokit = getOctokit(process.env.GITHUB_TOKEN) const { owner, repo } = context.repo const issue = context.pa...
est regards, The Next.js Team ` try { await octokit.rest.issues.createComment({ owner, repo, issue_number: issue.number, body, }) await octokit.rest.issues.update({ owner, repo, issue_number: issu
b.com/vercel/next.js/issues/new?assignees=&labels=bug&projects=&template=1.bug_report.yml). This will ensure that we have all the necessary information to triage your issue. Thank you for your understanding and contributions. B
{ "filepath": ".github/actions/next-repo-actions/src/wrong-issue-template.ts", "language": "typescript", "file_size": 1223, "cut_index": 518, "middle_length": 229 }
manifestFile) const contents = await fs.readFile(file, 'utf-8') const results = JSON.parse(contents) let failingCount = 0 let passingCount = 0 const currentDate = new Date() const isoString = currentDate.toISOString() const timestamp = isoString.slice(0, 19).replace('T', ' ') for (const isPassing of...
festFile) { const file = path.join(process.cwd(), manifestFile) const contents = await fs.readFile(file, 'utf-8') const results = JSON.parse(contents) let passingTests = '' let failingTests = '' let passCount = 0 let failCount = 0 const c
}/${ passingCount + failingCount }` return { status, // Uses JSON.stringify to create minified JSON, otherwise whitespace is preserved. data: JSON.stringify(results), } } async function collectResults(mani
{ "filepath": ".github/actions/upload-turboyet-data/src/main.js", "language": "javascript", "file_size": 6591, "cut_index": 716, "middle_length": 229 }
urationWebpack: 'Webpack Warm (First Request)', // Production metrics nextStartReadyDuration: 'Prod Start', // Build metrics - Webpack buildDurationWebpack: 'Webpack Build Time', buildDurationCachedWebpack: 'Webpack Build Time (cached)', // Build metrics - Turbopack buildDurationTurbo: 'Turbo Build Time',...
, key: 'nextDevColdListenDurationTurbo', description: 'Time until TCP port accepts connections', }, { label: 'Cold (Ready in log)', key: 'nextDevColdReadyInDurationTurbo', description: 'Time until "Ready
ing the comment const METRIC_GROUPS = { 'Dev Server': { icon: '⚡', description: 'Boot time for `next dev` (Turbopack). Cold = fresh build, Warm = with cache.', metrics: [ { label: 'Cold (Listen)'
{ "filepath": ".github/actions/next-stats-action/src/add-comment.js", "language": "javascript", "file_size": 39661, "cut_index": 2151, "middle_length": 229 }
./run') const addComment = require('./add-comment') const actionInfo = require('./prepare/action-info')() const { mainRepoDir, diffRepoDir, pnpmStoreDir } = require('./constants') const loadStatsConfig = require('./prepare/load-stats-config') const { cloneRepo, mergeBranch, getCommitId, linkPackages, getLastStable } = ...
ionInfo.actionName) && !actionInfo.isRelease) { logger( `Not running for ${actionInfo.actionName} event action on repo: ${actionInfo.prRepo} and ref ${actionInfo.prRef}` ) process.exit(0) } ;(async () => { try { if (existsSync(path.join(__
bundlerInput = (process.env.INPUT_BUNDLER || 'both').toLowerCase() const isShardedRun = bundlerInput !== 'both' if (isShardedRun) { logger(`Running in sharded mode for bundler: ${bundlerInput}`) } if (!allowedActions.has(act
{ "filepath": ".github/actions/next-stats-action/src/index.js", "language": "javascript", "file_size": 8451, "cut_index": 716, "middle_length": 229 }
= require('../util/exec') const logger = require('../util/logger') module.exports = (actionInfo) => { return { async cloneRepo(repoPath = '', dest = '', branch = '', depth = '20') { await fs.promises.rm(dest, { recursive: true, force: true }) await exec( `git clone ${actionInfo.gitRoot}${repo...
tatus}: ${await res.text()}` ) } const data = await res.json() return data.tag_name }, async getCommitId(repoDir = '') { const { stdout } = await exec(`cd ${repoDir} && git rev-parse HEAD`) return stdout.trim()
s/releases/latest`, { headers: { 'X-GitHub-Api-Version': '2022-11-28', }, } ) if (!res.ok) { throw new Error( `Failed to get latest stable tag ${res.s
{ "filepath": ".github/actions/next-stats-action/src/prepare/repo-setup.js", "language": "javascript", "file_size": 3220, "cut_index": 614, "middle_length": 229 }
nst exec = require('../util/exec') const glob = require('../util/glob') const logger = require('../util/logger') const { statsAppDir, diffingDir } = require('../constants') module.exports = async function collectDiffs( filesToTrack = [], initial = false ) { if (initial) { logger('Setting up directory for dif...
ath.join(diffingDir, file), { recursive: true, force: true }) ) ) } const diffs = {} await Promise.all( filesToTrack.map(async (fileGroup) => { const { globs } = fileGroup const curFiles = [] const prettierExts = ['.j
init`) } else { // remove any previous files in case they won't be overwritten const toRemove = await glob('!(.git)', { cwd: diffingDir, dot: true }) await Promise.all( toRemove.map((file) => fs.rm(p
{ "filepath": ".github/actions/next-stats-action/src/run/collect-diffs.js", "language": "javascript", "file_size": 4954, "cut_index": 614, "middle_length": 229 }
urlParse } = require('url') const benchmarkUrl = require('./benchmark-url') const { statsAppDir, diffingDir, benchTitle } = require('../constants') const { calcStats } = require('../util/stats') // Number of iterations for timing benchmarks to get stable median const BENCHMARK_ITERATIONS = process.env.BENCHMARK_ITERAT...
) socket.once('error', () => { socket.destroy() resolve(false) }) socket.connect(port, 'localhost') }) } // Wait for port to start accepting TCP connections async function waitForPort(port, timeoutMs = 60000) { const start = Da
st socket = new net.Socket() socket.setTimeout(timeout) socket.once('connect', () => { socket.destroy() resolve(true) }) socket.once('timeout', () => { socket.destroy() resolve(false) }
{ "filepath": ".github/actions/next-stats-action/src/run/collect-stats.js", "language": "javascript", "file_size": 17216, "cut_index": 921, "middle_length": 229 }
logger = require('./logger') const { promisify } = require('util') const { exec: execOrig, spawn: spawnOrig } = require('child_process') const execP = promisify(execOrig) const env = { ...process.env, GITHUB_TOKEN: '', PR_STATS_COMMENT_TOKEN: '', } function exec(command, noLog = false, opts = {}) { if (!noLog...
(${code}, ${signal}): ${command}`) }) return child } exec.spawnPromise = function spawnPromise(command = '', opts = {}) { return new Promise((resolve, reject) => { const child = exec.spawn(command, opts) child.on('exit', (code, signal) => {
`) const child = spawnOrig('/bin/bash', ['-c', command], { ...opts, env: { ...env, ...opts.env, }, stdio: opts.stdio || 'inherit', }) child.on('exit', (code, signal) => { logger(`spawn exit
{ "filepath": ".github/actions/next-stats-action/src/util/exec.js", "language": "javascript", "file_size": 1201, "cut_index": 518, "middle_length": 229 }
erface JobResult { job: string data: TestResult } interface TestResultManifest { ref: string result: Array<JobResult> flakyMonitorJobResults: Array<JobResult> } /** * Models parsed test results output from next.js integration test. * This is a subset of the full test result output from jest, partially com...
orTitles?: Array<string> | null failureMessages?: Array<string> | null fullName: string location?: null status: string title: string }> | null endTime: number message: string name: string startTime: number
ts: number numRuntimeErrorTestSuites: number numTodoTests: number numTotalTestSuites: number numTotalTests: number startTime: number success: boolean testResults?: Array<{ assertionResults?: Array<{ ancest
{ "filepath": ".github/actions/next-integration-stat/src/manifest.d.ts", "language": "typescript", "file_size": 1079, "cut_index": 515, "middle_length": 229 }
Translation from "next-translate/useTranslation"; import "./style.css"; export const metadata = { title: "Next.js", }; export default function Layout(props) { const { t, lang } = useTranslation(); return ( <html lang={lang}> <body className="container"> {props.children} <footer> ...
<span>&amp;</span> <a href="https://github.com/vinissimus/next-translate" target="_blank" rel="noopener noreferrer" > next-translate </a> </footer> </body
</a>
{ "filepath": "examples/with-next-translate/app/layout.js", "language": "javascript", "file_size": 815, "cut_index": 522, "middle_length": 14 }
nk"; import Trans from "next-translate/Trans"; import useTranslation from "next-translate/useTranslation"; export default function Home() { const { t, lang } = useTranslation(); const isRTL = lang === "ar" || lang === "he"; const arrow = isRTL ? String.fromCharCode(8592) : String.fromCharCode(8594); return ( ...
h3>{t("home:english")}</h3> <p> {t("home:change-to")} {t("home:english")} </p> </div> </Link> <Link href="/ca"> <div className="card"> <h3>{t("home:catalan")}</h3>
]} /> <p className="description"> {t("home:description")} <code>_pages/index.js</code> </p> <div className="grid"> <Link href="/en"> <div className="card"> <
{ "filepath": "examples/with-next-translate/app/[lang]/page.js", "language": "javascript", "file_size": 1940, "cut_index": 537, "middle_length": 229 }
ogPageView } from "../utils/analytics"; const MyApp = ({ Component, pageProps }) => { const router = useRouter(); useEffect(() => { initGA(); // `routeChangeComplete` won't run for the first page load unless the query string is // hydrated later on, so here we log a page view if this is the first rend...
n or when the query changes router.events.on("routeChangeComplete", logPageView); return () => { router.events.off("routeChangeComplete", logPageView); }; }, [router.events]); return <Component {...pageProps} />; }; export default M
> { // Listen for page changes after a navigatio
{ "filepath": "examples/with-react-ga4/pages/_app.js", "language": "javascript", "file_size": 920, "cut_index": 606, "middle_length": 52 }
port { useActionState } from "react"; import { useFormStatus } from "react-dom"; import { deleteTodo } from "@/app/actions"; const initialState = { message: "", }; function DeleteButton() { const { pending } = useFormStatus(); return ( <button type="submit" aria-disabled={pending}> Delete </butto...
m action={formAction}> <input type="hidden" name="id" value={id} /> <input type="hidden" name="todo" value={todo} /> <DeleteButton /> <p aria-live="polite" className="sr-only" role="status"> {state?.message} </p> <
tate(deleteTodo, initialState); return ( <for
{ "filepath": "examples/next-forms/app/delete-form.tsx", "language": "tsx", "file_size": 851, "cut_index": 529, "middle_length": 52 }
al.js [--with-history] * * This generates a sample PR comment using mock data so you can * quickly verify formatting changes without running the full action. * * Options: * --with-history Simulate KV history data to test trend sparklines */ const addComment = require('./src/add-comment') const withHistory =...
ColdReadyDurationWebpack: 1200, nextDevWarmListenDurationWebpack: 250, nextDevWarmReadyDurationWebpack: 800, nextStartReadyDuration: 150, buildDurationTurbo: 4500, buildDurationCachedTurbo: 4200, buildDuratio
tDevColdListenDurationTurbo: 280, nextDevColdReadyDurationTurbo: 450, nextDevWarmListenDurationTurbo: 180, nextDevWarmReadyDurationTurbo: 320, nextDevColdListenDurationWebpack: 350, nextDev
{ "filepath": ".github/actions/next-stats-action/test-local.js", "language": "javascript", "file_size": 3706, "cut_index": 614, "middle_length": 229 }
os = require('os') const fs = require('fs') const benchTitle = 'Page Load Tests' function getTempRoot() { const tempRoot = process.env.RUNNER_TEMP || os.tmpdir() try { fs.mkdirSync(tempRoot, { recursive: true }) return tempRoot } catch { return os.tmpdir() } } const workDir = fs.mkdtempSync(path...
p') const diffingDir = path.join(workDir, 'diff') const allowedConfigLocations = [ './', '.stats-app', 'test/.stats-app', '.github/.stats-app', ] module.exports = { benchTitle, workDir, pnpmStoreDir, diffingDir, mainRepoDir, diffRepoDi
o') const statsAppDir = path.join(workDir, 'stats-ap
{ "filepath": ".github/actions/next-stats-action/src/constants.js", "language": "javascript", "file_size": 901, "cut_index": 547, "middle_length": 52 }
= require('../util/exec') const parseField = (stdout = '', field = '') => { return stdout.split(field).pop().trim().split(/\s/).shift().trim() } // benchmark an url async function benchmarkUrl( url = '', options = { reqTimeout: 60, concurrency: 50, numRequests: 2500, } ) { const { numRequests, ...
for tests:'), 10) const failedRequests = parseInt(parseField(stdout, 'Failed requests:'), 10) const avgReqPerSec = parseFloat(parseField(stdout, 'Requests per second:')) return { totalTime, avgReqPerSec, failedRequests, } } module.ex
t, 'Time taken
{ "filepath": ".github/actions/next-stats-action/src/run/benchmark-url.js", "language": "javascript", "file_size": 813, "cut_index": 522, "middle_length": 14 }
/** * Shared statistics utilities for benchmark measurements */ /** * Calculate statistical summary for an array of numbers * @param {number[]} arr - Array of numeric values * @returns {Object|null} Stats object with median, min, max, mean, stddev, cv or null if empty */ function calcStats(arr) { if (arr.lengt...
h const stddev = Math.sqrt(variance) const cv = mean > 0 ? (stddev / mean) * 100 : 0 // coefficient of variation as % return { median, min, max, mean: Math.round(mean), stddev: Math.round(stddev), cv: Math.round(cv), } } m
ed[mid]) / 2 const min = sorted[0] const max = sorted[sorted.length - 1] const mean = arr.reduce((a, b) => a + b, 0) / arr.length const variance = arr.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / arr.lengt
{ "filepath": ".github/actions/next-stats-action/src/util/stats.js", "language": "javascript", "file_size": 1027, "cut_index": 512, "middle_length": 229 }
/github' import { minimatch } from 'minimatch' import config from './config.json' type AuthorRule = { type: 'user'; pattern: string } type LabelRule = string | AuthorRule type LabelerConfig = { labels: Record<string, LabelRule[]> } function isAuthorRule(rule: LabelRule): rule is AuthorRule { return ( typeof rul...
orRule(rule)) { if (rule.pattern.toLowerCase() === author.toLowerCase()) { matched.add(label) break } } else if (typeof rule === 'string') { const matches = changedFiles.some((file) => minimatch(f
config: LabelerConfig, author: string, changedFiles: string[] ): string[] { const matched = new Set<string>() for (const [label, rules] of Object.entries(config.labels)) { for (const rule of rules) { if (isAuth
{ "filepath": ".github/actions/pr-auto-label/src/index.ts", "language": "typescript", "file_size": 3664, "cut_index": 614, "middle_length": 229 }
; import { revalidatePath } from "next/cache"; import postgres from "postgres"; import { z } from "zod"; let sql = postgres(process.env.DATABASE_URL || process.env.POSTGRES_URL!, { ssl: "allow", }); // CREATE TABLE todos ( // id SERIAL PRIMARY KEY, // text TEXT NOT NULL // ); export async function createTodo(...
/"); return { message: `Added todo ${data.todo}` }; } catch (e) { return { message: "Failed to create todo" }; } } export async function deleteTodo( prevState: { message: string; }, formData: FormData, ) { const schema = z.object({
do"), }); if (!parse.success) { return { message: "Failed to create todo" }; } const data = parse.data; try { await sql` INSERT INTO todos (text) VALUES (${data.todo}) `; revalidatePath("
{ "filepath": "examples/next-forms/app/actions.ts", "language": "typescript", "file_size": 1402, "cut_index": 524, "middle_length": 229 }
const { diffRepoDir, allowedConfigLocations } = require('../constants') // load stats-config function loadStatsConfig() { let statsConfig let relativeStatsAppDir for (const configPath of allowedConfigLocations) { try { relativeStatsAppDir = configPath statsConfig = require( path.join(dif...
nfig) { throw new Error( `Failed to locate \`.stats-app\`, allowed locations are: ${allowedConfigLocations.join( ', ' )}` ) } logger( 'Got statsConfig at', path.join(relativeStatsAppDir, 'stats-config.js'), stat
, err) } /* */ } } if (!statsCo
{ "filepath": ".github/actions/next-stats-action/src/prepare/load-stats-config.js", "language": "javascript", "file_size": 994, "cut_index": 582, "middle_length": 52 }
ort { useState } from "react"; import { Book, Review } from "../mocks/types"; type Props = { book: Book; }; export default function Home({ book }: Props) { const [reviews, setReviews] = useState<Review[] | null>(null); const handleGetReviews = () => { // Client-side request are mocked by `mocks/browser.ts`...
w.text}</p> <p>{review.author}</p> </li> ))} </ul> )} </div> ); } export async function getServerSideProps() { // Server-side requests are mocked by `mocks/server.ts`. const res = await fetch("ht
e}</h1> <p>{book.description}</p> <button onClick={handleGetReviews}>Load reviews</button> {reviews && ( <ul> {reviews.map((review) => ( <li key={review.id}> <p>{revie
{ "filepath": "examples/with-msw/pages/index.tsx", "language": "tsx", "file_size": 1109, "cut_index": 515, "middle_length": 229 }
bution CDFs (Student's t and // standard normal). The rest — Welch's t-statistic, average-rank ranking, // and the Mann–Whitney U statistic + asymptotic-tail p-value — is // implemented here directly. // // For Mann–Whitney we use the normal approximation with continuity // correction. For very small samples this appro...
olation quantile (numpy/R "type 7" default). export function quantile(xs: number[], q: number): number { if (xs.length === 0) return NaN if (xs.length === 1) return xs[0] const sorted = [...xs].sort((a, b) => a - b) const pos = q * (sorted.length -
interface Summary { mean: number p50: number p90: number } export function mean(xs: number[]): number { if (xs.length === 0) return NaN let s = 0 for (const x of xs) s += x return s / xs.length } // Linear-interp
{ "filepath": "turbopack/packages/devlow-bench/src/statistics.ts", "language": "typescript", "file_size": 4032, "cut_index": 614, "middle_length": 229 }
minimist(process.argv.slice(2), { alias: { r: 'row', c: 'column', '?': 'help', h: 'help', }, }) const knownArgs = new Set(['row', 'r', 'column', 'c', 'help', 'h', '?', '_']) if (args.help || (Object.keys(args).length === 1 && args._.length === 0)) { console.log('Usage: devlow-...
=> { if (name === 'value') { return data.text as string } if (Array.isArray(name)) { return name .map((n) => getValue(data, n, true)) .filter((x) => x) .join(' ') } const value = data.key[name] i
console.log(' --help, -h, -? Show this help') } let data = JSON.parse(await readFile(args._[0], 'utf-8')) as any[] const getValue = ( data: any, name: string | string[], includeKey: boolean ): string
{ "filepath": "turbopack/packages/devlow-bench/src/table.ts", "language": "typescript", "file_size": 3540, "cut_index": 614, "middle_length": 229 }
mport { Interface } from '../index.js' import { SampleGroup, groupRows, makeKey, printComparison } from '../compare.js' import { readSnapshot } from '../snapshot.js' import { formatVariantProps } from '../utils.js' export default async function createInterface(options: { baselinePath: string }): Promise<Interface> {...
c) current.set(key, { scenario, variant, metric, unit: s.unit, samples: s.samples.slice(), }) } }, finish: async () => { printComparison(baseline, current, { baselineLabe
return { variantStatistics: async (scenario, props, stats) => { const variant = formatVariantProps(props) for (const [metric, s] of Object.entries(stats)) { const key = makeKey(scenario, variant, metri
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/compare.ts", "language": "typescript", "file_size": 1030, "cut_index": 513, "middle_length": 229 }
]): Interface { const allKeys = new Set<keyof Interface>() for (const iface of ifaces) { for (const key of Object.keys(iface)) { allKeys.add(key as keyof Interface) } } const composed: any = {} for (const key of allKeys) { if (key.startsWith('filter')) { composed[key] = async (items: a...
} else { composed[key] = async (...args: any[]) => { for (const iface of ifaces) { const anyIface = iface as any if (anyIface[key]) { await anyIface[key](...args) } } } } } retu
} } return items }
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/compose.ts", "language": "typescript", "file_size": 928, "cut_index": 606, "middle_length": 52 }
ace } from '../index.js' import { formatUnit } from '../units.js' import { formatVariant } from '../utils.js' const { bgCyan, bold, cyan, dim, magenta, red, underline } = picocolors export default function createInterface( options: { n?: number } = {} ): Interface { const n = options.n ?? 1 const showSummary = ...
sync (scenario, props, name, value, unit, relativeTo) => { console.log( bgCyan( bold( magenta( `${formatVariant(scenario, props)}: ${name} = ${formatUnit( value, unit
ress = runInfo.warmup ? ` [warmup ${runInfo.run}/${runInfo.total}]` : ` [${runInfo.run}/${runInfo.total}]` } console.log(bold(underline(`Running ${label}...${progress}`))) }, measurement: a
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/console.ts", "language": "typescript", "file_size": 2034, "cut_index": 563, "middle_length": 229 }
ommand } from '../shell.js' export const UNIT_MAPPING: Record<string, string> = { ms: 'millisecond', requests: 'request', bytes: 'byte', } export const GIT_SHA = process.env.GITHUB_SHA ?? (await (async () => { const cmd = command('git', ['rev-parse', 'HEAD']) await cmd.ok() return cmd.output.tri...
Boolean(process.env.CI) export const OS = process.platform export const OS_RELEASE = os.release() export const NUM_CPUS = os.cpus().length export const CPU_MODEL = os.cpus()[0].model export const USERNAME = os.userInfo().username export const CPU_ARCH = os
urn cmd.output.trim() })()) export const IS_CI =
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/constants.ts", "language": "typescript", "file_size": 907, "cut_index": 547, "middle_length": 52 }
etadata, } from '@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/index.js' import type { Interface } from '../index.js' import datadogApiClient from '@datadog/datadog-api-client' import os from 'os' import { CPU_ARCH, CPU_MODEL, GIT_BRANCH, GIT_SHA, IS_CI, NODE_VERSION, NUM_CPUS, OS, O...
(), }: { apiKey?: string; appKey?: string; host?: string } = {}): Interface { if (!apiKey) throw new Error('Datadog API key is required (set DATADOG_API_KEY)') const commonTags = [ `ci:${IS_CI}`, `os:${OS}`, `os_release:${OS_RELEASE}`,
'millisecond', requests: 'request', bytes: 'byte', } export default function createInterface({ apiKey = process.env.DATADOG_API_KEY, appKey = process.env.DATADOG_APP_KEY, host = process.env.DATADOG_HOST || os.hostname
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/datadog.ts", "language": "typescript", "file_size": 2835, "cut_index": 563, "middle_length": 229 }
{ Interface } from '../index.js' import inquirer from 'inquirer' import { formatVariant } from '../utils.js' export default function createInterface(): Interface { const iface: Interface = { filterScenarios: async (scenarios) => { if (scenarios.length === 1) { return scenarios } let an...
return variants } let answer = await inquirer.prompt({ type: 'checkbox', name: 'variants', default: variants.slice(), message: 'Choose variants to run', choices: variants.map((variant) => { ret
ap((scenario) => ({ name: scenario.name, value: scenario, })), }) return answer.scenarios }, filterScenarioVariants: async (variants) => { if (variants.length === 1) {
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/interactive.ts", "language": "typescript", "file_size": 1199, "cut_index": 518, "middle_length": 229 }
antile, mean as statsMean } from '../statistics.js' import { formatUnit } from '../units.js' import { writeFile } from 'fs/promises' function filterProp( prop: Record<string, string | number | boolean | null> ): Record<string, string | number | boolean> { const filteredProp: Record<string, string | number | boolea...
const n = options.n ?? 1 // Per-(scenario, props, name) sample accumulator. const metrics = new Map< string, { key: Record<string, string | number> samples: number[] unit: string relativeTo?: string } >() const
e( file: string = (() => { const file = process.env.JSON_OUTPUT_FILE if (!file) { throw new Error('env var JSON_OUTPUT_FILE is not set') } return file })(), options: { n?: number } = {} ): Interface {
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/json.ts", "language": "typescript", "file_size": 2544, "cut_index": 563, "middle_length": 229 }
t' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { test } from 'node:test' import { command } from '../shell.js' async function withTempScript( scriptContents: string, fn: (scriptPath: string) => Promise<void> ) { const dir = aw...
KER') setTimeout(() => {}, 1000) `, async (scriptPath) => { const shell = command('node', [scriptPath]) try { const first = await shell.waitForOutput(/FIRST_MARKER\n/, { timeoutMs: 2_000, }) assert.equal(f
lly { await rm(dir, { recursive: true, force: true }) } } test('waitForOutput handles sequential waits after buffered output', async () => { await withTempScript( ` console.log('FIRST_MARKER') console.log('SECOND_MAR
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/shell-test.ts", "language": "typescript", "file_size": 1844, "cut_index": 537, "middle_length": 229 }
t { promisify } from 'node:util' import picocolors from 'picocolors' import { Interface } from '../index.js' import { SnapshotRow, defaultSnapshotPath, writeSnapshot } from '../snapshot.js' import { formatVariantProps } from '../utils.js' const execFileAsync = promisify(execFile) async function readGitInfo(): Promise...
'' } } export default function createInterface( options: { path?: string } = {} ): Interface & { resolvedPath: string } { const path = options.path ?? defaultSnapshotPath() const rows: SnapshotRow[] = [] const timestamp = new Date().toISOString(
rse', '--abbrev-ref', 'HEAD'])) return { sha, branch } } async function tryGit(args: string[]): Promise<string> { try { const { stdout } = await execFileAsync('git', args) return stdout.trim() } catch { return
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/snapshot.ts", "language": "typescript", "file_size": 2027, "cut_index": 563, "middle_length": 229 }
t' import createInterface from './snowflake.js' import { mock, test } from 'node:test' test('sending measurements to the batch endpoint', async () => { const requests: Array<[string, RequestInit]> = [] const fetchMock = mock.method( global, 'fetch', (req: string, options: RequestInit) => { reque...
ent('scenario', { myprop: 'foo' }, 'three', 38, 'ms') assert(iface.end != null) await iface.end('scenario', { myprop: 'foo' }) assert.equal(requests.length, 1) const [url, options] = requests[0] assert.equal(url, 'http://127.0.0.1/v1/batch')
schemaId: 123, }) assert(iface.measurement != null) await iface.measurement('scenario', { myprop: 'foo' }, 'one', 42, 'ms') await iface.measurement('scenario', { myprop: 'foo' }, 'two', 45, 'ms') await iface.measurem
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/snowflake-test.ts", "language": "typescript", "file_size": 1829, "cut_index": 537, "middle_length": 229 }
IT_BRANCH, GIT_SHA, IS_CI, NODE_VERSION, NUM_CPUS, OS, OS_RELEASE, USERNAME, } from './constants.js' import { randomUUID } from 'crypto' type DevlowMetric = { event_time: number scenario: string props: Record<string, string | number | boolean | null> metric: string value: number unit: string ...
parseInt(process.env.SNOWFLAKE_SCHEMA_ID, 10) : undefined, }: { gatewayUri?: string topicName?: string schemaId?: number } = {}): Interface { if (!gatewayUri) throw new Error( 'Snowflake gateway URI is required (set SNOWFLAKE_GATEWAY
git_sha: string git_branch: string } export default function createInterface({ gatewayUri = process.env.SNOWFLAKE_BATCH_URI, topicName = process.env.SNOWFLAKE_TOPIC_NAME, schemaId = process.env.SNOWFLAKE_SCHEMA_ID ?
{ "filepath": "turbopack/packages/devlow-bench/src/interfaces/snowflake.ts", "language": "typescript", "file_size": 3428, "cut_index": 614, "middle_length": 229 }
-pprof-node-gyp', 'microtime-node-gyp', 'zeromq-node-gyp', ] const skipOnWindows = [ 'datadog-pprof-node-gyp', 'yarn-workspaces', 'yarn-workspaces-base-root', 'yarn-workspace-esm', 'asset-symlink', 'require-symlink', ] const skipOnMac = [] const skipOnNode20AndBelow = ['module-sync-condition-es'] const...
{ const originalModule = jest.requireActual('../out/analyze.js').default return { __esModule: true, default: jest.fn(originalModule), } }) jest.mock('graceful-fs', () => { const originalModule = jest.requireActual('graceful-fs') retur
addirSync(join(__dirname, 'unit')) const unitTests = [ ...unitTestDirs.map((testName) => ({ testName, isRoot: false })), ...unitTestDirs.map((testName) => ({ testName, isRoot: true })), ] jest.mock('../out/analyze.js', () =>
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/unit.test.js", "language": "javascript", "file_size": 11941, "cut_index": 921, "middle_length": 229 }
se = require('firebase/app') require('firebase/firestore') require('firebase/database') firebase.initializeApp({ projectId: 'noop' }) const store = firebase.firestore() store .collection('users') .get() .then( () => { console.log('ok') process.exit(0) }, (e) => { /* Error: un...
/a707d6b7ee4afe5b484993180e617e2d/index.js:16778:41) at NodePlatform.module.exports.278.NodePlatform.loadConnection (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T/a707d6b7ee4afe5b484993180e617e2d/index.js:16815:22) at FirestoreCl
ot.js:243:1) at Object.loadSync (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T/a707d6b7ee4afe5b484993180e617e2d/index.js:43406:16) at loadProtos (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/integration/firebase.js", "language": "javascript", "file_size": 1357, "cut_index": 524, "middle_length": 229 }
;(() => { var exports = {} exports.id = 829 exports.ids = [829] exports.modules = { /***/ 354: /***/ ( __unused_webpack_module, __webpack_exports__, __webpack_require__ ) => { // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__) // EXPORTS __webpack_r...
ync function handler(_req, res) { const hello = await (0, promises_namespaceObject.readFile)( __dirname + '/hello.txt', 'utf-8' ) return hello } /***/ }, } // load runtime var __webpack_req
ises') // CONCATENATED MODULE: ./pages/api/users.ts // Fake users data const users = [ { id: 1, }, { id: 2, }, { id: 3, }, ] as
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/integration/webpack-target-node/chunk.js", "language": "javascript", "file_size": 1280, "cut_index": 524, "middle_length": 229 }
le cache /******/ var __webpack_module_cache__ = {} /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId] /******/ if (cachedModule !== undefined) { /***...
/******/ __webpack_modules__[moduleId]( module, module.exports, __webpack_require__ ) /******/ threw = false /******/ } finally { /******/ if (threw) delete __webpack_module_cache__[moduleId] /
*****/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {}, /******/ }) /******/ /******/ // Execute the module function /******/ var threw = true /******/ try {
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/integration/webpack-target-node/webpack-api-runtime.js", "language": "javascript", "file_size": 6255, "cut_index": 716, "middle_length": 229 }
* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed ...
rts.LogVerbosity = exports.Status = void 0 var Status ;(function (Status) { Status[(Status['OK'] = 0)] = 'OK' Status[(Status['CANCELLED'] = 1)] = 'CANCELLED' Status[(Status['UNKNOWN'] = 2)] = 'UNKNOWN' Status[(Status['INVALID_ARGUMENT'] = 3)]
ions and * limitations under the License. * */ Object.defineProperty(exports, '__esModule', { value: true }) exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports.Propagate = expo
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/integration/source-map/constants.js", "language": "javascript", "file_size": 3041, "cut_index": 563, "middle_length": 229 }
**/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if (installedModules[moduleId]) { /******/ return installedModules[moduleId].exports /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = (in...
} finally { /******/ if (threw) delete installedModules[moduleId] /******/ } /******/ /******/ // Flag the module as loaded /******/ module.l = true /******/ /******/ // Return the exports of the module /******/
/******/ var threw = true /******/ try { /******/ modules[moduleId].call( module.exports, module, module.exports, __webpack_require__ ) /******/ threw = false /******/
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/webpack-wrapper-strs-namespaces/input.js", "language": "javascript", "file_size": 5936, "cut_index": 716, "middle_length": 229 }
opy-sync.js', // 'node_modules/fs-extra/lib/copy/copy.js', // 'node_modules/fs-extra/lib/copy/index.js', // 'node_modules/fs-extra/lib/empty/index.js', // 'node_modules/fs-extra/lib/ensure/file.js', // 'node_modules/fs-extra/lib/ensure/index.js', // 'node_modules/fs-extra/lib/ensure/link.js', // 'node_mod...
-extra/lib/json/output-json.js', // 'node_modules/fs-extra/lib/mkdirs/index.js', // 'node_modules/fs-extra/lib/mkdirs/make-dir.js', // 'node_modules/fs-extra/lib/mkdirs/utils.js', // 'node_modules/fs-extra/lib/move/index.js', // 'node_modules/fs-
x.js', // 'node_modules/fs-extra/lib/index.js', // 'node_modules/fs-extra/lib/json/index.js', // 'node_modules/fs-extra/lib/json/jsonfile.js', // 'node_modules/fs-extra/lib/json/output-json-sync.js', // 'node_modules/fs
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/asset-fs-extra/output.js", "language": "javascript", "file_size": 2061, "cut_index": 563, "middle_length": 229 }
-gyp-build/index.js', 'node_modules/@datadog/pprof/node_modules/node-gyp-build/package.json', 'node_modules/@datadog/pprof/node_modules/source-map/lib/array-set.js', 'node_modules/@datadog/pprof/node_modules/source-map/lib/base64-vlq.js', 'node_modules/@datadog/pprof/node_modules/source-map/lib/base64.js', 'n...
odules/source-map/lib/source-map-generator.js', 'node_modules/@datadog/pprof/node_modules/source-map/lib/source-node.js', 'node_modules/@datadog/pprof/node_modules/source-map/lib/util.js', 'node_modules/@datadog/pprof/node_modules/source-map/lib/wasm
es/source-map/lib/mappings.wasm', 'node_modules/@datadog/pprof/node_modules/source-map/lib/read-wasm.js', 'node_modules/@datadog/pprof/node_modules/source-map/lib/source-map-consumer.js', 'node_modules/@datadog/pprof/node_m
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/datadog-pprof-node-gyp/output.js", "language": "javascript", "file_size": 2167, "cut_index": 563, "middle_length": 229 }
__importDefault = (this && this.__importDefault) || function (mod) { return mod && mod.__esModule ? mod : { default: mod } } var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod var result = {} if (mod != null) for (var k in mod) ...
equire('path')) console.log( fs_1.default.readFileSync(path.join(__dirname, 'asset.txt'), 'utf8') ) /* Input source (with modules: 'commonjs'): import fs from 'fs'; import * as path from 'path'; console.log(fs.readFileSync(path.join(__dirname, 'asset.t
rtDefault(require('fs')) const path = __importStar(r
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/asset-fs-inline-path-ts/input.js", "language": "javascript", "file_size": 856, "cut_index": 529, "middle_length": 52 }
23 exports.ids = [223] exports.modules = { /***/ 0: /***/ function (module, exports, __webpack_require__) { module.exports = __webpack_require__('PicC') /***/ }, /***/ PicC: /***/ function ( module, __webpack_exports__, __webpack_require__ ) { 'use strict' ...
th__WEBPACK_IMPORTED_MODULE_0__) /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = require('fs') /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/ __webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE
andler } ) /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = require('path') /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/ __webpack_require__.n(pa
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/webpack-5-wrapper-namespace/input.js", "language": "javascript", "file_size": 2048, "cut_index": 563, "middle_length": 229 }
ges/applescript.tmLanguage.json', 'node_modules/shiki/languages/ara.tmLanguage.json', 'node_modules/shiki/languages/asm.tmLanguage.json', 'node_modules/shiki/languages/astro.tmLanguage.json', 'node_modules/shiki/languages/awk.tmLanguage.json', 'node_modules/shiki/languages/ballerina.tmLanguage.json', 'node_...
e.tmLanguage.json', 'node_modules/shiki/languages/clarity.tmLanguage.json', 'node_modules/shiki/languages/clojure.tmLanguage.json', 'node_modules/shiki/languages/cmake.tmLanguage.json', 'node_modules/shiki/languages/cobol.tmLanguage.json', 'node_
s/bibtex.tmLanguage.json', 'node_modules/shiki/languages/bicep.tmLanguage.json', 'node_modules/shiki/languages/blade.tmLanguage.json', 'node_modules/shiki/languages/c.tmLanguage.json', 'node_modules/shiki/languages/cadenc
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/shiki/output.js", "language": "javascript", "file_size": 11770, "cut_index": 921, "middle_length": 229 }
use strict' var os = require('os') var fs = require('fs') var path = require('path') var verifyFile var platform = os.platform() + '-' + os.arch() && '.' var packageName = '@ffmpeg-installer/' + platform var binary = os.platform() === 'win32' ? 'ffmpeg.exe' : 'ffmpeg.exe' // var npm3Path = path.resolve(__dirname,...
} else { throw ( 'Could not find ffmpeg executable, tried "' + npm3Binary + '" and "' + npm2Binary + '"' ) } var version = packageJson.ffmpeg || packageJson.version var url = packageJson.homepage module.exports = { path: ffmpegP
npm3Path, 'package.json') var npm2Package = path.join(npm2Path, 'package.json') var ffmpegPath, packageJson if (verifyFile(npm3Binary)) { ffmpegPath = npm3Binary } else if (verifyFile(npm2Binary)) { ffmpegPath = npm2Binary
{ "filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/ffmpeg-installer/ffmpeg.js", "language": "javascript", "file_size": 1037, "cut_index": 513, "middle_length": 229 }