{"prefix": "ant to pass to Jest\n/** @type {import('jest').Config} */\nconst customJestConfig = {\n displayName: process.env.IS_WEBPACK_TEST ? 'webpack' : 'Turbopack',\n testMatch: ['**/*.test.js', '**/*.test.ts', '**/*.test.jsx', '**/*.test.tsx'],\n globalSetup: '/jest-global-setup.ts',\n setupFilesAfterEnv: ['/jest-setup-after-env.ts'],\n verbose: true,\n rootDir: 'test',\n roots: [\n '',\n '/../packages/next/src/',\n '/../packages/next-codemod/',\n '/../pac", "suffix": "ision: true,\n },\n modulePathIgnorePatterns: [\n '/\\\\.next/',\n // Prevents jest-haste-map warnings due to multiple versions of the same\n // package being vendored. Also means tests in `compiled` will be ignored.\n // Jest does not normalize/reso", "middle": "kages/eslint-plugin-internal/',\n '/../packages/font/src/',\n '/../packages/next-routing/',\n ],\n haste: {\n // Throwing to avoid warnings creeping up over time polluting log output.\n throwOnModuleColl", "meta": {"filepath": "jest.config.js", "language": "javascript", "file_size": 3176, "cut_index": 614, "middle_length": 229}} {"prefix": "* pnpm eval --dry preview without executing\n * pnpm eval --all run every eval (slow — normally only CI does this)\n * NEXT_SKIP_PACK=1 pnpm eval ... reuse tarball from last run\n *\n * Mirrors run-tests.js: pack once, hand paths to child via env, forward args.\n *\n * We only pack `next`, not the whole workspace. The sandbox is remote Linux:\n * - @next/swc: local darwin binary wouldn't run there; the sandbox downloads\n * the right one at runtime (packages/next/s", "suffix": "ne place instead of\n * maintaining N committed experiment files that only differ by one line.\n */\nconst path = require('path')\nconst fs = require('fs')\nconst { execFileSync, spawnSync } = require('child_process')\n\nconst ROOT = __dirname\n\nconst EVALS_DIR = ", "middle": "rc/build/swc/index.ts).\n * - @next/env etc: resolved from npm at the pinned canary version.\n *\n * The experiments/ dir is generated fresh on every run and gitignored. This\n * keeps the two variants (baseline vs. AGENTS.md) in o", "meta": {"filepath": "run-evals.js", "language": "javascript", "file_size": 6587, "cut_index": 716, "middle_length": 229}} {"prefix": "ess.env.RSPACK_BINDING = require('node:path').dirname(\n require.resolve('@next/rspack-binding')\n)\n\nconst binding = require('@next/rspack-binding')\n\n// Register the plugins exported by `crates/binding/src/lib.rs`.\nbinding.registerNextExternalsPlugin()\nbinding.registerForceCompleteRuntimePlugin()\n\nconst core = require('@rspack/core')\n\nconst NextExternalsPlugin = core.experiments.createNativePlugin(\n 'NextExternalsPlugin',\n function (options) {\n return options\n }\n)\n\nconst ForceCompleteRuntimePlugin = co", "suffix": "untimePlugin',\n function () {\n return {}\n }\n)\n\nObject.defineProperty(core, 'NextExternalsPlugin', {\n value: NextExternalsPlugin,\n})\n\nObject.defineProperty(core, 'ForceCompleteRuntimePlugin', {\n value: ForceCompleteRuntimePlugin,\n})\n\nmodule.exports =", "middle": "re.experiments.createNativePlugin(\n 'ForceCompleteR", "meta": {"filepath": "rspack/lib/index.js", "language": "javascript", "file_size": 830, "cut_index": 516, "middle_length": 52}} {"prefix": "React from \"react\";\nimport { useForm, ValidationError } from \"@formspree/react\";\nimport formStyles from \"../styles/form.module.css\";\n\nexport default function ContactForm() {\n const [state, handleSubmit] = useForm(process.env.NEXT_PUBLIC_FORM);\n if (state.succeeded) {\n return

Thanks for your submission!

;\n }\n return (\n
\n \n \n \n \n {\n const counter = useSelector((state) => state.counter);\n const dispatch = useDispatch();\n const { increment } = useRematchDispatch((dispatch) => ({\n increment: dispatch.counter.increment,\n }));\n\n return (\n
\n
\n

Counter

\n

The count is {counter}

\n

\n \n \n \n <", "middle": ">increment\n \n \n \n \n \n \n Documentation\n \n Find in-depth information about Next.js features and A", "meta": {"filepath": "examples/with-reactstrap/pages/index.jsx", "language": "jsx", "file_size": 3262, "cut_index": 614, "middle_length": 229}} {"prefix": "\"react\";\nimport ClientOnlyPortal from \"./ClientOnlyPortal\";\n\nexport default function Modal() {\n const [open, setOpen] = useState();\n\n return (\n <>\n \n {open && (\n \n

\n
\n

\n This modal is rendered using{\" \"}\n setOpen(false)}>\n Close Modal\n \n

\n \n
\n );\n};\n\nexport default Cl", "middle": " 15px;\n display: inline-block;\n co", "meta": {"filepath": "examples/with-apollo-and-redux/components/Clock.js", "language": "javascript", "file_size": 848, "cut_index": 535, "middle_length": 52}} {"prefix": " Nav from \"./Nav\";\nimport PropTypes from \"prop-types\";\n\nconst Layout = ({ children }) => (\n
\n \n );\n};\n\nexport default Header", "middle": " }\n\n a + a {\n margin-left: 1r", "meta": {"filepath": "examples/with-edgedb/components/Header.tsx", "language": "tsx", "file_size": 916, "cut_index": 606, "middle_length": 52}} {"prefix": "import React, { ReactNode } from \"react\";\nimport Header from \"./Header\";\n\ntype Props = {\n children: ReactNode;\n};\n\nconst Layout: React.FC = (props) => (\n
\n
\n
{props.children}
\n \n \n
\n);\n\nexport default L", "middle": "font-family:\n -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica,\n Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\",\n \"Segoe UI Symbol\";\n background: rgba(0, 0, 0, 0);\n ", "meta": {"filepath": "examples/with-edgedb/components/Layout.tsx", "language": "tsx", "file_size": 1004, "cut_index": 512, "middle_length": 229}} {"prefix": "out from \"../components/Layout\";\nimport Router from \"next/router\";\nimport Link from \"next/link\";\n\nconst Draft: React.FC = () => {\n const [title, setTitle] = useState(\"\");\n const [content, setContent] = useState(\"\");\n const [authorName, setAuthorName] = useState(\"\");\n\n const submitData = async (e: React.SyntheticEvent) => {\n e.preventDefault();\n try {\n const body = { title, content, authorName };\n const result = await fetch(`/api/post`, {\n method: \"POST\",\n headers: { \"Conten", "suffix": "
\n \n

Create draft

\n setTitle(e.target.value)}\n placeholder=\"Title\"\n type=\"text\"\n value={title}\n ", "middle": "t-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n await result.json();\n await Router.push(\"/drafts\");\n } catch (error) {\n console.error(error);\n }\n };\n\n return (\n \n ", "meta": {"filepath": "examples/with-edgedb/pages/create.tsx", "language": "tsx", "file_size": 2459, "cut_index": 563, "middle_length": 229}} {"prefix": " from \"react\";\nimport \"../styles/global.css\";\nimport { GetServerSideProps } from \"next\";\nimport Layout from \"../components/Layout\";\nimport Post from \"../components/Post\";\nimport { PostProps } from \"./blog/[id]\";\nimport { client, e } from \"../client\";\n\ntype Props = {\n feed: PostProps[];\n};\n\nconst Blog: React.FC = (props) => {\n return (\n \n
\n

Published posts

\n
\n {props.feed.length ? (\n props.feed.map((post) => (\n ", "suffix": "jsx>{`\n .post {\n transition: box-shadow 0s ease-in;\n border: 2px solid #eee;\n border-radius: 8px;\n }\n\n .post:hover {\n box-shadow: 0px 2px 8px #ccc;\n border: 2px solid #727272;\n }\n\n ", "middle": "
\n \n
\n ))\n ) : (\n

No blog posts yet.

\n )}\n
\n
\n \n
\n \n );\n};\n\nexport default Po", "middle": " }\n h2 {\n margin: 0px;\n ", "meta": {"filepath": "examples/with-edgedb/components/Post.tsx", "language": "tsx", "file_size": 918, "cut_index": 606, "middle_length": 52}} {"prefix": ";\nimport { Cell, Grid } from \"@faceless-ui/css-grid\";\nimport { Page } from \"../../../payload-types\";\nimport { BackgroundColor } from \"../../BackgroundColor\";\nimport { Gutter } from \"../../Gutter\";\nimport { CMSLink } from \"../../Link\";\nimport RichText from \"../../RichText\";\n\nimport classes from \"./index.module.scss\";\n\ntype Props = {\n ctaBackgroundColor?: \"white\" | \"black\";\n richText: {\n [k: string]: unknown;\n }[];\n links: {\n link: {\n type?: \"reference\" | \"custom\";\n newTab?: boolean;\n ", "suffix": "lToActionBlock: React.FC = ({\n ctaBackgroundColor,\n links,\n richText,\n}) => {\n const oppositeBackgroundColor =\n ctaBackgroundColor === \"white\" ? \"black\" : \"white\";\n\n return (\n \n \n \n Home\n \n \n Apollo\n \n \n Redux\n \n \n ", "middle": " \n\n \n <", "middle": "\n `}\n \n \n );\n}\n\nexport default M", "middle": " margin", "meta": {"filepath": "examples/with-framer-motion/pages/_app.js", "language": "javascript", "file_size": 790, "cut_index": 514, "middle_length": 14}} {"prefix": "rom \"../interfaces\";\nimport React, { useState } from \"react\";\nimport useSWR from \"swr\";\nimport { useAuth0 } from \"@auth0/auth0-react\";\n\nconst fetcher = (url) =>\n fetch(url).then((res) => {\n if (res.ok) {\n return res.json();\n }\n\n throw new Error(`${res.status} ${res.statusText} while fetching: ${url}`);\n });\n\nexport default function useComments() {\n const { getAccessTokenSilently } = useAuth0();\n const [text, setText] = useState(\"\");\n\n const { data: comments, mutate } = useSWR(\n", "suffix": "ent\", {\n method: \"POST\",\n body: JSON.stringify({ text }),\n headers: {\n Authorization: token,\n \"Content-Type\": \"application/json\",\n },\n });\n setText(\"\");\n await mutate();\n } catch (err) {\n ", "middle": " \"/api/comment\",\n fetcher,\n { fallbackData: [] },\n );\n\n const onSubmit = async (e: React.FormEvent) => {\n e.preventDefault();\n const token = await getAccessTokenSilently();\n\n try {\n await fetch(\"/api/comm", "meta": {"filepath": "examples/blog-with-comment/hooks/useComment.ts", "language": "typescript", "file_size": 1524, "cut_index": 537, "middle_length": 229}} {"prefix": "{ NextApiRequest, NextApiResponse } from \"next\";\nimport type { User, Comment } from \"../interfaces\";\nimport redis from \"./redis\";\nimport getUser from \"./getUser\";\nimport clearUrl from \"./clearUrl\";\n\nexport default async function deleteComments(\n req: NextApiRequest,\n res: NextApiResponse,\n) {\n const url = clearUrl(req.headers.referer);\n const { comment }: { url: string; comment: Comment } = req.body;\n const { authorization } = req.headers;\n\n if (!comment || !authorization) {\n return res.status(400)", "suffix": ";\n if (!user) return res.status(400).json({ message: \"Invalid token.\" });\n comment.user.email = user.email;\n\n const isAdmin = process.env.NEXT_PUBLIC_AUTH0_ADMIN_EMAIL === user.email;\n const isAuthor = user.sub === comment.user.sub;\n\n if (!i", "middle": ".json({ message: \"Missing parameter.\" });\n }\n\n if (!redis) {\n return res.status(500).json({ message: \"Failed to connect to redis.\" });\n }\n\n try {\n // verify user token\n const user: User = await getUser(authorization)", "meta": {"filepath": "examples/blog-with-comment/lib/deleteComment.ts", "language": "typescript", "file_size": 1266, "cut_index": 524, "middle_length": 229}} {"prefix": " type { Post } from \"../interfaces\";\nimport fs from \"fs\";\nimport { join } from \"path\";\nimport matter from \"gray-matter\";\n\nconst postsDirectory = join(process.cwd(), \"_posts\");\n\nexport function getPostSlugs() {\n return fs.readdirSync(postsDirectory);\n}\n\nexport function getPostBySlug(slug: string, fields: string[] = []) {\n const realSlug = slug.replace(/\\.md$/, \"\");\n const fullPath = join(postsDirectory, `${realSlug}.md`);\n const fileContents = fs.readFileSync(fullPath, \"utf8\");\n const { data, content } ", "suffix": "\n items[field] = content;\n }\n\n if (typeof data[field] !== \"undefined\") {\n items[field] = data[field];\n }\n });\n\n return items;\n}\n\nexport function getAllPosts(fields: string[] = []) {\n const slugs = getPostSlugs();\n const posts = slugs", "middle": "= matter(fileContents);\n\n const items: Post = {};\n\n // Ensure only the minimal needed data is exposed\n fields.forEach((field) => {\n if (field === \"slug\") {\n items[field] = realSlug;\n }\n if (field === \"content\") {", "meta": {"filepath": "examples/blog-with-comment/lib/getPost.ts", "language": "typescript", "file_size": 1181, "cut_index": 518, "middle_length": 229}} {"prefix": "rom \"../../interfaces\";\nimport distanceToNow from \"../../lib/dateRelative\";\nimport { useAuth0 } from \"@auth0/auth0-react\";\n\ntype CommentListProps = {\n comments?: Comment[];\n onDelete: (comment: Comment) => Promise;\n};\n\nexport default function CommentList({ comments, onDelete }: CommentListProps) {\n const { user } = useAuth0();\n\n return (\n
\n {comments &&\n comments.map((comment) => {\n const isAuthor = user && user.sub === comment.user.sub;\n ", "suffix": "ink-0\">\n \n \n
\n \n \n ", "suffix": "tent=\"Clone and deploy your own Next.js portfolio in minutes.\"\n />\n My awesome blog\n \n\n
\n\n
\n \n
\n \n );\n}\n", "middle": " {\n const { user, isLoading } = useUser();\n\n const [data, setData] = useState(null);\n\n useEffect(() => {\n (async () => {\n const res = await fetch(\"/api/protected-api\");\n\n const data = await res.json();\n\n setData(data);\n })();\n }, []);\n\n return (\n \n

Profile

\n\n
\n

Public page (client rendered)

\n

W", "suffix": "

By making request to '/api/protected-api' serverless function

\n

so without a valid session cookie will fail

\n

{JSON.stringify(data)}

\n
\n
\n );\n};\n\n// Public route.(CSR) also accessing API from the cli", "middle": "e are fetching data on the client-side :

\n ", "meta": {"filepath": "examples/auth0/pages/advanced/api-profile.tsx", "language": "tsx", "file_size": 981, "cut_index": 582, "middle_length": 52}} {"prefix": "nt-side rendering\n\nimport { useState } from \"react\";\nimport Header from \"./_components/Header\"; // Adjust the path based on your directory structure\nimport dynamic from \"next/dynamic\";\n\nconst DynamicComponent1 = dynamic(() => import(\"./_components/hello1\"));\n\nconst DynamicComponent2WithCustomLoading = dynamic(\n () => import(\"./_components/hello2\"),\n { loading: () =>

Loading caused by client page transition ...

},\n);\n\nconst DynamicComponent3WithNoSSR = dynamic(\n () => import(\"./_components/hello3\")", "suffix": "\"Joe\", \"Bel\", \"Max\", \"Lee\"];\n\nexport default function IndexPage() {\n const [showMore, setShowMore] = useState(false);\n const [falsyField] = useState(false);\n const [results, setResults] = useState();\n\n return (\n
\n
\n\n {/* Loa", "middle": ",\n { loading: () =>

Loading ...

, ssr: false },\n);\n\nconst DynamicComponent4 = dynamic(() => import(\"./_components/hello4\"));\n\nconst DynamicComponent5 = dynamic(() => import(\"./_components/hello5\"));\n\nconst names = [\"Tim\", ", "meta": {"filepath": "examples/with-dynamic-import/app/page.tsx", "language": "tsx", "file_size": 2082, "cut_index": 563, "middle_length": 229}} {"prefix": "{ NextApiRequest, NextApiResponse } from \"next\";\nimport type { Comment } from \"../interfaces\";\nimport redis from \"./redis\";\nimport { nanoid } from \"nanoid\";\nimport getUser from \"./getUser\";\nimport clearUrl from \"./clearUrl\";\n\nexport default async function createComments(\n req: NextApiRequest,\n res: NextApiResponse,\n) {\n const url = clearUrl(req.headers.referer);\n const { text } = req.body;\n const { authorization } = req.headers;\n\n if (!text || !authorization) {\n return res.status(400).json({ messag", "suffix": ");\n if (!user) return res.status(400).json({ message: \"Need authorization.\" });\n\n const { name, picture, sub, email } = user;\n\n const comment: Comment = {\n id: nanoid(),\n created_at: Date.now(),\n url,\n text,\n user: { name,", "middle": "e: \"Missing parameter.\" });\n }\n\n if (!redis) {\n return res\n .status(400)\n .json({ message: \"Failed to connect to redis client.\" });\n }\n\n try {\n // verify user token\n const user = await getUser(authorization", "meta": {"filepath": "examples/blog-with-comment/lib/createComment.ts", "language": "typescript", "file_size": 1253, "cut_index": 524, "middle_length": 229}} {"prefix": "\"@auth0/auth0-react\";\n\ntype CommentFormProps = {\n text: string;\n setText: Function;\n onSubmit: (e: React.FormEvent) => Promise;\n};\n\nexport default function CommentForm({\n text,\n setText,\n onSubmit,\n}: CommentFormProps) {\n const { isAuthenticated, logout, loginWithPopup } = useAuth0();\n\n return (\n
\n \n\n
\n {isAuthenticated ? (\n
\n \n \n );\n}\n\nfunction SignOut({ children }: { children: React.ReactNode }) {\n return (\n {\n \"use server\";\n await signOut();\n }}\n >\n

{children}

\n
\n
\n {category && (\n \n ", "middle": " src={image}\n alt={name}\n />\n
\n
{name}
\n

{description}

\n

;\n}) {\n const { id } = await params;\n const postId = parseInt(id);\n\n const post = await prisma.post.findUnique({\n where: { id: postId },\n include: {\n author: true,\n },\n });\n\n if (!post) {\n notFound();\n }\n\n // Server action to delete the post\n async function deletePos", "suffix": "enter p-8\">\n

\n {/* Post Title */}\n

\n {post.title}\n

\n\n {/* Author Information *", "middle": "t() {\n \"use server\";\n\n await prisma.post.delete({\n where: {\n id: postId,\n },\n });\n\n redirect(\"/posts\");\n }\n\n return (\n
user.email === \"alice@example.com\")?.id,\n bob: userRecords.find((user) => user.email === ", "suffix": "=> user.email === \"edward@example.com\")?.id,\n };\n\n // Create 15 posts distributed among users\n await prisma.post.createMany({\n data: [\n // Alice's posts\n {\n title: \"Getting Started with TypeScript and Prisma\",\n content:\n ", "middle": "\"bob@example.com\")?.id,\n charlie: userRecords.find((user) => user.email === \"charlie@example.com\")\n ?.id,\n diana: userRecords.find((user) => user.email === \"diana@example.com\")?.id,\n edward: userRecords.find((user) ", "meta": {"filepath": "examples/prisma-postgres/prisma/seed.ts", "language": "typescript", "file_size": 5586, "cut_index": 716, "middle_length": 229}} {"prefix": "D here:\n// https://github.com/garmeeh/next-seo#json-ld\nexport default function JsonLd() {\n return (\n
\n \n

JSON-LD Added to Page

\n

\n Take a look at the head to see what has been added, yo", "middle": "Name=\"Jane Blogs\"\n publisherName=\"Mary Blogs\"", "meta": {"filepath": "examples/with-next-seo/pages/jsonld.js", "language": "javascript", "file_size": 989, "cut_index": 582, "middle_length": 52}} {"prefix": ";\n\nimport { HttpLink } from \"@apollo/client\";\nimport {\n ApolloNextAppProvider,\n NextSSRInMemoryCache,\n NextSSRApolloClient,\n} from \"@apollo/experimental-nextjs-app-support/ssr\";\n\nfunction makeClient() {\n const httpLink = new HttpLink({\n // See more information about this GraphQL endpoint at https://studio.apollographql.com/public/spacex-l4uc6p/variant/main/home\n uri: \"https://main--spacex-l4uc6p.apollographos.net/graphql\",\n // you can configure the Next.js fetch cache here if you want to\n fe", "suffix": "ata fetching hook, e.g.:\n // ```js\n // const { data } = useSuspenseQuery(\n // MY_QUERY,\n // {\n // context: {\n // fetchOptions: {\n // cache: \"no-store\"\n // }\n // }\n // }\n // );\n // ```\n ", "middle": "tchOptions: { cache: \"force-cache\" },\n // alternatively you can override the default `fetchOptions` on a per query basis\n // via the `context` property on the options passed as a second argument\n // to an Apollo Client d", "meta": {"filepath": "examples/with-apollo/src/components/ApolloClientProvider.tsx", "language": "tsx", "file_size": 1365, "cut_index": 524, "middle_length": 229}} {"prefix": "NextPageContext } from 'next'\nimport Layout from \"../../components/Layout\";\nimport { User } from \"../../interfaces\";\nimport { findAll, findData } from \"../../utils/sample-api\";\nimport ListDetail from \"../../components/ListDetail\";\nimport { GetStaticPaths, GetStaticProps } from \"next\";\n\ntype Params = {\n id?: string;\n};\n\ntype Props = {\n item?: User;\n errors?: string;\n};\n\nconst InitialPropsDetail = ({ item, errors }: Props) => {\n if (errors) {\n return (\n \n {item && }\n \n );\n};\n\nexport const getStaticPaths: GetStaticPaths = async () => {\n const items: User[] = await findAll();\n const paths = items.map((item) => `/detail/${item.id}`);\n return { p", "middle": " + Electron Example`}>\n

\n Error: {errors}\n

\n \n );\n }\n\n return (\n {\n await prepareNext(\"./renderer\");\n\n const mainWindow = new BrowserWindow({\n width: 800,\n height: 600,\n webPreferences: {\n nodeIntegration: false,\n contextIsolation: true,\n preload: j", "suffix": " });\n\n mainWindow.loadURL(url);\n});\n\n// Quit the app once all windows are closed\napp.on(\"window-all-closed\", app.quit);\n\n// listen the channel `message` and resend the received message to the renderer process\nipcMain.on(\"message\", (event: IpcMainEvent, m", "middle": "oin(__dirname, \"preload.js\"),\n },\n });\n\n const url = isDev\n ? \"http://localhost:8000/\"\n : format({\n pathname: join(__dirname, \"../renderer/out/index.html\"),\n protocol: \"file:\",\n slashes: true,\n ", "meta": {"filepath": "examples/with-electron-typescript/electron-src/index.ts", "language": "typescript", "file_size": 1121, "cut_index": 515, "middle_length": 229}} {"prefix": "ad\";\nimport Image from \"next/image\";\nimport styles from \"@/pages/index.module.css\";\n\nexport default function Home() {\n return (\n
\n \n Create Next App\n \n \n\n
\n

\n Welcome to Next.js!\n

\n\n

\n Get started by editing pages/index.js\n \n\n \n

Learn →

\n

Learn about Next.js in an interactive course with quizzes!

\n
\n\n \n

\n\n
\n \n

Documentation →

\n

Find in-depth information about Next.js feature", "meta": {"filepath": "examples/with-jest/pages/home/index.tsx", "language": "tsx", "file_size": 1976, "cut_index": 537, "middle_length": 229}} {"prefix": "rom \"next/head\";\nimport Image from \"next/image\";\nimport styles from \"../styles/Home.module.css\";\n\nconst Home: NextPage = () => {\n return (\n

\n \n Create Next App\n \n \n \n\n
\n

\n Welcome to Next.js!\n ", "suffix": "s://nextjs.org/docs\" className={styles.card}>\n

Documentation →

\n

Find in-depth information about Next.js features and API.

\n \n\n \n ", "middle": " \n\n

\n Get started by editing{\" \"}\n pages/index.tsx\n

\n\n
\n \n Name\n \n ", "middle": "ite rounded-lg shadow-md mt-12\">\n

Create New User

\n
\n
\n
\n \n ", "middle": "text-4xl lg:text-6xl leading-tight\">\n \n {title}\n \n \n
\n \n \n

SEO Added to Page data.id === Number(id));\n\n if (!selected) {\n throw new Error(\"Cannot find user\");\n ", "suffix": "elected;\n}\n\n/** Calls a mock API which returns the above array to simulate \"get all\". */\nexport async function findAll() {\n // Throw an error, just for example.\n if (!Array.isArray(dataArray)) {\n throw new Error(\"Cannot find users\");\n }\n\n return dat", "middle": " }\n\n return s", "meta": {"filepath": "examples/with-electron-typescript/renderer/utils/sample-api.ts", "language": "typescript", "file_size": 797, "cut_index": 517, "middle_length": 14}} {"prefix": "string\n description: string\n link: string\n}\n\nconst Card = (props: Props) => {\n return (\n \n ", "suffix": " fontSize: '1.5rem',\n fontWeight: 'bold',\n textAlign: 'left',\n }}\n >\n {props.title}\n \n (0);\nconst CounterDispatchContext = createContext>(\n () => null,\n);\n\nconst reducer = (state: CounterState, action: CounterAction) => {\n switch (action.type) {\n case \"I", "suffix": "type CounterProviderProps = {\n children: ReactNode;\n initialValue?: number;\n};\n\nexport const CounterProvider = ({\n children,\n initialValue = 0,\n}: CounterProviderProps) => {\n const [state, dispatch] = useReducer(reducer, initialValue);\n return (\n ", "middle": "NCREASE\":\n return state + 1;\n case \"DECREASE\":\n return state - 1;\n case \"INCREASE_BY\":\n return state + action.payload;\n default:\n throw new Error(`Unknown action: ${JSON.stringify(action)}`);\n }\n};\n\n", "meta": {"filepath": "examples/with-context-api/_components/Counter.tsx", "language": "tsx", "file_size": 1353, "cut_index": 524, "middle_length": 229}} {"prefix": " IClientOptions } from \"mqtt\";\nimport MQTT from \"mqtt\";\nimport { useEffect, useRef } from \"react\";\n\ninterface useMqttProps {\n uri: string;\n options?: IClientOptions;\n topicHandlers?: { topic: string; handler: (payload: any) => void }[];\n onConnectedHandler?: (client: MqttClient) => void;\n}\n\nfunction useMqtt({\n uri,\n options = {},\n topicHandlers = [{ topic: \"\", handler: ({ topic, payload, packet }) => {} }],\n onConnectedHandler = (client) => {},\n}: useMqttProps) {\n const clientRef = useRef {\n client?.subscribe(th.topic);\n });\n client?.on(\"message\", (topic: string, rawPa", "middle": "t | null>(null);\n\n useEffect(() => {\n if (clientRef.current) return;\n if (!topicHandlers || topicHandlers.length === 0) return () => {};\n\n try {\n clientRef.current = options\n ? MQTT.connect(uri, options)\n ", "meta": {"filepath": "examples/with-mqtt-js/lib/useMqtt.ts", "language": "typescript", "file_size": 1671, "cut_index": 537, "middle_length": 229}} {"prefix": "t useI18n from \"../hooks/use-i18n\";\nimport Title from \"../components/title\";\nimport { contentLanguageMap } from \"../lib/i18n\";\nimport EN from \"../locales/en.json\";\nimport DE from \"../locales/de.json\";\n\nconst Dashboard = () => {\n const i18n = useI18n();\n\n useEffect(() => {\n i18n.locale(\"en\", EN);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n
\n \n \n

{i18n.t(\"intro.text\")}

\n

{i18n.t(\"dashboard.description\")}

\n
Current locale: {i18n.activeLocale}
\n {\n i18n.locale(\"de\", DE);\n }}\n >\n ", "middle": "ale]}\n />\n \n ;\n\nexport default meta;\ntype Story = StoryObj", "middle": "todocs entry: https://storybook.js.org/docs/writing-docs/autodocs\n tags: [\"autodocs\"],\n // More on argTypes: https://storybook.js.org/docs/api/argtypes\n argTypes: {\n backgroundColor: {\n control: \"color\",\n },\n },\n ", "meta": {"filepath": "examples/with-storybook/stories/Button.stories.ts", "language": "typescript", "file_size": 1456, "cut_index": 524, "middle_length": 229}} {"prefix": "port type { Meta, StoryObj } from \"@storybook/react\";\nimport { fn } from \"@storybook/test\";\nimport { Header } from \"./Header\";\n\nconst meta = {\n title: \"Example/Header\",\n component: Header,\n // This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/react/writing-docs/autodocs\n tags: [\"autodocs\"],\n parameters: {\n // More on how to position stories at: https://storybook.js.org/docs/configure/story-layout\n layout: \"fullscreen\",\n },\n args: {\n onLogin: fn", "suffix": "ut: fn(),\n onCreateAccount: fn(),\n },\n} satisfies Meta<typeof Header>;\n\nexport default meta;\ntype Story = StoryObj<typeof meta>;\n\nexport const LoggedIn: Story = {\n args: {\n user: {\n name: \"Jane Doe\",\n },\n },\n};\n\nexport const LoggedOut: Sto", "middle": "(),\n onLogo", "meta": {"filepath": "examples/with-storybook/stories/Header.stories.ts", "language": "typescript", "file_size": 793, "cut_index": 514, "middle_length": 14}} {"prefix": "mport type { Meta, StoryObj } from \"@storybook/react\";\nimport { within, userEvent, expect } from \"@storybook/test\";\n\nimport { Page } from \"./Page\";\n\nconst meta = {\n title: \"Example/Page\",\n component: Page,\n parameters: {\n // More on how to position stories at: https://storybook.js.org/docs/configure/story-layout\n layout: \"fullscreen\",\n },\n} satisfies Meta<typeof Page>;\n\nexport default meta;\ntype Story = StoryObj<typeof meta>;\n\nexport const LoggedOut: Story = {};\n\n// More on interaction testing: ht", "suffix": "name: /Log in/i });\n await expect(loginButton).toBeInTheDocument();\n await userEvent.click(loginButton);\n await expect(loginButton).not.toBeInTheDocument();\n\n const logoutButton = canvas.getByRole(\"button\", { name: /Log out/i });\n await expe", "middle": "tps://storybook.js.org/docs/writing-tests/interaction-testing\nexport const LoggedIn: Story = {\n play: async ({ canvasElement }) => {\n const canvas = within(canvasElement);\n const loginButton = canvas.getByRole(\"button\", { ", "meta": {"filepath": "examples/with-storybook/stories/Page.stories.ts", "language": "typescript", "file_size": 1044, "cut_index": 513, "middle_length": 229}} {"prefix": "\"./page.module.css\";\n\nexport default function Home() {\n return (\n <main className={styles.main}>\n <div className={styles.description}>\n <p>\n Get started by editing \n <code className={styles.code}>src/app/page.tsx</code>\n </p>\n <div>\n <a\n href=\"https://vercel.com?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n By", "suffix": " </a>\n </div>\n </div>\n\n <div className={styles.center}>\n <Image\n className={styles.logo}\n src=\"/next.svg\"\n alt=\"Next.js Logo\"\n width={180}\n height={37}\n priority\n />\n ", "middle": "{\" \"}\n <Image\n src=\"/vercel.svg\"\n alt=\"Vercel Logo\"\n className={styles.vercelLogo}\n width={100}\n height={24}\n priority\n />\n ", "meta": {"filepath": "examples/with-storybook/app/page.tsx", "language": "tsx", "file_size": 2766, "cut_index": 563, "middle_length": 229}} {"prefix": ", Text } from \"@nextui-org/react\";\n\nconst CustomCollapse = () => {\n return (\n <Collapse.Group>\n <Collapse title=\"Option A\">\n <Text>\n I have had my invitation to this world's festival, and thus my life\n has been blessed.\n </Text>\n </Collapse>\n <Collapse title=\"Option B\">\n <Text>\n In the meanwhile I smile and I sing all alone. In the meanwhile the\n air is filling with the perfume of promise.\n </Text>\n </Collapse>\n <Co", "suffix": "came out on the chariot of the first gleam of light, and pursued my\n voyage through the wildernesses of worlds leaving my track on many a\n star and planet.\n </Text>\n </Collapse>\n </Collapse.Group>\n );\n};\n\nexport default Cu", "middle": "llapse title=\"Option C\">\n <Text>\n I ", "meta": {"filepath": "examples/with-next-ui/components/Collapse.tsx", "language": "tsx", "file_size": 851, "cut_index": 529, "middle_length": 52}} {"prefix": "Prop } from \"../common/interface\";\n\nexport const Password = ({ fill, size, height, width, ...props }: SvgProp) => {\n return (\n <svg\n width={size || width || 24}\n height={size || height || 24}\n viewBox=\"0 0 24 24\"\n {...props}\n >\n <g fill={fill}>\n <path d=\"M18.75 8v2.1a12.984 12.984 0 00-1.5-.1V8c0-3.15-.89-5.25-5.25-5.25S6.75 4.85 6.75 8v2a12.984 12.984 0 00-1.5.1V8c0-2.9.7-6.75 6.75-6.75S18.75 5.1 18.75 8z\" />\n <path d=\"M18.75 10.1a12.984 12.984 0 00-1.5-.1H6.75", "suffix": "0 01.21-.33 1.032 1.032 0 01.33-.21 1 1 0 011.09.21 1.155 1.155 0 01.21.33A1 1 0 019 16a1.052 1.052 0 01-.29.71zm4.21-.33a1.155 1.155 0 01-.21.33A1.052 1.052 0 0112 17a1.033 1.033 0 01-.71-.29 1.155 1.155 0 01-.21-.33A1 1 0 0111 16a1.033 1.033 0 01.29-.71 ", "middle": "a12.984 12.984 0 00-1.5.1C2.7 10.41 2 11.66 2 15v2c0 4 1 5 5 5h10c4 0 5-1 5-5v-2c0-3.34-.7-4.59-3.25-4.9zM8.71 16.71A1.052 1.052 0 018 17a1 1 0 01-.38-.08 1.032 1.032 0 01-.33-.21A1.052 1.052 0 017 16a1 1 0 01.08-.38 1.155 1.155 ", "meta": {"filepath": "examples/with-next-ui/components/Password.tsx", "language": "tsx", "file_size": 1283, "cut_index": 524, "middle_length": 229}} {"prefix": "m \"@twilio-paste/core/anchor\";\nimport { Heading } from \"@twilio-paste/core/heading\";\nimport { Box } from \"@twilio-paste/core/box\";\nimport { Paragraph } from \"@twilio-paste/core/paragraph\";\nimport { ListItem, UnorderedList } from \"@twilio-paste/core/list\";\nimport { ArrowForwardIcon } from \"@twilio-paste/icons/cjs/ArrowForwardIcon\";\nimport { Separator } from \"@twilio-paste/core/separator\";\n\nexport default function Home() {\n return (\n <Box as=\"main\" padding=\"space70\">\n <Head>\n <title>Paste Next", "suffix": "\n </Heading>\n\n <Paragraph>\n Everything you need to get started using Paste in a Production app.\n Start by editing <code>pages/index.tsx</code>\n </Paragraph>\n\n <Separator orientation=\"horizontal\" verticalSpacing=\"space120\" ", "middle": ".js App\n \n \n\n \n Welcome to the{\" \"}\n Paste Next.js App!", "meta": {"filepath": "examples/with-paste-typescript/pages/index.tsx", "language": "tsx", "file_size": 2697, "cut_index": 563, "middle_length": 229}} {"prefix": "lint-disable @typescript-eslint/no-namespace */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { contextBridge, ipcRenderer } from \"electron\";\nimport { IpcRendererEvent } from \"electron/main\";\n\n// We are using the context bridge to securely expose NodeAPIs.\n// Please note that many Node APIs grant access to local system resources.\n// Be very cautious about which globals and APIs you expose to untrusted remote content.\ncontextBridge.exposeInMainWorld(\"electron\", {\n sayHello: () => ipcR", "suffix": "llo: (handler: (event: IpcRendererEvent, ...args: any[]) => void) =>\n ipcRenderer.on(\"message\", handler),\n stopReceivingHello: (\n handler: (event: IpcRendererEvent, ...args: any[]) => void,\n ) => ipcRenderer.removeListener(\"message\", handler),\n});\n", "middle": "enderer.send(\"message\", \"hi from next\"),\n receiveHe", "meta": {"filepath": "examples/with-electron-typescript/electron-src/preload.ts", "language": "typescript", "file_size": 825, "cut_index": 517, "middle_length": 52}} {"prefix": "t { Box, Code, Text } from '@mantine/core'\nimport Card from '../components/Card'\nimport Grid from '../components/Grid'\n\nconst Home: NextPage = () => {\n return (\n \n \n Create Next App\n \n \n \n\n \n ([]);\n const addMessage = (message: any) => {\n setIncomingMessages((incomingMessages) => [...incomingMessages, message]);\n };\n const clearMessages = () => {\n setIncomingMessages(() => []);\n };\n\n const incomingMessageHandlers = useRef([\n {\n topic: \"topic1\",\n handler: (msg: string)", "suffix": "s.env.NEXT_PUBLIC_MQTT_URI,\n options: {\n username: process.env.NEXT_PUBLIC_MQTT_USERNAME,\n password: process.env.NEXT_PUBLIC_MQTT_PASSWORD,\n clientId: process.env.NEXT_PUBLIC_MQTT_CLIENTID,\n },\n topicHandlers: incomingMessageHandler", "middle": " => {\n addMessage(msg);\n },\n },\n ]);\n\n const mqttClientRef = useRef(null);\n const setMqttClient = (client: MqttClient) => {\n mqttClientRef.current = client;\n };\n useMqtt({\n uri: proces", "meta": {"filepath": "examples/with-mqtt-js/app/page.tsx", "language": "tsx", "file_size": 1836, "cut_index": 537, "middle_length": 229}} {"prefix": "ort Link from \"next/link\";\nimport Head from \"next/head\";\nimport Title from \"../../components/title\";\nimport useI18n from \"../../hooks/use-i18n\";\nimport { languages, contentLanguageMap } from \"../../lib/i18n\";\n\nconst HomePage = () => {\n const i18n = useI18n();\n\n return (\n
\n \n \n \n \n <h2>{i18n.t(\"intro.text\")}</h2>\n <h3", "suffix": "c function getStaticProps({ params }) {\n const { default: lngDict = {} } = await import(\n `../../locales/${params.lng}.json`\n );\n\n return {\n props: { lng: params.lng, lngDict },\n };\n}\n\nexport async function getStaticPaths() {\n return {\n paths", "middle": ">{i18n.t(\"intro.description\")}</h3>\n <div>Current locale: {i18n.activeLocale}</div>\n <Link href=\"/[lng]\" as=\"/de\">\n Use client-side routing to change language to 'de'\n </Link>\n </div>\n );\n};\n\nexport asyn", "meta": {"filepath": "examples/with-i18n-rosetta/pages/[lng]/index.js", "language": "javascript", "file_size": 1104, "cut_index": 515, "middle_length": 229}} {"prefix": "import React from \"react\";\nimport \"./button.css\";\n\ninterface ButtonProps {\n /**\n * Is this the principal call to action on the page?\n */\n primary?: boolean;\n /**\n * What background color to use\n */\n backgroundColor?: string;\n /**\n * How large should the button be?\n */\n size?: \"small\" | \"medium\" | \"large\";\n /**\n * Button contents\n */\n label: string;\n /**\n * Optional click handler\n */\n onClick?: () => void;\n}\n\n/**\n * Primary UI component for user interaction\n */\nexport const Butt", "suffix": "type=\"button\"\n className={[\"storybook-button\", `storybook-button--${size}`, mode].join(\n \" \",\n )}\n {...props}\n >\n {label}\n <style jsx>{`\n button {\n background-color: ${backgroundColor};\n }\n `}<", "middle": "on = ({\n primary = false,\n size = \"medium\",\n backgroundColor,\n label,\n ...props\n}: ButtonProps) => {\n const mode = primary\n ? \"storybook-button--primary\"\n : \"storybook-button--secondary\";\n return (\n <button\n ", "meta": {"filepath": "examples/with-storybook/stories/Button.tsx", "language": "tsx", "file_size": 1027, "cut_index": 512, "middle_length": 229}} {"prefix": ";\n\nimport { Button } from \"./Button\";\nimport \"./header.css\";\n\ntype User = {\n name: string;\n};\n\ninterface HeaderProps {\n user?: User;\n onLogin?: () => void;\n onLogout?: () => void;\n onCreateAccount?: () => void;\n}\n\nexport const Header = ({\n user,\n onLogin,\n onLogout,\n onCreateAccount,\n}: HeaderProps) => (\n <header>\n <div className=\"storybook-header\">\n <div>\n <svg\n width=\"32\"\n height=\"32\"\n viewBox=\"0 0 32 32\"\n xmlns=\"http://www.w3.org/2000/svg\"\n ", "suffix": " d=\"M5.3 10.6l10.4 6v11.1l-10.4-6v-11zm11.4-6.2l9.7 5.5-9.7 5.6V4.4z\"\n fill=\"#555AB9\"\n />\n <path\n d=\"M27.2 10.6v11.2l-10.5 6V16.5l10.5-6zM15.7 4.4v11L6 10l9.7-5.5z\"\n fill=\"#91BAF8\"\n ", "middle": " >\n <g fill=\"none\" fillRule=\"evenodd\">\n <path\n d=\"M10 0h12a10 10 0 0110 10v12a10 10 0 01-10 10H10A10 10 0 010 22V10A10 10 0 0110 0z\"\n fill=\"#FFF\"\n />\n <path\n ", "meta": {"filepath": "examples/with-storybook/stories/Header.tsx", "language": "tsx", "file_size": 1644, "cut_index": 537, "middle_length": 229}} {"prefix": "port { SvgProp } from \"../common/interface\";\n\nexport const Mail = ({ fill, size, height, width, ...props }: SvgProp) => {\n return (\n <svg\n width={size || width || 24}\n height={size || height || 24}\n viewBox=\"0 0 24 24\"\n {...props}\n >\n <g\n fill=\"none\"\n stroke={fill}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={1.5}\n >\n <path d=\"M12 20.5H7c-3 0-5-1.5-5-5v-7c0-3.5 2-5 5-5h10c3 0 5 1.5 5 5v3\" />\n <path d=\"M17 9", "suffix": "66 3.166 0 01-3.75 0L7 9M19.21 14.77l-3.539 3.54a1.232 1.232 0 00-.3.59l-.19 1.35a.635.635 0 00.76.76l1.35-.19a1.189 1.189 0 00.59-.3l3.54-3.54a1.365 1.365 0 000-2.22 1.361 1.361 0 00-2.211.01zM18.7 15.28a3.185 3.185 0 002.22 2.22\" />\n </g>\n </svg>", "middle": "l-3.13 2.5a3.1", "meta": {"filepath": "examples/with-next-ui/components/Mail.tsx", "language": "tsx", "file_size": 793, "cut_index": 514, "middle_length": 14}} {"prefix": "next/link\";\nimport { gql, useQuery } from \"@apollo/client\";\n\nconst ViewerQuery = gql`\n query ViewerQuery {\n viewer {\n id\n email\n }\n }\n`;\n\nconst Index = () => {\n const router = useRouter();\n const { data, loading, error } = useQuery(ViewerQuery);\n const viewer = data?.viewer;\n const shouldRedirect = !(loading || error || viewer);\n\n useEffect(() => {\n if (shouldRedirect) {\n router.push(\"/signin\");\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [shouldRedi", "suffix": "}</p>;\n }\n\n if (viewer) {\n return (\n <div>\n You're signed in as {viewer.email}. Go to{\" \"}\n <Link href=\"/about\">about</Link> page or{\" \"}\n <Link href=\"/signout\">signout</Link>.\n </div>\n );\n }\n\n return <p>Loading...<", "middle": "rect]);\n\n if (error) {\n return <p>{error.message", "meta": {"filepath": "examples/api-routes-apollo-server-and-client-auth/pages/index.tsx", "language": "tsx", "file_size": 945, "cut_index": 606, "middle_length": 52}} {"prefix": "rom \"next/head\";\nimport Image from \"next/image\";\nimport styles from \"../../styles/Home.module.css\";\n\nconst Home: NextPage = () => {\n return (\n <div className={styles.container}>\n <Head>\n <title>Create Next App\n \n \n \n\n
\n

\n Welcome to Next.js!\n ", "suffix": "ttps://nextjs.org/docs\" className={styles.card}>\n

Documentation →

\n

Find in-depth information about Next.js features and API.

\n \n\n \n ", "middle": "

\n\n

\n Get started by editing{\" \"}\n pages/index.tsx\n

\n\n
\n {\n const [user, setUser] = React.useState();\n\n return (\n
\n setUser({ name: \"Jane Doe\" })}\n onLogout={() => setUser(undefined)}\n onCreateAccount={() => setUser({ name: \"Jane Doe\" })}\n />\n\n
\n

Pages in Storybook

\n

\n We recommend building UIs", "suffix": "ocess starting with atomic components and ending with pages.\n

\n

\n Render pages with mock data. This makes it easy to build and review\n page states without needing to navigate to them in your app. Here are\n so", "middle": " with a{\" \"}\n \n component-driven\n {\" \"}\n pr", "meta": {"filepath": "examples/with-storybook/stories/Page.tsx", "language": "tsx", "file_size": 2790, "cut_index": 563, "middle_length": 229}} {"prefix": "ateContext, useState, useRef, useEffect } from \"react\";\nimport rosetta from \"rosetta\";\n// import rosetta from 'rosetta/debug';\n\nconst i18n = rosetta();\n\nexport const defaultLanguage = \"en\";\nexport const languages = [\"de\", \"en\"];\nexport const contentLanguageMap = { de: \"de-DE\", en: \"en-US\" };\n\nexport const I18nContext = createContext();\n\n// default language\ni18n.locale(defaultLanguage);\n\nexport default function I18n({ children, locale, lngDict }) {\n const activeLocaleRef = useRef(locale || defaultLanguage);", "suffix": " activeLocaleRef.current = l;\n if (dict) {\n i18n.set(l, dict);\n }\n // force rerender to update view\n setTick((tick) => tick + 1);\n },\n };\n\n // for initial SSR render\n if (locale && firstRender.current === true) {\n firs", "middle": "\n const [, setTick] = useState(0);\n const firstRender = useRef(true);\n\n const i18nWrapper = {\n activeLocale: activeLocaleRef.current,\n t: (...args) => i18n.t(...args),\n locale: (l, dict) => {\n i18n.locale(l);\n ", "meta": {"filepath": "examples/with-i18n-rosetta/lib/i18n.js", "language": "javascript", "file_size": 1379, "cut_index": 524, "middle_length": 229}} {"prefix": ". This is useful to test the logic for rewriting\n * paths to multi zones to make sure that the logic is correct before deploying the application.\n */\n\nimport { type MatchResult, compile, match } from \"path-to-regexp\";\nimport nextConfig from \"../next.config.js\";\n\nfunction getDestination(destination: string, pathMatch: MatchResult): string {\n const hasDifferentHost = destination.startsWith(\"https://\");\n if (hasDifferentHost) {\n const destinationUrl = new URL(destination);\n destinationUrl.pathname = co", "suffix": "st BLOG_URL = \"https://with-zones-blog.vercel.app\";\n\ndescribe(\"next.config.js test\", () => {\n describe(\"rewrites\", () => {\n let rewrites: Awaited>>;\n\n beforeAll(async () => {\n process.env.BLOG_", "middle": "mpile(destinationUrl.pathname, {\n encode: encodeURIComponent,\n })(pathMatch.params);\n return destinationUrl.toString();\n }\n return compile(destination, {\n encode: encodeURIComponent,\n })(pathMatch.params);\n}\n\ncon", "meta": {"filepath": "examples/with-zones/home/test/next-config.test.ts", "language": "typescript", "file_size": 2351, "cut_index": 563, "middle_length": 229}} {"prefix": "bles } = {} as any,\n preview: boolean,\n) {\n const url = preview\n ? `${process.env.NEXT_PUBLIC_WEBINY_PREVIEW_API_URL}`\n : `${process.env.NEXT_PUBLIC_WEBINY_API_UR}`;\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${process.env.WEBINY_API_SECRET}`,\n },\n body: JSON.stringify({\n query,\n variables,\n }),\n });\n\n const json = await res.json();\n if (json.errors) {\n console.error(json.errors)", "suffix": " slug\n }\n }\n }\n `,\n {},\n false,\n );\n return data?.listPosts.data;\n}\n\nexport async function getAllPostsForHome(preview) {\n const data = await fetchAPI(\n `\n query Posts {\n listPosts {\n data {\n ", "middle": ";\n throw new Error(\"Failed to fetch API\");\n }\n\n return json.data;\n}\n\nexport async function getAllPostsWithSlug() {\n const data = await fetchAPI(\n `\n query PostSlugs {\n listPosts {\n data {\n ", "meta": {"filepath": "examples/cms-webiny/lib/api.ts", "language": "typescript", "file_size": 2260, "cut_index": 563, "middle_length": 229}} {"prefix": "es\";\nimport Link from \"next/link\";\nimport Image from \"next/image\";\n\nexport type TCoverImage = {\n title: string;\n src: string;\n slug?: string;\n height: number;\n width: number;\n};\n\nconst CoverImage: React.FC = ({\n title,\n src,\n slug,\n height,\n width,\n}) => {\n const image = (\n \n );\n return (\n

\n {slug ? (\n \n {image}\n \n ) : (\n image\n )}\n
\n );\n};\nexport default CoverImage;", "middle": "width}\n h", "meta": {"filepath": "examples/cms-webiny/components/cover-image.tsx", "language": "tsx", "file_size": 807, "cut_index": 536, "middle_length": 14}} {"prefix": " Container from \"./container\";\nimport { EXAMPLE_PATH } from \"../lib/constants\";\n\nexport default function Footer() {\n return (\n
\n \n
\n

\n Statically Generated with Next.js.\n

\n
\n Read Documentation\n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n
\n

\n \n {title}\n \n

\n
\n \n
\n

{excerpt}

\n \n \n )}\n {morePo", "middle": "w={preview}>\n \n {`Next.js Blog Example with ${CMS_NAME}`}\n \n \n \n {heroPost && (\n \n
\n

\n Get started by editing \n app/page.tsx\n

\n
\n \n \n
\n
\n\n
\n
\n ", "middle": "medium=appdir-template&utm_campaign=create-next-app\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n By{\" \"}\n Docker!\n \n

\n A production-ready example demonstrating how to Dockerize Next.js\n applications using standalone mode.\n

\n
\n
\n \n
\n
    \n
  • Mu", "middle": "p-8 shadow-lg border border-zinc-200\">\n

    \n Standalone Mode\n

    \n

    \n This example ", "meta": {"filepath": "examples/with-docker/app/page.tsx", "language": "tsx", "file_size": 10248, "cut_index": 921, "middle_length": 229}} {"prefix": "reateOvermindSSR } from \"overmind\";\nimport { config } from \"../overmind\";\nimport Header from \"../components/Header\";\nimport Items from \"../components/Items\";\n\nexport async function getStaticProps() {\n // If we want to produce some mutations we do so by instantiating\n // an Overmind SSR instance, do whatever datafetching is needed and\n // change the state directly. We return the mutations performed with\n // \"hydrate\"\n const overmind = createOvermindSSR(config);\n\n overmind.state.page = \"Index\";\n overmi", "suffix": " = [\n {\n id: 0,\n title: \"foo\",\n },\n {\n id: 1,\n title: \"bar\",\n },\n ];\n\n return {\n props: { mutations: overmind.hydrate() },\n };\n}\n\nexport default function IndexPage() {\n return (\n

    \n
    \n {\n const [loaded, setLoaded] = useState(false);\n const { pageTransitionReadyToEnter } = props;\n\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n pageTransitionReadyToEnter();\n setLoaded(true);\n }, 2000);\n return () => {\n clearTimeout(timeoutId);\n };\n }, [pageTransitionReadyToEnter]);\n\n if (!loaded) return null;\n\n return (\n
    \n Go back home\n \n
    \n );\n};\n\nAbout.propTypes = {\n pageTransitionReadyToEnter: PropTypes.func,\n};\n\nAbout.defaultProps = {\n pageTransitionReadyToEnter: () => {},\n};\n\nAbout.pageTransitionDelayEnter = true;\n\nexport default A", "middle": "className=\"container bg-success page\">\n

    About us

    \n

    \n Notice how a loading spinner showed up while my content was \"loading\"?\n Pretty neat, huh?\n

    \n \n \n
    \n

    \n Statically Generated with Next.js.\n

    \n
    \n Read Documentation\n \n \n {\n const props = { style: {}, className: \"\" };\n\n if (block.data.textAlign) {\n props.style[\"textAlign\"] = block.data.textAlign;\n }\n if (block.data.className) {\n props.className = block.data.className;\n }\n return (\n \n );\n};\n\nconst renderDelimiter = () => {\n return
    ;\n};\n\nconst renderHeader = (block) ", "suffix": "lock.data.level) {\n case 1:\n return (\n {\n const props = { style: {}, className: \"\" };\n\n if (block.data.textAlign) {\n props.style[\"textAlign\"] = block.data.textAlign;\n }\n if (block.data.className) {\n props.className = block.data.className;\n }\n\n switch (b", "meta": {"filepath": "examples/cms-webiny/lib/rich-text-renderer.tsx", "language": "tsx", "file_size": 4100, "cut_index": 614, "middle_length": 229}} {"prefix": " Container from \"./container\";\nimport cn from \"classnames\";\nimport { EXAMPLE_PATH } from \"../lib/constants\";\n\nexport default function Alert({ preview }) {\n return (\n \n \n
    \n {preview ? (\n <>\n This page is a preview.{\" \"}\n \n ) : (\n <>\n The source code for this blog is{\" \"}\n \n Click here\n {\" \"}\n to exit preview mode.\n ", "meta": {"filepath": "examples/cms-webiny/components/alert.tsx", "language": "tsx", "file_size": 1203, "cut_index": 518, "middle_length": 229}} {"prefix": "URL } from \"../lib/constants\";\n\nexport default function Intro() {\n return (\n
    \n

    \n Blog.\n

    \n

    \n A statically generated blog example using{\" \"}\n {\" \"}\n and{\" \"}\n \n {CMS_NAME}\n \n .\n

    \n
    \n )", "middle": "on-colors duration-200 hover:text-success\"\n >", "meta": {"filepath": "examples/cms-webiny/components/intro.tsx", "language": "tsx", "file_size": 847, "cut_index": 535, "middle_length": 52}} {"prefix": ") {\n // Check the secret and next parameters\n // This secret should only be known to this API route and the CMS\n if (req.query.secret !== process.env.PREVIEW_API_SECRET || !req.query.slug) {\n return res.status(401).json({ message: \"Invalid token\" });\n }\n\n // Fetch the headless CMS to check if the provided `slug` exists\n const { post } = await getPostBySlug(req.query.slug, true);\n\n // If the slug doesn't exist prevent preview mode from being enabled\n if (!post) {\n return res.status(401).json({ ", "suffix": "ode by setting the cookie\n res.setDraftMode({ enable: true });\n\n // Redirect to the path from the fetched post\n // We don't redirect to req.query.slug as that might lead to open redirect vulnerabilities\n res.writeHead(307, { Location: `/posts/${post.da", "middle": "message: \"Invalid slug\" });\n }\n\n // Enable Draft M", "meta": {"filepath": "examples/cms-webiny/pages/api/preview.ts", "language": "typescript", "file_size": 943, "cut_index": 606, "middle_length": 52}} {"prefix": "./styles/Home.module.css\";\nimport { connectToDatabase } from \"../util/couchbase\";\n\nexport default function Home({ isConnected }) {\n return (\n
    \n \n Create Next App\n \n \n\n
    \n

    \n Welcome to Next.js with Couchbase!\n

    \n\n {isConnected ? (\n

    README.md for\n instructions.\n

    \n \n Note: if the database was recently sta", "middle": "={`${styles.subtitle} ${styles.green}`}>\n You are connected to Couchbase\n \n ) : (\n <>\n

    \n You are NOT connected to", "meta": {"filepath": "examples/with-couchbase/pages/index.js", "language": "javascript", "file_size": 2533, "cut_index": 563, "middle_length": 229}} {"prefix": " from \"react\";\nimport App from \"next/app\";\nimport { createOvermind, createOvermindSSR, rehydrate } from \"overmind\";\nimport { Provider } from \"overmind-react\";\nimport { config } from \"../overmind\";\n\nclass MyApp extends App {\n // CLIENT: On initial route\n // SERVER: On initial route\n constructor(props) {\n super(props);\n\n const mutations = props.pageProps.mutations || [];\n\n if (typeof window !== \"undefined\") {\n // On the client we just instantiate the Overmind instance and run\n // the \"ch", "suffix": "t want to run any additional logic here\n this.overmind = createOvermindSSR(config);\n rehydrate(this.overmind.state, mutations);\n }\n }\n // CLIENT: After initial route, on page change\n // SERVER: never\n componentDidUpdate() {\n // This run", "middle": "angePage\" action\n this.overmind = createOvermind(config);\n this.overmind.actions.changePage(mutations);\n } else {\n // On the server we rehydrate the mutations to an SSR instance of Overmind,\n // as we do no", "meta": {"filepath": "examples/with-overmind/pages/_app.js", "language": "javascript", "file_size": 1376, "cut_index": 524, "middle_length": 229}} {"prefix": " } = {}) {\n const res = await fetch(\"https://gapi.storyblok.com/v1/api\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Token: process.env.STORYBLOK_API_KEY,\n Version: preview ? \"draft\" : \"published\",\n },\n body: JSON.stringify({\n query,\n variables,\n }),\n });\n\n const json = await res.json();\n if (json.errors) {\n console.error(json.errors);\n throw new Error(\"Failed to fetch API\");\n }\n\n return json.data;\n}\n\nexport async function getPrevi", "suffix": " },\n );\n return post;\n}\n\nexport async function getAllPostsWithSlug() {\n const data = await fetchAPI(`\n {\n PostItems {\n items {\n slug\n }\n }\n }\n `);\n return data?.PostItems.items;\n}\n\nexport async function getAll", "middle": "ewPostBySlug(slug) {\n const post = await fetchAPI(\n `\n query PostBySlug($slug: ID!) {\n PostItem(id: $slug) {\n slug\n }\n }\n `,\n {\n preview: true,\n variables: {\n slug: `posts/${slug}`,\n },\n", "meta": {"filepath": "examples/cms-storyblok/lib/api.js", "language": "javascript", "file_size": 2465, "cut_index": 563, "middle_length": 229}} {"prefix": "ad\";\nimport Image from \"next/image\";\nimport styles from \"../styles/Home.module.css\";\nimport dynamic from \"next/dynamic\";\nimport { Avatar, Pagination } from \"@nextui-org/react\";\n\nconst CustomCheckbox = dynamic(() => import(\"../components/Checkbox\"));\nconst CustomTable = dynamic(() => import(\"../components/Table\"));\nconst CustomCollapse = dynamic(() => import(\"../components/Collapse\"));\n\nexport default function Home() {\n return (\n
    \n \n NextUI Examp", "suffix": "or=\"gradient\" textColor={\"white\"} size={\"xl\"} />\n </h1>\n <h1 className={styles.title}>\n Welcome to use <a href=\"https://nextui.org/\">NextUI!</a>\n </h1>\n {/* checkout */}\n <h2>Checkbox:</h2>\n <CustomCheckbo", "middle": "le\n \n \n \n
    \n

    \n \n
    \n \n
    \n ", "suffix": "ne\">\n {title}\n \n

    \n
    \n \n
    \n
    \n
    \n

    \n

    \n

    \n ;\n }\n return (\n \n \n
    \n {router.isFallback ? (\n Loading…\n ) : (\n <>\n
    \n \n \n \n }\n loadingDelay={500}\n loadingTimeout={{\n enter: TIMEOUT,\n exi", "suffix": "form: translate3d(0, 20px, 0);\n }\n .page-transition-enter-active {\n opacity: 1;\n transform: translate3d(0, 0, 0);\n transition:\n opacity ${TIMEOUT}ms,\n transform ${TIMEOUT}ms;\n }\n ", "middle": "t: 0,\n }}\n loadingClassNames=\"loading-indicator\"\n >\n \n \n \n ", "suffix": "com/hoangvvo/next-connect\">next-connect{\" \"}\n Example\n

    \n

    Steps to test the example:

    \n

    Sign up

    \n
      \n
    1. Click Sign up and enter a username and password.
    2. \n
    3. You will be logged in and", "middle": "

\n )}\n \n );\n}\n\nexport default function HomePage() {\n const [user] = useUser();\n return (\n <>\n

\n Passport.js +{\" \"}\n {\n // redirect to home", "middle": "t.rpassword.value) {\n setErrorMsg(`The passwords don't match`);\n return;\n }\n\n const res = await fetch(\"/api/users\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.s", "meta": {"filepath": "examples/with-passport-and-next-connect/pages/signup.js", "language": "javascript", "file_size": 2017, "cut_index": 537, "middle_length": 229}} {"prefix": " nextConnect from \"next-connect\";\nimport auth from \"../../middleware/auth\";\nimport { getAllUsers, createUser, findUserByUsername } from \"../../lib/db\";\n\nconst handler = nextConnect();\n\nhandler\n .use(auth)\n .get((req, res) => {\n // For demo purpose only. You will never have an endpoint which returns all users.\n // Remove this in production\n res.json({ users: getAllUsers(req) });\n })\n .post((req, res) => {\n const { username, password, name } = req.body;\n if (!username || !password || !name)", "suffix": "s.status(409).send(\"The username has already been used\");\n }\n const user = { username, password, name };\n // Security-wise, you must hash the password before saving it\n // const hashedPass = await argon2.hash(password);\n // const user = { us", "middle": " {\n return res.status(400).send(\"Missing fields\");\n }\n // Here you check if the username has already been used\n const usernameExisted = !!findUserByUsername(req, username);\n if (usernameExisted) {\n return re", "meta": {"filepath": "examples/with-passport-and-next-connect/pages/api/users.js", "language": "javascript", "file_size": 1251, "cut_index": 518, "middle_length": 229}} {"prefix": "mport { useEffect } from \"react\";\nimport { useRouter } from \"next/router\";\nimport Modal from \"react-modal\";\nimport Article from \"../../components/Article\";\nimport { data } from \"../../components/Grid\";\n\nModal.setAppElement(\"#__next\");\n\nconst ArticlePage = ({ articleId }) => {\n const router = useRouter();\n\n useEffect(() => {\n router.prefetch(\"/\");\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <>\n ({\n params: { articleId: articleId.toString(", "middle": "n on page load, it is the 'page'\n onRequestClose={() => router.push(\"/\")}\n contentLabel=\"Post modal\"\n >\n
\n \n \n );\n};\n\nexport defau", "meta": {"filepath": "examples/with-route-as-modal/pages/article/[articleId].js", "language": "javascript", "file_size": 1040, "cut_index": 513, "middle_length": 229}} {"prefix": "async function preview(req, res) {\n // Check the secret and next parameters\n // This secret should only be known to this API route and the CMS\n if (\n req.query.secret !== process.env.PLASMIC_PREVIEW_SECRET ||\n !req.query.slug\n ) {\n return res.status(401).json({ message: \"Invalid token\" });\n }\n\n // Check if the page with the given `slug` exists\n const pages = await PREVIEW_PLASMIC.fetchPages();\n const pageMeta = pages.find((p) => p.path === req.query.slug);\n\n // If the slug doesn't exist pr", "suffix": "a) {\n return res.status(401).json({ message: \"Invalid slug\" });\n }\n\n // Enable Draft Mode by setting the cookie\n res.setDraftMode({ enable: true });\n\n // Redirect to the path from the fetched post\n // We don't redirect to req.query.slug as that mig", "middle": "event preview mode from being enabled\n if (!pageMet", "meta": {"filepath": "examples/cms-plasmic/pages/api/preview.ts", "language": "typescript", "file_size": 964, "cut_index": 582, "middle_length": 52}} {"prefix": " * Generated data model types.\n *\n * THIS CODE IS AUTOMATICALLY GENERATED.\n *\n * Generated by convex@1.12.0.\n * To regenerate, run `npx convex dev`.\n * @module\n */\n\nimport type {\n DataModelFromSchemaDefinition,\n DocumentByName,\n TableNamesInDataModel,\n SystemTableNames,\n} from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\nimport schema from \"../schema.js\";\n\n/**\n * The names of all of your Convex tables.\n */\nexport type TableNames = TableNamesInDataModel;\n\n/**\n * The type of", "suffix": "ier for a document in Convex.\n *\n * Convex documents are uniquely identified by their `Id`, which is accessible\n * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).\n *\n * Documents can be loaded using `db.ge", "middle": " a document stored in Convex.\n *\n * @typeParam TableName - A string literal type of the table name (like \"users\").\n */\nexport type Doc = DocumentByName<\n DataModel,\n TableName\n>;\n\n/**\n * An identif", "meta": {"filepath": "examples/convex/convex/_generated/dataModel.d.ts", "language": "typescript", "file_size": 1756, "cut_index": 537, "middle_length": 229}} {"prefix": "mEvent, useEffect, useState } from \"react\";\nimport { useMutation, useQuery } from \"convex/react\";\nimport { api } from \"../convex/_generated/api\";\n\nexport default function App() {\n const messages = useQuery(api.messages.list);\n const sendMessage = useMutation(api.messages.send);\n\n const [newMessageText, setNewMessageText] = useState(\"\");\n const [name, setName] = useState(\"user\");\n\n useEffect(() => {\n setName(\"User \" + Math.floor(Math.random() * 10000));\n }, []);\n\n async function handleSendMessage(e", "suffix": "an>{name}\n

\n
    \n {messages?.map((message) => (\n
  • \n {message.author}:\n {message.body}\n {new Date(message._creationTime).t", "middle": "vent: FormEvent) {\n event.preventDefault();\n setNewMessageText(\"\");\n await sendMessage({ body: newMessageText, author: name });\n }\n return (\n
    \n

    Convex Chat

    \n

    \n ({\n increment: create.reducer((state) => {\n // Redux Toolkit allows us to write \"mutating\" logic in reducers. It\n ", "meta": {"filepath": "examples/with-redux/lib/features/counter/counterSlice.ts", "language": "typescript", "file_size": 3265, "cut_index": 614, "middle_length": 229}} {"prefix": "Node } from \"react\";\nimport { StoreProvider } from \"./StoreProvider\";\nimport { Nav } from \"./components/Nav\";\n\nimport \"./styles/globals.css\";\nimport styles from \"./styles/layout.module.css\";\n\ninterface Props {\n readonly children: ReactNode;\n}\n\nexport default function RootLayout({ children }: Props) {\n return (\n \n \n \n

    \n
    \n\n
    \n Learn \n \n

\n\n
user", "middle": ", \"sha512\")\n .toString(\"hex\");\n const user = {\n id: crypto.randomUUID(),\n createdAt: Date.now(),\n username,\n name,\n hash,\n salt,\n };\n\n // Here you should insert the user into the database\n // await db.cre", "meta": {"filepath": "examples/with-passport-and-next-connect/lib/db.js", "language": "javascript", "file_size": 1966, "cut_index": 537, "middle_length": 229}} {"prefix": "ect } from \"react\";\nimport Router from \"next/router\";\nimport Link from \"next/link\";\nimport { useUser } from \"../lib/hooks\";\n\nexport default function LoginPage() {\n const [user, { mutate }] = useUser();\n const [errorMsg, setErrorMsg] = useState(\"\");\n\n async function onSubmit(e) {\n e.preventDefault();\n\n const body = {\n username: e.currentTarget.username.value,\n password: e.currentTarget.password.value,\n };\n const res = await fetch(\"/api/login\", {\n method: \"POST\",\n headers: {", "suffix": "etErrorMsg(\"Incorrect username or password. Try better!\");\n }\n }\n\n useEffect(() => {\n // redirect to home if user is authenticated\n if (user) Router.push(\"/\");\n }, [user]);\n\n return (\n <>\n

Login to Example

\n {errorMsg && <", "middle": " \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n\n if (res.status === 200) {\n const userObj = await res.json();\n // set user to useSWR state\n mutate(userObj);\n } else {\n s", "meta": {"filepath": "examples/with-passport-and-next-connect/pages/login.js", "language": "javascript", "file_size": 1605, "cut_index": 537, "middle_length": 229}} {"prefix": "outer from \"next/router\";\nimport { useUser } from \"../lib/hooks\";\n\nfunction ProfileEdit() {\n const [user, { mutate }] = useUser();\n const nameRef = useRef();\n\n useEffect(() => {\n if (!user) return;\n nameRef.current.value = user.name;\n }, [user]);\n\n async function handleEditProfile(e) {\n e.preventDefault();\n\n const body = {\n name: nameRef.current.value,\n };\n const res = await fetch(`/api/user`, {\n method: \"PUT\",\n headers: { \"Content-Type\": \"application/json\" },\n bod", "suffix": " (res.status === 204) {\n mutate({ user: null });\n Router.replace(\"/\");\n }\n }\n\n return (\n <>\n
\n \n
\n

With QueryString Routing, and a reload won't use the modal

\n
\n {data.map((id, index) => (\n \n {id}\n \n ))}", "suffix": "eloads will keep the modal\n
\n {data.map((id, index) => (\n \n\n

With Dynamic Routing, and r", "meta": {"filepath": "examples/with-route-as-modal/components/Grid.js", "language": "javascript", "file_size": 989, "cut_index": 582, "middle_length": 52}} {"prefix": "ckageDefinition,\n} from \"./templates/component-factory\";\nimport { getItems, watchItems } from \"./utils\";\n\n/*\n COMPONENT FACTORY GENERATION\n Generates the `/src/temp/componentFactory.ts` file, which maps JSS React components\n to Sitecore renderings.\n\n The component factory is a mapping between a string name and a React component instance.\n When the Sitecore Layout service returns a layout definition, it returns named components.\n This mapping is used to construct the component hierarchy for the layout.", "suffix": "ponents/ComponentName.ts` would map to component `ComponentName`.\n This can be customized in writeComponentFactory().\n\n This script supports two modes. In default mode, the component factory file is written once.\n In watch mode, the component factory so", "middle": "\n\n Generating the componentFactory is optional, and it can be maintained manually if preferred.\n\n The default convention uses the component's filename (without the extension) as the component\n name. For example, the file `/com", "meta": {"filepath": "examples/cms-sitecore-xmcloud/scripts/generate-component-factory.ts", "language": "typescript", "file_size": 3692, "cut_index": 614, "middle_length": 229}} {"prefix": "TION\n NOTE: pluginName: the name of the plugin in the src/lib folder\n Generates the `/src/temp/{pluginName}-plugins.ts` file, which exports list of plugins\n\n Generating the plugins is optional, and it can be maintained manually if preferred.\n\n The default convention uses the plugin's filename (without the extension) as the first part of the component\n name. For example, the file `/lib/page-props-factory/plugins/exampleName.ts` would map to plugin `exampleNamePlugin`.\n This can be customized in writePl", "suffix": " [\n {\n listPath: \"scripts/temp/config-plugins.ts\",\n rootPath: \"scripts/config/plugins\",\n moduleType: ModuleType.ESM,\n },\n {\n listPath: \"src/temp/sitemap-fetcher-plugins.ts\",\n rootPath: \"src/lib/sitemap-fetcher/plugins\",\n moduleType: Mo", "middle": "ugins().\n*/\n\nenum ModuleType {\n CJS,\n ESM,\n}\n\ninterface PluginDefinition {\n listPath: string;\n rootPath: string;\n moduleType: ModuleType;\n}\n\ninterface PluginFile {\n path: string;\n name: string;\n}\n\nconst pluginDefinitions =", "meta": {"filepath": "examples/cms-sitecore-xmcloud/scripts/generate-plugins.ts", "language": "typescript", "file_size": 3757, "cut_index": 614, "middle_length": 229}} {"prefix": "rt chokidar from \"chokidar\";\n\n/**\n * Run watch mode, watching on @var rootPath\n */\nexport function watchItems(rootPath: string, cb: () => void): void {\n chokidar\n .watch(rootPath, { ignoreInitial: true, awaitWriteFinish: true })\n .on(\"add\", cb)\n .on(\"unlink\", cb);\n}\n\n/**\n * Using @var path find all files recursively and generate output using @var resolveItem by calling it for each file\n * @param path plugins path\n * @param resolveItem will resolve item in required data format\n * @param cb will be ", "suffix": ": string) => void;\n fileFormat?: RegExp;\n}): Item[] {\n const {\n path,\n resolveItem,\n cb,\n fileFormat = new RegExp(/(.+)(?(settings: {\n path: string;\n resolveItem: (path: string, name: string) => Item;\n cb?: (name", "meta": {"filepath": "examples/cms-sitecore-xmcloud/scripts/utils.ts", "language": "typescript", "file_size": 1624, "cut_index": 537, "middle_length": 229}} {"prefix": "onfigPlugin, JssConfig } from \"..\";\n\n/**\n * This plugin will set config props based on scjssconfig.json.\n * scjssconfig.json may not exist if you've never run `jss setup` (development)\n * or are depending on environment variables instead (production).\n */\nclass ScJssConfigPlugin implements ConfigPlugin {\n order = 1;\n\n async exec(config: JssConfig) {\n let scJssConfig;\n try {\n scJssConfig = require(\"scjssconfig.json\");\n } catch (e) {\n return config;\n }\n\n if (!scJssConfig) return con", "suffix": "rn Object.assign({}, config, {\n sitecoreApiKey: config.sitecoreApiKey || scJssConfig.sitecore?.apiKey,\n sitecoreApiHost:\n config.sitecoreApiHost || scJssConfig.sitecore?.layoutServiceHost,\n });\n }\n}\n\nexport const scjssconfigPlugin = ne", "middle": "fig;\n\n retu", "meta": {"filepath": "examples/cms-sitecore-xmcloud/scripts/config/plugins/scjssconfig.ts", "language": "typescript", "file_size": 815, "cut_index": 522, "middle_length": 14}} {"prefix": "ictionaryService,\n RestDictionaryService,\n GraphQLDictionaryService,\n constants,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\nimport config from \"temp/config\";\n\n/**\n * Factory responsible for creating a DictionaryService instance\n */\nexport class DictionaryServiceFactory {\n /**\n * @param {string} siteName site name\n * @returns {DictionaryService} service instance\n */\n create(siteName: string): DictionaryService {\n return process.env.FETCH_WITH === constants.FETCH_WITH.GRAPHQL\n ? new GraphQ", "suffix": "es for the current\n app. If your Sitecore instance only has 1 JSS App, you can specify the root item ID here;\n otherwise, the service will attempt to figure out the root item for the current JSS App using GraphQL and app name.\n ", "middle": "LDictionaryService({\n endpoint: config.graphQLEndpoint,\n apiKey: config.sitecoreApiKey,\n siteName,\n /*\n The Dictionary Service needs a root item ID in order to fetch dictionary phras", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/dictionary-service-factory.ts", "language": "typescript", "file_size": 1332, "cut_index": 524, "middle_length": 229}} {"prefix": "nt, NextRequest } from \"next/server\";\nimport * as plugins from \"temp/middleware-plugins\";\n\nexport interface MiddlewarePlugin {\n /**\n * Detect order when the plugin should be called, e.g. 0 - will be called first (can be a plugin which data is required for other plugins)\n */\n order: number;\n /**\n * A middleware to be called, it's required to return @type {NextResponse} for other middlewares\n */\n exec(\n req: NextRequest,\n res?: NextResponse,\n ev?: NextFetchEvent,\n ): Promise {\n const response = NextResponse.next();\n\n return (Object.values(plugins) as MiddlewarePlugin[])\n .sort((p1, p2) => p1.order - p2.order)\n .reduce(\n (p, plugin) => p.then((res) => p", "middle": ">;\n}\n\nexport default async function middleware(\n re", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/middleware/index.ts", "language": "typescript", "file_size": 959, "cut_index": 582, "middle_length": 52}} {"prefix": "psContext, GetStaticPropsContext } from \"next\";\nimport { SitecorePageProps } from \"lib/page-props\";\nimport * as plugins from \"temp/page-props-factory-plugins\";\n\n/**\n * Determines whether context is GetServerSidePropsContext (SSR) or GetStaticPropsContext (SSG)\n * @param {GetServerSidePropsContext | GetStaticPropsContext} context\n */\nexport const isServerSidePropsContext = function (\n context: GetServerSidePropsContext | GetStaticPropsContext,\n): context is GetServerSidePropsContext {\n return (context as G", "suffix": " order: number;\n /**\n * A function which will be called during page props generation\n */\n exec(\n props: SitecorePageProps,\n context: GetServerSidePropsContext | GetStaticPropsContext,\n ): Promise;\n}\n\nexport class SitecorePag", "middle": "etServerSidePropsContext).req !== undefined;\n};\n\nexport interface Plugin {\n /**\n * Detect order when the plugin should be called, e.g. 0 - will be called first (can be a plugin which data is required for other plugins)\n */\n ", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/page-props-factory/index.ts", "language": "typescript", "file_size": 1852, "cut_index": 537, "middle_length": 229}} {"prefix": "ponentPropsService } from \"@sitecore-jss/sitecore-jss-nextjs\";\nimport { SitecorePageProps } from \"lib/page-props\";\nimport { GetServerSidePropsContext, GetStaticPropsContext } from \"next\";\nimport { componentModule } from \"temp/componentFactory\";\nimport { Plugin, isServerSidePropsContext } from \"..\";\n\nclass ComponentPropsPlugin implements Plugin {\n private componentPropsService: ComponentPropsService;\n\n order = 2;\n\n constructor() {\n this.componentPropsService = new ComponentPropsService();\n }\n\n async ", "suffix": "onents level\n if (isServerSidePropsContext(context)) {\n props.componentProps =\n await this.componentPropsService.fetchServerSideComponentProps({\n layoutData: props.layoutData,\n context,\n componentModule,\n })", "middle": "exec(\n props: SitecorePageProps,\n context: GetServerSidePropsContext | GetStaticPropsContext,\n ) {\n if (!props.layoutData.sitecore.route) return props;\n\n // Retrieve component props using side-effects defined on comp", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/page-props-factory/plugins/component-props.ts", "language": "typescript", "file_size": 1316, "cut_index": 524, "middle_length": 229}} {"prefix": "om \"@sitecore-jss/sitecore-jss-nextjs\";\nimport * as plugins from \"temp/sitemap-fetcher-plugins\";\n\nexport interface SitemapFetcherPlugin {\n /**\n * A function which will be called during page props generation\n */\n exec(context?: GetStaticPathsContext): Promise;\n}\n\nexport class SitecoreSitemapFetcher {\n /**\n * Generates SitecoreSitemap for given mode (Export / Disconnected Export / SSG)\n * @param {GetStaticPathsContext} context\n */\n async fetch(context?: GetStaticPathsContext): Prom", "suffix": "alues(plugins) as SitemapFetcherPlugin[];\n const pluginsResults = await Promise.all(\n pluginsList.map((plugin) => plugin.exec(context)),\n );\n const results = pluginsResults.reduce((acc, cur) => [...acc, ...cur], []);\n return results;\n }\n}", "middle": "ise {\n const pluginsList = Object.v", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/sitemap-fetcher/index.ts", "language": "typescript", "file_size": 952, "cut_index": 582, "middle_length": 52}} {"prefix": "rate, run `npx convex dev`.\n * @module\n */\n\nimport {\n ActionBuilder,\n HttpActionBuilder,\n MutationBuilder,\n QueryBuilder,\n GenericActionCtx,\n GenericMutationCtx,\n GenericQueryCtx,\n GenericDatabaseReader,\n GenericDatabaseWriter,\n} from \"convex/server\";\nimport type { DataModel } from \"./dataModel.js\";\n\n/**\n * Define a query in this Convex app's public API.\n *\n * This function will be allowed to read your Convex database and will be accessible from the client.\n *\n * @param func - The query function. I", "suffix": "a query that is only accessible from other Convex functions (but not from the client).\n *\n * This function will be allowed to read from your Convex database. It will not be accessible from the client.\n *\n * @param func - The query function. It receives a {", "middle": "t receives a {@link QueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n */\nexport declare const query: QueryBuilder;\n\n/**\n * Define ", "meta": {"filepath": "examples/convex/convex/_generated/server.d.ts", "language": "typescript", "file_size": 5570, "cut_index": 716, "middle_length": 229}} {"prefix": "se the React-specific entry point to import `createApi`\nimport { createApi, fetchBaseQuery } from \"@reduxjs/toolkit/query/react\";\n\ninterface Quote {\n id: number;\n quote: string;\n author: string;\n}\n\ninterface QuotesApiResponse {\n quotes: Quote[];\n total: number;\n skip: number;\n limit: number;\n}\n\n// Define a service using a base URL and expected endpoints\nexport const quotesApiSlice = createApi({\n baseQuery: fetchBaseQuery({ baseUrl: \"https://dummyjson.com/quotes\" }),\n reducerPath: \"quotesApi\",\n // ", "suffix": " no argument, use `void`\n // for the argument type instead.\n getQuotes: build.query({\n query: (limit = 10) => `?limit=${limit}`,\n // `providesTags` determines which 'tag' is attached to the\n // cached data re", "middle": "Tag types are used for caching and invalidation.\n tagTypes: [\"Quotes\"],\n endpoints: (build) => ({\n // Supply generics for the return type (in this case `QuotesApiResponse`)\n // and the expected query argument. If there is", "meta": {"filepath": "examples/with-redux/lib/features/quotes/quotesApiSlice.ts", "language": "typescript", "file_size": 1269, "cut_index": 524, "middle_length": 229}} {"prefix": "st { getPublicUrl } = require(\"@sitecore-jss/sitecore-jss-nextjs\");\nconst plugins = require(\"./src/temp/next-config-plugins\") || {};\n\nconst publicUrl = getPublicUrl();\n\n/**\n * @type {import('next').NextConfig}\n */\nconst nextConfig = {\n // Set assetPrefix to our public URL\n assetPrefix: publicUrl,\n\n // Allow specifying a distinct distDir when concurrently running app in a container\n distDir: process.env.NEXTJS_DIST_DIR || \".next\",\n\n // Make the same PUBLIC_URL available as an environment variable on the", "suffix": "locales: [\"en\"],\n // This is the locale that will be used when visiting a non-locale\n // prefixed path e.g. `/styleguide`.\n defaultLocale: jssConfig.defaultLanguage,\n },\n\n // Enable React Strict Mode\n reactStrictMode: true,\n\n async rewrites() ", "middle": " client bundle\n env: {\n PUBLIC_URL: publicUrl,\n },\n\n i18n: {\n // These are all the locales you want to support in your application.\n // These should generally match (or at least be a subset of) those in Sitecore.\n ", "meta": {"filepath": "examples/cms-sitecore-xmcloud/next.config.js", "language": "javascript", "file_size": 2071, "cut_index": 563, "middle_length": 229}} {"prefix": "mage,\n Link as JssLink,\n RichText as JssRichText,\n ImageField,\n Field,\n LinkField,\n Text,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\n\ninterface Fields {\n PromoIcon: ImageField;\n PromoText: Field;\n PromoLink: LinkField;\n PromoText2: Field;\n}\n\ntype PromoProps = {\n params: { [key: string]: string };\n fields: Fields;\n};\n\nconst PromoDefaultComponent = (props: PromoProps): JSX.Element => (\n
\n
\n
\n
\n \n ", "middle": "nt\">\n Promo\n
\n
\n);\n\nexport const Default = (props: PromoProps): JSX.Element => {\n const id = props.params.RenderingIdentifier;\n if (props.fields) {\n return (\n ", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/components/Promo.tsx", "language": "tsx", "file_size": 2390, "cut_index": 563, "middle_length": 229}} {"prefix": "onfig} nextConfig\n */\nconst graphqlPlugin = (nextConfig = {}) => {\n return Object.assign({}, nextConfig, {\n webpack: (config, options) => {\n config.module.rules.push({\n test: /\\.graphql$/,\n exclude: /node_modules/,\n use: [options.defaultLoaders.babel, { loader: \"graphql-let/loader\" }],\n });\n\n config.module.rules.push({\n test: /\\.graphqls$/,\n exclude: /node_modules/,\n use: [\"graphql-let/schema/loader\"],\n });\n\n config.module.rules.push({\n ", "suffix": " use: \"yaml-loader\",\n });\n\n // Overload the Webpack config if it was already overloaded\n if (typeof nextConfig.webpack === \"function\") {\n return nextConfig.webpack(config, options);\n }\n\n return config;\n },\n });\n};\n\nmod", "middle": " test: /\\.ya?ml$/,\n type: \"json\",\n ", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/next-config/plugins/graphql.js", "language": "javascript", "file_size": 884, "cut_index": 547, "middle_length": 52}} {"prefix": "\n LayoutService,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\nimport { dictionaryServiceFactory } from \"lib/dictionary-service-factory\";\nimport { layoutServiceFactory } from \"lib/layout-service-factory\";\nimport { SitecorePageProps } from \"lib/page-props\";\nimport { pathExtractor } from \"lib/extract-path\";\nimport { Plugin, isServerSidePropsContext } from \"..\";\n\nclass NormalModePlugin implements Plugin {\n private dictionaryServices: Map;\n private layoutServices: Map;\n\n order = 1;\n\n constructor() {\n this.dictionaryServices = new Map();\n this.layoutServices = new Map();\n }\n\n async exec(\n props: SitecorePageProps,\n contex", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/page-props-factory/plugins/normal-mode.ts", "language": "typescript", "file_size": 3116, "cut_index": 614, "middle_length": 229}} {"prefix": "(() => import(\"react-quill\"), {\n ssr: false,\n loading: () =>

Loading ...

,\n});\n\nconst modules = {\n toolbar: [\n [{ header: \"1\" }, { header: \"2\" }, { font: [] }],\n [{ size: [] }],\n [\"bold\", \"italic\", \"underline\", \"strike\", \"blockquote\"],\n [\n { list: \"ordered\" },\n { list: \"bullet\" },\n { indent: \"-1\" },\n { indent: \"+1\" },\n ],\n [\"link\", \"image\", \"video\"],\n [\"clean\"],\n ],\n clipboard: {\n // toggle to add extra line breaks when pasting HTML:\n matchVisual: fa", "suffix": "://quilljs.com/docs/formats/\n */\nconst formats = [\n \"header\",\n \"font\",\n \"size\",\n \"bold\",\n \"italic\",\n \"underline\",\n \"strike\",\n \"blockquote\",\n \"list\",\n \"bullet\",\n \"indent\",\n \"link\",\n \"image\",\n \"video\",\n];\n\nexport default function Home() {\n ret", "middle": "lse,\n },\n};\n/*\n * Quill editor formats\n * See https", "meta": {"filepath": "examples/with-quill-js/pages/index.js", "language": "javascript", "file_size": 968, "cut_index": 582, "middle_length": 52}} {"prefix": " path from \"path\";\nimport { constantCase } from \"constant-case\";\nimport { JssConfig, jssConfigFactory } from \"./config\";\n\n/*\n CONFIG GENERATION\n Generates the /src/temp/config.js file which contains runtime configuration\n that the app can import and use.\n*/\n\nconst defaultConfig: JssConfig = {\n sitecoreApiKey: process.env[`${constantCase(\"sitecoreApiKey\")}`],\n sitecoreApiHost: process.env[`${constantCase(\"sitecoreApiHost\")}`],\n jssAppName: process.env[`${constantCase(\"jssAppName\")}`],\n graphQLEndpoint", "suffix": " object to disk with support for environment variables.\n * @param {JssConfig} config JSS configuration to write.\n */\nfunction writeConfig(config: JssConfig): void {\n let configText = `/* eslint-disable */\n// Do not edit this file, it is auto-generated at ", "middle": "Path: process.env[`${constantCase(\"graphQLEndpointPath\")}`],\n defaultLanguage: process.env[`${constantCase(\"defaultLanguage\")}`],\n graphQLEndpoint: process.env[`${constantCase(\"graphQLEndpoint\")}`],\n};\n\n/**\n * Writes the config", "meta": {"filepath": "examples/cms-sitecore-xmcloud/scripts/generate-config.ts", "language": "typescript", "file_size": 2114, "cut_index": 563, "middle_length": 229}} {"prefix": "g `jss scaffold `.\n The default convention is that component names must start with a capital letter, and can contain\n letters, number, underscores, or dashes.\n \n If the parameter includes a path, it must be relative to the src/components folder.\n For example, `jss scaffold search/SearchBox` will create a component called `SearchBox` in\n `src/components/search/SearchBox.tsx`. Specifying a relative path is optional, and just providing\n the name is ok.\n\n Edit this script ", "suffix": "tSrc from \"./templates/component-src\";\n\nconst componentRootPath = \"src/components\";\n\n// Matches component names that start with a capital letter, and contain only letters, number,\n// underscores, or dashes. Optionally, the component name can be preceded by", "middle": "if you wish to use your own conventions for component storage in your JSS app.\n*/\n\n/* eslint-disable no-throw-literal,no-console */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport generateComponen", "meta": {"filepath": "examples/cms-sitecore-xmcloud/scripts/scaffold-component.ts", "language": "typescript", "file_size": 3141, "cut_index": 614, "middle_length": 229}} {"prefix": "int-disable-next-line @typescript-eslint/no-var-requires\nconst plugins = require(\"scripts/temp/config-plugins\");\n\n/**\n * JSS configuration object\n */\nexport interface JssConfig extends Record {\n sitecoreApiKey?: string;\n sitecoreApiHost?: string;\n jssAppName?: string;\n graphQLEndpointPath?: string;\n defaultLanguage?: string;\n graphQLEndpoint?: string;\n}\n\nexport interface ConfigPlugin {\n /**\n * Detect order when the plugin should be called, e.g. 0 - will be called first (", "suffix": " JssConfig): Promise;\n}\n\nexport class JssConfigFactory {\n public async create(defaultConfig: JssConfig = {}): Promise {\n return (Object.values(plugins) as ConfigPlugin[])\n .sort((p1, p2) => p1.order - p2.order)\n .reduce(", "middle": "can be a plugin which data is required for other plugins)\n */\n order: number;\n /**\n * A function which will be called during config generation\n * @param {JssConfig} config Current (accumulated) config\n */\n exec(config:", "meta": {"filepath": "examples/cms-sitecore-xmcloud/scripts/config/index.ts", "language": "typescript", "file_size": 1192, "cut_index": 518, "middle_length": 229}} {"prefix": "rystring\";\nimport * as plugins from \"temp/extract-path-plugins\";\n\nexport interface Plugin {\n /**\n * A function which will be called during path extraction\n */\n exec(path: string): string;\n}\n\nexport class PathExtractor {\n /**\n * Extract normalized Sitecore item path\n * @param {ParsedUrlQuery} [params]\n */\n public extract(params: ParsedUrlQuery | undefined): string {\n if (params === undefined) {\n return \"/\";\n }\n let path = Array.isArray(params.path)\n ? params.path.join(\"/\")\n ", "suffix": "/'\n if (!path.startsWith(\"/\")) {\n path = \"/\" + path;\n }\n\n const extractedPath = (Object.values(plugins) as Plugin[]).reduce(\n (resultPath, plugin) => plugin.exec(resultPath),\n path,\n );\n\n return extractedPath;\n }\n}\n\nexport co", "middle": " : (params.path ?? \"/\");\n\n // Ensure leading '", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/extract-path/index.ts", "language": "typescript", "file_size": 896, "cut_index": 547, "middle_length": 52}} {"prefix": ";\nimport {\n ComponentParams,\n ComponentRendering,\n Placeholder,\n useSitecoreContext,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\n\nconst BACKGROUND_REG_EXP = new RegExp(\n /[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/gi,\n);\n\ninterface ComponentProps {\n rendering: ComponentRendering & { params: ComponentParams };\n params: ComponentParams;\n}\n\nconst DefaultContainer = (props: ComponentProps): JSX.Element => {\n const { sitecoreContext } = useSitecoreContext();\n const container", "suffix": "t id = props.params.RenderingIdentifier;\n let backgroundImage = props.params.BackgroundImage as string;\n let backgroundStyle: { [key: string]: string } = {};\n\n if (backgroundImage) {\n const prefix = `${\n sitecoreContext.pageState !== \"normal\" ? ", "middle": "Styles =\n props.params && props.params.Styles ? props.params.Styles : \"\";\n const styles = `${props.params.GridParameters} ${containerStyles}`.trimEnd();\n const phKey = `container-${props.params.DynamicPlaceholderId}`;\n cons", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/components/Container.tsx", "language": "tsx", "file_size": 1949, "cut_index": 537, "middle_length": 229}} {"prefix": "mage,\n Link as JssLink,\n ImageField,\n Field,\n LinkField,\n Text,\n useSitecoreContext,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\n\ninterface Fields {\n Image: ImageField;\n ImageCaption: Field;\n TargetUrl: LinkField;\n}\n\ntype ImageProps = {\n params: { [key: string]: string };\n fields: Fields;\n};\n\nconst ImageDefault = (props: ImageProps): JSX.Element => (\n
\n
\n Image\n
\n
\n);\n\nexport const Banner = (props: ImageProps): JSX.Element => {\n const { sitecoreContext } = useSitecoreContext();\n const backgroundStyle = {\n backgroundImage: `url('${props?.fields?", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/components/Image.tsx", "language": "tsx", "file_size": 2421, "cut_index": 563, "middle_length": 229}} {"prefix": "nk,\n Text,\n LinkField,\n TextField,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\n\ntype ResultsFieldLink = {\n field: {\n link: LinkField;\n };\n};\n\ninterface Fields {\n data: {\n datasource: {\n children: {\n results: ResultsFieldLink[];\n };\n field: {\n title: TextField;\n };\n };\n };\n}\n\ntype LinkListProps = {\n params: { [key: string]: string };\n fields: Fields;\n};\n\ntype LinkListItemProps = {\n key: string;\n index: number;\n total: number;\n field: LinkField;\n};\n\ncons", "suffix": " 1 === props.total) {\n className += \" last\";\n }\n return (\n
  • \n
    \n \n
    \n
  • \n );\n};\n\nexport const Default = (props: LinkListProps): JSX.Elem", "middle": "t LinkListItem = (props: LinkListItemProps) => {\n let className = `item${props.index}`;\n className += (props.index + 1) % 2 === 0 ? \" even\" : \" odd\";\n if (props.index === 0) {\n className += \" first\";\n }\n if (props.index +", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/components/LinkList.tsx", "language": "tsx", "file_size": 2028, "cut_index": 563, "middle_length": 229}} {"prefix": ";\nimport {\n RichText as JssRichText,\n useSitecoreContext,\n RichTextField,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\n\ninterface Fields {\n Content: RichTextField;\n}\n\ntype PageContentProps = {\n params: { [key: string]: string };\n fields: Fields;\n};\n\ntype ComponentContentProps = {\n id: string;\n styles: string;\n children: JSX.Element;\n};\n\nconst ComponentContent = (props: ComponentContentProps) => {\n const id = props.id;\n return (\n {\n const { sitecoreContext } = useSitecoreContext();\n const id = props.params.RenderingIdentifier;\n\n if (\n !(props.fields && props.fields.Content) &&\n !sitecoreContext?.route?.fields?.Content\n ) {\n return (\n \n
    \n
    {props.children}
    \n
    \n
    \n );\n};\n\nexport const Default = (props: PageContentProps): JSX.Element ", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/components/PageContent.tsx", "language": "tsx", "file_size": 1543, "cut_index": 537, "middle_length": 229}} {"prefix": "itecore-jss/sitecore-jss-nextjs\";\nimport config from \"temp/config\";\n\n/**\n * Factory responsible for creating a LayoutService instance\n */\nexport class LayoutServiceFactory {\n /**\n * @param {string} siteName site name\n * @returns {LayoutService} service instance\n */\n create(siteName: string): LayoutService {\n return process.env.FETCH_WITH === constants.FETCH_WITH.GRAPHQL\n ? new GraphQLLayoutService({\n endpoint: config.graphQLEndpoint,\n apiKey: config.sitecoreApiKey,\n ", "suffix": "({\n apiHost: config.sitecoreApiHost,\n apiKey: config.sitecoreApiKey,\n siteName,\n configurationName: \"default\",\n });\n }\n}\n\n/** LayoutServiceFactory singleton */\nexport const layoutServiceFactory = new LayoutServic", "middle": " siteName,\n })\n : new RestLayoutService", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/layout-service-factory.ts", "language": "typescript", "file_size": 926, "cut_index": 606, "middle_length": 52}} {"prefix": "ort { SiteInfo } from \"@sitecore-jss/sitecore-jss-nextjs\";\nimport { editingDataService } from \"@sitecore-jss/sitecore-jss-nextjs/editing\";\nimport { SitecorePageProps } from \"lib/page-props\";\nimport { GetServerSidePropsContext, GetStaticPropsContext } from \"next\";\nimport { Plugin } from \"..\";\n\nclass PreviewModePlugin implements Plugin {\n order = 1;\n\n async exec(\n props: SitecorePageProps,\n context: GetServerSidePropsContext | GetStaticPropsContext,\n ) {\n if (!context.preview) return props;\n\n /", "suffix": "get editing data for preview ${JSON.stringify(\n context.previewData,\n )}`,\n );\n }\n props.site = data.layoutData.sitecore.context.site as SiteInfo;\n props.locale = data.language;\n props.layoutData = data.layoutData;\n prop", "middle": "/ If we're in preview (editing) mode, use data already sent along with the editing request\n const data = await editingDataService.getEditingData(context.previewData);\n if (!data) {\n throw new Error(\n `Unable to ", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/page-props-factory/plugins/preview-mode.ts", "language": "typescript", "file_size": 1116, "cut_index": 515, "middle_length": 229}} {"prefix": " name: string;\n components: {\n moduleName: string;\n componentName: string;\n }[];\n}\n\nconst isLazyLoadingModule = (componentPath: string) =>\n componentPath.includes(\".dynamic\");\n\nconst removeDynamicModuleNameEnding = (moduleName: string) =>\n moduleName.replace(/\\.?dynamic$/i, \"\");\n\n/**\n * Generates the contents of the component factory file using a predefined string template.\n * @param components - the list of component files to include\n * @returns component factory file contents\n */\nfunction genera", "suffix": "ponents.filter(\n (component) => (component as PackageDefinition).components,\n ) as PackageDefinition[];\n\n const hasLazyModules = componentFiles.find((component) =>\n isLazyLoadingModule(component.path),\n );\n\n return `/* eslint-disable */\n// Do not", "middle": "teComponentFactory(\n components: (PackageDefinition | ComponentFile)[],\n): string {\n const componentFiles = components.filter(\n (component) => (component as ComponentFile).path,\n ) as ComponentFile[];\n const packages = com", "meta": {"filepath": "examples/cms-sitecore-xmcloud/scripts/templates/component-factory.ts", "language": "typescript", "file_size": 5100, "cut_index": 716, "middle_length": 229}} {"prefix": "t {\n SiteInfo,\n SiteResolver,\n} from \"@sitecore-jss/sitecore-jss-nextjs/middleware\";\nimport * as plugins from \"temp/site-resolver-plugins\";\n\n/*\n The site resolver stores site information and is used in the app\n whenever site lookup is required (e.g. by name in page props factory\n or by host in Next.js middleware).\n\n By default, the app is single-site (one JSS app per Sitecore site).\n However, multi-site is available with the `nextjs-multisite` add-on.\n*/\n\nexport interface SiteResolverPlugin {\n /**\n ", "suffix": " which will be called during sites collection\n */\n exec(sites: SiteInfo[]): SiteInfo[];\n}\n\nconst sites = (Object.values(plugins) as SiteResolverPlugin[]).reduce(\n (sites, plugin) => plugin.exec(sites),\n [],\n);\n\nexport const siteResolver = new SiteReso", "middle": " * A function", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/site-resolver/index.ts", "language": "typescript", "file_size": 800, "cut_index": 517, "middle_length": 14}} {"prefix": "t {\n Text,\n RichText,\n Field,\n withDatasourceCheck,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\nimport { ComponentProps } from \"lib/component-props\";\n\ntype ContentBlockProps = ComponentProps & {\n fields: {\n heading: Field;\n content: Field;\n };\n};\n\n/**\n * A simple Content Block component, with a heading and rich text block.\n * This is the most basic building block of a content site, and the most basic\n * JSS component that's useful.\n */\nconst ContentBlock = ({ fields }: ContentBlo", "suffix": "Element => (\n
    \n \n\n \n
    \n);\n\nexport default withDatasourceCheck()", "middle": "ckProps): JSX.", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/components/ContentBlock.tsx", "language": "tsx", "file_size": 803, "cut_index": 517, "middle_length": 14}} {"prefix": "ded for Starter Kit.\n */\nimport React from \"react\";\nimport Head from \"next/head\";\nimport {\n Placeholder,\n getPublicUrl,\n LayoutServiceData,\n Field,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\nimport Scripts from \"src/Scripts\";\n\n// Prefix public assets with a public URL to enable compatibility with Sitecore Experience Editor.\n// If you're not supporting the Experience Editor, you can remove this.\nconst publicUrl = getPublicUrl();\n\ninterface LayoutProps {\n layoutData: LayoutServiceData;\n}\n\ninterface Rout", "suffix": "= layoutData.sitecore.context.pageEditing;\n const mainClassPageEditing = isPageEditing ? \"editing-mode\" : \"prod-mode\";\n\n return (\n <>\n \n \n {fields?.Title?.value?.toString() || \"Page\"}\n {\n const { route } = layoutData.sitecore;\n const fields = route?.fields as RouteFields;\n const isPageEditing ", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/Layout.tsx", "language": "tsx", "file_size": 1742, "cut_index": 537, "middle_length": 229}} {"prefix": "onnect from \"next-connect\";\nimport auth from \"../../middleware/auth\";\nimport { deleteUser, createUser, updateUserByUsername } from \"../../lib/db\";\n\nconst handler = nextConnect();\n\nhandler\n .use(auth)\n .get((req, res) => {\n // You do not generally want to return the whole user object\n // because it may contain sensitive fields such as !!password!! Only return what is needed\n // const { name, username, favoriteColor } = req.user\n // res.json({ user: { name, username, favoriteColor } })\n res.j", "suffix": "\n })\n .use((req, res, next) => {\n // handlers after this (PUT, DELETE) all require an authenticated user\n // This middleware to check if user is authenticated before continuing\n if (!req.user) {\n res.status(401).send(\"unauthenticated\");\n ", "middle": "son({ user: req.user });\n })\n .post((req, res) => {\n const { username, password, name } = req.body;\n createUser(req, { username, password, name });\n res.status(200).json({ success: true, message: \"created new user\" });", "meta": {"filepath": "examples/with-passport-and-next-connect/pages/api/user.js", "language": "javascript", "file_size": 1323, "cut_index": 524, "middle_length": 229}} {"prefix": "phQLRequestClient } from \"@sitecore-jss/sitecore-jss-nextjs\";\nimport fs from \"fs\";\nimport { getIntrospectionQuery } from \"graphql\";\n\n// This script load graphql introspection data in order to use graphql code generator and generate typescript types\n// The `jss graphql:update` command should be executed when Sitecore templates related to the site are altered.\n\nlet jssConfig;\n\ntry {\n // eslint-disable-next-line\n jssConfig = require(\"../src/temp/config\");\n} catch (e) {\n console.error(\n \"Unable to require", "suffix": "int}...`,\n);\n\nconst client = new GraphQLRequestClient(jssConfig.graphQLEndpoint, {\n apiKey: jssConfig.sitecoreApiKey,\n});\n\nclient\n .request(getIntrospectionQuery())\n .then((result) => {\n fs.writeFile(\n \"./src/temp/GraphQLIntrospectionResult.json", "middle": " JSS config. Ensure `jss setup` has been run, and the app has been started at least once after setup.\",\n );\n console.error(e);\n process.exit(1);\n}\n\nconsole.log(\n `Fetch graphql introspection data from ${jssConfig.graphQLEndpo", "meta": {"filepath": "examples/cms-sitecore-xmcloud/scripts/fetch-graphql-introspection-data.ts", "language": "typescript", "file_size": 1356, "cut_index": 524, "middle_length": 229}} {"prefix": "oreContext,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\n\ninterface Fields {\n Id: string;\n DisplayName: string;\n Title: TextField;\n NavigationTitle: TextField;\n Href: string;\n Querystring: string;\n Children: Array;\n Styles: string[];\n}\n\ntype NavigationProps = {\n params?: { [key: string]: string };\n fields: Fields;\n handleClick: (event?: React.MouseEvent) => void;\n relativeLevel: number;\n};\n\nconst getNavigationText = function (\n props: NavigationProps,\n): JSX.Element | string", "suffix": ".DisplayName;\n }\n\n return text;\n};\n\nconst getLinkTitle = (props: NavigationProps): string | undefined => {\n let title;\n if (props.fields.NavigationTitle?.value) {\n title = props.fields.NavigationTitle.value.toString();\n } else if (props.fields.Titl", "middle": " {\n let text;\n\n if (props.fields.NavigationTitle) {\n text = ;\n } else if (props.fields.Title) {\n text = ;\n } else {\n text = props.fields", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/components/Navigation.tsx", "language": "tsx", "file_size": 4280, "cut_index": 614, "middle_length": 229}} {"prefix": "sitecore-jss/sitecore-jss-nextjs\";\nimport config from \"temp/config\";\nimport { SitemapFetcherPlugin } from \"..\";\nimport { GetStaticPathsContext } from \"next\";\n\nclass GraphqlSitemapServicePlugin implements SitemapFetcherPlugin {\n _graphqlSitemapService: GraphQLSitemapService;\n\n constructor() {\n this._graphqlSitemapService = new GraphQLSitemapService({\n endpoint: config.graphQLEndpoint,\n apiKey: config.sitecoreApiKey,\n siteName: config.jssAppName,\n });\n }\n\n async exec(context?: GetStat", "suffix": "cess.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {\n return [];\n }\n return process.env.EXPORT_MODE\n ? this._graphqlSitemapService.fetchExportSitemap(config.defaultLanguage)\n : this._graphqlSitemapService.fetchSSGSitemap(context?.l", "middle": "icPathsContext): Promise {\n if (pro", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/lib/sitemap-fetcher/plugins/graphql-sitemap-service.ts", "language": "typescript", "file_size": 990, "cut_index": 582, "middle_length": 52}} {"prefix": ";\nimport {\n ComponentParams,\n ComponentRendering,\n Placeholder,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\n\ninterface ComponentProps {\n rendering: ComponentRendering & { params: ComponentParams };\n params: ComponentParams;\n}\n\nexport const Default = (props: ComponentProps): JSX.Element => {\n const styles = `${props.params.GridParameters ?? \"\"} ${\n props.params.Styles ?? \"\"\n }`.trimEnd();\n const columnWidths = [\n props.params.ColumnWidth1,\n props.params.ColumnWidth2,\n props.params.ColumnW", "suffix": "arams.Styles2,\n props.params.Styles3,\n props.params.Styles4,\n props.params.Styles5,\n props.params.Styles6,\n props.params.Styles7,\n props.params.Styles8,\n ];\n const enabledPlaceholders = props.params.EnabledPlaceholders.split(\",\");\n con", "middle": "idth3,\n props.params.ColumnWidth4,\n props.params.ColumnWidth5,\n props.params.ColumnWidth6,\n props.params.ColumnWidth7,\n props.params.ColumnWidth8,\n ];\n const columnStyles = [\n props.params.Styles1,\n props.p", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/components/ColumnSplitter.tsx", "language": "tsx", "file_size": 1720, "cut_index": 537, "middle_length": 229}} {"prefix": "le,\n MDBCol,\n MDBContainer,\n MDBFooter,\n MDBRow,\n} from \"mdbreact\";\n\nexport default function Home() {\n return (\n <>\n \n Next.js with Material Design Bootstrap for React\n \n \n \n

    \n Welcome to Next.js!\n

    \n

    \n Get started by ed", "suffix": " \n Find in-depth information about Next.js features and API.\n \n pages/index.js\n

    \n \n \n \n \n Documentation\n ", "meta": {"filepath": "examples/with-mdbreact/pages/index.js", "language": "javascript", "file_size": 3787, "cut_index": 614, "middle_length": 229}} {"prefix": "port type { Types } from \"ably\";\nimport type { ProxyMessage, TextMessage } from \"../types\";\n\nimport Head from \"next/head\";\nimport Image from \"next/image\";\nimport styles from \"../styles/Home.module.css\";\n\nexport default function Home() {\n const [messages, setMessages] = useState([]);\n\n const [channel, ably] = useChannel(\n \"some-channel-name\",\n async (message: Types.Message) => {\n console.log(\"Received Ably message\", message);\n setMessages((messages) => [...messages, message.d", "suffix": "= presenceData.map((msg, index) => (\n
  • \n {msg.clientId}: {msg.data}\n
  • \n ));\n\n return (\n
    \n \n Create Next App\n {\n return
  • {message.text}
  • ;\n });\n\n const presentClients ", "meta": {"filepath": "examples/with-ably/pages/index.tsx", "language": "tsx", "file_size": 3158, "cut_index": 614, "middle_length": 229}} {"prefix": "* @type {import('tailwindcss').Config} */\nmodule.exports = {\n content: [\n \"./pages/**/*.{js,ts,jsx,tsx}\",\n \"./components/**/*.{js,ts,jsx,tsx}\",\n ],\n theme: {\n extend: {\n colors: {\n \"accent-1\": \"#FAFAFA\",\n \"accent-2\": \"#EAEAEA\",\n \"accent-7\": \"#333\",\n success: \"#0070f3\",\n cyan: \"#79FFE1\",\n },\n spacing: {\n 28: \"7rem\",\n },\n letterSpacing: {\n tighter: \"-.04em\",\n },\n lineHeight: {\n tight: 1.2,\n },\n fon", "suffix": " \"5xl\": \"2.5rem\",\n \"6xl\": \"2.75rem\",\n \"7xl\": \"4.5rem\",\n \"8xl\": \"6.25rem\",\n },\n boxShadow: {\n small: \"0 5px 10px rgba(0, 0, 0, 0.12)\",\n medium: \"0 8px 30px rgba(0, 0, 0, 0.12)\",\n },\n },\n },\n plugins: ", "middle": "tSize: {\n ", "meta": {"filepath": "examples/cms-umbraco-heartcore/tailwind.config.js", "language": "javascript", "file_size": 791, "cut_index": 514, "middle_length": 14}} {"prefix": "ql.umbraco.io\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Api-Key\": process.env.UMBRACO_API_KEY,\n \"Umb-Project-Alias\": process.env.UMBRACO_PROJECT_ALIAS,\n },\n body: JSON.stringify({\n query,\n variables,\n }),\n });\n const json = await res.json();\n\n if (json.errors) {\n console.error(json.errors);\n throw new Error(\"Failed to fetch API\");\n }\n\n return json.data;\n}\n\nexport async function getPreviewPostBySlug(slug) {\n const data = await ", "suffix": "}\n\nexport async function getAllPostsWithSlug() {\n const data = await fetchAPI(`\n {\n allPost {\n edges {\n node {\n slug:url\n }\n }\n }\n }\n `);\n return data.allPost.edges.map((x) => x.node);\n}\n\nexport", "middle": "fetchAPI(\n `\n query PostBySlug($slug: String!) {\n post(url: $slug, preview: true) {\n slug:url\n }\n }`,\n {\n preview: true,\n variables: {\n slug,\n },\n },\n );\n return data.post;\n", "meta": {"filepath": "examples/cms-umbraco-heartcore/lib/umbraco-heartcore.js", "language": "javascript", "file_size": 3408, "cut_index": 614, "middle_length": 229}} {"prefix": " Container from \"./container\";\nimport cn from \"classnames\";\nimport { EXAMPLE_PATH } from \"../lib/constants\";\n\nexport default function Alert({ preview }) {\n return (\n \n \n
    \n {preview ? (\n <>\n This page is a preview.{\" \"}\n \n ) : (\n <>\n The source code for this blog is{\" \"}\n \n Click here\n {\" \"}\n to exit preview mode.\n ", "meta": {"filepath": "examples/cms-umbraco-heartcore/components/alert.js", "language": "javascript", "file_size": 1203, "cut_index": 518, "middle_length": 229}} {"prefix": " Container from \"./container\";\nimport { EXAMPLE_PATH } from \"../lib/constants\";\n\nexport default function Footer() {\n return (\n
    \n \n
    \n

    \n Statically Generated with Next.js.\n

    \n
    \n Read Documentation\n \n \n \n
    \n \n
    \n
    \n
    \n ", "suffix": ">\n \n
    \n
    \n
    \n

    {excerpt}

    \n \n
    \n
    \n ", "middle": "

    \n \n {title}\n \n

    \n
    \n

    \n Blog.\n

    \n

    \n A statically generated blog example using{\" \"}\n {\" \"}\n and{\" \"}\n \n {CMS_NAME}\n \n .\n

    \n \n )", "middle": "xt-success duration-200 transition-colors\"\n >", "meta": {"filepath": "examples/cms-umbraco-heartcore/components/intro.js", "language": "javascript", "file_size": 847, "cut_index": 535, "middle_length": 52}} {"prefix": "from \"next/head\";\nimport { CMS_NAME, HOME_OG_IMAGE_URL } from \"../lib/constants\";\n\nexport default function Meta() {\n return (\n \n \n \n \n \n \n \n \n \n \n \n {title}\n
    \n \n
    \n
    \n \n
    \n \n
    \n
    \n \n
    \n <", "middle": "url={coverImage.url} />\n
    \n
    \n \n
    \n {router.isFallback ? (\n Loading…\n ) : (\n <>\n
    \n \n \n ", "middle": "xt/head\";\nimport { CMS_NAME } from \"lib/constants\";\n\nexport default function Post({ post, morePosts, preview }) {\n const router = useRouter();\n\n if (!router.isFallback && !post?.slug) {\n return <ErrorPage statusCode={404} />", "meta": {"filepath": "examples/cms-umbraco-heartcore/pages/[...slug].js", "language": "javascript", "file_size": 2095, "cut_index": 563, "middle_length": 229}} {"prefix": "iner from \"../components/container\";\nimport MoreStories from \"../components/more-stories\";\nimport HeroPost from \"../components/hero-post\";\nimport Intro from \"../components/intro\";\nimport Layout from \"../components/layout\";\nimport { getAllPostsForHome } from \"../lib/umbraco-heartcore\";\nimport Head from \"next/head\";\nimport { CMS_NAME } from \"../lib/constants\";\n\nexport default function Index({ posts, preview }) {\n const heroPost = posts[0];\n const morePosts = posts.slice(1);\n return (\n <>\n <Layout p", "suffix": "ost.title}\n coverImage={heroPost.coverImage}\n date={heroPost.date}\n author={heroPost.author}\n slug={heroPost.slug}\n excerpt={heroPost.excerpt}\n />\n )}\n {morePosts", "middle": "review={preview}>\n <Head>\n <title>{`Next.js Blog Example with ${CMS_NAME}`}\n \n \n \n {heroPost && (\n ([]);\n\nconst drawingAtom = atom(false);\n\nconst handleMouseDownAtom = atom(null, (get, set) => {\n set(drawingAtom, true);\n});\n\nconst handleMouseUpAtom = atom(null, (get, set) => {\n set(drawingAtom, false);\n});\n\nconst handleMouseMoveAtom = atom(\n (get) => get(dotsAtom),\n (get, set, update: Point) => {\n if (get(drawingAtom)) {\n set(dotsAtom, (prev) => [...prev, update]);\n }\n },\n);\n\nc", "suffix": "lt function Canvas() {\n const [, handleMouseUp] = useAtom(handleMouseUpAtom);\n const [, handleMouseDown] = useAtom(handleMouseDownAtom);\n const [, handleMouseMove] = useAtom(handleMouseMoveAtom);\n return (\n {\n const [dots] = useAtom(handleMouseMoveAtom);\n return (\n \n {dots.map(([x, y], index) => (\n \n ))}\n \n );\n};\n\nexport defau", "meta": {"filepath": "examples/with-jotai/components/Canvas.tsx", "language": "tsx", "file_size": 1303, "cut_index": 524, "middle_length": 229}} {"prefix": "ule.css\";\nimport \"../styles/globals.css\";\nimport Canvas from \"../components/Canvas\";\nimport { Metadata } from \"next\";\n\nexport const metadata: Metadata = {\n title: \"with-jotai\",\n description: \"Generated by create next app\",\n};\n\nexport default function Home() {\n return (\n
    \n

    With Jotai example

    \n
    \n \n
    \n
    \n \n Powered by{\" \"}\n \n \"Vercel {\n this.timer = setInterval(() => {\n runInA", "suffix": "())}:${pad(t.getUTCMinutes())}:${pad(\n t.getUTCSeconds(),\n )}`;\n return format(new Date(this.lastUpdate));\n }\n\n stop = () => clearInterval(this.timer);\n\n hydrate = (data) => {\n if (!data) return;\n\n this.lastUpdate = data.lastUpdate ", "middle": "ction(() => {\n this.lastUpdate = Date.now();\n this.light = true;\n });\n }, 1000);\n };\n\n get timeString() {\n const pad = (n) => (n < 10 ? `0${n}` : n);\n const format = (t) =>\n `${pad(t.getUTCHours", "meta": {"filepath": "examples/with-mobx/store.js", "language": "javascript", "file_size": 1079, "cut_index": 515, "middle_length": 229}} {"prefix": "mport { createContext, useContext } from \"react\";\nimport { Store } from \"../store\";\n\nlet store;\nexport const StoreContext = createContext();\n\nexport function useStore() {\n const context = useContext(StoreContext);\n if (context === undefined) {\n throw new Error(\"useStore must be used within StoreProvider\");\n }\n\n return context;\n}\n\nfunction initializeStore(initialData = null) {\n const _store = store ?? new Store();\n\n // If your page has Next.js data fetching methods that use a Mobx store, it will\n /", "suffix": "tore;\n // Create the store once in the client\n if (!store) store = _store;\n\n return _store;\n}\n\nexport function StoreProvider({ children, initialState: initialData }) {\n const store = initializeStore(initialData);\n\n return (\n [\"kea\"],\n actions: () => ({\n increment: (amount) => ({ amount }),\n decrement: (amount) => ({ amount }),\n }),\n reducers: ({ actions }) => ({\n counter: [\n 0,\n PropTypes.number,\n {\n [actions.increment]: (state, payload) => state + payload.amount,\n [actions.decrement]: (state, payload) => state - payload.amount,\n },\n ],\n }),\n selectors: ({ s", "suffix": "

    Double Counter: {this.props.doubleCounter}

    \n \n

    \n
    \n \n
    \n
    \n ", "middle": "e={title} url={coverImage.imgix_url} slug={slug} />\n
    \n
    \n
    \n

    {\n return (\n
    \n

    \n Blog.\n

    \n

    \n A statically generated blog example using{\" \"}\n {\" \"}\n and{\" \"}\n \n {CMS_NAME}\n \n .\n

    \n
    \n );\n};\n\ne", "middle": "ess duration-200 transition-colors\"\n >\n ", "meta": {"filepath": "examples/cms-cosmic/components/intro.tsx", "language": "tsx", "file_size": 858, "cut_index": 529, "middle_length": 52}} {"prefix": "from \"next/head\";\nimport { CMS_NAME, HOME_OG_IMAGE_URL } from \"@/lib/constants\";\n\nconst Meta = () => {\n return (\n \n \n \n \n \n \n \n \n \n \n {\n const { posts } = props;\n return (\n
    \n

    \n More Stories\n

    \n
    \n {posts.map((post) => (\n \n ))}\n
    \n
    \n );\n};\n\nexport default MoreStorie", "middle": " title={post.title}\n coverImage={post.met", "meta": {"filepath": "examples/cms-cosmic/components/more-stories.tsx", "language": "tsx", "file_size": 870, "cut_index": 559, "middle_length": 52}} {"prefix": " Avatar from \"./avatar\";\nimport Date from \"./date\";\nimport CoverImage from \"./cover-image\";\nimport PostTitle from \"./post-title\";\nimport { AuthorType, ImgixType } from \"interfaces\";\n\ntype PostHeaderProps = {\n title: string;\n coverImage: ImgixType;\n date: string;\n author: AuthorType;\n};\n\nconst PostHeader = (props: PostHeaderProps) => {\n const { title, coverImage, date, author } = props;\n return (\n <>\n {title}\n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n ", "meta": {"filepath": "examples/cms-cosmic/components/post-header.tsx", "language": "tsx", "file_size": 1132, "cut_index": 518, "middle_length": 229}} {"prefix": "import Avatar from \"./avatar\";\nimport Date from \"./date\";\nimport CoverImage from \"./cover-image\";\nimport Link from \"next/link\";\nimport { AuthorType, ImgixType } from \"interfaces\";\n\ntype PostPreviewProps = {\n title: string;\n coverImage: ImgixType;\n date: string;\n excerpt: string;\n author: AuthorType;\n slug: string;\n};\n\nconst PostPreview = (props: PostPreviewProps) => {\n const { title, coverImage, date, excerpt, author, slug } = props;\n\n return (\n
    \n
    \n \n
    \n \n
    \n

    {excerpt}

    \n \n
    \n );\n};\n", "middle": "age slug={slug} title={title} url={coverImage.imgix_url} />\n
    \n

    \n \n {title}\n \n ", "meta": {"filepath": "examples/cms-cosmic/components/post-preview.tsx", "language": "tsx", "file_size": 1026, "cut_index": 512, "middle_length": 229}} {"prefix": "components/container\";\nimport MoreStories from \"@/components/more-stories\";\nimport HeroPost from \"@/components/hero-post\";\nimport Intro from \"@/components/intro\";\nimport Layout from \"@/components/layout\";\nimport { getAllPostsForHome } from \"@/lib/api\";\nimport Head from \"next/head\";\nimport { CMS_NAME } from \"@/lib/constants\";\nimport { PostType } from \"interfaces\";\n\ntype IndexProps = {\n allPosts: PostType[];\n preview: boolean;\n};\n\nconst Index = (props: IndexProps) => {\n const { allPosts, preview } = props;", "suffix": " \n \n {heroPost && (\n \n \n \n {`Next.js Blog Example with ${CMS_NAME}`}\n \n ", "meta": {"filepath": "examples/cms-cosmic/pages/index.tsx", "language": "tsx", "file_size": 1548, "cut_index": 537, "middle_length": 229}} {"prefix": "c function preview(req, res) {\n // Check the secret and next parameters\n // This secret should only be known to this API route and the CMS\n if (\n req.query.secret !== process.env.COSMIC_PREVIEW_SECRET ||\n !req.query.slug\n ) {\n return res.status(401).json({ message: \"Invalid token\" });\n }\n\n // Fetch the headless CMS to check if the provided `slug` exists\n const post = await getPreviewPostBySlug(req.query.slug);\n\n // If the slug doesn't exist prevent preview mode from being enabled\n if (!pos", "suffix": "alid slug\" });\n }\n\n // Enable Draft Mode by setting the cookie\n res.setDraftMode({ enable: true });\n\n // Redirect to the path from the fetched post\n // We don't redirect to req.query.slug as that might lead to open redirect vulnerabilities\n res.write", "middle": "t) {\n return res.status(401).json({ message: \"Inv", "meta": {"filepath": "examples/cms-cosmic/pages/api/preview.ts", "language": "typescript", "file_size": 953, "cut_index": 582, "middle_length": 52}} {"prefix": "orPage from \"next/error\";\nimport Container from \"@/components/container\";\nimport PostBody from \"@/components/post-body\";\nimport MoreStories from \"@/components/more-stories\";\nimport Header from \"@/components/header\";\nimport PostHeader from \"@/components/post-header\";\nimport SectionSeparator from \"@/components/section-separator\";\nimport Layout from \"@/components/layout\";\nimport { getAllPostsWithSlug, getPostAndMorePosts } from \"@/lib/api\";\nimport PostTitle from \"@/components/post-title\";\nimport Head from \"nex", "suffix": "e;\n morePosts: PostType[];\n preview;\n};\n\nconst Post = (props: PostProps) => {\n const { post, morePosts, preview } = props;\n const router = useRouter();\n if (!router.isFallback && !post?.slug) {\n return ;\n }\n return (", "middle": "t/head\";\nimport { CMS_NAME } from \"@/lib/constants\";\nimport markdownToHtml from \"@/lib/markdownToHtml\";\nimport { PostType } from \"interfaces\";\nimport { ParsedUrlQueryInput } from \"querystring\";\n\ntype PostProps = {\n post: PostTyp", "meta": {"filepath": "examples/cms-cosmic/pages/posts/[slug].tsx", "language": "tsx", "file_size": 2830, "cut_index": 563, "middle_length": 229}} {"prefix": "{ Html, Head, Main, NextScript } from \"next/document\";\nimport { renderToNodeList } from \"react-fela\";\n\nimport getFelaRenderer from \"../getFelaRenderer\";\n\nexport default class MyDocument extends Document {\n static async getInitialProps(ctx) {\n const renderer = getFelaRenderer();\n const originalRenderPage = ctx.renderPage;\n\n ctx.renderPage = () =>\n originalRenderPage({\n enhanceApp: (App) => (props) => ,\n });\n\n const initialProps = await Docum", "suffix": "oNodeList(renderer);\n return {\n ...initialProps,\n styles: [...initialProps.styles, ...styles],\n };\n }\n\n render() {\n return (\n \n \n \n
    \n \n \n ", "middle": "ent.getInitialProps(ctx);\n const styles = renderT", "meta": {"filepath": "examples/with-fela/pages/_document.js", "language": "javascript", "file_size": 859, "cut_index": 529, "middle_length": 52}} {"prefix": "setRandomNumber] = useState(null);\n\n const recalculate = () => {\n setRandomNumber(Math.ceil(Math.random() * 100));\n };\n\n useEffect(() => {\n recalculate();\n }, []);\n\n const message = do {\n if (randomNumber < 30) {\n // eslint-disable-next-line no-unused-expressions\n (\"Do not give up. Try again.\");\n } else if (randomNumber < 60) {\n // eslint-disable-next-line no-unused-expressions\n (\"You are a lucky guy\");\n } else {\n // eslint-disable-next-line no-unused-expressions", "suffix": "andomNumber === null) return

    Please wait..

    ;\n return (\n
    \n

    Your Lucky number is: \"{randomNumber}\"

    \n

    {message}

    \n \n
    \n );\n};\n\nexport default MyLuckNo;", "middle": "\n (\"You are soooo lucky!\");\n }\n };\n\n if (r", "meta": {"filepath": "examples/with-custom-babel-config/pages/index.js", "language": "javascript", "file_size": 915, "cut_index": 606, "middle_length": 52}} {"prefix": "

    \n Get started by editing app/page.tsx\n

    \n\n
    \n \n

    Documentation →

    \n

    Find in-depth information about Next.js features and API.

    \n
    \n\n \n

    Learn →

    \n

    Learn about Next.js in an interactive course with quizzes!

    \n ", "suffix": " Next.js projects.

    \n
    \n\n \n\n \n

    Examples →

    \n

    Discover and deploy boilerplate example", "meta": {"filepath": "examples/with-sitemap/app/page.tsx", "language": "tsx", "file_size": 5099, "cut_index": 716, "middle_length": 229}} {"prefix": " from \"react\";\nimport {\n ComponentParams,\n ComponentRendering,\n Placeholder,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\n\ninterface ComponentProps {\n rendering: ComponentRendering & { params: ComponentParams };\n params: ComponentParams;\n}\n\nexport const Default = (props: ComponentProps): JSX.Element => {\n const styles = `${props.params.GridParameters ?? \"\"} ${\n props.params.Styles ?? \"\"\n }`.trimEnd();\n const rowStyles = [\n props.params.Styles1,\n props.params.Styles2,\n props.params.Styles3", "suffix": "s.params.RenderingIdentifier;\n\n return (\n \n {enabledPlaceholders.map((ph, index) => {\n const phKey = `row-${ph}-{*}`;\n const phStyles = `${", "middle": ",\n props.params.Styles4,\n props.params.Styles5,\n props.params.Styles6,\n props.params.Styles7,\n props.params.Styles8,\n ];\n const enabledPlaceholders = props.params.EnabledPlaceholders.split(\",\");\n const id = prop", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/components/RowSplitter.tsx", "language": "tsx", "file_size": 1475, "cut_index": 524, "middle_length": 229}} {"prefix": "config\";\nimport {\n GraphQLErrorPagesService,\n SitecoreContext,\n ErrorPages,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\nimport { SitecorePageProps } from \"lib/page-props\";\nimport NotFound from \"src/NotFound\";\nimport { componentFactory } from \"temp/componentFactory\";\nimport Layout from \"src/Layout\";\nimport { GetStaticProps } from \"next\";\nimport { siteResolver } from \"lib/site-resolver\";\n\nconst Custom404 = (props: SitecorePageProps): JSX.Element => {\n if (!(props && props.layoutData)) {\n return {\n const site = siteResolver.getByName(config.jssAppName);\n const errorPagesService = new GraphQLErrorPagesService({\n endpoint: config.graphQLEndpoint,\n apiKey: config.sitecoreApiKey,\n siteName: site.na", "middle": "nd />;\n }\n\n return (\n \n \n \n );\n};\n\nexport const getStatic", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/pages/404.tsx", "language": "tsx", "file_size": 1514, "cut_index": 537, "middle_length": 229}} {"prefix": "ad\";\nimport {\n GraphQLErrorPagesService,\n SitecoreContext,\n ErrorPages,\n} from \"@sitecore-jss/sitecore-jss-nextjs\";\nimport { SitecorePageProps } from \"lib/page-props\";\nimport Layout from \"src/Layout\";\nimport { componentFactory } from \"temp/componentFactory\";\nimport { GetStaticProps } from \"next\";\nimport config from \"temp/config\";\nimport { siteResolver } from \"lib/site-resolver\";\n\n/**\n * Rendered in case if we have 500 error\n */\nconst ServerError = (): JSX.Element => (\n <>\n \n 500: Se", "suffix": " <a href=\"/\">Go to the Home page</a>\n </div>\n </>\n);\n\nconst Custom500 = (props: SitecorePageProps): JSX.Element => {\n if (!(props && props.layoutData)) {\n return <ServerError />;\n }\n\n return (\n <SitecoreContext\n componentFactory={com", "middle": "rver Error\n \n

    \n

    500 Internal Server Error

    \n

    \n There is a problem with the resource you are looking for, and it cannot\n be displayed.\n

    \n", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/pages/500.tsx", "language": "tsx", "file_size": 1956, "cut_index": 537, "middle_length": 229}} {"prefix": "piResponse } from \"next\";\nimport { GraphQLRobotsService } from \"@sitecore-jss/sitecore-jss-nextjs\";\nimport { siteResolver } from \"lib/site-resolver\";\nimport config from \"temp/config\";\n\nconst robotsApi = async (\n req: NextApiRequest,\n res: NextApiResponse,\n): Promise => {\n // Ensure response is text/html\n res.setHeader(\"Content-Type\", \"text/html;charset=utf-8\");\n\n // Resolve site based on hostname\n const hostName = req.headers[\"host\"]?.split(\":\")[0] || \"localhost\";\n const site = siteResolver.get", "suffix": "e\n const robotsService = new GraphQLRobotsService({\n endpoint: config.graphQLEndpoint,\n apiKey: config.sitecoreApiKey,\n siteName: site.name,\n });\n\n const robotsResult = await robotsService.fetchRobots();\n\n return res.status(200).send(robotsRes", "middle": "ByHost(hostName);\n\n // create robots graphql servic", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/pages/api/robots.ts", "language": "typescript", "file_size": 891, "cut_index": 547, "middle_length": 52}} {"prefix": "tingRenderMiddleware } from \"@sitecore-jss/sitecore-jss-nextjs/editing\";\n\n/**\n * This Next.js API route is used to handle POST requests from Sitecore editors.\n * This route should match the `serverSideRenderingEngineEndpointUrl` in your Sitecore configuration,\n * which is set to \"http://localhost:3000/api/editing/render\" by default (see \\sitecore\\config\\xmcloud-nextjs-starter.config).\n *\n * The `EditingRenderMiddleware` will\n * 1. Extract editing data from the Sitecore editor POST request\n * 2. Stash this", "suffix": "e render request, passing along the Preview Mode cookies.\n * This allows retrieval of the editing data in preview context (via an `EditingDataService`) - see `SitecorePagePropsFactory`\n * 5. Return the rendered page HTML to the Sitecore editor\n */\n\n//", "middle": " data (for later use in the page render request) via an `EditingDataService`, which returns a key for retrieval\n * 3. Enable Next.js Preview Mode, passing our stashed editing data key as preview data\n * 4. Invoke the actual pag", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/pages/api/editing/render.ts", "language": "typescript", "file_size": 1425, "cut_index": 524, "middle_length": 229}} {"prefix": "e-jss/sitecore-jss-nextjs/editing\";\n\n/**\n * This Next.js API route is used to handle Sitecore editor data storage and retrieval by key\n * on serverless deployment architectures (e.g. Vercel) via the `ServerlessEditingDataService`.\n *\n * The `EditingDataMiddleware` expects this dynamic route name to be '[key]' by default, but can\n * be configured to use something else with the `dynamicRouteKey` option.\n */\n\n// Bump body size limit (1mb by default) and disable response limit for Sitecore editor payloads\n// Se", "suffix": "#custom-config\nexport const config = {\n api: {\n bodyParser: {\n sizeLimit: \"2mb\",\n },\n responseLimit: false,\n },\n};\n\n// Wire up the EditingDataMiddleware handler\nconst handler = new EditingDataMiddleware().getHandler();\n\nexport default handl", "middle": "e https://nextjs.org/docs/api-routes/request-helpers", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/pages/api/editing/data/[key].ts", "language": "typescript", "file_size": 871, "cut_index": 559, "middle_length": 52}} {"prefix": "ib/makeswift/register-components\";\n\nimport { Makeswift } from \"@makeswift/runtime/next\";\nimport {\n GetStaticPathsResult,\n GetStaticPropsContext,\n GetStaticPropsResult,\n} from \"next\";\n\nimport {\n Page as MakeswiftPage,\n PageProps as MakeswiftPageProps,\n} from \"@makeswift/runtime/next\";\n\ntype ParsedUrlQuery = { path?: string[] };\n\nexport async function getStaticPaths(): Promise<\n GetStaticPathsResult\n> {\n const makeswift = new Makeswift(process.env.MAKESWIFT_SITE_API_KEY!);\n const pages", "suffix": " MakeswiftPageProps;\n\nexport async function getStaticProps(\n ctx: GetStaticPropsContext,\n): Promise> {\n const makeswift = new Makeswift(process.env.MAKESWIFT_SITE_API_KEY!);\n const path = \"/\" + (ctx.params?.pa", "middle": " = await makeswift.getPages();\n\n return {\n paths: pages.map((page) => ({\n params: {\n path: page.path.split(\"/\").filter((segment) => segment !== \"\"),\n },\n })),\n fallback: \"blocking\",\n };\n}\n\ntype Props =", "meta": {"filepath": "examples/cms-makeswift/pages/[[...path]].tsx", "language": "tsx", "file_size": 1313, "cut_index": 524, "middle_length": 229}} {"prefix": "ort { initializeApp, getApps } from \"firebase/app\";\nimport { getAnalytics } from \"firebase/analytics\";\nexport const createFirebaseApp = () => {\n const clientCredentials = {\n apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,\n authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,\n databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,\n projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,\n storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,\n messagingSenderId: process", "suffix": "eApp(clientCredentials);\n // Check that `window` is in scope for the analytics module!\n if (typeof window !== \"undefined\") {\n // Enable analytics. https://firebase.google.com/docs/analytics/get-started\n if (\"measurementId\" in clientCredenti", "middle": ".env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,\n appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,\n measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,\n };\n\n if (getApps().length <= 0) {\n const app = initializ", "meta": {"filepath": "examples/with-firebase/firebase/clientApp.js", "language": "javascript", "file_size": 1068, "cut_index": 515, "middle_length": 229}} {"prefix": "ink from \"next/link\";\nimport { useEffect } from \"react\";\nimport { useUser } from \"../context/userContext\";\n\nexport default function Home() {\n // Our custom hook to get context values\n const { loadingUser, user } = useUser();\n\n const profile = { username: \"nextjs_user\", message: \"Awesome!!\" };\n\n useEffect(() => {\n if (!loadingUser) {\n // You know that the user is loaded: either logged in or out!\n console.log(user);\n }\n // You also have your firebase app initialized\n }, [loadingUser, u", "suffix": ">\n Next.js w/ Firebase Client-Side\n \n \n\n
    \n

    Next.js w/ Firebase Client-Side

    \n

    Fill in your credenti", "middle": "ser]);\n\n const createUser = async () => {\n const db = getFirestore();\n await setDoc(doc(db, \"profile\", profile.username), profile);\n\n alert(\"User created!!\");\n };\n\n return (\n

    \n \n
    \n
    \n
    \n \n

    \n Built with Next.js.\n \n

    \n Blog.\n

    \n", "suffix": "n-200 transition-colors\"\n >\n Next.js\n {\" \"}\n and{\" \"}\n \n {CMS_NAME}\n \n ", "middle": "

    \n A statically generated blog example using{\" \"}\n {\n return localforage.getItem(\"fcm_token\");\n },\n\n init: async function () {\n firebase.initializeApp({\n apiKey: \"YOUR-API-KEY\",\n projectId: \"YOUR-PROJECT-ID\",\n messagingSenderId: \"YOUR-SENDER-ID\",\n appId: \"YOUR-APP-ID\",\n });\n\n try {\n if ((await this.tokenInlocalforage()) !== null) {\n return false;\n }\n\n ", "suffix": "it Notification.requestPermission();\n const token = await messaging.getToken();\n\n localforage.setItem(\"fcm_token\", token);\n console.log(\"fcm_token\", token);\n } catch (error) {\n console.error(error);\n }\n },\n};\n\nexport { firebaseCl", "middle": " const messaging = firebase.messaging();\n awa", "meta": {"filepath": "examples/with-firebase-cloud-messaging/utils/webPush.js", "language": "javascript", "file_size": 853, "cut_index": 529, "middle_length": 52}} {"prefix": "\n {children}\n \n);\n\nconst textRule = ({ size, theme }) => ({\n fontFamily:\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif',\n fontSize: size,\n color: \"#333\",\n});\n\nfunction Text({ size = 16, children }) {\n const { css } = useFela({ size });\n\n return

    {children}

    ;", "suffix": "t { css } = useFela();\n\n return

    {children}

    ;\n}\n\nexport default function Home() {\n return (\n \n My Title\n Hi, I am Fela.\n \n \n Create Next App\n \n \n\n
    \n

    \n Welcome to Next.js on Docker!\n

    \n

    with Multiple Deployment Environments

    \n

    API_URL: {process.env.NEXT_PUBLI", "suffix": "\"https://nextjs.org/docs\" className={styles.card}>\n

    Documentation →

    \n

    Find in-depth information about Next.js features and API.

    \n \n\n \n", "middle": "C_API_URL}

    \n

    \n Get started by editing{\" \"}\n pages/index.js\n

    \n\n
    \n {\n const id = props.id;\n return (\n
    \n
    \n
    {props.children}
    \n {\n useEffect(() => {\n // Since Siteco", "meta": {"filepath": "examples/cms-sitecore-xmcloud/src/pages/[[...path]].tsx", "language": "tsx", "file_size": 3848, "cut_index": 614, "middle_length": 229}} {"prefix": "sable */\n/* tslint:disable */\n/**\n * This is an autogenerated file created by the Stencil compiler.\n * It contains typing information for all components that exist in this project.\n */\n\nimport { HTMLStencilElement, JSXBase } from \"@stencil/core/internal\";\n\nexport namespace Components {\n interface MyComponent {\n /**\n * The first name\n */\n first: string;\n /**\n * The last name\n */\n last: string;\n /**\n * The middle name\n */\n middle: string;\n }\n}\n\ndeclare global {\n in", "suffix": "tTagNameMap {\n \"my-component\": HTMLMyComponentElement;\n }\n}\n\ndeclare namespace LocalJSX {\n interface MyComponent {\n /**\n * The first name\n */\n first?: string;\n /**\n * The last name\n */\n last?: string;\n /**\n * The mid", "middle": "terface HTMLMyComponentElement\n extends Components.MyComponent,\n HTMLStencilElement {}\n var HTMLMyComponentElement: {\n prototype: HTMLMyComponentElement;\n new (): HTMLMyComponentElement;\n };\n interface HTMLElemen", "meta": {"filepath": "examples/with-stencil/packages/test-component/src/components.d.ts", "language": "typescript", "file_size": 1358, "cut_index": 524, "middle_length": 229}} {"prefix": "State, useEffect, createContext, useContext } from \"react\";\nimport { createFirebaseApp } from \"../firebase/clientApp\";\nimport { getAuth, onAuthStateChanged } from \"firebase/auth\";\n\nexport const UserContext = createContext();\n\nexport default function UserContextComp({ children }) {\n const [user, setUser] = useState(null);\n const [loadingUser, setLoadingUser] = useState(true); // Helpful, to update the UI accordingly.\n\n useEffect(() => {\n // Listen authenticated user\n const app = createFirebaseApp();", "suffix": " // You could also look for the user doc in your Firestore (if you have one):\n // const userDoc = await firebase.firestore().doc(`users/${uid}`).get()\n setUser({ uid, displayName, email, photoURL });\n } else setUser(null);\n ", "middle": "\n const auth = getAuth(app);\n const unsubscriber = onAuthStateChanged(auth, async (user) => {\n try {\n if (user) {\n // User is signed in.\n const { uid, displayName, email, photoURL } = user;\n ", "meta": {"filepath": "examples/with-firebase/context/userContext.js", "language": "javascript", "file_size": 1480, "cut_index": 524, "middle_length": 229}} {"prefix": "rom \"@contentful/rich-text-react-renderer\";\nimport { BLOCKS } from \"@contentful/rich-text-types\";\n\ninterface Asset {\n sys: {\n id: string;\n };\n url: string;\n description: string;\n}\n\ninterface AssetLink {\n block: Asset[];\n}\n\ninterface Content {\n json: any;\n links: {\n assets: AssetLink;\n };\n}\n\nfunction RichTextAsset({\n id,\n assets,\n}: {\n id: string;\n assets: Asset[] | undefined;\n}) {\n const asset = assets?.find((asset) => asset.sys.id === id);\n\n if (asset?.url) {\n return (\n ;\n }", "meta": {"filepath": "examples/cms-contentful/lib/markdown.tsx", "language": "tsx", "file_size": 976, "cut_index": 582, "middle_length": 52}} {"prefix": "from \"next/headers\";\n\nimport MoreStories from \"../../more-stories\";\nimport Avatar from \"../../avatar\";\nimport Date from \"../../date\";\nimport CoverImage from \"../../cover-image\";\n\nimport { Markdown } from \"@/lib/markdown\";\nimport { getAllPosts, getPostAndMorePosts } from \"@/lib/api\";\n\nexport async function generateStaticParams() {\n const allPosts = await getAllPosts(false);\n\n return allPosts.map((post) => ({\n slug: post.slug,\n }));\n}\n\nexport default async function PostPage({\n params,\n}: {\n params: { ", "suffix": "ext-2xl font-bold leading-tight tracking-tight md:text-4xl md:tracking-tighter\">\n \n Blog\n \n .\n

    \n
    \n

    \n

    \n

    Default

    \n

    \n Automatically prefetch pages in the background as soon the Link appears\n in the view:\n

    \n Home Features\n

    Imperative

    \n

    Prefetch on onMouseEnter or on other events:

    \n \n \n Contact\n \n \n
      \n
    • \n \n Home\n \n
    • \n
    • \n \n About\n \n
    • \n
    • \n \n
    • \n
    • \n \n Dynamic Route\n \n
    • \n
    \n \n);\n\nexpo", "middle": "className=\"nav-link\" href=\"/blog\">\n Blog\n ", "meta": {"filepath": "examples/active-class-name/components/Nav.tsx", "language": "tsx", "file_size": 930, "cut_index": 606, "middle_length": 52}} {"prefix": "alidates internal links in /docs and /errors including internal,\n * hash, source and related links. It does not validate external links.\n * 1. Collects all .mdx files in /docs and /errors.\n * 2. For each file, it extracts the content, metadata, and heading slugs.\n * 3. It creates a document map to efficiently lookup documents by path.\n * 4. It then traverses each document modified in the PR and...\n * - Checks if each internal link (links starting with \"/docs/\") points\n * to an existing document\n * ", "suffix": "iscovered during these checks are categorized and a\n * comment is added to the PR.\n */\n\ninterface Document {\n body: string\n path: string\n headings: string[]\n source?: string\n related?: {\n links: string[]\n }\n}\n\ninterface Errors {\n doc: Document\n ", "middle": " - Validates hash links (links starting with \"#\") against the list of\n * headings in the current document.\n * - Checks the source and related links found in the metadata of each\n * document.\n * 5. Any broken links d", "meta": {"filepath": ".github/actions/validate-docs-links/src/index.ts", "language": "typescript", "file_size": 13933, "cut_index": 921, "middle_length": 229}} {"prefix": "js\n * product gallery app covering shared element morphs, directional navigation,\n * Suspense reveal animations, and accessibility.\n *\n * Tricky because agents may:\n * - Not know about the experimental.viewTransition flag in next.config\n * - Try to call document.startViewTransition manually instead of using\n * React's component\n * - Import ViewTransition from a third-party library instead of 'react'\n * - Not know about the transitionTypes prop on next/link\n * - Forget default=\"none\" causi", "suffix": "\nimport { join } from 'path'\n\nconst IGNORE_DIRS = new Set([\n 'node_modules',\n '.next',\n '.git',\n 'dist',\n 'build',\n 'coverage',\n])\n\nfunction findFiles(dir: string, ext: string): string[] {\n const results: string[] = []\n const base = join(process.cw", "middle": "ng every transition to cross-fade everything\n * - Skip prefers-reduced-motion (React does NOT disable animations automatically)\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, existsSync, readdirSync } from 'fs'", "meta": {"filepath": "evals/evals/agent-043-view-transitions/EVAL.ts", "language": "typescript", "file_size": 3919, "cut_index": 614, "middle_length": 229}} {"prefix": "tring\n price: number\n color: string\n}\n\nexport const products: Product[] = [\n {\n slug: 'classic-sneakers',\n name: 'Classic Sneakers',\n description: 'Timeless design meets everyday comfort.',\n price: 89,\n color: '#4F46E5',\n },\n {\n slug: 'leather-backpack',\n name: 'Leather Backpack',\n description: 'Handcrafted from premium full-grain leather.',\n price: 129,\n color: '#059669',\n },\n {\n slug: 'wireless-headphones',\n name: 'Wireless Headphones',\n description: 'Crystal-", "suffix": "ice: 199,\n color: '#DC2626',\n },\n {\n slug: 'cotton-hoodie',\n name: 'Cotton Hoodie',\n description: 'Ultra-soft organic cotton blend for all-day wear.',\n price: 65,\n color: '#D97706',\n },\n]\n\nexport function getProduct(slug: string): Prod", "middle": "clear audio with active noise cancellation.',\n pr", "meta": {"filepath": "evals/evals/agent-043-view-transitions/lib/products.ts", "language": "typescript", "file_size": 957, "cut_index": 582, "middle_length": 52}} {"prefix": "pense } from 'react'\nimport Link from 'next/link'\nimport { getProduct, products } from '@/lib/products'\nimport { notFound } from 'next/navigation'\n\nasync function ProductDetails({ slug }: { slug: string }) {\n await new Promise((resolve) => setTimeout(resolve, 100))\n const product = getProduct(slug)\n if (!product) notFound()\n\n return (\n
    \n

    {product.name}

    \n

    ${product.price}

    \n

    {product.", "suffix": "ton-text\" />\n

    \n )\n}\n\nexport default async function ProductPage({\n params,\n}: {\n params: Promise<{ slug: string }>\n}) {\n const { slug } = await params\n const product = products.find((p) => p.slug === slug)\n if (!product) notFound()\n\n return ", "middle": "description}

    \n
    \n )\n}\n\nfunction DetailsSkeleton() {\n return (\n
    \n
    \n
    \n
    {\n const proxyPath = join(p", "suffix": "xyPath)\n const hasMiddleware = existsSync(middlewarePath)\n\n // Must have proxy.ts\n expect(hasProxy).toBe(true)\n\n // Should NOT have middleware.ts (deprecated)\n expect(hasMiddleware).toBe(false)\n})\n\ntest('Proxy function uses correct name (not middlewar", "middle": "rocess.cwd(), 'proxy.ts')\n const middlewarePath = join(process.cwd(), 'middleware.ts')\n\n // In Next.js 16+, the file should be named proxy.ts, not middleware.ts\n // middleware.ts is deprecated\n const hasProxy = existsSync(pro", "meta": {"filepath": "evals/evals/agent-031-proxy-middleware/EVAL.ts", "language": "typescript", "file_size": 2676, "cut_index": 563, "middle_length": 229}} {"prefix": "/**\n * Enable PPR\n *\n * Tests whether the agent knows that partial pre-rendering is enabled via\n * `cacheComponents: true` in next.config.ts, NOT the old\n * `experimental: { ppr: true }` flag.\n *\n * Tricky because most training data and older docs reference the experimental\n * flag. The current way to enable PPR in Next.js 16 is `cacheComponents: true`.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\ntest('Enables PPR via cacheComponents in next.conf", "suffix": "adFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8')\n\n // Strip comments to avoid false positives from explanatory comments\n const stripped = config\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .replace(/\\/\\/.*$/gm, '')\n\n expect(stripped).not.toMatch", "middle": "ig', () => {\n const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8')\n\n expect(config).toMatch(/cacheComponents\\s*:\\s*true/)\n})\n\ntest('Does not use the old experimental.ppr flag', () => {\n const config = re", "meta": {"filepath": "evals/evals/agent-042-enable-ppr/EVAL.ts", "language": "typescript", "file_size": 1019, "cut_index": 512, "middle_length": 229}} {"prefix": "js project from Pages Router to\n * App Router — creating app/layout.tsx, app/page.tsx, and app/about/page.tsx,\n * removing next/head usage, and cleaning up the pages/ directory.\n *\n * Tricky because agents often do incomplete migrations: missing the root\n * layout, mixing router conventions, or leaving Pages Router artifacts.\n */\n\nimport { expect, test } from 'vitest'\nimport { existsSync, readdirSync, readFileSync } from 'fs'\nimport { join } from 'path'\n\ntest('App Router migration completed successfully', (", "suffix": "yout.tsx')\n const pagePath = join(appDir, 'page.tsx')\n\n expect(existsSync(layoutPath)).toBe(true)\n expect(existsSync(pagePath)).toBe(true)\n})\n\ntest('App layout.tsx has proper structure', () => {\n const rootDir = process.cwd()\n const layoutPath = join(", "middle": ") => {\n const rootDir = process.cwd()\n\n // 1. App directory should exist\n const appDir = join(rootDir, 'app')\n expect(existsSync(appDir)).toBe(true)\n\n // 2. App Router files should exist\n const layoutPath = join(appDir, 'la", "meta": {"filepath": "evals/evals/agent-000-app-router-migration-simple/EVAL.ts", "language": "typescript", "file_size": 3753, "cut_index": 614, "middle_length": 229}} {"prefix": "r Next.js Link\n *\n * Tests whether the agent uses the Next.js Link component for internal\n * navigation instead of plain tags or programmatic router.push().\n *\n * Tricky because agents often use raw anchor tags or useRouter for simple\n * navigation where Link provides prefetching and client-side transitions.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\ntest('Navigation component has required links', () => {\n const content = readFileSync(\n ", "suffix": ".toMatch(/['\"]\\/support['\"]/)\n})\n\ntest('Navigation uses Next.js Link component', () => {\n const content = readFileSync(\n join(process.cwd(), 'app', 'Navigation.tsx'),\n 'utf-8'\n )\n\n // Should import Link from next/link\n expect(content).toMatch(/im", "middle": "join(process.cwd(), 'app', 'Navigation.tsx'),\n 'utf-8'\n )\n\n // Should have links to /blog, /products, and /support\n expect(content).toMatch(/['\"]\\/blog['\"]/)\n expect(content).toMatch(/['\"]\\/products['\"]/)\n expect(content)", "meta": {"filepath": "evals/evals/agent-025-prefer-next-link/EVAL.ts", "language": "typescript", "file_size": 1320, "cut_index": 524, "middle_length": 229}} {"prefix": "ache in a Server Action\n * for immediate cache invalidation (read-your-own-writes semantics).\n *\n * Tricky because agents use revalidateTag() which has stale-while-revalidate\n * semantics — updateTag() waits for fresh data and only works in Server Actions.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, readdirSync } from 'fs'\nimport { join } from 'path'\n\n// Helper to find all .ts and .tsx files\nfunction findAllTsFiles(dir: string): string[] {\n const files: string[] = []\n try {\n const", "suffix": " '.next'\n ) {\n files.push(...findAllTsFiles(fullPath))\n } else if (\n item.isFile() &&\n (item.name.endsWith('.ts') || item.name.endsWith('.tsx'))\n ) {\n files.push(fullPath)\n }\n }\n } catch {\n // Ignore d", "middle": " items = readdirSync(dir, { withFileTypes: true })\n for (const item of items) {\n const fullPath = join(dir, item.name)\n if (\n item.isDirectory() &&\n item.name !== 'node_modules' &&\n item.name !==", "meta": {"filepath": "evals/evals/agent-037-updatetag-cache/EVAL.ts", "language": "typescript", "file_size": 3681, "cut_index": 614, "middle_length": 229}} {"prefix": "\n * with authInterrupts enabled, plus a forbidden.tsx error boundary.\n *\n * Tricky because agents use redirect() or notFound() for authorization failures\n * instead of the dedicated forbidden() API that returns a proper 403 status.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, existsSync } from 'fs'\nimport { join } from 'path'\n\ntest('next.config enables authInterrupts', () => {\n const configPath = join(process.cwd(), 'next.config.ts')\n if (existsSync(configPath)) {\n const content = ", "suffix": " const adminPagePath = join(process.cwd(), 'app', 'admin', 'page.tsx')\n if (existsSync(adminPagePath)) {\n const content = readFileSync(adminPagePath, 'utf-8')\n\n // Should import forbidden from next/navigation\n expect(content).toMatch(\n /impo", "middle": "readFileSync(configPath, 'utf-8')\n\n // The forbidden() function requires authInterrupts: true\n expect(content).toMatch(/authInterrupts\\s*:\\s*true/)\n }\n})\n\ntest('Admin page imports forbidden from next/navigation', () => {\n ", "meta": {"filepath": "evals/evals/agent-033-forbidden-auth/EVAL.ts", "language": "typescript", "file_size": 3554, "cut_index": 614, "middle_length": 229}} {"prefix": "gent decomposes a monolithic loading.tsx (which creates\n * a single implicit Suspense boundary around the entire page) into granular\n * Suspense boundaries — one per dashboard section — so each section can\n * stream independently and the PPR shell contains more static content.\n *\n * Tricky because the starting code uses Next.js's loading.tsx convention,\n * which is an implicit Suspense boundary. Agents need to recognize that\n * loading.tsx creates an all-or-nothing loading state, and that optimizing\n * the ", "suffix": "Dir = join(process.cwd(), 'app')\n\nfunction readFile(name: string): string {\n return readFileSync(join(appDir, name), 'utf-8')\n}\n\ntest('Page has at least 3 Suspense boundaries', () => {\n const page = readFile('page.tsx')\n\n const suspenseCount = (page.mat", "middle": "PPR shell requires replacing it with per-section Suspense boundaries\n * so each section can stream independently.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\nconst app", "meta": {"filepath": "evals/evals/agent-041-optimize-ppr-shell/EVAL.ts", "language": "typescript", "file_size": 2377, "cut_index": 563, "middle_length": 229}} {"prefix": "ache inside a\n * Server Action to refresh the current page after a mutation.\n *\n * Tricky because agents use redirect() to the same page (loses scroll/state),\n * return data for manual refresh, or use client-side router.refresh().\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, readdirSync } from 'fs'\nimport { join } from 'path'\n\n// Helper to find all .ts and .tsx files\nfunction findAllTsFiles(dir: string): string[] {\n const files: string[] = []\n try {\n const items = readdirSync(dir, ", "suffix": " files.push(...findAllTsFiles(fullPath))\n } else if (\n item.isFile() &&\n (item.name.endsWith('.ts') || item.name.endsWith('.tsx'))\n ) {\n files.push(fullPath)\n }\n }\n } catch {\n // Ignore directories that can't be r", "middle": "{ withFileTypes: true })\n for (const item of items) {\n const fullPath = join(dir, item.name)\n if (\n item.isDirectory() &&\n item.name !== 'node_modules' &&\n item.name !== '.next'\n ) {\n ", "meta": {"filepath": "evals/evals/agent-038-refresh-settings/EVAL.ts", "language": "typescript", "file_size": 3925, "cut_index": 614, "middle_length": 229}} {"prefix": "ument, metadata, and client/server component separation.\n *\n * Tricky because it requires migrating multiple advanced patterns at once:\n * data fetching, route handlers, metadata API, and proper 'use client'\n * directive placement — all while maintaining functionality.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, existsSync } from 'fs'\nimport { join } from 'path'\n\n/** Strip JS/TS comments so we only test actual code, not migration notes */\nfunction stripComments(code: string): string {\n", "suffix": "h)).toBe(true)\n\n const layoutContent = readFileSync(layoutPath, 'utf-8')\n\n // Should have html and body tags (replacing _document.js)\n expect(layoutContent).toMatch(/ {\n const layoutPath = join(process.cwd(), 'app', 'layout.tsx')\n expect(existsSync(layoutPat", "meta": {"filepath": "evals/evals/agent-030-app-router-migration-hard/EVAL.ts", "language": "typescript", "file_size": 6243, "cut_index": 716, "middle_length": 229}} {"prefix": " Head from 'next/head'\nimport { useRouter } from 'next/router'\n\nexport async function getServerSideProps({ req }) {\n const userAgent = req.headers['user-agent'] || ''\n const posts = await fetch(\n 'https://jsonplaceholder.typicode.com/posts?_limit=5'\n ).then((res) => res.json())\n\n return {\n props: {\n posts,\n userAgent,\n timestamp: new Date().toISOString(),\n },\n }\n}\n\nexport default function HomePage({ posts, userAgent, timestamp }) {\n const router = useRouter()\n\n const navigateT", "suffix": "t=\"Home - My Blog\" />\n \n\n
    \n

    Welcome to My Blog

    \n

    Server-side rendered at: {timestamp}

    \n

    Your user agent: {userAgent}

    \n\n

    Recent Posts

    \n

    \n

    {post.body.substring(0, 100)}...

    \n \n ", "middle": "ll blog posts\" />\n \n\n
    \n

    All Blog Posts

    \n\n
    \n {posts.map((post) => (\n
    \n

    \n ", "meta": {"filepath": "evals/evals/agent-030-app-router-migration-hard/pages/blog/index.js", "language": "javascript", "file_size": 1068, "cut_index": 515, "middle_length": 229}} {"prefix": "\n\n if (req.method === 'GET') {\n // Simulate fetching a single post\n const post = {\n id: parseInt(id),\n title: `Post ${id}`,\n content: `This is the content for post ${id}`,\n createdAt: new Date().toISOString(),\n }\n\n res.status(200).json(post)\n } else if (req.method === 'PUT') {\n const { title, content } = req.body\n\n // Simulate updating a post\n const updatedPost = {\n id: parseInt(id),\n title: title || `Post ${id}`,\n content: content || `Updated conten", "suffix": "String(),\n }\n\n res.status(200).json(updatedPost)\n } else if (req.method === 'DELETE') {\n // Simulate deleting a post\n res.status(200).json({ message: `Post ${id} deleted successfully` })\n } else {\n res.setHeader('Allow', ['GET', 'PUT', 'DE", "middle": "t for post ${id}`,\n updatedAt: new Date().toISO", "meta": {"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}} {"prefix": "ault function handler(req, res) {\n if (req.method === 'GET') {\n // Simulate fetching posts\n const posts = [\n { id: 1, title: 'First Post', content: 'This is the first post' },\n { id: 2, title: 'Second Post', content: 'This is the second post' },\n ]\n\n res.status(200).json(posts)\n } else if (req.method === 'POST') {\n const { title, content } = req.body\n\n if (!title || !content) {\n return res.status(400).json({ error: 'Title and content are required' })\n }\n\n // Simulate", "suffix": "st\n const newPost = {\n id: Date.now(),\n title,\n content,\n createdAt: new Date().toISOString(),\n }\n\n res.status(201).json(newPost)\n } else {\n res.setHeader('Allow', ['GET', 'POST'])\n res.status(405).end(`Method ${req.meth", "middle": " creating a po", "meta": {"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}} {"prefix": "ts whether the agent uses connection() from next/server to force dynamic\n * rendering instead of the deprecated unstable_noStore().\n *\n * Tricky because agents use unstable_noStore(), force-dynamic segment config,\n * or unrelated Dynamic APIs instead of the stable connection() function.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, existsSync, readdirSync } from 'fs'\nimport { join } from 'path'\n\nfunction readAppFiles(): string {\n const appDir = join(process.cwd(), 'app')\n if (!existsSy", "suffix": "utf-8')).join('\\n')\n}\n\ntest('Component imports connection from next/server', () => {\n const content = readAppFiles()\n\n // Should import connection from next/server\n expect(content).toMatch(/import.*connection.*from\\s+['\"]next\\/server['\"]/)\n})\n\ntest('Com", "middle": "nc(appDir)) return ''\n const entries = readdirSync(appDir, { recursive: true }) as string[]\n const files = entries.filter((f) => f.endsWith('.tsx') || f.endsWith('.ts'))\n return files.map((f) => readFileSync(join(appDir, f), '", "meta": {"filepath": "evals/evals/agent-035-connection-dynamic/EVAL.ts", "language": "typescript", "file_size": 2665, "cut_index": 563, "middle_length": 229}} {"prefix": "('../util/logger')\nconst { execSync } = require('child_process')\nconst releaseTypes = new Set(['release', 'published'])\n\nmodule.exports = function actionInfo() {\n let {\n ISSUE_ID,\n SKIP_CLONE,\n GITHUB_REF,\n LOCAL_STATS,\n GIT_ROOT_DIR,\n GITHUB_ACTION,\n COMMENT_ENDPOINT,\n GITHUB_REPOSITORY,\n GITHUB_EVENT_PATH,\n PR_STATS_COMMENT_TOKEN,\n PREVIEW_BUILDS_BASE_URL,\n } = process.env\n\n delete process.env.GITHUB_TOKEN\n delete process.env.PR_STATS_COMMENT_TOKEN\n\n // only use custo", "suffix": "UB_REF) {\n // get the current branch name\n GITHUB_REF = execSync(`cd \"${cwd}\" && git rev-parse --abbrev-ref HEAD`)\n .toString()\n .trim()\n }\n if (!GIT_ROOT_DIR) {\n GIT_ROOT_DIR = path.join(parentDir, '/')\n }\n if (!GI", "middle": "m endpoint if we don't have a token\n const commentEndpoint = !PR_STATS_COMMENT_TOKEN && COMMENT_ENDPOINT\n\n if (LOCAL_STATS === 'true') {\n const cwd = process.cwd()\n const parentDir = path.join(cwd, '../..')\n\n if (!GITH", "meta": {"filepath": ".github/actions/next-stats-action/src/prepare/action-info.js", "language": "javascript", "file_size": 2809, "cut_index": 563, "middle_length": 229}} {"prefix": "he + cacheTag(\"products\")\n * - getAllProducts() from lib/db is used\n * - an inline Server Action flow exists and is form-triggered\n * - revalidateTag(\"products\", profile) is used\n * - updateTag is not used\n */\n\nimport { expect, test } from 'vitest'\nimport { existsSync, readdirSync, readFileSync, statSync } from 'fs'\nimport { join } from 'path'\n\ntype SourceFile = { path: string; content: string }\n\nconst IGNORE_DIRS = new Set([\n '.git',\n '.next',\n 'node_modules',\n 'dist',\n 'build',\n 'coverage',\n])\n\ncons", "suffix": "E_DIRS.has(entry)) continue\n\n const fullPath = join(dir, entry)\n const stats = statSync(fullPath)\n\n if (stats.isDirectory()) {\n files.push(...readSourceFiles(fullPath))\n continue\n }\n\n if (IGNORE_FILES.has(entry)) continue\n\n if (", "middle": "t IGNORE_FILES = new Set(['EVAL.ts', 'PROMPT.md'])\n\nfunction readSourceFiles(dir: string): SourceFile[] {\n if (!existsSync(dir)) return []\n\n const files: SourceFile[] = []\n for (const entry of readdirSync(dir)) {\n if (IGNOR", "meta": {"filepath": "evals/evals/agent-029-use-cache-directive/EVAL.ts", "language": "typescript", "file_size": 3374, "cut_index": 614, "middle_length": 229}} {"prefix": "t\n *\n * Tests whether the agent uses next/font/google for font loading instead of\n * external CDN links or CSS @import.\n *\n * Tricky because agents reach for Google Fonts CDN links or CSS imports\n * instead of the zero-layout-shift next/font approach.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\ntest('BlogHeader uses Next.js fonts correctly', () => {\n const blogHeaderContent = readFileSync(\n join(process.cwd(), 'app', 'BlogHeader.tsx'),\n 'u", "suffix": "r_Display/)\n expect(blogHeaderContent).toMatch(/Roboto/)\n\n // Should use .className to apply fonts\n expect(blogHeaderContent).toMatch(/className.*\\.className/)\n\n // Should NOT use external CSS links or font-family styles\n expect(blogHeaderContent).not", "middle": "tf-8'\n )\n\n // Should import fonts from next/font/google\n expect(blogHeaderContent).toMatch(/import.*from ['\"]next\\/font\\/google['\"]/)\n\n // Should import Playfair_Display and Roboto\n expect(blogHeaderContent).toMatch(/Playfai", "meta": {"filepath": "evals/evals/agent-028-prefer-next-font/EVAL.ts", "language": "typescript", "file_size": 1588, "cut_index": 537, "middle_length": 229}} {"prefix": "th cacheComponents\n * enabled in next.config, plus proper cacheLife() and cacheTag() usage.\n *\n * Tricky because agents use deprecated patterns like fetch({ next: { revalidate } }),\n * route segment config, or unstable_cache instead of 'use cache' + cacheComponents.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, existsSync } from 'fs'\nimport { join } from 'path'\n\ntest('next.config enables cacheComponents', () => {\n const configPath = join(process.cwd(), 'next.config.ts')\n if (existsSync", "suffix": "or component uses \"use cache\" directive', () => {\n const pagePath = join(process.cwd(), 'app', 'page.tsx')\n if (existsSync(pagePath)) {\n const content = readFileSync(pagePath, 'utf-8')\n\n // Should use the 'use cache' directive (Next.js 16+ pattern)", "middle": "(configPath)) {\n const content = readFileSync(configPath, 'utf-8')\n\n // In Next.js 16+, cacheComponents must be enabled for 'use cache' directive\n expect(content).toMatch(/cacheComponents\\s*:\\s*true/)\n }\n})\n\ntest('Page ", "meta": {"filepath": "evals/evals/agent-032-use-cache-directive/EVAL.ts", "language": "typescript", "file_size": 3253, "cut_index": 614, "middle_length": 229}} {"prefix": " the agent uses server-side data fetching in a server component\n * instead of the client-side useEffect + fetch + useState pattern.\n *\n * Tricky because agents default to the familiar client-side pattern\n * (useEffect/fetch/useState) instead of using async server components.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\ntest('Page is an async server component', () => {\n const pageContent = readFileSync(\n join(process.cwd(), 'app', 'page.tsx'),\n", "suffix": ")\n\ntest('UserProfile component is a server component', () => {\n const userProfileContent = readFileSync(\n join(process.cwd(), 'app', 'UserProfile.tsx'),\n 'utf-8'\n )\n\n // Should NOT have 'use client' directive\n expect(userProfileContent).not.toMat", "middle": " 'utf-8'\n )\n\n // Should be an async function\n expect(pageContent).toMatch(/async\\s+function|export\\s+default\\s+async/)\n\n // Should NOT have 'use client' directive\n expect(pageContent).not.toMatch(/['\"]use client['\"];?/)\n}", "meta": {"filepath": "evals/evals/agent-021-avoid-fetch-in-effect/EVAL.ts", "language": "typescript", "file_size": 2364, "cut_index": 563, "middle_length": 229}} {"prefix": " attribute\n * instead of client-side onSubmit handlers and fetch calls.\n *\n * Tricky because agents tend to reach for 'use client' + onSubmit + fetch\n * instead of the simpler server action pattern with 'use server'.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, existsSync, readdirSync } from 'fs'\nimport { join } from 'path'\n\nfunction readAppFiles(): string {\n const appDir = join(process.cwd(), 'app')\n if (!existsSync(appDir)) return ''\n const entries = readdirSync(appDir, { recursive", "suffix": "it imports from the app directory.\n * Models sometimes extract form UI into a separate component file, so we need\n * to check all related files for patterns like , validation, etc.\n */\nfunction readContactFormAndImports(): string {\n const appDir = j", "middle": ": true }) as string[]\n const files = entries.filter((f) => f.endsWith('.tsx') || f.endsWith('.ts'))\n return files.map((f) => readFileSync(join(appDir, f), 'utf-8')).join('\\n')\n}\n\n/**\n * Read ContactForm.tsx and any local files ", "meta": {"filepath": "evals/evals/agent-022-prefer-server-actions/EVAL.ts", "language": "typescript", "file_size": 3828, "cut_index": 614, "middle_length": 229}} {"prefix": " the agent computes derived values directly from props/data\n * instead of storing them in redundant useState + useEffect.\n *\n * Tricky because agents overuse useState for values that can be computed\n * inline, adding unnecessary state and useEffect synchronization.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\ntest('Page renders User Management heading', () => {\n const content = readFileSync(join(process.cwd(), 'app', 'page.tsx'), 'utf-8')\n expec", "suffix": "use useState for calculated values\n expect(userStatsContent).not.toMatch(/useState.*active|active.*useState/)\n expect(userStatsContent).not.toMatch(/useState.*count|count.*useState/)\n expect(userStatsContent).not.toMatch(\n /useState.*percentage|perce", "middle": "t(content).toMatch(/User\\s+Management/)\n})\n\ntest('UserStats component avoids redundant useState', () => {\n const userStatsContent = readFileSync(\n join(process.cwd(), 'app', 'UserStats.tsx'),\n 'utf-8'\n )\n\n // Should NOT ", "meta": {"filepath": "evals/evals/agent-024-avoid-redundant-usestate/EVAL.ts", "language": "typescript", "file_size": 2385, "cut_index": 563, "middle_length": 229}} {"prefix": "s\n *\n * Verifies that the agent enables instant navigation on the product route.\n *\n * The eval harness runs `next build` as a script — with `cacheComponents: true`,\n * the build validates that the caching structure produces an instant static shell.\n * This test checks the agent actually exported `unstable_instant` (the build would\n * pass without it, since Suspense alone satisfies the build on a static route).\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, existsSync, readdirSync, statSy", "suffix": " Set(['EVAL.ts', 'PROMPT.md'])\n\nfunction readSourceFiles(dir: string): SourceFile[] {\n if (!existsSync(dir)) return []\n\n const files: SourceFile[] = []\n for (const entry of readdirSync(dir)) {\n if (IGNORE_DIRS.has(entry)) continue\n\n const fullPath", "middle": "nc } from 'fs'\nimport { join } from 'path'\n\ntype SourceFile = { path: string; content: string }\n\nconst IGNORE_DIRS = new Set([\n '.git',\n '.next',\n 'node_modules',\n 'dist',\n 'build',\n 'coverage',\n])\n\nconst IGNORE_FILES = new", "meta": {"filepath": "evals/evals/agent-040-unstable-instant/EVAL.ts", "language": "typescript", "file_size": 1844, "cut_index": 537, "middle_length": 229}} {"prefix": " the agent uses an async server component for request-time\n * data fetching instead of the Pages Router getServerSideProps pattern.\n *\n * Tricky because agents trained on older docs reach for getServerSideProps\n * instead of fetching directly in an async App Router server component.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\n/** Strip JS/TS comments so we only test actual code, not migration notes */\nfunction stripComments(code: string): string ", "suffix": "'),\n 'utf-8'\n )\n\n // Should be an async function\n expect(pageContent).toMatch(/async\\s+function|export\\s+default\\s+async/)\n\n // Should NOT have 'use client' directive\n expect(pageContent).not.toMatch(/['\"]use client['\"];?/)\n\n // Should fetch data ", "middle": "{\n return code.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '').replace(/\\/\\/.*$/gm, '')\n}\n\ntest('Page is an async server component with proper data fetching', () => {\n const pageContent = readFileSync(\n join(process.cwd(), 'app', 'page.tsx", "meta": {"filepath": "evals/evals/agent-023-avoid-getserversideprops/EVAL.ts", "language": "typescript", "file_size": 2145, "cut_index": 563, "middle_length": 229}} {"prefix": "e agent awaits cookies() and headers() calls, which became\n * async in Next.js 16 (breaking change from synchronous access in Next.js 15).\n *\n * Tricky because agents trained on Next.js 15 call cookies()/headers()\n * synchronously — Next.js 16 removed synchronous access entirely.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, existsSync, readdirSync } from 'fs'\nimport { join } from 'path'\n\nfunction readAppFiles(): string {\n const appDir = join(process.cwd(), 'app')\n if (!existsSync(appD", "suffix": ").join('\\n')\n}\n\ntest('Component uses await with cookies()', () => {\n const content = readAppFiles()\n\n // In Next.js 16, cookies() returns a Promise and MUST be awaited\n // Correct: const cookieStore = await cookies()\n // Wrong: const cookieStore = cook", "middle": "ir)) return ''\n const entries = readdirSync(appDir, { recursive: true }) as string[]\n const files = entries.filter((f) => f.endsWith('.tsx') || f.endsWith('.ts'))\n return files.map((f) => readFileSync(join(appDir, f), 'utf-8')", "meta": {"filepath": "evals/evals/agent-034-async-cookies/EVAL.ts", "language": "typescript", "file_size": 2542, "cut_index": 563, "middle_length": 229}} {"prefix": " whether the agent creates proxy.ts to log all requests — without the\n * prompt mentioning \"proxy\" or \"middleware.\" The agent must infer that request\n * interception requires the proxy layer.\n *\n * Tricky because unlike agent-031 which explicitly asks for middleware, this\n * only asks to \"log every request\" — the agent must know proxy.ts is the\n * right tool, and use the Next.js 16 convention (not middleware.ts).\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync, existsSync } from 'fs'\nimport", "suffix": "the file should be named proxy.ts, not middleware.ts\n // middleware.ts is deprecated\n const hasProxy = existsSync(proxyPath)\n const hasMiddleware = existsSync(middlewarePath)\n\n // Must have proxy.ts\n expect(hasProxy).toBe(true)\n\n // Should NOT have m", "middle": " { join } from 'path'\n\ntest('proxy.ts file exists in root (Next.js 16+ convention)', () => {\n const proxyPath = join(process.cwd(), 'proxy.ts')\n const middlewarePath = join(process.cwd(), 'middleware.ts')\n\n // In Next.js 16+, ", "meta": {"filepath": "evals/evals/agent-039-indirect-proxy/EVAL.ts", "language": "typescript", "file_size": 2408, "cut_index": 563, "middle_length": 229}} {"prefix": "t parallelizes independent data fetches with\n * Promise.all() instead of using sequential await calls.\n *\n * Tricky because agents default to sequential await for multiple fetches,\n * missing the opportunity to run independent requests concurrently.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\ntest('Page is an async server component with parallel data fetching', () => {\n const pageContent = readFileSync(\n join(process.cwd(), 'app', 'page.tsx')", "suffix": "\n\n // Should use parallel data fetching with Promise.all\n expect(pageContent).toMatch(/Promise\\.all/)\n})\n\ntest('Dashboard component fetches from all required APIs', () => {\n const dashboardContent = readFileSync(\n join(process.cwd(), 'app', 'Dashboar", "middle": ",\n 'utf-8'\n )\n\n // Should be an async function\n expect(pageContent).toMatch(/async\\s+function|export\\s+default\\s+async/)\n\n // Should NOT have 'use client' directive\n expect(pageContent).not.toMatch(/['\"]use client['\"];?/)", "meta": {"filepath": "evals/evals/agent-026-no-serial-await/EVAL.ts", "language": "typescript", "file_size": 2774, "cut_index": 563, "middle_length": 229}} {"prefix": "\n\n// Good example: parallel data fetching\nasync function getParallelData() {\n try {\n const [users, posts, stats] = await Promise.all([\n fetch('https://api.example.com/users').then((r) => r.json()),\n fetch('https://api.example.com/posts').then((r) => r.json()),\n fetch('https://api.example.com/stats').then((r) => r.json()),\n ])\n\n return { users, posts, stats }\n } catch {\n // Return mock data for build time\n return {\n users: [{ id: 1, name: 'User 1' }],\n posts: [{ id: ", "suffix": "\n }\n }\n}\n\nexport default async function Page() {\n const { users, posts, stats } = await getParallelData()\n\n return (\n
    \n

    Dashboard

    \n

    Users: {users.length}

    \n

    Posts: {posts.length}

    \n

    Total views: {stats", "middle": "1, title: 'Post 1' }],\n stats: { views: 1000 },", "meta": {"filepath": "evals/evals/agent-026-no-serial-await/app/page.tsx", "language": "tsx", "file_size": 905, "cut_index": 547, "middle_length": 52}} {"prefix": "r Next.js Image\n *\n * Tests whether the agent uses the Next.js Image component from next/image\n * instead of plain HTML tags.\n *\n * Tricky because agents default to tags, missing Next.js automatic\n * image optimization, lazy loading, and responsive sizing.\n */\n\nimport { expect, test } from 'vitest'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\ntest('ProductGallery uses Next.js Image component', () => {\n const galleryContent = readFileSync(\n join(process.cwd(), 'app', 'Produc", "suffix": "h(/ {\n const galleryContent = readFileSync(\n join(process.cwd(), 'app', 'ProductGallery.tsx'", "middle": "tGallery.tsx'),\n 'utf-8'\n )\n\n // Should import Image from next/image\n expect(galleryContent).toMatch(/import.*Image.*from ['\"]next\\/image['\"]/)\n\n // Should use Image components, not img tags\n expect(galleryContent).toMatc", "meta": {"filepath": "evals/evals/agent-027-prefer-next-image/EVAL.ts", "language": "typescript", "file_size": 1385, "cut_index": 524, "middle_length": 229}} {"prefix": " \"./types\";\n\nexport const handlers = [\n http.get(\"https://my.backend/book\", () => {\n const book: Book = {\n title: \"Lord of the Rings\",\n imageUrl: \"/book-cover.jpg\",\n description:\n \"The Lord of the Rings is an epic high-fantasy novel written by English author and scholar J. R. R. Tolkien.\",\n };\n return HttpResponse.json(book);\n }),\n\n http.get(\"/reviews\", () => {\n const reviews: Review[] = [\n {\n id: \"60333292-7ca1-4361-bf38-b6b43b90cb16\",\n author: \"John ", "suffix": " 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!\",\n ", "middle": "Maverick\",\n text: \"Lord of The Rings, is with", "meta": {"filepath": "examples/with-msw/mocks/handlers.ts", "language": "typescript", "file_size": 958, "cut_index": 582, "middle_length": 52}} {"prefix": "ct-dropdown-menu\";\n\nfunction RightSlot({ children }) {\n return (\n

    \n {children}\n
    \n );\n}\n\nfunction DropdownMenuItem({ children, ...props }) {\n return (\n \n {children}\n", "suffix": " rounded flex items-center h-6 px-1 pl-6 relative select-none\"\n >\n {children}\n \n );\n}\n\nfunction DropdownMenuItemIndicator({ children, ...props }) {\n return (\n \n );\n}\n\nfunction DropdownMenuCheckboxItem({ children, ...props }) {\n return (\n \n Add\n \n );\n}\n\nexport function AddForm() {\n // useActionState is available with React 19 (Next.js App Router)\n const [state, formAction] = useActionState(createTodo, initialState);\n\n r", "suffix": "orm action={formAction}>\n \n \n \n

    \n {state?.message}\n

    \n ", "middle": "eturn (\n =${ninetyDaysAgo()}`,\n sort: 'reactions',\n })\n\n if (prs.items.length > 0) {\n let text = ''\n let count = 0\n\n prs.items.forEach((pr, i) => {\n if (pr.reactions) {\n if (pr.react", "middle": " = new WebClient(process.env.SLACK_TOKEN)\n\n const { owner, repo } = context.repo\n\n const { data: prs } = await octoClient.rest.search.issuesAndPullRequests({\n order: 'desc',\n per_page: 15,\n q: `repo:${owner}/", "meta": {"filepath": ".github/actions/next-repo-actions/src/popular-prs.ts", "language": "typescript", "file_size": 2137, "cut_index": 563, "middle_length": 229}} {"prefix": " { info, setFailed } from '@actions/core'\nimport { context, getOctokit } from '@actions/github'\n\nasync function main() {\n if (!process.env.GITHUB_TOKEN) throw new TypeError('GITHUB_TOKEN not set')\n\n const octokit = getOctokit(process.env.GITHUB_TOKEN)\n\n const { owner, repo } = context.repo\n const issue = context.payload.issue\n const body = `\n\nThis issue has been closed due to the incorrect issue template being used. Please make sure to submit a new issue using the [correct issue template](https://githu", "suffix": "est regards,\nThe Next.js Team\n `\n\n try {\n await octokit.rest.issues.createComment({\n owner,\n repo,\n issue_number: issue.number,\n body,\n })\n\n await octokit.rest.issues.update({\n owner,\n repo,\n issue_number: issu", "middle": "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.\n\nThank you for your understanding and contributions.\n\nB", "meta": {"filepath": ".github/actions/next-repo-actions/src/wrong-issue-template.ts", "language": "typescript", "file_size": 1223, "cut_index": 518, "middle_length": 229}} {"prefix": " manifestFile)\n const contents = await fs.readFile(file, 'utf-8')\n const results = JSON.parse(contents)\n\n let failingCount = 0\n let passingCount = 0\n\n const currentDate = new Date()\n const isoString = currentDate.toISOString()\n const timestamp = isoString.slice(0, 19).replace('T', ' ')\n\n for (const isPassing of Object.values(results)) {\n if (isPassing) {\n passingCount += 1\n } else {\n failingCount += 1\n }\n }\n const status = `${process.env.GITHUB_SHA}\\t${timestamp}\\t${passingCount", "suffix": "festFile) {\n const file = path.join(process.cwd(), manifestFile)\n const contents = await fs.readFile(file, 'utf-8')\n const results = JSON.parse(contents)\n\n let passingTests = ''\n let failingTests = ''\n let passCount = 0\n let failCount = 0\n\n const c", "middle": "}/${\n passingCount + failingCount\n }`\n\n return {\n status,\n // Uses JSON.stringify to create minified JSON, otherwise whitespace is preserved.\n data: JSON.stringify(results),\n }\n}\n\nasync function collectResults(mani", "meta": {"filepath": ".github/actions/upload-turboyet-data/src/main.js", "language": "javascript", "file_size": 6591, "cut_index": 716, "middle_length": 229}} {"prefix": "urationWebpack: 'Webpack Warm (First Request)',\n // Production metrics\n nextStartReadyDuration: 'Prod Start',\n // Build metrics - Webpack\n buildDurationWebpack: 'Webpack Build Time',\n buildDurationCachedWebpack: 'Webpack Build Time (cached)',\n // Build metrics - Turbopack\n buildDurationTurbo: 'Turbo Build Time',\n buildDurationCachedTurbo: 'Turbo Build Time (cached)',\n // General metrics\n nodeModulesSize: 'node_modules Size',\n swcBinarySize: 'SWC Binary Size',\n}\n\n// Group configuration for organiz", "suffix": ",\n key: 'nextDevColdListenDurationTurbo',\n description: 'Time until TCP port accepts connections',\n },\n {\n label: 'Cold (Ready in log)',\n key: 'nextDevColdReadyInDurationTurbo',\n description: 'Time until \"Ready ", "middle": "ing the comment\nconst METRIC_GROUPS = {\n 'Dev Server': {\n icon: '⚡',\n description:\n 'Boot time for `next dev` (Turbopack). Cold = fresh build, Warm = with cache.',\n metrics: [\n {\n label: 'Cold (Listen)'", "meta": {"filepath": ".github/actions/next-stats-action/src/add-comment.js", "language": "javascript", "file_size": 39661, "cut_index": 2151, "middle_length": 229}} {"prefix": "./run')\nconst addComment = require('./add-comment')\nconst actionInfo = require('./prepare/action-info')()\nconst { mainRepoDir, diffRepoDir, pnpmStoreDir } = require('./constants')\nconst loadStatsConfig = require('./prepare/load-stats-config')\nconst { cloneRepo, mergeBranch, getCommitId, linkPackages, getLastStable } =\n require('./prepare/repo-setup')(actionInfo)\n\nconst allowedActions = new Set(['synchronize', 'opened'])\n\n// Get bundler filter from action input (set by GitHub Actions as INPUT_BUNDLER)\nconst", "suffix": "ionInfo.actionName) && !actionInfo.isRelease) {\n logger(\n `Not running for ${actionInfo.actionName} event action on repo: ${actionInfo.prRepo} and ref ${actionInfo.prRef}`\n )\n process.exit(0)\n}\n\n;(async () => {\n try {\n if (existsSync(path.join(__", "middle": " bundlerInput = (process.env.INPUT_BUNDLER || 'both').toLowerCase()\nconst isShardedRun = bundlerInput !== 'both'\n\nif (isShardedRun) {\n logger(`Running in sharded mode for bundler: ${bundlerInput}`)\n}\n\nif (!allowedActions.has(act", "meta": {"filepath": ".github/actions/next-stats-action/src/index.js", "language": "javascript", "file_size": 8451, "cut_index": 716, "middle_length": 229}} {"prefix": "= require('../util/exec')\nconst logger = require('../util/logger')\n\nmodule.exports = (actionInfo) => {\n return {\n async cloneRepo(repoPath = '', dest = '', branch = '', depth = '20') {\n await fs.promises.rm(dest, { recursive: true, force: true })\n await exec(\n `git clone ${actionInfo.gitRoot}${repoPath} --single-branch --branch ${branch} --depth=${depth} ${dest}`\n )\n },\n async getLastStable() {\n const res = await fetch(\n `https://api.github.com/repos/vercel/next.j", "suffix": "tatus}: ${await res.text()}`\n )\n }\n const data = await res.json()\n return data.tag_name\n },\n async getCommitId(repoDir = '') {\n const { stdout } = await exec(`cd ${repoDir} && git rev-parse HEAD`)\n return stdout.trim()", "middle": "s/releases/latest`,\n {\n headers: {\n 'X-GitHub-Api-Version': '2022-11-28',\n },\n }\n )\n\n if (!res.ok) {\n throw new Error(\n `Failed to get latest stable tag ${res.s", "meta": {"filepath": ".github/actions/next-stats-action/src/prepare/repo-setup.js", "language": "javascript", "file_size": 3220, "cut_index": 614, "middle_length": 229}} {"prefix": "nst exec = require('../util/exec')\nconst glob = require('../util/glob')\nconst logger = require('../util/logger')\nconst { statsAppDir, diffingDir } = require('../constants')\n\nmodule.exports = async function collectDiffs(\n filesToTrack = [],\n initial = false\n) {\n if (initial) {\n logger('Setting up directory for diffing')\n // set-up diffing directory\n await fs.rm(diffingDir, { recursive: true, force: true })\n await fs.mkdir(diffingDir, { recursive: true })\n await exec(`cd ${diffingDir} && git", "suffix": "ath.join(diffingDir, file), { recursive: true, force: true })\n )\n )\n }\n const diffs = {}\n\n await Promise.all(\n filesToTrack.map(async (fileGroup) => {\n const { globs } = fileGroup\n const curFiles = []\n const prettierExts = ['.j", "middle": " init`)\n } else {\n // remove any previous files in case they won't be overwritten\n const toRemove = await glob('!(.git)', { cwd: diffingDir, dot: true })\n\n await Promise.all(\n toRemove.map((file) =>\n fs.rm(p", "meta": {"filepath": ".github/actions/next-stats-action/src/run/collect-diffs.js", "language": "javascript", "file_size": 4954, "cut_index": 614, "middle_length": 229}} {"prefix": "urlParse } = require('url')\nconst benchmarkUrl = require('./benchmark-url')\nconst { statsAppDir, diffingDir, benchTitle } = require('../constants')\nconst { calcStats } = require('../util/stats')\n\n// Number of iterations for timing benchmarks to get stable median\nconst BENCHMARK_ITERATIONS = process.env.BENCHMARK_ITERATIONS\n ? parseInt(process.env.BENCHMARK_ITERATIONS)\n : 9\n\n// Check if a port is accepting TCP connections\nfunction checkPort(port, timeout = 100) {\n return new Promise((resolve) => {\n con", "suffix": ")\n socket.once('error', () => {\n socket.destroy()\n resolve(false)\n })\n socket.connect(port, 'localhost')\n })\n}\n\n// Wait for port to start accepting TCP connections\nasync function waitForPort(port, timeoutMs = 60000) {\n const start = Da", "middle": "st socket = new net.Socket()\n socket.setTimeout(timeout)\n socket.once('connect', () => {\n socket.destroy()\n resolve(true)\n })\n socket.once('timeout', () => {\n socket.destroy()\n resolve(false)\n }", "meta": {"filepath": ".github/actions/next-stats-action/src/run/collect-stats.js", "language": "javascript", "file_size": 17216, "cut_index": 921, "middle_length": 229}} {"prefix": "logger = require('./logger')\nconst { promisify } = require('util')\nconst { exec: execOrig, spawn: spawnOrig } = require('child_process')\n\nconst execP = promisify(execOrig)\nconst env = {\n ...process.env,\n GITHUB_TOKEN: '',\n PR_STATS_COMMENT_TOKEN: '',\n}\n\nfunction exec(command, noLog = false, opts = {}) {\n if (!noLog) logger(`exec: ${command}`)\n return execP(command, {\n ...opts,\n env: { ...env, ...opts.env },\n })\n}\n\nexec.spawn = function spawn(command = '', opts = {}) {\n logger(`spawn: ${command}", "suffix": "(${code}, ${signal}): ${command}`)\n })\n return child\n}\n\nexec.spawnPromise = function spawnPromise(command = '', opts = {}) {\n return new Promise((resolve, reject) => {\n const child = exec.spawn(command, opts)\n child.on('exit', (code, signal) => {\n", "middle": "`)\n const child = spawnOrig('/bin/bash', ['-c', command], {\n ...opts,\n env: {\n ...env,\n ...opts.env,\n },\n stdio: opts.stdio || 'inherit',\n })\n\n child.on('exit', (code, signal) => {\n logger(`spawn exit ", "meta": {"filepath": ".github/actions/next-stats-action/src/util/exec.js", "language": "javascript", "file_size": 1201, "cut_index": 518, "middle_length": 229}} {"prefix": "erface JobResult {\n job: string\n data: TestResult\n}\n\ninterface TestResultManifest {\n ref: string\n result: Array\n flakyMonitorJobResults: Array\n}\n\n/**\n * Models parsed test results output from next.js integration test.\n * This is a subset of the full test result output from jest, partially compatible.\n */\ninterface TestResult {\n numFailedTestSuites: number\n numFailedTests: number\n numPassedTestSuites: number\n numPassedTests: number\n numPendingTestSuites: number\n numPendingTes", "suffix": "orTitles?: Array | null\n failureMessages?: Array | null\n fullName: string\n location?: null\n status: string\n title: string\n }> | null\n endTime: number\n message: string\n name: string\n startTime: number\n", "middle": "ts: number\n numRuntimeErrorTestSuites: number\n numTodoTests: number\n numTotalTestSuites: number\n numTotalTests: number\n startTime: number\n success: boolean\n testResults?: Array<{\n assertionResults?: Array<{\n ancest", "meta": {"filepath": ".github/actions/next-integration-stat/src/manifest.d.ts", "language": "typescript", "file_size": 1079, "cut_index": 515, "middle_length": 229}} {"prefix": "Translation from \"next-translate/useTranslation\";\nimport \"./style.css\";\n\nexport const metadata = {\n title: \"Next.js\",\n};\n\nexport default function Layout(props) {\n const { t, lang } = useTranslation();\n\n return (\n \n \n {props.children}\n
    \n {t(\"common:powered\")} \n \n ▲ Vercel\n ", "suffix": " &\n \n next-translate\n \n
    \n \n", "meta": {"filepath": "examples/with-next-translate/app/layout.js", "language": "javascript", "file_size": 815, "cut_index": 522, "middle_length": 14}} {"prefix": "nk\";\nimport Trans from \"next-translate/Trans\";\nimport useTranslation from \"next-translate/useTranslation\";\n\nexport default function Home() {\n const { t, lang } = useTranslation();\n const isRTL = lang === \"ar\" || lang === \"he\";\n const arrow = isRTL ? String.fromCharCode(8592) : String.fromCharCode(8594);\n\n return (\n
    \n ,\n Next.js!,\n", "suffix": "h3>{t(\"home:english\")}

    \n

    \n {t(\"home:change-to\")} {t(\"home:english\")}\n

    \n
    \n \n\n \n
    \n

    {t(\"home:catalan\")}

    \n ", "middle": " ]}\n />\n\n

    \n {t(\"home:description\")} _pages/index.js\n

    \n\n
    \n \n
    \n <", "meta": {"filepath": "examples/with-next-translate/app/[lang]/page.js", "language": "javascript", "file_size": 1940, "cut_index": 537, "middle_length": 229}} {"prefix": "ogPageView } from \"../utils/analytics\";\n\nconst MyApp = ({ Component, pageProps }) => {\n const router = useRouter();\n\n useEffect(() => {\n initGA();\n // `routeChangeComplete` won't run for the first page load unless the query string is\n // hydrated later on, so here we log a page view if this is the first render and\n // there's no query string\n if (!router.asPath.includes(\"?\")) {\n logPageView();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() =", "suffix": "n or when the query changes\n router.events.on(\"routeChangeComplete\", logPageView);\n return () => {\n router.events.off(\"routeChangeComplete\", logPageView);\n };\n }, [router.events]);\n\n return ;\n};\n\nexport default M", "middle": "> {\n // Listen for page changes after a navigatio", "meta": {"filepath": "examples/with-react-ga4/pages/_app.js", "language": "javascript", "file_size": 920, "cut_index": 606, "middle_length": 52}} {"prefix": "port { useActionState } from \"react\";\nimport { useFormStatus } from \"react-dom\";\nimport { deleteTodo } from \"@/app/actions\";\n\nconst initialState = {\n message: \"\",\n};\n\nfunction DeleteButton() {\n const { pending } = useFormStatus();\n\n return (\n \n );\n}\n\nexport function DeleteForm({ id, todo }: { id: number; todo: string }) {\n // useActionState is available with React 19 (Next.js App Router)\n const [state, formAction] = useActionS", "suffix": "m action={formAction}>\n \n \n \n

    \n {state?.message}\n

    \n <", "middle": "tate(deleteTodo, initialState);\n\n return (\n {\n return stdout.split(field).pop().trim().split(/\\s/).shift().trim()\n}\n\n// benchmark an url\nasync function benchmarkUrl(\n url = '',\n options = {\n reqTimeout: 60,\n concurrency: 50,\n numRequests: 2500,\n }\n) {\n const { numRequests, concurrency, reqTimeout } = options\n\n const { stdout } = await exec(\n `ab -n ${numRequests} -c ${concurrency} -s ${reqTimeout} \"${url}\"`\n )\n const totalTime = parseFloat(parseField(stdou", "suffix": " for tests:'), 10)\n const failedRequests = parseInt(parseField(stdout, 'Failed requests:'), 10)\n const avgReqPerSec = parseFloat(parseField(stdout, 'Requests per second:'))\n\n return {\n totalTime,\n avgReqPerSec,\n failedRequests,\n }\n}\n\nmodule.ex", "middle": "t, 'Time taken", "meta": {"filepath": ".github/actions/next-stats-action/src/run/benchmark-url.js", "language": "javascript", "file_size": 813, "cut_index": 522, "middle_length": 14}} {"prefix": "/**\n * Shared statistics utilities for benchmark measurements\n */\n\n/**\n * Calculate statistical summary for an array of numbers\n * @param {number[]} arr - Array of numeric values\n * @returns {Object|null} Stats object with median, min, max, mean, stddev, cv or null if empty\n */\nfunction calcStats(arr) {\n if (arr.length === 0) return null\n\n const sorted = [...arr].sort((a, b) => a - b)\n const mid = Math.floor(sorted.length / 2)\n const median =\n sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sort", "suffix": "h\n const stddev = Math.sqrt(variance)\n const cv = mean > 0 ? (stddev / mean) * 100 : 0 // coefficient of variation as %\n\n return {\n median,\n min,\n max,\n mean: Math.round(mean),\n stddev: Math.round(stddev),\n cv: Math.round(cv),\n }\n}\n\nm", "middle": "ed[mid]) / 2\n const min = sorted[0]\n const max = sorted[sorted.length - 1]\n const mean = arr.reduce((a, b) => a + b, 0) / arr.length\n const variance =\n arr.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / arr.lengt", "meta": {"filepath": ".github/actions/next-stats-action/src/util/stats.js", "language": "javascript", "file_size": 1027, "cut_index": 512, "middle_length": 229}} {"prefix": "/github'\nimport { minimatch } from 'minimatch'\nimport config from './config.json'\n\ntype AuthorRule = { type: 'user'; pattern: string }\ntype LabelRule = string | AuthorRule\ntype LabelerConfig = { labels: Record }\n\nfunction isAuthorRule(rule: LabelRule): rule is AuthorRule {\n return (\n typeof rule === 'object' &&\n rule !== null &&\n 'type' in rule &&\n rule.type === 'user'\n )\n}\n\n/**\n * Compute the set of labels to apply for a pull request.\n */\nexport function computeLabels(\n ", "suffix": "orRule(rule)) {\n if (rule.pattern.toLowerCase() === author.toLowerCase()) {\n matched.add(label)\n break\n }\n } else if (typeof rule === 'string') {\n const matches = changedFiles.some((file) =>\n minimatch(f", "middle": "config: LabelerConfig,\n author: string,\n changedFiles: string[]\n): string[] {\n const matched = new Set()\n\n for (const [label, rules] of Object.entries(config.labels)) {\n for (const rule of rules) {\n if (isAuth", "meta": {"filepath": ".github/actions/pr-auto-label/src/index.ts", "language": "typescript", "file_size": 3664, "cut_index": 614, "middle_length": 229}} {"prefix": ";\n\nimport { revalidatePath } from \"next/cache\";\nimport postgres from \"postgres\";\nimport { z } from \"zod\";\n\nlet sql = postgres(process.env.DATABASE_URL || process.env.POSTGRES_URL!, {\n ssl: \"allow\",\n});\n\n// CREATE TABLE todos (\n// id SERIAL PRIMARY KEY,\n// text TEXT NOT NULL\n// );\n\nexport async function createTodo(\n prevState: {\n message: string;\n },\n formData: FormData,\n) {\n const schema = z.object({\n todo: z.string().min(1),\n });\n const parse = schema.safeParse({\n todo: formData.get(\"to", "suffix": "/\");\n return { message: `Added todo ${data.todo}` };\n } catch (e) {\n return { message: \"Failed to create todo\" };\n }\n}\n\nexport async function deleteTodo(\n prevState: {\n message: string;\n },\n formData: FormData,\n) {\n const schema = z.object({", "middle": "do\"),\n });\n\n if (!parse.success) {\n return { message: \"Failed to create todo\" };\n }\n\n const data = parse.data;\n\n try {\n await sql`\n INSERT INTO todos (text)\n VALUES (${data.todo})\n `;\n\n revalidatePath(\"", "meta": {"filepath": "examples/next-forms/app/actions.ts", "language": "typescript", "file_size": 1402, "cut_index": 524, "middle_length": 229}} {"prefix": "const { diffRepoDir, allowedConfigLocations } = require('../constants')\n\n// load stats-config\nfunction loadStatsConfig() {\n let statsConfig\n let relativeStatsAppDir\n\n for (const configPath of allowedConfigLocations) {\n try {\n relativeStatsAppDir = configPath\n statsConfig = require(\n path.join(diffRepoDir, configPath, 'stats-config.js')\n )\n break\n } catch (err) {\n if (err.code !== 'MODULE_NOT_FOUND') {\n console.error('Failed to load stats-config at', configPath", "suffix": "nfig) {\n throw new Error(\n `Failed to locate \\`.stats-app\\`, allowed locations are: ${allowedConfigLocations.join(\n ', '\n )}`\n )\n }\n\n logger(\n 'Got statsConfig at',\n path.join(relativeStatsAppDir, 'stats-config.js'),\n stat", "middle": ", err)\n }\n /* */\n }\n }\n\n if (!statsCo", "meta": {"filepath": ".github/actions/next-stats-action/src/prepare/load-stats-config.js", "language": "javascript", "file_size": 994, "cut_index": 582, "middle_length": 52}} {"prefix": "ort { useState } from \"react\";\nimport { Book, Review } from \"../mocks/types\";\n\ntype Props = {\n book: Book;\n};\n\nexport default function Home({ book }: Props) {\n const [reviews, setReviews] = useState(null);\n\n const handleGetReviews = () => {\n // Client-side request are mocked by `mocks/browser.ts`.\n fetch(\"/reviews\")\n .then((res) => res.json())\n .then(setReviews);\n };\n\n return (\n
    \n {book.title}\n

    {book.titl", "suffix": "w.text}

    \n

    {review.author}

    \n \n ))}\n \n )}\n

    \n );\n}\n\nexport async function getServerSideProps() {\n // Server-side requests are mocked by `mocks/server.ts`.\n const res = await fetch(\"ht", "middle": "e}\n

    {book.description}

    \n \n {reviews && (\n
      \n {reviews.map((review) => (\n
    • \n

      {revie", "meta": {"filepath": "examples/with-msw/pages/index.tsx", "language": "tsx", "file_size": 1109, "cut_index": 515, "middle_length": 229}} {"prefix": "bution CDFs (Student's t and\n// standard normal). The rest — Welch's t-statistic, average-rank ranking,\n// and the Mann–Whitney U statistic + asymptotic-tail p-value — is\n// implemented here directly.\n//\n// For Mann–Whitney we use the normal approximation with continuity\n// correction. For very small samples this approximation is less accurate\n// (n=5 vs n=5 has a minimum exact two-sided p ≈ 0.008 vs the\n// approximation's ≈ 0.012). Document this at the call site, not here.\nimport jstat from 'jstat'\n\nexport", "suffix": "olation quantile (numpy/R \"type 7\" default).\nexport function quantile(xs: number[], q: number): number {\n if (xs.length === 0) return NaN\n if (xs.length === 1) return xs[0]\n const sorted = [...xs].sort((a, b) => a - b)\n const pos = q * (sorted.length -", "middle": " interface Summary {\n mean: number\n p50: number\n p90: number\n}\n\nexport function mean(xs: number[]): number {\n if (xs.length === 0) return NaN\n let s = 0\n for (const x of xs) s += x\n return s / xs.length\n}\n\n// Linear-interp", "meta": {"filepath": "turbopack/packages/devlow-bench/src/statistics.ts", "language": "typescript", "file_size": 4032, "cut_index": 614, "middle_length": 229}} {"prefix": "minimist(process.argv.slice(2), {\n alias: {\n r: 'row',\n c: 'column',\n '?': 'help',\n h: 'help',\n },\n })\n\n const knownArgs = new Set(['row', 'r', 'column', 'c', 'help', 'h', '?', '_'])\n if (args.help || (Object.keys(args).length === 1 && args._.length === 0)) {\n console.log('Usage: devlow-table ')\n console.log(' --row= Key to show as row')\n console.log(' --column= Key to show as column')\n console.log(' --= Filter values')\n", "suffix": " => {\n if (name === 'value') {\n return data.text as string\n }\n if (Array.isArray(name)) {\n return name\n .map((n) => getValue(data, n, true))\n .filter((x) => x)\n .join(' ')\n }\n const value = data.key[name]\n i", "middle": " console.log(' --help, -h, -? Show this help')\n }\n\n let data = JSON.parse(await readFile(args._[0], 'utf-8')) as any[]\n\n const getValue = (\n data: any,\n name: string | string[],\n includeKey: boolean\n ): string", "meta": {"filepath": "turbopack/packages/devlow-bench/src/table.ts", "language": "typescript", "file_size": 3540, "cut_index": 614, "middle_length": 229}} {"prefix": "mport { Interface } from '../index.js'\nimport { SampleGroup, groupRows, makeKey, printComparison } from '../compare.js'\nimport { readSnapshot } from '../snapshot.js'\nimport { formatVariantProps } from '../utils.js'\n\nexport default async function createInterface(options: {\n baselinePath: string\n}): Promise {\n const baselinePath = options.baselinePath\n const baselineRows = await readSnapshot(baselinePath)\n const baseline = groupRows(baselineRows)\n const current = new Map()", "suffix": "c)\n current.set(key, {\n scenario,\n variant,\n metric,\n unit: s.unit,\n samples: s.samples.slice(),\n })\n }\n },\n finish: async () => {\n printComparison(baseline, current, { baselineLabe", "middle": "\n\n return {\n variantStatistics: async (scenario, props, stats) => {\n const variant = formatVariantProps(props)\n for (const [metric, s] of Object.entries(stats)) {\n const key = makeKey(scenario, variant, metri", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/compare.ts", "language": "typescript", "file_size": 1030, "cut_index": 513, "middle_length": 229}} {"prefix": "]): Interface {\n const allKeys = new Set()\n for (const iface of ifaces) {\n for (const key of Object.keys(iface)) {\n allKeys.add(key as keyof Interface)\n }\n }\n const composed: any = {}\n for (const key of allKeys) {\n if (key.startsWith('filter')) {\n composed[key] = async (items: any, ...args: any[]) => {\n for (const iface of ifaces) {\n const anyIface = iface as any\n if (anyIface[key]) {\n items = await anyIface[key](items, ...args)\n ", "suffix": " } else {\n composed[key] = async (...args: any[]) => {\n for (const iface of ifaces) {\n const anyIface = iface as any\n if (anyIface[key]) {\n await anyIface[key](...args)\n }\n }\n }\n }\n }\n retu", "middle": " }\n }\n return items\n }\n ", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/compose.ts", "language": "typescript", "file_size": 928, "cut_index": 606, "middle_length": 52}} {"prefix": "ace } from '../index.js'\nimport { formatUnit } from '../units.js'\nimport { formatVariant } from '../utils.js'\n\nconst { bgCyan, bold, cyan, dim, magenta, red, underline } = picocolors\n\nexport default function createInterface(\n options: { n?: number } = {}\n): Interface {\n const n = options.n ?? 1\n const showSummary = n > 1\n const iface: Interface = {\n start: async (scenario, props, runInfo) => {\n const label = formatVariant(scenario, props)\n let progress = ''\n if (runInfo) {\n prog", "suffix": "sync (scenario, props, name, value, unit, relativeTo) => {\n console.log(\n bgCyan(\n bold(\n magenta(\n `${formatVariant(scenario, props)}: ${name} = ${formatUnit(\n value,\n unit\n ", "middle": "ress = runInfo.warmup\n ? ` [warmup ${runInfo.run}/${runInfo.total}]`\n : ` [${runInfo.run}/${runInfo.total}]`\n }\n console.log(bold(underline(`Running ${label}...${progress}`)))\n },\n measurement: a", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/console.ts", "language": "typescript", "file_size": 2034, "cut_index": 563, "middle_length": 229}} {"prefix": "ommand } from '../shell.js'\n\nexport const UNIT_MAPPING: Record = {\n ms: 'millisecond',\n requests: 'request',\n bytes: 'byte',\n}\n\nexport const GIT_SHA =\n process.env.GITHUB_SHA ??\n (await (async () => {\n const cmd = command('git', ['rev-parse', 'HEAD'])\n await cmd.ok()\n return cmd.output.trim()\n })())\n\nexport const GIT_BRANCH =\n process.env.GITHUB_REF_NAME ??\n (await (async () => {\n const cmd = command('git', ['rev-parse', '--abbrev-ref', 'HEAD'])\n await cmd.ok()\n ret", "suffix": "Boolean(process.env.CI)\nexport const OS = process.platform\nexport const OS_RELEASE = os.release()\nexport const NUM_CPUS = os.cpus().length\nexport const CPU_MODEL = os.cpus()[0].model\nexport const USERNAME = os.userInfo().username\nexport const CPU_ARCH = os", "middle": "urn cmd.output.trim()\n })())\n\nexport const IS_CI = ", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/constants.ts", "language": "typescript", "file_size": 907, "cut_index": 547, "middle_length": 52}} {"prefix": "etadata,\n} from '@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/index.js'\nimport type { Interface } from '../index.js'\nimport datadogApiClient from '@datadog/datadog-api-client'\nimport os from 'os'\nimport {\n CPU_ARCH,\n CPU_MODEL,\n GIT_BRANCH,\n GIT_SHA,\n IS_CI,\n NODE_VERSION,\n NUM_CPUS,\n OS,\n OS_RELEASE,\n USERNAME,\n} from './constants.js'\n\nfunction toIdentifier(str: string) {\n return str.replace(/\\//g, '.').replace(/ /g, '_')\n}\n\nconst UNIT_MAPPING: Record = {\n ms:", "suffix": "(),\n}: { apiKey?: string; appKey?: string; host?: string } = {}): Interface {\n if (!apiKey)\n throw new Error('Datadog API key is required (set DATADOG_API_KEY)')\n const commonTags = [\n `ci:${IS_CI}`,\n `os:${OS}`,\n `os_release:${OS_RELEASE}`,\n", "middle": " 'millisecond',\n requests: 'request',\n bytes: 'byte',\n}\n\nexport default function createInterface({\n apiKey = process.env.DATADOG_API_KEY,\n appKey = process.env.DATADOG_APP_KEY,\n host = process.env.DATADOG_HOST || os.hostname", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/datadog.ts", "language": "typescript", "file_size": 2835, "cut_index": 563, "middle_length": 229}} {"prefix": " { Interface } from '../index.js'\nimport inquirer from 'inquirer'\nimport { formatVariant } from '../utils.js'\n\nexport default function createInterface(): Interface {\n const iface: Interface = {\n filterScenarios: async (scenarios) => {\n if (scenarios.length === 1) {\n return scenarios\n }\n let answer = await inquirer.prompt({\n type: 'checkbox',\n name: 'scenarios',\n default: scenarios.slice(),\n message: 'Choose scenarios to run',\n choices: scenarios.m", "suffix": " return variants\n }\n let answer = await inquirer.prompt({\n type: 'checkbox',\n name: 'variants',\n default: variants.slice(),\n message: 'Choose variants to run',\n choices: variants.map((variant) => {\n ret", "middle": "ap((scenario) => ({\n name: scenario.name,\n value: scenario,\n })),\n })\n return answer.scenarios\n },\n filterScenarioVariants: async (variants) => {\n if (variants.length === 1) {\n ", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/interactive.ts", "language": "typescript", "file_size": 1199, "cut_index": 518, "middle_length": 229}} {"prefix": "antile, mean as statsMean } from '../statistics.js'\nimport { formatUnit } from '../units.js'\nimport { writeFile } from 'fs/promises'\n\nfunction filterProp(\n prop: Record\n): Record {\n const filteredProp: Record = {}\n for (const [key, value] of Object.entries(prop)) {\n if (value !== null) {\n filteredProp[key] = value\n }\n }\n return filteredProp\n}\n\nexport default function createInterfac", "suffix": " const n = options.n ?? 1\n // Per-(scenario, props, name) sample accumulator.\n const metrics = new Map<\n string,\n {\n key: Record\n samples: number[]\n unit: string\n relativeTo?: string\n }\n >()\n const", "middle": "e(\n file: string = (() => {\n const file = process.env.JSON_OUTPUT_FILE\n if (!file) {\n throw new Error('env var JSON_OUTPUT_FILE is not set')\n }\n return file\n })(),\n options: { n?: number } = {}\n): Interface {\n", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/json.ts", "language": "typescript", "file_size": 2544, "cut_index": 563, "middle_length": 229}} {"prefix": "t'\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { test } from 'node:test'\nimport { command } from '../shell.js'\n\nasync function withTempScript(\n scriptContents: string,\n fn: (scriptPath: string) => Promise\n) {\n const dir = await mkdtemp(join(tmpdir(), 'devlow-shell-test-'))\n const scriptPath = join(dir, 'script.js')\n\n try {\n await writeFile(scriptPath, scriptContents, 'utf8')\n await fn(scriptPath)\n } fina", "suffix": "KER')\nsetTimeout(() => {}, 1000)\n`,\n async (scriptPath) => {\n const shell = command('node', [scriptPath])\n\n try {\n const first = await shell.waitForOutput(/FIRST_MARKER\\n/, {\n timeoutMs: 2_000,\n })\n assert.equal(f", "middle": "lly {\n await rm(dir, { recursive: true, force: true })\n }\n}\n\ntest('waitForOutput handles sequential waits after buffered output', async () => {\n await withTempScript(\n `\nconsole.log('FIRST_MARKER')\nconsole.log('SECOND_MAR", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/shell-test.ts", "language": "typescript", "file_size": 1844, "cut_index": 537, "middle_length": 229}} {"prefix": "t { promisify } from 'node:util'\nimport picocolors from 'picocolors'\nimport { Interface } from '../index.js'\nimport { SnapshotRow, defaultSnapshotPath, writeSnapshot } from '../snapshot.js'\nimport { formatVariantProps } from '../utils.js'\n\nconst execFileAsync = promisify(execFile)\n\nasync function readGitInfo(): Promise<{ sha: string; branch: string }> {\n const sha = process.env.GITHUB_SHA || (await tryGit(['rev-parse', 'HEAD']))\n const branch =\n process.env.GITHUB_REF_NAME ||\n (await tryGit(['rev-pa", "suffix": "''\n }\n}\n\nexport default function createInterface(\n options: { path?: string } = {}\n): Interface & { resolvedPath: string } {\n const path = options.path ?? defaultSnapshotPath()\n const rows: SnapshotRow[] = []\n const timestamp = new Date().toISOString(", "middle": "rse', '--abbrev-ref', 'HEAD']))\n return { sha, branch }\n}\n\nasync function tryGit(args: string[]): Promise {\n try {\n const { stdout } = await execFileAsync('git', args)\n return stdout.trim()\n } catch {\n return ", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/snapshot.ts", "language": "typescript", "file_size": 2027, "cut_index": 563, "middle_length": 229}} {"prefix": "t'\nimport createInterface from './snowflake.js'\nimport { mock, test } from 'node:test'\n\ntest('sending measurements to the batch endpoint', async () => {\n const requests: Array<[string, RequestInit]> = []\n\n const fetchMock = mock.method(\n global,\n 'fetch',\n (req: string, options: RequestInit) => {\n requests.push([req, options])\n return Promise.resolve(Response.json({}))\n }\n )\n\n const iface = createInterface({\n gatewayUri: 'http://127.0.0.1/v1/batch',\n topicName: 'my-topic',\n ", "suffix": "ent('scenario', { myprop: 'foo' }, 'three', 38, 'ms')\n\n assert(iface.end != null)\n await iface.end('scenario', { myprop: 'foo' })\n\n assert.equal(requests.length, 1)\n const [url, options] = requests[0]\n assert.equal(url, 'http://127.0.0.1/v1/batch')\n ", "middle": " schemaId: 123,\n })\n\n assert(iface.measurement != null)\n await iface.measurement('scenario', { myprop: 'foo' }, 'one', 42, 'ms')\n await iface.measurement('scenario', { myprop: 'foo' }, 'two', 45, 'ms')\n await iface.measurem", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/snowflake-test.ts", "language": "typescript", "file_size": 1829, "cut_index": 537, "middle_length": 229}} {"prefix": "IT_BRANCH,\n GIT_SHA,\n IS_CI,\n NODE_VERSION,\n NUM_CPUS,\n OS,\n OS_RELEASE,\n USERNAME,\n} from './constants.js'\nimport { randomUUID } from 'crypto'\n\ntype DevlowMetric = {\n event_time: number\n scenario: string\n props: Record\n metric: string\n value: number\n unit: string\n relative_to?: string\n is_ci: boolean\n os: string\n os_release: string\n cpus: number\n cpu_model: string\n user: string\n arch: string\n total_memory_bytes: number\n node_version: string\n ", "suffix": " parseInt(process.env.SNOWFLAKE_SCHEMA_ID, 10)\n : undefined,\n}: {\n gatewayUri?: string\n topicName?: string\n schemaId?: number\n} = {}): Interface {\n if (!gatewayUri)\n throw new Error(\n 'Snowflake gateway URI is required (set SNOWFLAKE_GATEWAY", "middle": " git_sha: string\n git_branch: string\n}\n\nexport default function createInterface({\n gatewayUri = process.env.SNOWFLAKE_BATCH_URI,\n topicName = process.env.SNOWFLAKE_TOPIC_NAME,\n schemaId = process.env.SNOWFLAKE_SCHEMA_ID\n ?", "meta": {"filepath": "turbopack/packages/devlow-bench/src/interfaces/snowflake.ts", "language": "typescript", "file_size": 3428, "cut_index": 614, "middle_length": 229}} {"prefix": "-pprof-node-gyp',\n 'microtime-node-gyp',\n 'zeromq-node-gyp',\n]\n\nconst skipOnWindows = [\n 'datadog-pprof-node-gyp',\n 'yarn-workspaces',\n 'yarn-workspaces-base-root',\n 'yarn-workspace-esm',\n 'asset-symlink',\n 'require-symlink',\n]\nconst skipOnMac = []\nconst skipOnNode20AndBelow = ['module-sync-condition-es']\nconst skipOnNode22AndAbove = ['module-sync-condition-es-node20']\nif (process.platform === 'darwin' && process.arch === 'arm64') {\n skipOnMac.push('microtime-node-gyp')\n}\nconst unitTestDirs = fs.re", "suffix": " {\n const originalModule = jest.requireActual('../out/analyze.js').default\n\n return {\n __esModule: true,\n default: jest.fn(originalModule),\n }\n})\n\njest.mock('graceful-fs', () => {\n const originalModule = jest.requireActual('graceful-fs')\n\n retur", "middle": "addirSync(join(__dirname, 'unit'))\nconst unitTests = [\n ...unitTestDirs.map((testName) => ({ testName, isRoot: false })),\n ...unitTestDirs.map((testName) => ({ testName, isRoot: true })),\n]\n\njest.mock('../out/analyze.js', () =>", "meta": {"filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/unit.test.js", "language": "javascript", "file_size": 11941, "cut_index": 921, "middle_length": 229}} {"prefix": "se = require('firebase/app')\nrequire('firebase/firestore')\nrequire('firebase/database')\n\nfirebase.initializeApp({ projectId: 'noop' })\nconst store = firebase.firestore()\n\nstore\n .collection('users')\n .get()\n .then(\n () => {\n console.log('ok')\n process.exit(0)\n },\n (e) => {\n /*\n Error: unresolvable extensions: 'extend google.protobuf.MethodOptions' in .google.api\n at Root.resolveAll (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T/node_modules/protobufjs/src/ro", "suffix": "/a707d6b7ee4afe5b484993180e617e2d/index.js:16778:41)\n at NodePlatform.module.exports.278.NodePlatform.loadConnection (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T/a707d6b7ee4afe5b484993180e617e2d/index.js:16815:22)\n at FirestoreCl", "middle": "ot.js:243:1)\n at Object.loadSync (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T/a707d6b7ee4afe5b484993180e617e2d/index.js:43406:16)\n at loadProtos (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T", "meta": {"filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/integration/firebase.js", "language": "javascript", "file_size": 1357, "cut_index": 524, "middle_length": 229}} {"prefix": "\n;(() => {\n var exports = {}\n exports.id = 829\n exports.ids = [829]\n exports.modules = {\n /***/ 354: /***/ (\n __unused_webpack_module,\n __webpack_exports__,\n __webpack_require__\n ) => {\n // ESM COMPAT FLAG\n __webpack_require__.r(__webpack_exports__)\n\n // EXPORTS\n __webpack_require__.d(__webpack_exports__, {\n default: () => /* binding */ handler,\n }) // CONCATENATED MODULE: external \"fs/promises\"\n\n const promises_namespaceObject = require('fs/prom", "suffix": "ync function handler(_req, res) {\n const hello = await (0, promises_namespaceObject.readFile)(\n __dirname + '/hello.txt',\n 'utf-8'\n )\n return hello\n }\n\n /***/\n },\n }\n // load runtime\n var __webpack_req", "middle": "ises') // CONCATENATED MODULE: ./pages/api/users.ts\n // Fake users data\n const users = [\n {\n id: 1,\n },\n {\n id: 2,\n },\n {\n id: 3,\n },\n ]\n as", "meta": {"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}} {"prefix": "le cache\n /******/ var __webpack_module_cache__ = {}\n /******/\n /******/ // The require function\n /******/ function __webpack_require__(moduleId) {\n /******/ // Check if module is in cache\n /******/ var cachedModule = __webpack_module_cache__[moduleId]\n /******/ if (cachedModule !== undefined) {\n /******/ return cachedModule.exports\n /******/\n }\n /******/ // Create a new module (and put it into the cache)\n /******/ var module = (__webpack_module_cache__[moduleId] = {\n /*", "suffix": " /******/ __webpack_modules__[moduleId](\n module,\n module.exports,\n __webpack_require__\n )\n /******/ threw = false\n /******/\n } finally {\n /******/ if (threw) delete __webpack_module_cache__[moduleId]\n /", "middle": "*****/ // no module.id needed\n /******/ // no module.loaded needed\n /******/ exports: {},\n /******/\n })\n /******/\n /******/ // Execute the module function\n /******/ var threw = true\n /******/ try {\n ", "meta": {"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}} {"prefix": " * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permiss", "suffix": "rts.LogVerbosity =\n exports.Status =\n void 0\nvar Status\n;(function (Status) {\n Status[(Status['OK'] = 0)] = 'OK'\n Status[(Status['CANCELLED'] = 1)] = 'CANCELLED'\n Status[(Status['UNKNOWN'] = 2)] = 'UNKNOWN'\n Status[(Status['INVALID_ARGUMENT'] = 3)]", "middle": "ions and\n * limitations under the License.\n *\n */\nObject.defineProperty(exports, '__esModule', { value: true })\nexports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH =\n exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH =\n exports.Propagate =\n expo", "meta": {"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}} {"prefix": "**/ function __webpack_require__(moduleId) {\n /******/\n /******/ // Check if module is in cache\n /******/ if (installedModules[moduleId]) {\n /******/ return installedModules[moduleId].exports\n /******/\n }\n /******/ // Create a new module (and put it into the cache)\n /******/ var module = (installedModules[moduleId] = {\n /******/ i: moduleId,\n /******/ l: false,\n /******/ exports: {},\n /******/\n })\n /******/\n /******/ // Execute the module function\n ", "suffix": " } finally {\n /******/ if (threw) delete installedModules[moduleId]\n /******/\n }\n /******/\n /******/ // Flag the module as loaded\n /******/ module.l = true\n /******/\n /******/ // Return the exports of the module\n /******/ ", "middle": " /******/ var threw = true\n /******/ try {\n /******/ modules[moduleId].call(\n module.exports,\n module,\n module.exports,\n __webpack_require__\n )\n /******/ threw = false\n /******/\n", "meta": {"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}} {"prefix": "opy-sync.js',\n // 'node_modules/fs-extra/lib/copy/copy.js',\n // 'node_modules/fs-extra/lib/copy/index.js',\n // 'node_modules/fs-extra/lib/empty/index.js',\n // 'node_modules/fs-extra/lib/ensure/file.js',\n // 'node_modules/fs-extra/lib/ensure/index.js',\n // 'node_modules/fs-extra/lib/ensure/link.js',\n // 'node_modules/fs-extra/lib/ensure/symlink-paths.js',\n // 'node_modules/fs-extra/lib/ensure/symlink-type.js',\n // 'node_modules/fs-extra/lib/ensure/symlink.js',\n // 'node_modules/fs-extra/lib/fs/inde", "suffix": "-extra/lib/json/output-json.js',\n // 'node_modules/fs-extra/lib/mkdirs/index.js',\n // 'node_modules/fs-extra/lib/mkdirs/make-dir.js',\n // 'node_modules/fs-extra/lib/mkdirs/utils.js',\n // 'node_modules/fs-extra/lib/move/index.js',\n // 'node_modules/fs-", "middle": "x.js',\n // 'node_modules/fs-extra/lib/index.js',\n // 'node_modules/fs-extra/lib/json/index.js',\n // 'node_modules/fs-extra/lib/json/jsonfile.js',\n // 'node_modules/fs-extra/lib/json/output-json-sync.js',\n // 'node_modules/fs", "meta": {"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}} {"prefix": "-gyp-build/index.js',\n 'node_modules/@datadog/pprof/node_modules/node-gyp-build/package.json',\n 'node_modules/@datadog/pprof/node_modules/source-map/lib/array-set.js',\n 'node_modules/@datadog/pprof/node_modules/source-map/lib/base64-vlq.js',\n 'node_modules/@datadog/pprof/node_modules/source-map/lib/base64.js',\n 'node_modules/@datadog/pprof/node_modules/source-map/lib/binary-search.js',\n 'node_modules/@datadog/pprof/node_modules/source-map/lib/mapping-list.js',\n 'node_modules/@datadog/pprof/node_modul", "suffix": "odules/source-map/lib/source-map-generator.js',\n 'node_modules/@datadog/pprof/node_modules/source-map/lib/source-node.js',\n 'node_modules/@datadog/pprof/node_modules/source-map/lib/util.js',\n 'node_modules/@datadog/pprof/node_modules/source-map/lib/wasm", "middle": "es/source-map/lib/mappings.wasm',\n 'node_modules/@datadog/pprof/node_modules/source-map/lib/read-wasm.js',\n 'node_modules/@datadog/pprof/node_modules/source-map/lib/source-map-consumer.js',\n 'node_modules/@datadog/pprof/node_m", "meta": {"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}} {"prefix": "__importDefault =\n (this && this.__importDefault) ||\n function (mod) {\n return mod && mod.__esModule ? mod : { default: mod }\n }\nvar __importStar =\n (this && this.__importStar) ||\n function (mod) {\n if (mod && mod.__esModule) return mod\n var result = {}\n if (mod != null)\n for (var k in mod)\n if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]\n result['default'] = mod\n return result\n }\nObject.defineProperty(exports, '__esModule', { value: true })\nconst fs_1 = __impo", "suffix": "equire('path'))\nconsole.log(\n fs_1.default.readFileSync(path.join(__dirname, 'asset.txt'), 'utf8')\n)\n\n/* Input source (with modules: 'commonjs'):\nimport fs from 'fs';\nimport * as path from 'path';\n\nconsole.log(fs.readFileSync(path.join(__dirname, 'asset.t", "middle": "rtDefault(require('fs'))\nconst path = __importStar(r", "meta": {"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}} {"prefix": "23\n exports.ids = [223]\n exports.modules = {\n /***/ 0: /***/ function (module, exports, __webpack_require__) {\n module.exports = __webpack_require__('PicC')\n\n /***/\n },\n\n /***/ PicC: /***/ function (\n module,\n __webpack_exports__,\n __webpack_require__\n ) {\n 'use strict'\n __webpack_require__.r(__webpack_exports__)\n /* harmony export (binding) */ __webpack_require__.d(\n __webpack_exports__,\n 'default',\n function () {\n return h", "suffix": "th__WEBPACK_IMPORTED_MODULE_0__)\n /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = require('fs')\n /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default =\n /*#__PURE__*/ __webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE", "middle": "andler\n }\n )\n /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = require('path')\n /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default =\n /*#__PURE__*/ __webpack_require__.n(pa", "meta": {"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}} {"prefix": "ges/applescript.tmLanguage.json',\n 'node_modules/shiki/languages/ara.tmLanguage.json',\n 'node_modules/shiki/languages/asm.tmLanguage.json',\n 'node_modules/shiki/languages/astro.tmLanguage.json',\n 'node_modules/shiki/languages/awk.tmLanguage.json',\n 'node_modules/shiki/languages/ballerina.tmLanguage.json',\n 'node_modules/shiki/languages/bat.tmLanguage.json',\n 'node_modules/shiki/languages/beancount.tmLanguage.json',\n 'node_modules/shiki/languages/berry.tmLanguage.json',\n 'node_modules/shiki/language", "suffix": "e.tmLanguage.json',\n 'node_modules/shiki/languages/clarity.tmLanguage.json',\n 'node_modules/shiki/languages/clojure.tmLanguage.json',\n 'node_modules/shiki/languages/cmake.tmLanguage.json',\n 'node_modules/shiki/languages/cobol.tmLanguage.json',\n 'node_", "middle": "s/bibtex.tmLanguage.json',\n 'node_modules/shiki/languages/bicep.tmLanguage.json',\n 'node_modules/shiki/languages/blade.tmLanguage.json',\n 'node_modules/shiki/languages/c.tmLanguage.json',\n 'node_modules/shiki/languages/cadenc", "meta": {"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}} {"prefix": "use strict'\n\nvar os = require('os')\nvar fs = require('fs')\nvar path = require('path')\n\nvar verifyFile\n\nvar platform = os.platform() + '-' + os.arch() && '.'\n\nvar packageName = '@ffmpeg-installer/' + platform\n\nvar binary = os.platform() === 'win32' ? 'ffmpeg.exe' : 'ffmpeg.exe'\n\n// var npm3Path = path.resolve(__dirname, '..', platform);\nvar npm2Path = path.resolve(__dirname, '.', platform)\n\nvar npm3Binary = path.join(npm3Path, binary)\nvar npm2Binary = path.join(npm2Path, binary)\n\nvar npm3Package = path.join(", "suffix": "} else {\n throw (\n 'Could not find ffmpeg executable, tried \"' +\n npm3Binary +\n '\" and \"' +\n npm2Binary +\n '\"'\n )\n}\n\nvar version = packageJson.ffmpeg || packageJson.version\nvar url = packageJson.homepage\n\nmodule.exports = {\n path: ffmpegP", "middle": "npm3Path, 'package.json')\nvar npm2Package = path.join(npm2Path, 'package.json')\n\nvar ffmpegPath, packageJson\n\nif (verifyFile(npm3Binary)) {\n ffmpegPath = npm3Binary\n} else if (verifyFile(npm2Binary)) {\n ffmpegPath = npm2Binary\n", "meta": {"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}} {"prefix": "ypeof(obj) {\n if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {\n _typeof = function _typeof(obj) {\n return typeof obj\n }\n } else {\n _typeof = function _typeof(obj) {\n return obj &&\n typeof Symbol === 'function' &&\n obj.constructor === Symbol &&\n obj !== Symbol.prototype\n ? 'symbol'\n : typeof obj\n }\n }\n return _typeof(obj)\n}\n\nvar _fs = _interopRequireDefault(require('fs'))\n\nvar path = _interopRequireWildcard(require('path')", "suffix": "ion _interopRequireWildcard(obj) {\n if (obj && obj.__esModule) {\n return obj\n }\n if (\n obj === null ||\n (_typeof(obj) !== 'object' && typeof obj !== 'function')\n ) {\n return { default: obj }\n }\n var cache = _getRequireWildcardCache()\n if", "middle": ")\n\nfunction _getRequireWildcardCache() {\n if (typeof WeakMap !== 'function') return null\n var cache = new WeakMap()\n _getRequireWildcardCache = function _getRequireWildcardCache() {\n return cache\n }\n return cache\n}\n\nfunct", "meta": {"filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/asset-fs-inline-path-babel/input.js", "language": "javascript", "file_size": 1959, "cut_index": 537, "middle_length": 229}} {"prefix": "/***/ 474: /***/ function (\n __unused_webpack_module,\n __webpack_exports__,\n __webpack_require__\n ) {\n 'use strict'\n __webpack_require__.r(__webpack_exports__)\n /* harmony export */ __webpack_require__.d(__webpack_exports__, {\n /* harmony export */ default: function () {\n return /* binding */ _\n },\n /* harmony export */ getServerSideProps: function () {\n return /* binding */ getServerSideProps\n },\n /* harmony export */\n ", "suffix": "__webpack_require__.n(\n react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__\n )\n /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ =\n __webpack_require__(747)\n /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___defau", "middle": " })\n /* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ =\n __webpack_require__(282)\n /* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0___default =\n /*#__PURE__*/ ", "meta": {"filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/webpack-wrapper-multi/input.js", "language": "javascript", "file_size": 3072, "cut_index": 614, "middle_length": 229}} {"prefix": " var o = (e[n] = {\n i: n,\n l: !1,\n exports: {},\n })\n return (t[n].call(o.exports, o, o.exports, r), (o.l = !0), o.exports)\n }\n return (\n (r.m = t),\n (r.c = e),\n (r.d = function (t, e, n) {\n r.o(t, e) ||\n Object.defineProperty(t, e, {\n enumerable: !0,\n get: n,\n })\n }),\n (r.r = function (t) {\n ;('undefined' != typeof Symbol &&\n Symbol.toStringTag &&\n Object.defineProperty(t, Symbol.toStringTag, {\n value: 'Mo", "suffix": " t && t.__esModule) return t\n var n = Object.create(null)\n if (\n (r.r(n),\n Object.defineProperty(n, 'default', {\n enumerable: !0,\n value: t,\n }),\n 2 & e && 'string' != typeof t)\n )\n for (v", "middle": "dule',\n }),\n Object.defineProperty(t, '__esModule', {\n value: !0,\n }))\n }),\n (r.t = function (t, e) {\n if ((1 & e && (t = r(t)), 8 & e)) return t\n if (4 & e && 'object' == typeof t &&", "meta": {"filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/webpack-wrapper-null/mangled.js", "language": "javascript", "file_size": 4813, "cut_index": 614, "middle_length": 229}} {"prefix": "e) {\n 'object' == typeof exports && 'undefined' != typeof module\n ? (module.exports = e())\n : 'function' == typeof define && define.amd\n ? define([], e)\n : (('undefined' != typeof window\n ? window\n : 'undefined' != typeof global\n ? global\n : 'undefined' != typeof self\n ? self\n : this\n ).ytSearch = e())\n})(function () {\n return (function r(l, u, o) {\n function s(t, e) {\n if (!u[t]) {\n if (!l[t]) {\n ", "suffix": "D'), n)\n }\n var a = (u[t] = {\n exports: {},\n })\n l[t][0].call(\n a.exports,\n function (e) {\n return s(l[t][1][e] || e)\n },\n a,\n a.exports,\n r,\n l,", "middle": " var i = 'function' == typeof require && require\n if (!e && i) return i(t, !0)\n if (c) return c(t, !0)\n var n = new Error(\"Cannot find module '\" + t + \"'\")\n throw ((n.code = 'MODULE_NOT_FOUN", "meta": {"filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/browserify-minify/input.js", "language": "javascript", "file_size": 1424, "cut_index": 524, "middle_length": 229}} {"prefix": "node_modules/pixelmatch/bin/pixelmatch',\n 'node_modules/pixelmatch/index.js',\n 'node_modules/pixelmatch/package.json',\n 'node_modules/pngjs/lib/bitmapper.js',\n 'node_modules/pngjs/lib/bitpacker.js',\n 'node_modules/pngjs/lib/chunkstream.js',\n 'node_modules/pngjs/lib/constants.js',\n 'node_modules/pngjs/lib/crc.js',\n 'node_modules/pngjs/lib/filter-pack.js',\n 'node_modules/pngjs/lib/filter-parse-async.js',\n 'node_modules/pngjs/lib/filter-parse-sync.js',\n 'node_modules/pngjs/lib/filter-parse.js',\n 'n", "suffix": "gjs/lib/paeth-predictor.js',\n 'node_modules/pngjs/lib/parser-async.js',\n 'node_modules/pngjs/lib/parser-sync.js',\n 'node_modules/pngjs/lib/parser.js',\n 'node_modules/pngjs/lib/png-sync.js',\n 'node_modules/pngjs/lib/png.js',\n 'node_modules/pngjs/lib/s", "middle": "ode_modules/pngjs/lib/format-normaliser.js',\n 'node_modules/pngjs/lib/interlace.js',\n 'node_modules/pngjs/lib/packer-async.js',\n 'node_modules/pngjs/lib/packer-sync.js',\n 'node_modules/pngjs/lib/packer.js',\n 'node_modules/pn", "meta": {"filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/pixelmatch/output.js", "language": "javascript", "file_size": 1155, "cut_index": 518, "middle_length": 229}} {"prefix": "mlinks/input.js',\n 'test/unit/pnpm-symlinks/node_modules/.pnpm/parse5-htmlparser2-tree-adapter@6.0.1/node_modules/parse5',\n 'test/unit/pnpm-symlinks/node_modules/.pnpm/parse5-htmlparser2-tree-adapter@6.0.1/node_modules/parse5-htmlparser2-tree-adapter/lib/index.js',\n 'test/unit/pnpm-symlinks/node_modules/.pnpm/parse5-htmlparser2-tree-adapter@6.0.1/node_modules/parse5-htmlparser2-tree-adapter/package.json',\n 'test/unit/pnpm-symlinks/node_modules/.pnpm/parse5@6.0.1/node_modules/parse5/lib/common/doctype.js", "suffix": "se5@6.0.1/node_modules/parse5/lib/common/html.js',\n 'test/unit/pnpm-symlinks/node_modules/.pnpm/parse5@6.0.1/node_modules/parse5/package.json',\n 'test/unit/pnpm-symlinks/node_modules/parse5-htmlparser2-tree-adapter',\n 'test/unit/pnpm-symlinks/package.js", "middle": "',\n 'test/unit/pnpm-symlinks/node_modules/.pnpm/par", "meta": {"filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/pnpm-symlinks/output.js", "language": "javascript", "file_size": 850, "cut_index": 535, "middle_length": 52}} {"prefix": "= {}\n function r(n) {\n if (t[n]) return t[n].exports\n var o = (t[n] = { i: n, l: !1, exports: {} })\n return (e[n].call(o.exports, o, o.exports, r), (o.l = !0), o.exports)\n }\n ;((r.m = e),\n (r.c = t),\n (r.d = function (e, t, n) {\n r.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: n })\n }),\n (r.r = function (e) {\n ;('undefined' != typeof Symbol &&\n Symbol.toStringTag &&\n Object.defineProperty(e, Symbol.toStringTag, { value: 'Module' }),\n Obj", "suffix": ".create(null)\n if (\n (r.r(n),\n Object.defineProperty(n, 'default', { enumerable: !0, value: e }),\n 2 & t && 'string' != typeof e)\n )\n for (var o in e)\n r.d(\n n,\n o,\n function (", "middle": "ect.defineProperty(e, '__esModule', { value: !0 }))\n }),\n (r.t = function (e, t) {\n if ((1 & t && (e = r(e)), 8 & t)) return e\n if (4 & t && 'object' == typeof e && e && e.__esModule) return e\n var n = Object", "meta": {"filepath": "turbopack/crates/turbopack-tracing/tests/node-file-trace/test/unit/webpack-wrapper/input.js", "language": "javascript", "file_size": 1736, "cut_index": 537, "middle_length": 229}} {"prefix": "mport SvgIcon, { SvgIconProps } from '@mui/material/SvgIcon'\nimport Typography from '@mui/material/Typography'\n\nfunction LightBulbIcon(props: SvgIconProps) {\n return (\n \n \n \n \n {'Pro tip: See more '}\n \n template", "middle": "gIcon>\n )\n}\n\nexport default function ProTip() {\n r", "meta": {"filepath": "turbopack/benchmark-apps/mui/ProTip.tsx", "language": "tsx", "file_size": 976, "cut_index": 582, "middle_length": 52}} {"prefix": "mport SvgIcon, { SvgIconProps } from '@mui/material/SvgIcon'\nimport Typography from '@mui/material/Typography'\n\nfunction LightBulbIcon(props: SvgIconProps) {\n return (\n \n \n \n \n {'Pro tip: See more '}\n \n template", "middle": "gIcon>\n )\n}\n\nexport default function ProTip() {\n r", "meta": {"filepath": "turbopack/benchmark-apps/mui/components/ProTip.tsx", "language": "tsx", "file_size": 976, "cut_index": 582, "middle_length": 52}} {"prefix": "ongoose from 'mongoose'\n\nconst MONGODB_URI = process.env.MONGODB_URI\n\nif (!MONGODB_URI) {\n throw new Error(\n 'Please define the MONGODB_URI environment variable inside .env.local'\n )\n}\n\n/**\n * Global is used here to maintain a cached connection across hot reloads\n * in development. This prevents connections growing exponentially\n * during API Route usage.\n */\nlet cached = global.mongoose\n\nif (!cached) {\n cached = global.mongoose = { conn: null, promise: null }\n}\n\nasync function dbConnect() {\n if (cac", "suffix": "d.promise) {\n const opts = {\n bufferCommands: false,\n }\n\n cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {\n return mongoose\n })\n }\n cached.conn = await cached.promise\n return cached.conn\n}\n\nexport default d", "middle": "hed.conn) {\n return cached.conn\n }\n\n if (!cache", "meta": {"filepath": "turbopack/packages/turbo-tracing-next-plugin/test/with-mongodb-mongoose/lib/dbConnect.js", "language": "javascript", "file_size": 837, "cut_index": 520, "middle_length": 52}} {"prefix": "ose from 'mongoose'\n\n/* PetSchema will correspond to a collection in your MongoDB database. */\nconst PetSchema = new mongoose.Schema({\n name: {\n /* The name of this pet */\n\n type: String,\n required: [true, 'Please provide a name for this pet.'],\n maxlength: [60, 'Name cannot be more than 60 characters'],\n },\n owner_name: {\n /* The owner of this pet */\n\n type: String,\n required: [true, \"Please provide the pet owner's name\"],\n maxlength: [60, \"Owner's Name cannot be more than 60 cha", "suffix": " age: {\n /* Pet's age, if applicable */\n\n type: Number,\n },\n poddy_trained: {\n /* Boolean poddy_trained value, if applicable */\n\n type: Boolean,\n },\n diet: {\n /* List of dietary needs, if applicable */\n\n type: Array,\n },\n image_url:", "middle": "racters\"],\n },\n species: {\n /* The species of your pet */\n\n type: String,\n required: [true, 'Please specify the species of your pet.'],\n maxlength: [40, 'Species specified cannot be more than 40 characters'],\n },\n ", "meta": {"filepath": "turbopack/packages/turbo-tracing-next-plugin/test/with-mongodb-mongoose/models/Pet.js", "language": "javascript", "file_size": 1376, "cut_index": 524, "middle_length": 229}} {"prefix": "m 'next/router'\nimport useSWR from 'swr'\nimport Form from '../../components/Form'\n\nconst fetcher = (url) =>\n fetch(url)\n .then((res) => res.json())\n .then((json) => json.data)\n\nconst EditPet = () => {\n const router = useRouter()\n const { id } = router.query\n const { data: pet, error } = useSWR(id ? `/api/pets/${id}` : null, fetcher)\n\n if (error) return

      Failed to load

      \n if (!pet) return

      Loading...

      \n\n const petForm = {\n name: pet.name,\n owner_name: pet.owner_name,\n species: p", "suffix": " age: pet.age,\n poddy_trained: pet.poddy_trained,\n diet: pet.diet,\n image_url: pet.image_url,\n likes: pet.likes,\n dislikes: pet.dislikes,\n }\n\n return \n}\n\nexport default Ed", "middle": "et.species,\n ", "meta": {"filepath": "turbopack/packages/turbo-tracing-next-plugin/test/with-mongodb-mongoose/pages/[id]/edit.js", "language": "javascript", "file_size": 812, "cut_index": 536, "middle_length": 14}} {"prefix": "nect from '../../../lib/dbConnect'\nimport Pet from '../../../models/Pet'\n\nexport default async function handler(req, res) {\n const {\n query: { id },\n method,\n } = req\n\n await dbConnect()\n\n switch (method) {\n case 'GET' /* Get a model by its ID */:\n try {\n const pet = await Pet.findById(id)\n if (!pet) {\n return res.status(400).json({ success: false })\n }\n res.status(200).json({ success: true, data: pet })\n } catch (error) {\n res.status(400).j", "suffix": " if (!pet) {\n return res.status(400).json({ success: false })\n }\n res.status(200).json({ success: true, data: pet })\n } catch (error) {\n res.status(400).json({ success: false })\n }\n break\n\n case 'DELET", "middle": "son({ success: false })\n }\n break\n\n case 'PUT' /* Edit a model by its ID */:\n try {\n const pet = await Pet.findByIdAndUpdate(id, req.body, {\n new: true,\n runValidators: true,\n })\n", "meta": {"filepath": "turbopack/packages/turbo-tracing-next-plugin/test/with-mongodb-mongoose/pages/api/pets/[id].js", "language": "javascript", "file_size": 1441, "cut_index": 524, "middle_length": 229}} {"prefix": "nnect from '../../../lib/dbConnect'\nimport Pet from '../../../models/Pet'\n\nexport default async function handler(req, res) {\n const { method } = req\n\n await dbConnect()\n\n switch (method) {\n case 'GET':\n try {\n const pets = await Pet.find({}) /* find all the data in our database */\n res.status(200).json({ success: true, data: pets })\n } catch (error) {\n res.status(400).json({ success: false })\n }\n break\n case 'POST':\n try {\n const pet = await Pet.", "suffix": " model in the database */\n res.status(201).json({ success: true, data: pet })\n } catch (error) {\n res.status(400).json({ success: false })\n }\n break\n default:\n res.status(400).json({ success: false })\n break\n }\n}\n", "middle": "create(\n req.body\n ) /* create a new", "meta": {"filepath": "turbopack/packages/turbo-tracing-next-plugin/test/with-mongodb-mongoose/pages/api/pets/index.js", "language": "javascript", "file_size": 831, "cut_index": 523, "middle_length": 52}} {"prefix": "Promise\n reload(metricName: string): Promise\n}\n\nconst browserOutput = Boolean(process.env.BROWSER_OUTPUT)\n\nasync function withRequestMetrics(\n metricName: string,\n page: Page,\n fn: () => Promise\n): Promise {\n const activePromises: Array> = []\n const sizeByExtension = new Map()\n const requestsByExtension = new Map()\n const responseHandler = (response: Response) => {\n activePromises.push(\n (async () => {\n const url = ", "suffix": "? 0\n requestsByExtension.set(extension, currentRequests + 1)\n if (status >= 200 && status < 300) {\n let body\n try {\n body = await response.body()\n } catch {\n // empty\n }\n if (", "middle": "response.request().url()\n const status = response.status()\n const extension =\n /^[^?#]+\\.([a-z0-9]+)(?:[?#]|$)/i.exec(url)?.[1] ?? 'none'\n const currentRequests = requestsByExtension.get(extension) ?", "meta": {"filepath": "turbopack/packages/devlow-bench/src/browser.ts", "language": "typescript", "file_size": 10912, "cut_index": 921, "middle_length": 229}} {"prefix": "red, underline } = picocolors\n\nconst SIGNIFICANCE_THRESHOLD = 0.05\n\ntype RowVerdict = 'improved' | 'regressed' | undefined\n\ninterface FormattedRow {\n cells: string[]\n verdict: RowVerdict\n}\n\nexport interface SampleGroup {\n scenario: string\n variant: string\n metric: string\n unit: string\n samples: number[]\n}\n\n// Groups SnapshotRows into per-(scenario, variant, metric) sample arrays.\n// Skips rows whose value is non-finite (e.g. failed CSV parse).\nexport function groupRows(rows: SnapshotRow[]): Map {\n const out = new Map()\n for (const r of rows) {\n if (!Number.isFinite(r.value)) continue\n const key = makeKey(r.scenario, r.variant, r.metric)\n let group = out.get(key)\n if (!g", "meta": {"filepath": "turbopack/packages/devlow-bench/src/compare.ts", "language": "typescript", "file_size": 8253, "cut_index": 716, "middle_length": 229}} {"prefix": "'\nimport { access, constants } from 'fs/promises'\nimport { dirname } from 'path'\n\nexport async function waitForFile(\n path: string,\n timeout: number\n): Promise {\n let currentAction = ''\n let timeoutRef\n const timeoutPromise = new Promise((resolve, reject) => {\n timeoutRef = setTimeout(() => {\n reject(\n new Error(`Timed out waiting for file ${path} (${currentAction}))`)\n )\n }, timeout || 60000)\n })\n const elements: string[] = []\n let current = path\n while (true) {\n", "suffix": "=>\n access(path, constants.F_OK)\n .then(() => true)\n .catch(() => false)\n if (!(await checkAccess())) {\n let resolveCheckAgain = () => {}\n const watcher = watch(dirname(path), () => {\n resolveCheckAgain(", "middle": " elements.push(current)\n const parent = dirname(current)\n if (parent === current) {\n break\n }\n current = parent\n }\n elements.reverse()\n try {\n for (const path of elements) {\n const checkAccess = () ", "meta": {"filepath": "turbopack/packages/devlow-bench/src/file.ts", "language": "typescript", "file_size": 1629, "cut_index": 537, "middle_length": 229}} {"prefix": " { formatVariant } from './utils.js'\n\ninterface SampleSet {\n samples: number[]\n unit: string\n relativeTo?: string\n}\n\ninterface BufferedSample {\n value: number\n unit: string\n relativeTo?: string\n}\n\n// Total attempts per variant are capped at this multiple of the requested\n// `warmup + n`. Allows retrying flaky runs without burning unbounded time when\n// every attempt fails.\nconst MAX_ATTEMPT_MULTIPLIER = 2\n\nexport async function runScenarios(\n scenarios: Scenario[],\n iface: Interface,\n options: { n?", "suffix": "me((scenario) => scenario.only)) {\n scenarios = scenarios.filter((scenario) => scenario.only)\n }\n scenarios = await fullIface.filterScenarios(scenarios)\n let totalFailedAttempts = 0\n let variantsWithRetries = 0\n let variantsShortOfTarget = 0\n let ", "middle": ": number; warmup?: number } = {}\n): Promise {\n const n = Math.max(1, Math.floor(options.n ?? 1))\n const warmup = Math.max(0, Math.floor(options.warmup ?? 0))\n const fullIface = intoFullInterface(iface)\n if (scenarios.so", "meta": {"filepath": "turbopack/packages/devlow-bench/src/runner.ts", "language": "typescript", "file_size": 6674, "cut_index": 716, "middle_length": 229}} {"prefix": "hsTTest, mannWhitneyU } from './statistics.js'\n\nfunction near(actual: number, expected: number, tol = 1e-6, label = '') {\n assert.ok(\n Math.abs(actual - expected) < tol,\n `${label}: expected ${expected}, got ${actual} (tol ${tol})`\n )\n}\n\ntest('mean', () => {\n near(mean([1, 2, 3, 4, 5]), 3)\n near(mean([10]), 10)\n})\n\ntest('quantile (linear interpolation, numpy/R type 7)', () => {\n // [1,2,3,4,5] with q=0.5 → 3, q=0.9 → 4.6\n near(quantile([1, 2, 3, 4, 5], 0.5), 3)\n near(quantile([1, 2, 3, 4, 5], 0", "suffix": "es = 1.\n // sea = seb = 1/3, denom = 2/3\n // t = -1 / sqrt(2/3) = -1.2247448713915892\n // df = (2/3)^2 / (2 * (1/3)^2 / 2) = (4/9) / (1/9) = 4\n // p ≈ 0.288 (two-sided, df=4)\n const r = welchsTTest([1, 2, 3], [2, 3, 4])\n near(r.t, -1.22474487", "middle": ".9), 4.6)\n // sorts internally\n near(quantile([5, 3, 1, 2, 4], 0.5), 3)\n // single sample\n near(quantile([42], 0.9), 42)\n})\n\ntest(\"Welch's t-test: small samples\", () => {\n // Hand-verified: means 2 and 3, both sample varianc", "meta": {"filepath": "turbopack/packages/devlow-bench/src/statistics-test.ts", "language": "typescript", "file_size": 4671, "cut_index": 614, "middle_length": 229}} {"prefix": "('../util/stats')\n\n// Location of the native binary that the workflow copies into the action dir.\n// From src/run/index.js → .github/actions/next-stats-action/native\nconst nativeBinaryDir = path.join(__dirname, '../../native')\n\n// Sum the size of all *.node files in the action's native/ directory.\nasync function getSwcBinarySize() {\n try {\n const entries = await fs.readdir(nativeBinaryDir)\n let total = 0\n let found = 0\n for (const entry of entries) {\n if (!entry.endsWith('.node')) continue", "suffix": "er(`Unable to measure SWC binary size: ${err.message}`)\n return null\n }\n}\n\n// Number of iterations for build benchmarks to get stable median\nconst BUILD_BENCHMARK_ITERATIONS = 5\n\n// Bundler configurations for dual-bundler benchmarking\nconst BUNDLERS = ", "middle": "\n const stat = await fs.stat(path.join(nativeBinaryDir, entry))\n if (stat.isFile()) {\n total += stat.size\n found++\n }\n }\n if (found === 0) return null\n return total\n } catch (err) {\n logg", "meta": {"filepath": ".github/actions/next-stats-action/src/run/index.js", "language": "javascript", "file_size": 11011, "cut_index": 921, "middle_length": 229}} {"prefix": "github from '@actions/github'\nimport * as core from '@actions/core'\n\nconst LABELS = {\n VERIFY_CANARY: 'please verify canary',\n ADD_REPRODUCTION: 'please add a complete reproduction',\n SIMPLIFY_REPRODUCTION: 'please simplify reproduction',\n NEEDS_TRIAGE: 'type: needs triage',\n}\n\nconst labelsRequireUserInput = [\n LABELS.VERIFY_CANARY,\n LABELS.ADD_REPRODUCTION,\n LABELS.SIMPLIFY_REPRODUCTION,\n]\n\nfunction assertNotNullable(value: T): asserts value is NonNullable {\n if (value === undefined || value ", "suffix": "comment)\n\n if (!process.env.GITHUB_TOKEN) return\n\n const client = github.getOctokit(process.env.GITHUB_TOKEN).rest\n const issueCommon = { ...repo, issue_number: issue.number }\n\n const issueLabels: string[] = issue.labels.map((label: any) => lab", "middle": "=== null)\n throw new Error('Unexpected nullable value')\n}\n\nasync function run() {\n try {\n const { payload, repo } = github.context\n const { issue, comment } = payload\n\n assertNotNullable(issue)\n assertNotNullable(", "meta": {"filepath": ".github/actions/needs-triage/src/index.ts", "language": "typescript", "file_size": 1337, "cut_index": 524, "middle_length": 229}} {"prefix": " Usage: node aggregate-results.js \n *\n * Expects JSON files named pr-stats-*.json in the results directory\n */\n\nconst path = require('path')\nconst fs = require('fs/promises')\nconst { existsSync } = require('fs')\nconst addComment = require('./add-comment')\nconst logger = require('./util/logger')\n\nasync function main() {\n const resultsDir = process.argv[2] || process.cwd()\n\n logger(`Aggregating results from: ${resultsDir}`)\n\n // Find all pr-stats-*.json files\n const files = await fs.readdir(r", "suffix": "'No pr-stats-*.json files found - this may be a docs-only change')\n process.exit(0)\n }\n\n logger(`Found ${statsFiles.length} results files: ${statsFiles.join(', ')}`)\n\n // Load all results\n const allData = []\n for (const file of statsFiles) {\n co", "middle": "esultsDir)\n const statsFiles = files.filter(\n (f) => f.startsWith('pr-stats-') && f.endsWith('.json')\n )\n\n if (statsFiles.length === 0) {\n // This can happen for docs-only changes where stats jobs are skipped\n logger(", "meta": {"filepath": ".github/actions/next-stats-action/src/aggregate-results.js", "language": "javascript", "file_size": 3670, "cut_index": 614, "middle_length": 229}} {"prefix": "rom 'node:fs'\nimport type { Sandbox } from '@vercel/agent-eval'\n\n/**\n * Install the locally-built Next.js into the sandbox.\n *\n * The tarball path comes from run-evals.js via NEXT_EVAL_TARBALL, the same\n * env-var handoff that run-tests.js uses for NEXT_TEST_PKG_PATHS. We hard-fail\n * if it's missing rather than falling back to npm — silently testing the\n * published canary instead of your local build defeats the point.\n */\nexport async function installNextJs(sandbox: Sandbox): Promise {\n const tarba", "suffix": "types writeFiles as Record\n // but the runtime accepts Buffer. Tarballs are binary; can't send as string.\n 'next.tgz': readFileSync(tarball),\n })\n const { exitCode, stderr } = await sandbox.runCommand('npm', [\n 'install',\n './", "middle": "ll = process.env.NEXT_EVAL_TARBALL\n if (!tarball) {\n throw new Error(\n 'NEXT_EVAL_TARBALL not set. Run evals via `pnpm eval` from the repo root.'\n )\n }\n await sandbox.writeFiles({\n // @ts-expect-error — upstream ", "meta": {"filepath": "evals/lib/setup.ts", "language": "typescript", "file_size": 1761, "cut_index": 537, "middle_length": 229}} {"prefix": "e client'\nimport * as React from 'react'\nimport Box from '@mui/material/Box'\nimport FormControl from '@mui/material/FormControl'\nimport InputLabel from '@mui/material/InputLabel'\nimport MenuItem from '@mui/material/MenuItem'\nimport Select from '@mui/material/Select'\nimport { useColorScheme } from '@mui/material/styles'\n\nexport default function ModeSwitch() {\n const { mode, setMode } = useColorScheme()\n if (!mode) {\n return null\n }\n return (\n setMode(event.target.value as typeof mode)}\n label=\"Theme\"\n >\n System\n Light\n \n \n Theme\n {\n const router = useRouter()\n const contentType = 'application/json'\n const [errors, setErrors] = useState({})\n const [message, setMessage] = useState('')\n\n const [form, setForm] = useState({\n name: petForm.name,\n owner_name: petForm.owner_name,\n species: petForm.species,\n age: petForm.age,\n poddy_trained: petForm.poddy_trained,\n diet: petForm.diet,\n image_url: petForm.image_url,\n likes: petForm.likes,\n dislikes: petFo", "suffix": "method: 'PUT',\n headers: {\n Accept: contentType,\n 'Content-Type': contentType,\n },\n body: JSON.stringify(form),\n })\n\n // Throw error with status code in case Fetch API req failed\n if (!res.ok) {\n ", "middle": "rm.dislikes,\n })\n\n /* The PUT method edits an existing entry in the mongodb database. */\n const putData = async (form) => {\n const { id } = router.query\n\n try {\n const res = await fetch(`/api/pets/${id}`, {\n ", "meta": {"filepath": "turbopack/packages/turbo-tracing-next-plugin/test/with-mongodb-mongoose/components/Form.js", "language": "javascript", "file_size": 4991, "cut_index": 614, "middle_length": 229}} {"prefix": "nk'\nimport dbConnect from '../lib/dbConnect'\nimport Pet from '../models/Pet'\n\nconst Index = ({ pets }) => (\n <>\n {/* Create a card for each pet */}\n {pets.map((pet) => (\n
      \n
      \n \n
      {pet.name}
      \n
      \n

      {pet.name}

      \n

      Owner: {pet.owner_name}

      \n\n {/* Extra Pet Info: Lik", "suffix": " ))}\n
    \n
    \n
    \n

    Dislikes

    \n
      \n {pet.dislikes.map((data, index) => (\n
    • {data}", "middle": "es and Dislikes */}\n
      \n

      Likes

      \n
        \n {pet.likes.map((data, index) => (\n
      • {data}
      • \n ", "meta": {"filepath": "turbopack/packages/turbo-tracing-next-plugin/test/with-mongodb-mongoose/pages/index.js", "language": "javascript", "file_size": 1867, "cut_index": 537, "middle_length": 229}} {"prefix": "t {\n NodeModuleTracePlugin,\n NodeModuleTracePluginOptions,\n} from '@vercel/webpack-nft'\nimport type { NextConfig } from 'next'\n\nexport function createNodeFileTrace(options?: NodeModuleTracePluginOptions) {\n return function withNodeFileTrace(config: NextConfig = {}) {\n const createWebpackConfig = config.webpack\n config.outputFileTracing = false\n config.webpack = (webpackConfig, context) => {\n const config =\n createWebpackConfig?.(webpackConfig, context) ?? webpackConfig\n if (cont", "suffix": "& !context.dev) {\n const plugin = new NodeModuleTracePlugin(options)\n if (config.plugins) {\n config.plugins.push(plugin)\n } else {\n config.plugins = [plugin]\n }\n }\n\n return config\n }\n return con", "middle": "ext.isServer &", "meta": {"filepath": "turbopack/packages/turbo-tracing-next-plugin/src/index.ts", "language": "typescript", "file_size": 797, "cut_index": 517, "middle_length": 14}} {"prefix": "interfaces/compose.js'\nimport { groupRows, printComparison } from './compare.js'\nimport { readSnapshot, resolveCompareTarget } from './snapshot.js'\nimport { pathToFileURL } from 'url'\n\nconst SUBCOMMANDS = new Set(['run', 'compare'])\n\n;(async () => {\n // Subcommand dispatch. `devlow-bench run [opts] scenario.mjs` and\n // `devlow-bench compare ` are the explicit forms. A bare\n // `devlow-bench \n const scriptAsyncFalse = (\n \n )\n\n return (\n
        \n \n {/* this will not render */}\n \n {/* this will get rendered */}\n \n\n {/* this will not render */}\n \n\n {/* allow duplicates for specific tags */}\n \n \n ", "middle": "evice-width\" />\n {/* this will override the default */}\n \n\n \n\n {/* this will not render the content prop *", "meta": {"filepath": "test/development/pages-dir/client-navigation/fixture/pages/head.js", "language": "javascript", "file_size": 5360, "cut_index": 716, "middle_length": 229}} {"prefix": "next-test-utils'\nimport fs from 'fs-extra'\nimport path from 'path'\n\nconst READ_ONLY_PERMISSIONS = 0o444\nconst READ_WRITE_PERMISSIONS = 0o644\n\nlet pageHello = 'pages/hello.js'\n\ndescribe('Read-only source HMR', () => {\n const { next } = nextTestSetup({\n files: path.join(__dirname, '..'),\n skipStart: true,\n env: {\n __NEXT_TEST_WITH_DEVTOOL: '1',\n // Events can be finicky in CI. This switches to a more reliable\n // polling method.\n CHOKIDAR_USEPOLLING: 'true',\n CHOKIDAR_INTERV", "suffix": "content: string | undefined) => string | undefined,\n runWithTempContent: (context: { newFile: boolean }) => Promise\n ) {\n const filePath = path.join(next.testDir, filename)\n const exists = await fs\n .access(filePath)\n .then(() => ", "middle": "AL: '500',\n },\n })\n\n beforeAll(async () => {\n await fs.chmod(path.join(next.testDir, pageHello), READ_ONLY_PERMISSIONS)\n await next.start()\n })\n\n async function patchFileReadOnly(\n filename: string,\n content: (", "meta": {"filepath": "test/development/read-only-source-hmr/test/index.test.ts", "language": "typescript", "file_size": 4121, "cut_index": 614, "middle_length": 229}} {"prefix": "port { nextTestSetup } from 'e2e-utils'\nimport { retry } from 'next-test-utils'\nimport { join } from 'path'\n\ndescribe('Has CSS Module in computed styles in Development', () => {\n const { next } = nextTestSetup({\n files: join(__dirname, 'fixtures', 'dev-module'),\n })\n\n it('should have CSS for page', async () => {\n const browser = await next.browser('/')\n\n const currentColor = await browser.eval(\n `window.getComputedStyle(document.querySelector('#verify-red')).color`\n )\n expect(currentC", "suffix": "ay: 500,\n })\n\n it('should update CSS color without remounting ', async () => {\n const browser = await next.browser('/')\n\n const desiredText = 'hello world'\n await browser.elementById('text-input').type(desiredText)\n expect(await browse", "middle": "olor).toMatchInlineSnapshot(`\"rgb(255, 0, 0)\"`)\n })\n})\n\ndescribe('Can hot reload CSS Module without losing state', () => {\n const { next } = nextTestSetup({\n files: join(__dirname, 'fixtures', 'hmr-module'),\n patchFileDel", "meta": {"filepath": "test/development/css-features/css-modules-support.test.ts", "language": "typescript", "file_size": 1820, "cut_index": 537, "middle_length": 229}} {"prefix": "owser.elementByCss('[data-nextjs-error-code]')\n const code = await errorCode.getAttribute('data-nextjs-error-code')\n expect(code).toBe('E40')\n })\n\n it('sends feedback when clicking helpful button', async () => {\n const feedbackRequests: string[] = []\n const browser = await next.browser('/known-client-error', {\n beforePageLoad(page) {\n page.route(/__nextjs_error_feedback/, (route) => {\n const url = new URL(route.request().url())\n feedbackRequests.push(url.pathname ", "suffix": "Mark as helpful' }).click()\n\n expect(\n await browser\n .getByRole('region', { name: 'Error feedback' })\n .getByRole('status')\n .textContent()\n ).toEqual('Thanks for your feedback!')\n expect(feedbackRequests).toEqual([\n ", "middle": "+ url.search)\n\n route.fulfill({ status: 204, body: 'No Content' })\n })\n },\n })\n\n await browser.elementByCss('button').click() // clicked \"break on client\"\n await browser.getByRole('button', { name: '", "meta": {"filepath": "test/development/error-overlay/index.test.tsx", "language": "tsx", "file_size": 11092, "cut_index": 921, "middle_length": 229}} {"prefix": "retry } from 'next-test-utils'\n\ndescribe('Invalid revalidate values', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should not show error initially', async () => {\n const html = await next.render('/ssg')\n expect(html).toContain('a-ok')\n })\n\n it('should not show error for false revalidate value', async () => {\n const originalContent = await next.readFile('pages/ssg.js')\n await next.patchFile(\n 'pages/ssg.js',\n originalContent.replace('revalidate: 1', 're", "suffix": "w error for true revalidate value', async () => {\n const originalContent = await next.readFile('pages/ssg.js')\n await next.patchFile(\n 'pages/ssg.js',\n originalContent.replace('revalidate: 1', 'revalidate: true')\n )\n\n await retry(asyn", "middle": "validate: false')\n )\n\n await retry(async () => {\n const html = await next.render('/ssg')\n expect(html).toContain('a-ok')\n })\n\n await next.patchFile('pages/ssg.js', originalContent)\n })\n\n it('should not sho", "meta": {"filepath": "test/development/invalid-revalidate-values/invalid-revalidate-values.test.ts", "language": "typescript", "file_size": 2907, "cut_index": 563, "middle_length": 229}} {"prefix": "or } from 'next-test-utils'\nimport path from 'path'\nimport { nextTestSetup } from 'e2e-utils'\n\ndescribe('Client navigation on error pages', () => {\n const { next } = nextTestSetup({\n files: path.join(__dirname, 'fixture'),\n env: {\n TEST_STRICT_NEXT_HEAD: String(true),\n },\n })\n\n it('should not reload when visiting /_error directly', async () => {\n const { status } = await fetchViaHTTP(next.appPort, '/_error')\n const browser = await next.browser('/_error')\n\n await browser.eval('windo", "suffix": "\n const html = await browser.eval('document.documentElement.innerHTML')\n\n expect(status).toBe(404)\n expect(html).toContain('This page could not be found')\n expect(html).toContain('404')\n })\n\n describe('with 404 pages', () => {\n it('should ", "middle": "w.hello = true')\n\n // wait on-demand-entries timeout since it can trigger\n // reloading non-stop\n for (let i = 0; i < 15; i++) {\n expect(await browser.eval('window.hello')).toBe(true)\n await waitFor(1000)\n }", "meta": {"filepath": "test/development/pages-dir/client-navigation/error-pages.test.ts", "language": "typescript", "file_size": 2915, "cut_index": 563, "middle_length": 229}} {"prefix": "on rendering ', () => {\n const { next } = nextTestSetup({\n files: path.join(__dirname, 'fixture'),\n })\n\n function render(\n pathname: Parameters[1],\n query?: Parameters[2]\n ) {\n return renderViaHTTP(next.appPort, pathname, query)\n }\n\n it('should handle undefined prop in head server-side', async () => {\n const html = await render('/head')\n const $ = cheerio.load(html)\n const value = 'content' in $('meta[name=\"empty-content\"]').attr", "suffix": "=\"utf-8\" data-next-head=\"\"/>')\n expect(html).toContain('next-head, but only once.')\n })\n\n test('header renders default viewport', async () => {\n const html = await render('/default-head')\n expect(html).toContain(\n '.\n test('header renders default charset', async () => {\n const html = await render('/default-head')\n expect(html).toContain(' {\n const { next } = nextTestSetup({\n files: {\n 'app/layout.tsx': `\n import { ReactNode } from 'react'\n export default function Root({ children }: { children: ReactNode }) {\n return (\n \n {children}\n \n )\n }\n `,\n 'app/page.tsx': `\n export default function Page() {\n return

        hello world

        \n }\n ", "suffix": ",\n noEmit: true,\n esModuleInterop: true,\n module: 'esnext',\n moduleResolution: 'bundler',\n resolveJsonModule: true,\n isolatedModules: true,\n jsx: 'preserve',\n incremental: true,\n ", "middle": " `,\n 'tsconfig.json': JSON.stringify({\n compilerOptions: {\n target: 'ES2017',\n lib: ['dom', 'dom.iterable', 'esnext'],\n allowJs: true,\n skipLibCheck: true,\n strict: true", "meta": {"filepath": "test/development/typescript-native-preview/index.test.ts", "language": "typescript", "file_size": 2351, "cut_index": 563, "middle_length": 229}} {"prefix": "git repository is dirty[^\\n]*\\n?/g, '')\n .replace(/.*at async handler .*next-route-loader.*/g, '')\n .replace(/.*at async handleResponse.*/g, '')\n .replace(/.*at async doRender \\(.*/g, '')\n .split(/\\n/)\n .filter((item) => {\n const trimmed = item.trim()\n if (!trimmed) return false\n // Drop bootstrap/startup banner lines that may appear after\n // `next.cliOutput` was sliced. The Experiments banner is logged\n // asynchronously after the dev server repo", "suffix": "rn false\n // Drop compiling indicator lines (e.g. \"○ Compiling /gsp ...\").\n if (trimmed.startsWith('○ ')) return false\n return true\n })\n .join('\\n')\n }\n\n it('should show server-side error for gsp page correctly', async () =", "middle": "rts ready (see\n // `logExperimentalInfo` in `start-server.ts`), so it can race\n // with the test capturing `cliOutputIdx`.\n if (trimmed.startsWith('- ')) return false\n if (/^[✓⚠△] /.test(trimmed)) retu", "meta": {"filepath": "test/development/server-side-dev-errors/server-side-dev-errors.test.ts", "language": "typescript", "file_size": 15238, "cut_index": 921, "middle_length": 229}} {"prefix": "t } = nextTestSetup({\n files: path.join(__dirname, 'fixture'),\n })\n\n it.each([true, false])(\n 'should handle boolean async prop in next/head client-side: %s',\n async (bool) => {\n const browser = await next.browser('/head')\n const value = await browser.eval(\n `document.querySelector('script[src=\"/test-async-${JSON.stringify(\n bool\n )}.js\"]').async`\n )\n\n expect(value).toBe(bool)\n }\n )\n\n it('should only execute async and defer scripts once', async () =", "suffix": "wser.eval('window.__test_defer_executions'))).toBe(1)\n\n await browser.elementByCss('#reverseScriptOrder').click()\n await waitFor(2000)\n\n expect(Number(await browser.eval('window.__test_async_executions'))).toBe(1)\n expect(Number(await browser.e", "middle": "> {\n const browser = await next.browser('/head')\n\n await browser.waitForElementByCss('h1')\n await waitFor(2000)\n expect(Number(await browser.eval('window.__test_async_executions'))).toBe(1)\n expect(Number(await bro", "meta": {"filepath": "test/development/pages-dir/client-navigation/head.test.ts", "language": "typescript", "file_size": 5455, "cut_index": 716, "middle_length": 229}} {"prefix": "retry } from 'next-test-utils'\n\ndescribe('_app/_document add HMR', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n // TODO: figure out why test fails.\n it.skip('should HMR when _app is added', async () => {\n const browser = await next.browser('/')\n try {\n const html = await browser.eval('document.documentElement.innerHTML')\n expect(html).not.toContain('custom _app')\n expect(html).toContain('index page')\n\n await next.patchFile(\n 'pages/_app.js',\n ", "suffix": " )\n\n await retry(async () => {\n const html = await browser.eval('document.documentElement.innerHTML')\n expect(html).toContain('custom _app')\n expect(html).toContain('index page')\n })\n } finally {\n await next.delet", "middle": " `\n export default function MyApp({ Component, pageProps }) {\n return (\n <>\n

        custom _app

        \n \n \n )\n }\n `\n ", "meta": {"filepath": "test/development/app-document-add-hmr/app-document-add-hmr.test.ts", "language": "typescript", "file_size": 2844, "cut_index": 563, "middle_length": 229}} {"prefix": "tTestSetup({\n files: path.join(__dirname, 'fixture'),\n env: {\n TEST_STRICT_NEXT_HEAD: String(true),\n },\n })\n\n describe('when hash changes', () => {\n describe('check hydration mis-match', () => {\n it('should not have hydration mis-match for hash link', async () => {\n const browser = await next.browser('/nav/hash-changes')\n const browserLogs = await browser.log()\n let found = false\n browserLogs.forEach((log) => {\n console.log('log.message', log.mess", "suffix": "not run getInitialProps', async () => {\n const browser = await next.browser('/nav/hash-changes')\n\n await browser.elementByCss('#via-link').click()\n\n await retry(async () => {\n expect(await browser.elementByCss('p').text()).toB", "middle": "age)\n if (log.message.includes('Warning: Prop')) {\n found = true\n }\n })\n expect(found).toEqual(false)\n })\n })\n\n describe('when hash change via Link', () => {\n it('should ", "meta": {"filepath": "test/development/pages-dir/client-navigation/url-hash.test.ts", "language": "typescript", "file_size": 8248, "cut_index": 716, "middle_length": 229}} {"prefix": "t-test-utils'\nimport path from 'path'\nimport { nextTestSetup } from 'e2e-utils'\n\ndescribe('Client Navigation', () => {\n const { next } = nextTestSetup({\n files: path.join(__dirname, 'fixture'),\n env: {\n TEST_STRICT_NEXT_HEAD: String(true),\n },\n })\n\n describe('with tag inside the ', () => {\n it('should navigate the page', async () => {\n const browser = await next.browser('/nav/about')\n const text = await browser\n .elementByCss('#home-link')\n .click()\n ", "suffix": "c () => {\n const browser = await next.browser('/nav')\n\n await browser\n .elementByCss('#increase')\n .click()\n .elementByCss('#target-link')\n .click()\n\n await waitFor(1000)\n\n const counterText = await browser.e", "middle": " .waitForElementByCss('.nav-home')\n .elementByCss('p')\n .text()\n\n expect(text).toBe('This is the home.')\n await browser.close()\n })\n\n it('should not navigate if the tag has a target', asyn", "meta": {"filepath": "test/development/pages-dir/client-navigation/anchor-in-link.test.ts", "language": "typescript", "file_size": 2104, "cut_index": 563, "middle_length": 229}} {"prefix": "tureBuffer,\n readFixtureText,\n} from './utils'\n\ndescribe('metadata-files-static-output-dynamic-route', () => {\n const { next, skipped } = nextTestSetup({\n files: __dirname,\n })\n\n if (skipped) {\n return\n }\n\n it('should have correct link tags for dynamic page with static placeholder', async () => {\n const browser = await next.browser('/dynamic/123')\n\n // Static metadata files under dynamic routes use \"-\" as placeholder\n // since the file content is the same regardless of params\n expect", "suffix": " },\n {\n \"href\": \"/dynamic/-/icon.png\",\n \"rel\": \"icon\",\n \"type\": \"image/png\",\n },\n {\n \"href\": \"/favicon.ico\",\n \"rel\": \"icon\",\n \"type\": \"image/x-icon\",\n },\n {", "middle": "(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(`\n {\n \"links\": [\n {\n \"href\": \"/dynamic/-/apple-icon.png\",\n \"rel\": \"apple-touch-icon\",\n \"type\": \"image/png\",\n ", "meta": {"filepath": "test/e2e/app-dir/metadata-static-file/metadata-static-file-dynamic-route.test.ts", "language": "typescript", "file_size": 4368, "cut_index": 614, "middle_length": 229}} {"prefix": " readFixtureText,\n} from './utils'\n\ndescribe('metadata-files-static-output-group-route', () => {\n const { next, skipped } = nextTestSetup({\n files: __dirname,\n })\n\n if (skipped) {\n return\n }\n\n it('should have correct link tags for group page', async () => {\n const browser = await next.browser('/group')\n\n expect(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(`\n {\n \"links\": [\n {\n \"href\": \"/favicon.ico\",\n \"rel\": \"icon\",\n \"type\": ", "suffix": " \"rel\": \"icon\",\n \"type\": \"image/png\",\n },\n {\n \"href\": \"/manifest.json\",\n \"rel\": \"manifest\",\n },\n ],\n \"metas\": [\n {\n \"name\": \"twitter:card\",\n },\n {\n", "middle": "\"image/x-icon\",\n },\n {\n \"href\": \"/group/apple-icon-131tc6.png\",\n \"rel\": \"apple-touch-icon\",\n \"type\": \"image/png\",\n },\n {\n \"href\": \"/group/icon-131tc6.png\",\n ", "meta": {"filepath": "test/e2e/app-dir/metadata-static-file/metadata-static-file-group-route.test.ts", "language": "typescript", "file_size": 3412, "cut_index": 614, "middle_length": 229}} {"prefix": "retry } from 'next-test-utils'\n\ndescribe('app-dir action progressive enhancement', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies: {\n nanoid: '4.0.1',\n 'server-only': 'latest',\n },\n })\n\n it('should support formData and redirect without JS', async () => {\n let responseCode: number | undefined\n const browser = await next.browser('/server', {\n disableJavaScript: true,\n beforePageLoad(page) {\n page.on('response', (response) => {\n ", "suffix": "yId('name').type('test')\n await browser.elementById('submit').click()\n\n await retry(async () => {\n expect(await browser.url()).toBe(\n `${next.url}/header?name=test&hidden-info=hi`\n )\n })\n\n expect(responseCode).toBe(303)\n })\n\n ", "middle": "const url = new URL(response.url())\n const status = response.status()\n if (url.pathname.includes('/server')) {\n responseCode = status\n }\n })\n },\n })\n\n await browser.elementB", "meta": {"filepath": "test/e2e/app-dir/actions/app-action-progressive-enhancement.test.ts", "language": "typescript", "file_size": 2263, "cut_index": 563, "middle_length": 229}} {"prefix": "\nimport { accountForOverhead } from './account-for-overhead'\nimport { join } from 'path'\n\nconst CONFIG_ERROR =\n 'Server Actions Size Limit must be a valid number or filesize format larger than 1MB'\n\ndescribe('app-dir action size limit invalid config', () => {\n const { next, isNextStart, isNextDeploy, skipped } = nextTestSetup({\n files: __dirname,\n overrideFiles: process.env.TEST_NODE_MIDDLEWARE\n ? {\n 'middleware.js': new FileRef(join(__dirname, 'middleware-node.js')),\n }\n :", "suffix": "gs.push(stripAnsi(log.trim()))\n }\n\n next.on('stdout', onLog)\n next.on('stderr', onLog)\n })\n\n afterEach(async () => {\n logs.length = 0\n\n await next.stop()\n })\n\n if (isNextStart) {\n it('should error if serverActions.bodySizeLimit config", "middle": " {},\n skipStart: true,\n dependencies: {\n nanoid: '4.0.1',\n 'server-only': 'latest',\n },\n })\n if (skipped) return\n\n const logs: string[] = []\n\n beforeAll(() => {\n const onLog = (log: string) => {\n lo", "meta": {"filepath": "test/e2e/app-dir/actions/app-action-size-limit-invalid.test.ts", "language": "typescript", "file_size": 8540, "cut_index": 716, "middle_length": 229}} {"prefix": "').error(`Invalid action entry ${item}`, err)\n throw err\n }\n }\n for (const item in referenceManifest.edge) {\n try {\n const itemInfo = referenceManifest.edge[item]\n\n foundExportNames.push(itemInfo.exportedName)\n\n expect(itemInfo.filename).toBeString()\n expect(itemInfo.exportedName).toBeString()\n } catch (err) {\n require('console').error(`Invalid action entry ${item}`, err)\n throw err\n }\n }\n\n expect(", "suffix": "('should handle action correctly with middleware rewrite', async () => {\n const browser = await next.browser('/rewrite-to-static-first')\n let actionRequestStatus: number | undefined\n\n browser.on('response', async (res) => {\n if (\n res.", "middle": "foundExportNames).toContain('setCookie')\n expect(foundExportNames).toContain('getCookie')\n expect(foundExportNames).toContain('getHeader')\n expect(foundExportNames).toContain('setCookieWithMaxAge')\n })\n }\n\n it", "meta": {"filepath": "test/e2e/app-dir/actions/app-action.test.ts", "language": "typescript", "file_size": 65137, "cut_index": 2151, "middle_length": 229}} {"prefix": "s page is forced into dynamic rendering because POST requests to\n// a static/ISR page will cause an error when deployed.\nexport const dynamic = 'force-dynamic'\n\nexport default function Home() {\n return (\n
        \n

        POST /api-redirect (`redirect()`)

        \n \n \n \n

        POST /api-redirect-permanent (`permanentRedirect()`)

        \n
        \n \n \n
        \n

        POST /api-reponse-redirect-308

        \n
        \n \n \n

        POST /api-reponse-redirect-30", "meta": {"filepath": "test/e2e/app-dir/actions/app/redirects/page.js", "language": "javascript", "file_size": 1126, "cut_index": 518, "middle_length": 229}} {"prefix": "mport { cookies } from 'next/headers'\nimport { redirect } from 'next/navigation'\n\nexport default async function Page({ searchParams }) {\n const foo = (await cookies()).get('foo')\n const bar = (await cookies()).get('bar')\n return (\n
        \n

        \n foo={foo ? foo.value : ''}; bar={bar ? bar.value : ''}\n

        \n {\n 'use server'\n ;(await cookies()).delete('foo')\n ;(await cookies()).set('bar', '2')\n redirect('/redirect", "suffix": "? ''}

        \n {\n 'use server'\n redirect('/redirects/action-redirect/redirect-target?baz=1')\n }}\n >\n \n \n

        baz={(await searchParams).baz ?", "meta": {"filepath": "test/e2e/app-dir/actions/app/redirects/action-redirect/page.js", "language": "javascript", "file_size": 1058, "cut_index": 513, "middle_length": 229}} {"prefix": "rt Link from 'next/link'\n\nimport { cookies } from 'next/headers'\nimport RedirectClientComponent from './client'\n\nexport default async function Page() {\n const cookie = (await cookies()).get('random')\n const data = await fetch(\n 'https://next-data-api-endpoint.vercel.app/api/random?page',\n {\n next: { revalidate: 3600, tags: ['thankyounext'] },\n }\n ).then((res) => res.text())\n\n const data2 = await fetch(\n 'https://next-data-api-endpoint.vercel.app/api/random?a=b',\n {\n next: { reva", "suffix": "ext\">\n {data}\n {' '}\n \n \n /revalidate-2\n \n \n

        \n

        \n revalidate (tags: thankyounext, justputit):{' '}\n ", "middle": "lidate: 3600, tags: ['thankyounext', 'justputit'] },\n }\n ).then((res) => res.text())\n\n return (\n <>\n

        revalidate

        \n

        \n {' '}\n revalidate (tags: thankyounext): \n {wasSubmitted &&

        Submitted!
        }\n {\n startTransition(() => {\n getServerData()\n ", "suffix": " \n\n {\n startTransition(() => {\n badAction()\n .catch(() => {\n console.log('error caught in user code')\n ", "middle": ".catch(() => {\n console.log('error caught in user code')\n })\n .finally(() => {\n setWasSubmitted(true)\n })\n })\n }}\n >\n Submit Action\n", "meta": {"filepath": "test/e2e/app-dir/actions/app/catching-error/page.tsx", "language": "tsx", "file_size": 1196, "cut_index": 518, "middle_length": 229}} {"prefix": "n Counter({ inc, dec, double, slowInc }) {\n const [count, setCount] = useState(0)\n\n return (\n
        \n

        {count}

        \n {\n const newCount = await inc(count)\n setCount(newCount)\n }}\n >\n +1\n \n {\n const newCount = await slowInc(count)\n setCount(newCount)\n }}\n >\n +1 (Slow)\n {\n const newCount = await dec(count)\n setCount(newCount)\n }}\n >\n -1\n \n {\n const newCount = await double(count)\n ", "middle": "ton>\n \n {\n 'use server'\n if (data ===", "suffix": " return x * two.value\n }\n // Wrong answer\n return 42\n }}\n />\n
        \n \n \n \n \n \n )\n", "middle": " '你好') {\n ", "meta": {"filepath": "test/e2e/app-dir/actions/app/server/page.js", "language": "javascript", "file_size": 793, "cut_index": 513, "middle_length": 14}} {"prefix": "ort default function UI({\n getCookie,\n getHeader,\n setCookie,\n setCookieAndRedirect,\n getAuthedUppercase,\n}) {\n const [result, setResult] = useState('')\n\n return (\n
        \n

        {result}

        \n {\n // set cookie\n const random = Math.random()\n document.cookie = `random=${random}`\n const res = await getCookie('random')\n setResult(random + ':' + res.value)\n }}\n >\n getCookie\n ", "suffix": " setResult(\n random +\n ':' +\n res.value +\n ':' +\n document.cookie.match(/random-server=([^;]+)/)?.[1]\n )\n }}\n >\n setCookie\n \n \n {\n // set cookie on server side\n const random = Math.random()\n const res = await setCookie('random-server', random)\n ", "meta": {"filepath": "test/e2e/app-dir/actions/app/header/ui.js", "language": "javascript", "file_size": 2307, "cut_index": 563, "middle_length": 229}} {"prefix": "e, getHeader, setCookie } from '../../actions'\n\nconst getReferrer = getHeader.bind(null, 'referer')\nconst setTestCookie = setCookie.bind(null, 'test', '42')\nconst getTestCookie = getCookie.bind(null, 'test')\n\nexport default function Page() {\n const [referer, getReferrerAction] = useActionState(getReferrer, null)\n\n const [cookie, getTestCookieAction] = useActionState | null>(getTestCookie, null)\n\n return (\n <>\n
        \n

        Get Referer\n

        \n
        \n

        {cookie?.value}

        \n \n \n\n {\n startTransition(() => action())\n }}\n >\n Action that triggers an error\n \n
        \n )\n}\n\nclass Foo {\n va", "middle": " }}\n >\n ", "meta": {"filepath": "test/e2e/app-dir/actions/app/error-handling/page.js", "language": "javascript", "file_size": 798, "cut_index": 517, "middle_length": 14}} {"prefix": "mport { accountForOverhead } from '../../account-for-overhead'\n\nasync function action(formData) {\n 'use server'\n const payload = formData.get('payload').toString()\n console.log('size =', payload.length)\n}\n\nexport default function Page() {\n return (\n <>\n \n \n \n \n \n
        \n \n \n {\n const newCoun", "middle": "+1\n \n {\n const newCount = await slowInc(count)\n setCount(newCount)\n }}\n >\n +1 (Slow)\n \n \n \n redirectAction('/redirect-target')}\n >\n redirect relative\n \n \n
        \n \n redirectAction(\n 'https://next-data-api-endpoint.vercel.app/api/random?page'\n )\n }\n ", "suffix": ">\n \n
        \n \n redirectAction(location.origin + '/redirect-target')\n }\n >\n redirect internal with domain\n \n ", "middle": " >\n redirect external\n \n

        {count}

        \n {\n const newCount = await inc(count)\n setCount(newCount)\n }}\n >\n +1\n \n {\n const newCount = await dec(count)\n ", "suffix": " *2\n \n \n redirectAction('/redirect-target')}\n >\n redirect to a relative URL\n \n \n
        \n \n -1\n \n {\n const newCount = await double(count)\n setCount(newCount)\n }}\n >\n ", "meta": {"filepath": "test/e2e/app-dir/actions/app/client/edge/page.js", "language": "javascript", "file_size": 1712, "cut_index": 537, "middle_length": 229}} {"prefix": "mport { updateTag } from 'next/cache'\nimport { cookies } from 'next/headers'\nimport Link from 'next/link'\n\nexport default async function Page() {\n const randomCookie = (await cookies()).get('random')\n const data = await fetch(\n 'https://next-data-api-endpoint.vercel.app/api/random?page',\n {\n next: { revalidate: 3600, tags: ['thankyounext'] },\n }\n ).then((res) => res.text())\n\n return (\n <>\n

        another route

        \n \n Back\n ", "suffix": " 'use server'\n updateTag('thankyounext')\n }}\n >\n revalidate thankyounext\n \n \n

        \n random cookie:{' '}\n \n {JSON.stringify({ cookie: random", "middle": " \n

        \n {' '}\n revalidate (tags: thankyounext): {data}\n

        \n
        \n {\n ", "meta": {"filepath": "test/e2e/app-dir/actions/app/revalidate-2/page.js", "language": "javascript", "file_size": 1050, "cut_index": 513, "middle_length": 229}} {"prefix": " metadata-streaming', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should only insert metadata once for parallel routes when slots match', async () => {\n const browser = await next.browser('/parallel-routes')\n\n expect((await browser.elementsByCss('title')).length).toBe(1)\n expect(await browser.elementByCss('title').text()).toBe('parallel title')\n\n const $ = await next.render$('/parallel-routes')\n expect($('title').length).toBe(1)\n // We can't ensure if it's ", "suffix": " await browser.elementByCss('[href=\"/parallel-routes/test-page\"]').click()\n\n await retry(async () => {\n expect(await browser.elementByCss('title').text()).toContain(\n 'Dynamic api'\n )\n })\n\n expect((await browser.elementsByCss('t", "middle": "inserted into head or body since it's a race condition,\n // where sometimes the metadata can be suspended.\n expect($('title').text()).toBe('parallel title')\n\n // validate behavior remains the same on client navigations\n ", "meta": {"filepath": "test/e2e/app-dir/metadata-streaming-parallel-routes/metadata-streaming-parallel-routes.test.ts", "language": "typescript", "file_size": 3135, "cut_index": 614, "middle_length": 229}} {"prefix": "rom 'next/server'\nimport Link from 'next/link'\n\n// skip rendering children\nexport default function Layout({ bar, foo }) {\n return (\n
        \n

        Parallel Routes Layout - No Children

        \n\n \n {`to /parallel-routes-no-children/first`}\n \n
        \n \n {`to /parallel-routes-no-children/second`}\n ", "suffix": "{foo}
        \n
        {bar}
        \n
        \n )\n}\n\nexport async function generateMetadata() {\n await connection()\n await new Promise((resolve) => setTimeout(resolve, 300))\n return {\n title: 'parallel-routes-default layout title',\n }\n", "middle": " \n
        \n\n
        ", "meta": {"filepath": "test/e2e/app-dir/metadata-streaming-parallel-routes/app/parallel-routes-no-children/layout.tsx", "language": "tsx", "file_size": 845, "cut_index": 535, "middle_length": 52}} {"prefix": "utils'\n\ndescribe('parallel-routes-and-interception-basepath', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should show parallel intercepted slot with basepath', async () => {\n const browser = await next.browser('/base')\n await browser.elementByCss('#link-to-nested').click()\n const homePage = await browser.elementByCss('#home-page').text()\n const slot = await browser.elementByCss('#nested-page-slot').text()\n expect(homePage).toBe('Home page')\n expect(slot).to", "suffix": " route via direct link with basepath when parallel intercepted slot exist', async () => {\n const browser = await next.browser('/base/nested')\n const nestedPageFull = await browser\n .elementByCss('#nested-page-full')\n .text()\n expect(nest", "middle": "Be('Nested Page Slot')\n })\n it('should show normal", "meta": {"filepath": "test/e2e/app-dir/parallel-routes-and-interception-basepath/parallel-routes-and-interception-basepath.test.ts", "language": "typescript", "file_size": 900, "cut_index": 547, "middle_length": 52}} {"prefix": "mport { nextTestSetup } from 'e2e-utils'\nimport { retry } from 'next-test-utils'\n\ndescribe('parallel-routes-catchall-specificity', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should match the catch-all route when navigating from a page with a similar path depth as the previously matched slot', async () => {\n const browser = await next.browser('/')\n\n await browser.elementByCss('[href=\"/comments/some-text\"]').click()\n\n await browser.waitForElementByCss('h1')\n\n // w", "suffix": "await retry(async () => {\n expect(await browser.elementByCss('h1').text()).toBe('Profile')\n })\n\n await browser.back()\n\n await browser.elementByCss('[href=\"/trending\"]').click()\n\n await retry(async () => {\n expect(await browser.element", "middle": "e're matching @modal/(...comments)/[productId]\n expect(await browser.elementByCss('h1').text()).toBe('Modal')\n\n await browser.elementByCss('[href=\"/u/foobar/l\"]').click()\n\n // we're now matching @modal/[...catchAll]\n ", "meta": {"filepath": "test/e2e/app-dir/parallel-routes-catchall-specificity/parallel-routes-catchall-specificity.test.ts", "language": "typescript", "file_size": 1050, "cut_index": 513, "middle_length": 229}} {"prefix": "t.readFile('.next/server/app/api/hello.json.meta')\n ).toBeTruthy()\n }\n expect(\n JSON.parse(await next.render(basePath + '/api/hello.json'))\n ).toEqual({\n pathname: '/api/hello.json',\n })\n })\n\n it('does not statically generate with dynamic usage', async () => {\n if (isNextStart) {\n expect(\n await next\n .readFile('.next/server/app/api/dynamic.body')\n .catch(() => '')\n ).toBeFalsy()\n expect(\n await ", "suffix": "ynamic',\n query: {},\n })\n })\n })\n\n describe('works with generateStaticParams correctly', () => {\n it.each([\n '/static/first/data.json',\n '/static/second/data.json',\n '/static/three/data.json',\n ])('responds correctly o", "middle": "next\n .readFile('.next/server/app/api/dynamic.meta')\n .catch(() => '')\n ).toBeFalsy()\n }\n expect(JSON.parse(await next.render(basePath + '/api/dynamic'))).toEqual({\n pathname: '/api/d", "meta": {"filepath": "test/e2e/app-dir/app-routes/app-custom-routes.test.ts", "language": "typescript", "file_size": 22443, "cut_index": 1331, "middle_length": 229}} {"prefix": "ver/web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies'\nimport type { Headers as NodeFetchHeaders } from 'node-fetch'\n\nconst KEY = 'x-request-meta'\n\n/**\n * Adds a new header to the headers object and serializes it. To be used in\n * conjunction with the `getRequestMeta` function in tests to verify request\n * data from the handler.\n *\n * @param meta metadata to inject into the headers\n * @param headers the existing hea", "suffix": "return {\n ...headers,\n [KEY]: JSON.stringify(meta),\n }\n}\n\n/**\n * Adds a cookie to the headers with the provided request metadata. Existing\n * cookies will be merged, but it will not merge request metadata that already\n * exists on an existing cookie", "middle": "ders on the response to merge with\n * @returns the merged headers with the request meta added\n */\nexport function withRequestMeta(\n meta: Record,\n headers: Record = {}\n): Record {\n ", "meta": {"filepath": "test/e2e/app-dir/app-routes/helpers.ts", "language": "typescript", "file_size": 2519, "cut_index": 563, "middle_length": 229}} {"prefix": " type NextRequest } from 'next/server'\nimport { withRequestMeta } from '../helpers'\n\nconst helloHandler = async (\n request: NextRequest,\n { params }: { params?: Promise> }\n): Promise => {\n const { pathname } = request.nextUrl\n\n if (typeof WebSocket === 'undefined') {\n throw new Error('missing WebSocket constructor!!')\n }\n\n const resolvedParams = params ? await params : null\n\n return new Response('hello, world', {\n headers: withRequestMeta({\n meth", "suffix": " pathname,\n }),\n })\n}\n\nexport const GET = helloHandler\nexport const HEAD = helloHandler\nexport const OPTIONS = helloHandler\nexport const POST = helloHandler\nexport const PUT = helloHandler\nexport const DELETE = helloHandler\nexport const PATCH = hell", "middle": "od: request.method,\n params: resolvedParams,\n ", "meta": {"filepath": "test/e2e/app-dir/app-routes/handlers/hello.ts", "language": "typescript", "file_size": 837, "cut_index": 520, "middle_length": 52}} {"prefix": "from 'e2e-utils'\n\ndescribe('parallel-routes-catchall-default', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should match default paths before catch-all', async () => {\n let browser = await next.browser('/en/nested')\n\n // we have a top-level catch-all but the /nested dir doesn't have a default/page until the /[foo]/[bar] segment\n // so we expect the top-level catch-all to render\n expect(await browser.elementById('children').text()).toBe(\n '/[locale]/[[...catch", "suffix": ".elementById('nested-children').text()).toBe(\n '/[locale]/nested/[foo]/[bar]/default.tsx'\n )\n\n // we expect the slot to match since there's a page defined at this segment\n expect(await browser.elementById('slot').text()).toBe(\n '/[locale", "middle": "All]]/page.tsx'\n )\n\n browser = await next.browser('/en/nested/foo/bar')\n\n // we're now at the /[foo]/[bar] segment, so we expect the matched page to be the default (since there's no page defined)\n expect(await browser", "meta": {"filepath": "test/e2e/app-dir/parallel-routes-catchall-default/parallel-routes-catchall-default.test.ts", "language": "typescript", "file_size": 1646, "cut_index": 537, "middle_length": 229}} {"prefix": " =>\n await browser.eval('document.documentElement.scrollTop')\n\n const getLeftScroll = async (browser: Playwright) =>\n await browser.eval('document.documentElement.scrollLeft')\n\n const waitForScrollToComplete = async (\n browser: Playwright,\n options: { x: number; y: number }\n ) => {\n await retry(async function expectScrolledTo() {\n const top = await getTopScroll(browser)\n const left = await getLeftScroll(browser)\n expect({ top, left }).toEqual({ top: options.y, left: options.", "suffix": " await waitForScrollToComplete(browser, options)\n }\n\n describe('vertical scroll', () => {\n it('should scroll to top of document when navigating between to pages without layout', async () => {\n const browser = await next.browser('/0/0/100/10000/p", "middle": "x })\n })\n await assertNoConsoleErrors(browser)\n }\n\n const scrollTo = async (\n browser: Playwright,\n options: { x: number; y: number }\n ) => {\n await browser.eval(`window.scrollTo(${options.x}, ${options.y})`)\n ", "meta": {"filepath": "test/e2e/app-dir/router-autoscroll/router-autoscroll.test.ts", "language": "typescript", "file_size": 10495, "cut_index": 921, "middle_length": 229}} {"prefix": "import { useRouter } from 'next/navigation'\n\nexport default function Layout({ children }: { children: React.ReactNode }) {\n const router = useRouter()\n\n // We export these so that we can access them from tests\n useEffect(() => {\n // @ts-ignore\n window.router = router\n // @ts-ignore\n window.React = React\n }, [router])\n\n return (\n \n \n \n }\n >\n \n \n \n \n
        \n {children}\n \n \n ", "middle": " margin: 0,\n }}\n >\n ", "meta": {"filepath": "test/e2e/app-dir/router-autoscroll/app/layout.tsx", "language": "tsx", "file_size": 933, "cut_index": 606, "middle_length": 52}} {"prefix": "n (\n <>\n {\n // Repeat 500 elements\n Array.from({ length: 500 }, (_, i) => (\n
        {i}
        \n ))\n }\n
        \n \n To loading scroll\n \n
        \n
        \n \n To invisible first element\n \n
        \n\n
        \n \n
        \n\n
        \n \n To sticky first element\n \n
        \n\n
        \n To new metadata\n
        \n\n ", "middle": "lement\">\n To fixed first element\n {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n // Cache Components build fails when metadata files are inside a dynamic route.\n //\n // Route \"/dynamic/[id]\": Next.js encountered uncached or runtime data in `generateMetadata()`.\n //\n // This prevents the page from being prerendered, leading to a slower user experience.\n //\n // Ways to fix this:\n // - Use a static metadata export instea", "suffix": "onst instant = false` to allow a blocking route\n //\n // Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata\n // Error occurred prerendering page \"/dynamic/[id]\". Read more: https://nextjs.org/docs/messages/prerender-error\n", "middle": "d of `generateMetadata()`\n // - Cache the metadata with `\"use cache\"` in `generateMetadata()`\n // - Add a dynamic data access (e.g. `await connection()`) to the page to render it at request time\n // - Set `export c", "meta": {"filepath": "test/e2e/app-dir/metadata-static-file/metadata-static-file-parallel-route.test.ts", "language": "typescript", "file_size": 4659, "cut_index": 614, "middle_length": 229}} {"prefix": " readFixtureText,\n} from './utils'\n\ndescribe('metadata-files-static-output-static-route', () => {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n // Cache Components build fails when metadata files are inside a dynamic route.\n //\n // Route \"/dynamic/[id]\": Next.js encountered uncached or runtime data in `generateMetadata()`.\n //\n // This prevents the page from being prerendered, leading to a slower user experience.\n //\n // Ways to fix this:\n // - Use a static metadata export instead ", "suffix": "st instant = false` to allow a blocking route\n //\n // Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata\n // Error occurred prerendering page \"/dynamic/[id]\". Read more: https://nextjs.org/docs/messages/prerender-error\n ", "middle": "of `generateMetadata()`\n // - Cache the metadata with `\"use cache\"` in `generateMetadata()`\n // - Add a dynamic data access (e.g. `await connection()`) to the page to render it at request time\n // - Set `export con", "meta": {"filepath": "test/e2e/app-dir/metadata-static-file/metadata-static-file-static-route.test.ts", "language": "typescript", "file_size": 4525, "cut_index": 614, "middle_length": 229}} {"prefix": "ype error.\nimport { promises as fs } from 'fs'\nimport path from 'path'\nimport type { Playwright } from 'e2e-utils'\n\n// Fixture files live in this directory (`test/e2e/app-dir/metadata-static-file`),\n// so we read them from the repo on the test runner. Using `next.readFile` would\n// hit the deployed filesystem, which is not available in deploy test mode.\nexport function readFixtureBuffer(relativePath: string) {\n return fs.readFile(path.join(__dirname, relativePath))\n}\n\nexport function readFixtureText(relati", "suffix": "urn elements\n .filter((el) => {\n if (el.href.includes('/_next/static')) {\n return false\n }\n\n return [\n '/favicon.ico',\n '/manifest.json',\n '/manifest.webmanifest',\n // Below may have su", "middle": "vePath: string) {\n return fs.readFile(path.join(__dirname, relativePath), 'utf8')\n}\n\nasync function getMetadataLinks(browser: Playwright) {\n const links = await browser.locator('link').evaluateAll((elements: any[]) => {\n ret", "meta": {"filepath": "test/e2e/app-dir/metadata-static-file/utils.ts", "language": "typescript", "file_size": 2867, "cut_index": 563, "middle_length": 229}} {"prefix": "retry } from 'next-test-utils'\nimport { type Collector, connectCollector } from './collector'\n\nconst COLLECTOR_PORT = 9876\n\ndescribe('otel-parent-span-propagation', () => {\n const { next, skipped } = nextTestSetup({\n files: __dirname,\n skipDeployment: true,\n dependencies: require('./package.json').dependencies,\n env: {\n TEST_OTEL_COLLECTOR_PORT: String(COLLECTOR_PORT),\n NEXT_TELEMETRY_DISABLED: '1',\n },\n })\n\n if (skipped) {\n return\n }\n\n let collector: Collector\n\n beforeEach", "suffix": "on, when external OTEL instrumentation (e.g. Datadog,\n // @opentelemetry/instrumentation-http) creates a parent HTTP server span,\n // our fix also propagates http.route to that parent span so APM tools\n // derive the resource name correctly (e.g. \"GET /", "middle": "(async () => {\n collector = await connectCollector({ port: COLLECTOR_PORT })\n })\n\n afterEach(async () => {\n await collector.shutdown()\n })\n\n // Verifies that http.route is set on the handleRequest span.\n // In producti", "meta": {"filepath": "test/e2e/app-dir/otel-parent-span-propagation/otel-parent-span-propagation.test.ts", "language": "typescript", "file_size": 2444, "cut_index": 563, "middle_length": 229}} {"prefix": "* eslint-env jest */\nimport path from 'path'\nimport { nextTestSetup, FileRef } from 'e2e-utils'\n\ndescribe('app dir - middleware with middleware in src dir', () => {\n const { next } = nextTestSetup({\n files: {\n 'src/app': new FileRef(path.join(__dirname, 'app')),\n 'next.config.js': new FileRef(path.join(__dirname, 'next.config.js')),\n 'src/middleware.js': `\n import { NextResponse } from 'next/server'\n import { cookies } from 'next/headers'\n\n export async function middleware(", "suffix": "r = await next.browser('/')\n await browser.addCookie({\n name: 'test-cookie',\n value: 'test-cookie-response',\n })\n await browser.refresh()\n\n const html = await browser.eval('document.documentElement.innerHTML')\n\n expect(html).toCont", "middle": "request) {\n const cookie = (await cookies()).get('test-cookie')\n return NextResponse.json({ cookie })\n }\n `,\n },\n })\n\n it('works without crashing when using RequestStore', async () => {\n const browse", "meta": {"filepath": "test/e2e/app-dir/app-middleware/app-middleware-in-src-dir.test.ts", "language": "typescript", "file_size": 1034, "cut_index": 513, "middle_length": 229}} {"prefix": "ync () => {\n expect(next.cliOutput).toContain(\n 'The \"middleware\" file convention is deprecated. Please use \"proxy\" instead.'\n )\n })\n })\n\n it('should filter correctly after middleware rewrite', async () => {\n const browser = await next.browser('/start')\n\n await browser.eval('window.beforeNav = 1')\n await browser.eval('window.next.router.push(\"/rewrite-to-app\")')\n\n await check(async () => {\n return browser.eval('document.documentElement.innerHTML')\n }, /app-dir/)\n }", "suffix": "dge',\n toJson: (res: Response) => res.json(),\n },\n {\n title: 'next/headers',\n path: '/headers',\n toJson: async (res: Response) => {\n const $ = cheerio.load(await res.text())\n return JSON.parse($('#headers').text())\n ", "middle": ")\n\n describe.each([\n {\n title: 'Serverless Functions',\n path: '/api/dump-headers-serverless',\n toJson: (res: Response) => res.json(),\n },\n {\n title: 'Edge Functions',\n path: '/api/dump-headers-e", "meta": {"filepath": "test/e2e/app-dir/app-middleware/app-middleware.test.ts", "language": "typescript", "file_size": 9979, "cut_index": 921, "middle_length": 229}} {"prefix": "import { check } from 'next-test-utils'\nimport { join } from 'path'\n\ndescribe('app-dir action useActionState', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n overrideFiles: process.env.TEST_NODE_MIDDLEWARE\n ? {\n 'middleware.js': new FileRef(join(__dirname, 'middleware-node.js')),\n }\n : {},\n dependencies: {\n nanoid: '4.0.1',\n },\n })\n it('should support submitting form state with JS', async () => {\n const browser = await next.browser('/client/for", "suffix": " }, 'initial-state:test')\n })\n\n it('should support submitting form state without JS', async () => {\n const browser = await next.browser('/client/form-state', {\n disableJavaScript: true,\n })\n\n await browser.eval(`document.getElementById('nam", "middle": "m-state')\n\n await browser.eval(`document.getElementById('name-input').value = 'test'`)\n await browser.elementByCss('#submit-form').click()\n\n await check(() => {\n return browser.elementByCss('#form-state').text()\n ", "meta": {"filepath": "test/e2e/app-dir/actions/app-action-form-state.test.ts", "language": "typescript", "file_size": 2516, "cut_index": 563, "middle_length": 229}} {"prefix": "'\n\ndescribe('Configuration', () => {\n const { next } = nextTestSetup({ files: __dirname })\n\n async function get$(path: string) {\n const html = await next.render(path)\n return cheerio.load(html)\n }\n\n it('should disable X-Powered-By header support', async () => {\n const res = await next.fetch('/')\n const header = res.headers.get('X-Powered-By')\n expect(header).not.toBe('Next.js')\n })\n\n test('correctly imports a package that defines `module` but no `main` in package.json', async () => {\n ", "suffix": "xpect($('#messageInAPackage').text()).toBe('OK')\n })\n\n it('should have env variables available on the client', async () => {\n const browser = await next.browser('/next-config')\n const envValue = await browser.elementByCss('#env').text()\n expect(", "middle": " const $ = await get$('/module-only-content')\n e", "meta": {"filepath": "test/development/config/config.test.ts", "language": "typescript", "file_size": 948, "cut_index": 582, "middle_length": 52}} {"prefix": "document components error', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n async function checkMissing(missing: string[], docContent: string) {\n const outputIndex = next.cliOutput.length\n await next.patchFile('pages/_document.js', docContent)\n\n await next.render('/').catch(() => {})\n\n await retry(async () => {\n const newOutput = next.cliOutput.slice(outputIndex)\n expect(newOutput).toContain('missing-document-component')\n expect(newOutput).toContain(missin", "suffix": "ript } from 'next/document'\n\n class MyDocument extends Document {\n render() {\n return (\n \n \n \n
        \n \n \n ", "middle": "g.join(', '))\n })\n\n await next.deleteFile('pages/_document.js')\n }\n\n it('should detect missing Html component', async () => {\n await checkMissing(\n [''],\n `\n import Document, { Head, Main, NextSc", "meta": {"filepath": "test/development/missing-document-component-error/missing-document-component-error.test.ts", "language": "typescript", "file_size": 3086, "cut_index": 614, "middle_length": 229}} {"prefix": "retry } from 'next-test-utils'\nimport path from 'path'\n\nconst reactDependencies = {\n react: '19.3.0-canary-fef12a01-20260413',\n 'react-dom': '19.3.0-canary-fef12a01-20260413',\n}\n\n// This test only applies to Turbopack\n;(!process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(\n 'turbopack unsupported features log',\n () => {\n describe('no config', () => {\n const { next } = nextTestSetup({\n files: path.join(__dirname, 'fixtures/no-config'),\n dependencies: reactDependencies,\n }", "suffix": "ut).not.toContain(\n 'You are using configuration and/or tools that are not yet'\n )\n })\n })\n\n describe('empty config', () => {\n const { next } = nextTestSetup({\n files: path.join(__dirname, 'fixtures/empty-config'),\n ", "middle": ")\n\n it('should not warn by default', async () => {\n const html = await next.render('/')\n expect(html).toContain('hello world')\n expect(next.cliOutput).toContain('(Turbopack)')\n expect(next.cliOutp", "meta": {"filepath": "test/development/turbopack-unsupported-log/turbopack-unsupported-log.test.ts", "language": "typescript", "file_size": 2159, "cut_index": 563, "middle_length": 229}} {"prefix": "renderViaHTTP } from 'next-test-utils'\n\ndescribe('Prerender crawler handling', () => {\n const { next } = nextTestSetup({\n files: {\n 'pages/index.js': `\n export default function Page() { \n return

        index page

        \n } \n `,\n 'pages/blog/[slug].js': `\n import {useRouter} from 'next/router'\n \n export default function Page({ slug }) { \n const router = useRouter()\n \n if (router.isFallback) {\n return 'Loading...'\n ", "suffix": "params }) {\n return {\n props: {\n slug: params.slug\n }\n }\n } \n \n export async function getStaticPaths() {\n return {\n paths: ['/blog/first'],\n fallback: ", "middle": " }\n \n return (\n <>\n

        slug page

        \n

        {slug}

        \n \n )\n } \n \n export async function getStaticProps({ ", "meta": {"filepath": "test/e2e/prerender-crawler.test.ts", "language": "typescript", "file_size": 2985, "cut_index": 563, "middle_length": 229}} {"prefix": "t/data/${next.buildId}/blog/post-4.json`,\n initialExpireSeconds: 31536000,\n initialRevalidateSeconds: 10,\n srcRoute: '/blog/[post]',\n },\n '/blog/post-1/comment-1': {\n allowHeader,\n dataRoute: `/_next/data/${next.buildId}/blog/post-1/comment-1.json`,\n initialExpireSeconds: 31536000,\n initialRevalidateSeconds: 2,\n srcRoute: '/blog/[post]/[comment]',\n },\n '/blog/post-2/comment-2': {\n allowHeader,\n dataRoute: `/_next/data/${next.buildId}/blog/post-2/", "suffix": "g/post.1.json`,\n initialExpireSeconds: 31536000,\n initialRevalidateSeconds: 10,\n srcRoute: '/blog/[post]',\n },\n '/catchall-explicit/another/value': {\n allowHeader,\n dataRoute: `/_next/data/${next.buildId}/catchall-explicit/an", "middle": "comment-2.json`,\n initialExpireSeconds: 31536000,\n initialRevalidateSeconds: 2,\n srcRoute: '/blog/[post]/[comment]',\n },\n '/blog/post.1': {\n allowHeader,\n dataRoute: `/_next/data/${next.buildId}/blo", "meta": {"filepath": "test/e2e/prerender.test.ts", "language": "typescript", "file_size": 94609, "cut_index": 3790, "middle_length": 229}} {"prefix": "from 'e2e-utils'\nimport { retry } from 'next-test-utils'\n\ndescribe('Scroll Back Restoration Support', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies: {\n react: '19.3.0-canary-fef12a01-20260413',\n 'react-dom': '19.3.0-canary-fef12a01-20260413',\n },\n // Vercel deployment fails to build/deploy this fixture in CI; skip in deploy mode.\n skipDeployment: true,\n })\n\n it('should restore the scroll position on navigating back', async () => {\n const browser = ", "suffix": "ect(scrollRestoration).toBe('manual')\n\n const scrollX = Math.floor(await browser.eval(() => window.scrollX))\n const scrollY = Math.floor(await browser.eval(() => window.scrollY))\n\n expect(scrollX).not.toBe(0)\n expect(scrollY).not.toBe(0)\n\n a", "middle": "await next.browser('/')\n await browser.eval(() =>\n document.querySelector('#to-another').scrollIntoView()\n )\n const scrollRestoration = await browser.eval(\n () => window.history.scrollRestoration\n )\n\n exp", "meta": {"filepath": "test/e2e/scroll-back-restoration/scroll-back-restoration.test.ts", "language": "typescript", "file_size": 1727, "cut_index": 537, "middle_length": 229}} {"prefix": "str) {\n return (\n str &&\n str.replace(/^ +(?:at|in) ([\\S]+)[^\\n]*/gm, function (m, name) {\n const dot = name.lastIndexOf('.')\n if (dot !== -1) {\n name = name.slice(dot + 1)\n }\n return ' at ' + name + (/\\d/.test(m) ? ' (**)' : '')\n })\n )\n}\n\ndescribe.each(['default', 'babelrc'] as const)(\n 'react-compiler %s',\n (variant) => {\n const dependencies = (global as any).isNextDeploy\n ? // `link` is incompatible with the npm version used when this test is deployed\n ", "suffix": "\n variant === 'babelrc'\n ? __dirname\n : {\n app: new FileRef(join(__dirname, 'app')),\n pages: new FileRef(join(__dirname, 'pages')),\n 'next.config.js': new FileRef(join(__dirname, 'next.config.", "middle": " {\n 'reference-library': 'file:./reference-library',\n }\n : {\n 'reference-library': 'link:./reference-library',\n }\n const { next, isNextDev, isTurbopack } = nextTestSetup({\n files:", "meta": {"filepath": "test/e2e/react-compiler/react-compiler.test.ts", "language": "typescript", "file_size": 6485, "cut_index": 716, "middle_length": 229}} {"prefix": "mport { nextTestSetup } from 'e2e-utils'\nimport { renderViaHTTP } from 'next-test-utils'\n\ndescribe('browserslist-extends', () => {\n const { next } = nextTestSetup({\n files: {\n 'pages/index.js': `\n import styles from './index.module.css'\n \n export default function Page() { \n return

        hello world

        \n } \n `,\n 'pages/index.module.css': `\n .hello {\n color: pink;\n }\n `,\n },\n dependencies: {\n '", "suffix": "onfig-google': '^3.0.1',\n },\n packageJson: {\n browserslist: ['extends browserslist-config-google'],\n },\n })\n\n it('should work', async () => {\n const html = await renderViaHTTP(next.url, '/')\n expect(html).toContain('hello world')\n })", "middle": "browserslist-c", "meta": {"filepath": "test/e2e/browserslist-extends/index.test.ts", "language": "typescript", "file_size": 787, "cut_index": 513, "middle_length": 14}} {"prefix": " readFixtureText,\n} from './utils'\n\ndescribe('metadata-files-static-output-intercepting-route', () => {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n // Cache Components build fails when metadata files are inside a dynamic route.\n //\n // Route \"/dynamic/[id]\": Next.js encountered uncached or runtime data in `generateMetadata()`.\n //\n // This prevents the page from being prerendered, leading to a slower user experience.\n //\n // Ways to fix this:\n // - Use a static metadata export in", "suffix": "rt const instant = false` to allow a blocking route\n //\n // Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata\n // Error occurred prerendering page \"/dynamic/[id]\". Read more: https://nextjs.org/docs/messages/prerender-er", "middle": "stead of `generateMetadata()`\n // - Cache the metadata with `\"use cache\"` in `generateMetadata()`\n // - Add a dynamic data access (e.g. `await connection()`) to the page to render it at request time\n // - Set `expo", "meta": {"filepath": "test/e2e/app-dir/metadata-static-file/metadata-static-file-intercepting-route.test.ts", "language": "typescript", "file_size": 5062, "cut_index": 614, "middle_length": 229}} {"prefix": "ver as HttpServer } from 'node:http'\nimport { SavedSpan } from './constants'\n\nexport interface Collector {\n getSpans: () => SavedSpan[]\n shutdown: () => Promise\n}\n\nexport async function connectCollector({\n port,\n}: {\n port: number\n}): Promise {\n const spans: SavedSpan[] = []\n\n const server = new HttpServer(async (req, res) => {\n if (req.method !== 'POST') {\n res.writeHead(405)\n res.end()\n return\n }\n\n const body = await new Promise((resolve, reject) => {", "suffix": "ewSpans = JSON.parse(body.toString('utf-8')) as SavedSpan[]\n spans.push(...newSpans)\n res.statusCode = 202\n res.end()\n })\n\n await new Promise((resolve, reject) => {\n server.listen(port, (err?: Error) => {\n if (err) {\n reject", "middle": "\n const acc: Buffer[] = []\n req.on('data', (chunk: Buffer) => {\n acc.push(chunk)\n })\n req.on('end', () => {\n resolve(Buffer.concat(acc))\n })\n req.on('error', reject)\n })\n\n const n", "meta": {"filepath": "test/e2e/app-dir/otel-parent-span-propagation/collector.ts", "language": "typescript", "file_size": 1374, "cut_index": 524, "middle_length": 229}} {"prefix": "('app-dir assetPrefix with basePath handling', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should redirect route when requesting it directly', async () => {\n const res = await next.fetch('/custom-base-path/a/', {\n redirect: 'manual',\n })\n expect(res.status).toBe(308)\n expect(new URL(res.headers.get('location'), next.url).pathname).toBe(\n '/custom-base-path/a'\n )\n })\n\n it('should render link', async () => {\n const $ = await next.render$('/custom-", "suffix": "ase-path/a')\n expect(await browser.waitForElementByCss('#a-page').text()).toBe('A page')\n })\n\n it('should redirect route when clicking link', async () => {\n const browser = await next.browser('/custom-base-path')\n await browser\n .elementByC", "middle": "base-path')\n expect($('#to-a-trailing-slash').attr('href')).toBe('/custom-base-path/a')\n })\n\n it('should redirect route when requesting it directly by browser', async () => {\n const browser = await next.browser('/custom-b", "meta": {"filepath": "test/e2e/app-dir/asset-prefix-with-basepath/asset-prefix-with-basepath.test.ts", "language": "typescript", "file_size": 2463, "cut_index": 563, "middle_length": 229}} {"prefix": "ndling - next export', () => {\n const { next, isNextStart, skipped } = nextTestSetup({\n files: __dirname,\n skipStart: true,\n skipDeployment: true,\n dependencies: {\n nanoid: '4.0.1',\n 'server-only': 'latest',\n },\n })\n if (skipped) return\n\n if (!isNextStart) {\n it('skip test for development mode', () => {})\n return\n }\n\n beforeAll(async () => {\n await next.stop()\n await next.patchFile(\n 'next.config.js',\n `\n module.exports = {\n output: 'export'\n ", "suffix": "also not supported with export\n await next.remove('app/interception-routes')\n try {\n await next.start()\n } catch {}\n })\n\n it('should error when use export output for server actions', async () => {\n expect(next.cliOutput).toContain(\n ", "middle": " }\n `\n )\n // interception routes are ", "meta": {"filepath": "test/e2e/app-dir/actions/app-action-export.test.ts", "language": "typescript", "file_size": 960, "cut_index": 582, "middle_length": 52}} {"prefix": "ort { nextTestSetup } from 'e2e-utils'\nimport { retry, waitForRedbox, getRedboxSource } from 'next-test-utils'\n\n// Webpack specific config test.\n;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(\n 'devtool set in development mode in next config',\n () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should warn and revert when a devtool is set in development mode', async () => {\n await retry(async () => {\n expect(next.cliOutput).toMatch(/Reverting webp", "suffix": " \"pages/index.js (5:11) @ Index.useEffect\n\n 3 | export default function Index(props) {\n 4 | useEffect(() => {\n > 5 | throw new Error('this should render')\n | ^\n 6 | }, [])\n ", "middle": "ack devtool to /)\n })\n\n const browser = await next.browser('/')\n await waitForRedbox(browser)\n if (process.platform !== 'win32') {\n expect(await getRedboxSource(browser)).toMatchInlineSnapshot(`\n ", "meta": {"filepath": "test/development/config-devtool-dev/config-devtool-dev.test.ts", "language": "typescript", "file_size": 1117, "cut_index": 515, "middle_length": 229}} {"prefix": "from 'e2e-utils'\nimport { waitForRedbox, getRedboxSource } from 'next-test-utils'\n\ndescribe('app dir - css', () => {\n const { next, skipped } = nextTestSetup({\n files: __dirname,\n dependencies: {\n sass: 'latest',\n },\n })\n\n if (skipped) {\n return\n }\n\n describe('sass support', () => {\n ;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(\n 'error handling',\n () => {\n it('should use original source points for sass errors', async () => {\n const browser =", "suffix": "lineSnapshot(`\n \"./app/global.scss.css (45:1)\n Parsing CSS source code failed\n 43 | }\n 44 |\n > 45 | input.defaultCheckbox::before path {\n | ^\n 46 | fill: currentColor;\n ", "middle": " await next.browser('/sass-error')\n\n await waitForRedbox(browser)\n const source = await getRedboxSource(browser)\n\n // css-loader does not report an error for this case\n expect(source).toMatchIn", "meta": {"filepath": "test/development/sass-error/index.test.ts", "language": "typescript", "file_size": 1861, "cut_index": 537, "middle_length": 229}} {"prefix": "n } from 'path'\nimport { nextTestSetup, FileRef } from 'e2e-utils'\n\ndescribe('i18-default-locale-redirect', () => {\n const { next } = nextTestSetup({\n files: {\n pages: new FileRef(join(__dirname, './app/pages')),\n 'next.config.js': new FileRef(join(__dirname, './app/next.config.js')),\n },\n })\n\n it('should not request a path prefixed with default locale', async () => {\n const browser = await next.browser('/')\n let requestedDefaultLocalePath = false\n browser.on('request', (request:", "suffix": "ct(await browser.elementByCss('#new').text()).toBe('New')\n expect(requestedDefaultLocalePath).toBe(false)\n })\n\n it('should request a path prefixed with non-default locale', async () => {\n const browser = await next.browser('/')\n let requestedNon", "middle": " any) => {\n if (new URL(request.url(), 'http://n').pathname === '/en/to-new') {\n requestedDefaultLocalePath = true\n }\n })\n\n await browser.elementByCss('#to-new').click().waitForElementByCss('#new')\n expe", "meta": {"filepath": "test/e2e/i18n-default-locale-redirect/i18n-default-locale-redirect.test.ts", "language": "typescript", "file_size": 1424, "cut_index": 524, "middle_length": 229}} {"prefix": "tTestSetup, type Playwright } from 'e2e-utils'\n\nconst getPathname = (url: string) => {\n const urlObj = new URL(url)\n return urlObj.pathname\n}\n\nconst createRequestsListener = async (browser: Playwright) => {\n // wait for network idle\n await browser.waitForIdleNetwork()\n\n let requests = []\n\n browser.on('request', (req) => {\n requests.push([req.url(), !!req.headers()['next-router-prefetch']])\n })\n\n await browser.refresh()\n\n return {\n getRequests: () => requests,\n clearRequests: () => {\n ", "suffix": "e {\n it('should avoid double-fetching when optimistic navigation fails', async () => {\n const browser = await next.browser('/foo')\n const { getRequests } = await createRequestsListener(browser)\n\n await browser.elementByCss('[href=\"/foo\"]'", "middle": "requests = []\n },\n }\n}\n\ndescribe('app-prefetch-false', () => {\n const { next, isNextDev } = nextTestSetup({\n files: __dirname,\n })\n\n if (isNextDev) {\n it.skip('should skip test in development mode', () => {})\n } els", "meta": {"filepath": "test/e2e/app-dir/app-prefetch-false/app-prefetch-false.test.ts", "language": "typescript", "file_size": 1255, "cut_index": 524, "middle_length": 229}} {"prefix": " readFixtureText,\n} from './utils'\n\ndescribe('metadata-files-static-output-root-route', () => {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n // Cache Components build fails when metadata files are inside a dynamic route.\n //\n // Route \"/dynamic/[id]\": Next.js encountered uncached or runtime data in `generateMetadata()`.\n //\n // This prevents the page from being prerendered, leading to a slower user experience.\n //\n // Ways to fix this:\n // - Use a static metadata export instead of", "suffix": " instant = false` to allow a blocking route\n //\n // Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata\n // Error occurred prerendering page \"/dynamic/[id]\". Read more: https://nextjs.org/docs/messages/prerender-error\n ", "middle": " `generateMetadata()`\n // - Cache the metadata with `\"use cache\"` in `generateMetadata()`\n // - Add a dynamic data access (e.g. `await connection()`) to the page to render it at request time\n // - Set `export const", "meta": {"filepath": "test/e2e/app-dir/metadata-static-file/metadata-static-file-root-route.test.ts", "language": "typescript", "file_size": 3085, "cut_index": 614, "middle_length": 229}} {"prefix": "\nimport { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'\nimport {\n SimpleSpanProcessor,\n SpanExporter,\n ReadableSpan,\n BasicTracerProvider,\n} from '@opentelemetry/sdk-trace-base'\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'\nimport {\n ExportResult,\n ExportResultCode,\n hrTimeToMicroseconds,\n} from '@opentelemetry/core'\n\nimport { SavedSpan } from './constants'\n\nconst serializeSpan = (span: ReadableSpan): SavedSpan => ({\n runtime: process.", "suffix": "oMicroseconds(span.duration),\n attributes: span.attributes,\n status: span.status,\n})\n\nclass TestExporter implements SpanExporter {\n constructor(private port: number) {}\n\n async export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResul", "middle": "env.NEXT_RUNTIME,\n traceId: span.spanContext().traceId,\n parentId: span.parentSpanId,\n name: span.name,\n id: span.spanContext().spanId,\n kind: span.kind,\n timestamp: hrTimeToMicroseconds(span.startTime),\n duration: hrTimeT", "meta": {"filepath": "test/e2e/app-dir/otel-parent-span-propagation/instrumentation.ts", "language": "typescript", "file_size": 2400, "cut_index": 563, "middle_length": 229}} {"prefix": "from 'e2e-utils'\nimport { check, renderViaHTTP } from 'next-test-utils'\nimport stripAnsi from 'strip-ansi'\n\ndescribe('typescript-auto-install', () => {\n const { next } = nextTestSetup({\n files: {\n 'pages/index.js': `\n export default function Page() {\n return

        hello world

        \n }\n `,\n },\n env: {\n // unset CI env as this skips the auto-install behavior\n // being tested\n CI: '',\n CIRCLECI: '',\n GITHUB_ACTIONS: '',\n CONTINUOUS_INTEGRATION", "suffix": " detect TypeScript being added and auto setup', async () => {\n const browser = await next.browser('/')\n const pageContent = await next.readFile('pages/index.js')\n\n await check(\n () => browser.eval('document.documentElement.innerHTML'),\n ", "middle": ": '',\n RUN_ID: '',\n BUILD_NUMBER: '',\n },\n dependencies: {},\n })\n\n it('should work', async () => {\n const html = await renderViaHTTP(next.url, '/')\n expect(html).toContain('hello world')\n })\n\n it('should", "meta": {"filepath": "test/development/typescript-auto-install/index.test.ts", "language": "typescript", "file_size": 1595, "cut_index": 537, "middle_length": 229}} {"prefix": "nder native module', () => {\n const { next } = nextTestSetup({\n files: {\n pages: new FileRef(path.join(__dirname, 'prerender-native-module/pages')),\n 'data.sqlite': new FileRef(\n path.join(__dirname, 'prerender-native-module/data.sqlite')\n ),\n },\n dependencies: {\n sqlite: '4.0.22',\n sqlite3: '5.0.2',\n },\n packageJson: {\n pnpm: {\n onlyBuiltDependencies: ['sqlite3'],\n },\n },\n })\n\n it('should render index correctly', async () => {\n const ", "suffix": "ld render /blog/first correctly', async () => {\n const browser = await next.browser('/blog/first')\n\n expect(await browser.elementByCss('#blog').text()).toBe('blog page')\n expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({\n ", "middle": "browser = await next.browser('/')\n expect(await browser.elementByCss('#index').text()).toBe('index page')\n expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({\n index: true,\n })\n })\n\n it('shou", "meta": {"filepath": "test/e2e/prerender-native-module.test.ts", "language": "typescript", "file_size": 3541, "cut_index": 614, "middle_length": 229}} {"prefix": "{ unstable_cache } from 'next/cache'\nimport { headers as nextHeaders, draftMode } from 'next/headers'\n\nconst getCachedValue = unstable_cache(\n async () => Math.random().toString(),\n ['middleware-cache-probe']\n)\n\n/**\n * @param {import('next/server').NextRequest} request\n */\nexport async function middleware(request) {\n const headersFromRequest = new Headers(request.headers)\n // It should be able to import and use `headers` inside middleware\n const headersFromNext = await nextHeaders()\n headersFromReques", "suffix": "rsFromRequest.get('x-from-client')\n ) {\n throw new Error('Expected headers from client to match')\n }\n\n if (request.nextUrl.searchParams.get('draft')) {\n ;(await draftMode()).enable()\n }\n\n const removeHeaders = request.nextUrl.searchParams.get('r", "middle": "t.set('x-from-middleware', 'hello-from-middleware')\n\n // make sure headers() from `next/headers` is behaving properly\n if (\n headersFromRequest.get('x-from-client') &&\n headersFromNext.get('x-from-client') !==\n heade", "meta": {"filepath": "test/e2e/app-dir/app-middleware/middleware.js", "language": "javascript", "file_size": 2910, "cut_index": 563, "middle_length": 229}} {"prefix": "import { createSandbox } from 'development-sandbox'\nimport path from 'path'\nimport { outdent } from 'outdent'\n\nconst middlewarePath = 'middleware.js'\nconst middlewareWarning = `A middleware can not alter response's body`\n\ndescribe('middlewares', () => {\n const { next } = nextTestSetup({\n files: new FileRef(\n path.join(__dirname, '..', 'acceptance', 'fixtures', 'default-template')\n ),\n skipStart: true,\n })\n\n it.each([\n {\n title: 'returning response with literal string',\n code: o", "suffix": "rt default function middleware() {\n return new Response(10);\n }\n `,\n },\n {\n title: 'returning response with JSON.stringify',\n code: outdent`\n export default function middleware() {\n return new Response(J", "middle": "utdent`\n export default function middleware() {\n return new Response('this is not allowed');\n }\n `,\n },\n {\n title: 'returning response with literal number',\n code: outdent`\n expo", "meta": {"filepath": "test/development/middleware-warnings/index.test.ts", "language": "typescript", "file_size": 2834, "cut_index": 563, "middle_length": 229}} {"prefix": "tTestSetup } from 'e2e-utils'\n\ndescribe('i18n-disallow-multiple-locales', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it.each([\n ['/non-existent'],\n ['/es/non-existent'],\n ['/first/non-existent'],\n ['/es/first/non-existent'],\n ['/first/second/non-existent'],\n ['/es/first/second/non-existent'],\n ])(\n 'should 404 properly for fallback: false non-prerendered %s',\n async (pathname) => {\n const res = await next.fetch(pathname)\n expect(res.status).to", "suffix": "th: '/first/second/third/fourth',\n page: '/[first]/[second]/[third]/[fourth]',\n },\n ])(\n 'should render properly for fallback: false prerendered $urlPath',\n async ({ urlPath, page }) => {\n const res = await next.fetch(urlPath)\n exp", "middle": "Be(404)\n }\n )\n\n it.each([\n { urlPath: '/first', page: '/[first]' },\n { urlPath: '/first/second', page: '/[first]/[second]' },\n { urlPath: '/first/second/third', page: '/[first]/[second]/[third]' },\n {\n urlPa", "meta": {"filepath": "test/e2e/i18n-fallback-collision/i18n-fallback-collision.test.ts", "language": "typescript", "file_size": 1343, "cut_index": 524, "middle_length": 229}} {"prefix": "ype Playwright } from 'e2e-utils'\nimport { check } from 'next-test-utils'\n\ndescribe('app a11y features', () => {\n const { next, skipped } = nextTestSetup({\n files: __dirname,\n packageJson: {},\n skipDeployment: true,\n })\n\n if (skipped) {\n return\n }\n\n describe('route announcer', () => {\n async function getAnnouncerContent(browser: Playwright) {\n return browser.eval(\n `document.getElementsByTagName('next-route-announcer')[0]?.shadowRoot.childNodes[0]?.innerHTML`\n )\n }\n\n ", "suffix": "ges', async () => {\n const browser = await next.browser('/page-with-h1')\n await browser.elementById('page-with-title').click()\n await check(() => getAnnouncerContent(browser), 'page-with-title')\n })\n\n it('should announce h1 changes', a", "middle": " it('should not announce the initital title', async () => {\n const browser = await next.browser('/page-with-h1')\n await check(() => getAnnouncerContent(browser), '')\n })\n\n it('should announce document.title chan", "meta": {"filepath": "test/e2e/app-dir/app-a11y/index.test.ts", "language": "typescript", "file_size": 1549, "cut_index": 537, "middle_length": 229}} {"prefix": "ierContext } from './internal-context'\n\nexport interface CacheIdentifier {}\nconst cacheById = new WeakMap()\n\nexport type DataCache = Map>\n\nfunction createDataCache(): DataCache {\n return new Map()\n}\n\nexport function useDataCache() {\n const id = use(CacheIdentifierContext)\n if (id === null) {\n throw new Error('Missing DataCacheProvider')\n }\n\n let cache = cacheById.get(id)\n if (!cache) {\n cacheById.set(id, (cache = createDataCache()))\n }\n retu", "suffix": "se): Promise {\n let promise = cache.get(key) as Promise | undefined\n if (!promise) {\n console.log('client-data-fetching-lib :: MISS', key)\n cache.set(key, (promise = func()))\n } else {\n console.log('client-data-", "middle": "rn {\n getOrLoad(key: string, func: () => Promi", "meta": {"filepath": "test/e2e/app-dir/instant-validation/client-data-fetching-lib/client.ts", "language": "typescript", "file_size": 959, "cut_index": 582, "middle_length": 52}} {"prefix": " { cacheLife } from 'next/cache'\nimport Link from 'next/link'\nimport { setTimeout } from 'timers/promises'\n\nexport function DebugLinks({ href }: { href: string }) {\n return (\n \n {href}{' '}\n \n [SPA]\n {' '}\n
        \n [MPA]\n \n \n )\n}\n\nexport async function uncachedIO() {\n await setTimeout(0)\n}\n\nexport async function cachedDelay(key: any) {\n 'use cache'\n ca", "suffix": "-render/work-unit-async-storage.external')\n const workUnitStore = workUnitAsyncStorage.getStore()!\n return (\n
        \n workUnitStore.type: {workUnitStore.type}\n {(() => {\n switch (workUnitStore.type) {\n case 'prerender':\n ", "middle": "cheLife('minutes')\n await setTimeout(1)\n}\n\nexport function DebugRenderKind() {\n const { workUnitAsyncStorage } =\n require('next/dist/server/app-render/work-unit-async-storage.external') as typeof import('next/dist/server/app", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/shared.tsx", "language": "tsx", "file_size": 1194, "cut_index": 518, "middle_length": 229}} {"prefix": " { ReactNode, Suspense } from 'react'\n\nexport default function RootLayout({ children }: { children: ReactNode }) {\n return (\n // We're mostly interested in checking client navigations,\n // so to avoid having to give each test case a valid static shell,\n // we put a Suspense above the body.\n Root suspense boundary...
        }>\n \n \n
        \n
        \n {children}\n \n \n Home{' '}\n \n
        \n \n
        \n
        \n
        \n )\n}\n\nasync function Now() {\n await connection()\n return Date.n", "middle": "tml>\n \n )\n}\n\nfunction Header() {\n re", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/layout.tsx", "language": "tsx", "file_size": 874, "cut_index": 559, "middle_length": 52}} {"prefix": "nd-params/123\" />\n \n
      • \n \n
      • \n
      • \n \n
      • \n
      • \n \n
      • \n
      • \n \n
      • \n ", "suffix": "
      • \n \n
      • \n
      • \n \n
      • \n
      • \n \n \n
      • \n
      • \n \n
      • \n ", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/page.tsx", "language": "tsx", "file_size": 10939, "cut_index": 921, "middle_length": 229}} {"prefix": "'\nimport { cookies } from 'next/headers'\nimport { connection } from 'next/server'\nimport { Suspense } from 'react'\n\nexport const unstable_instant = { level: 'experimental-error' }\nexport const unstable_prefetch = 'force-runtime'\n\n// Note that we're inside a root layout with suspense, so we skip the static shell\nexport async function generateViewport(): Promise {\n await connection()\n return {\n themeColor: 'aliceblue',\n }\n}\n\nexport default async function Page() {\n await cookies()\n return (\n ", "suffix": "iewport

        \n

        \n We also access dynamic data in the page itself, because a static page\n with a dynamic viewport is not allowed.\n

        \n \n \n \n
        \n )\n}\n\nasync function Dynamic(", "middle": "
        \n

        This page has a dynamic generateV", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/head/invalid-dynamic-viewport-in-runtime/page.tsx", "language": "tsx", "file_size": 896, "cut_index": 547, "middle_length": 52}} {"prefix": "rom 'next/server'\nimport { Suspense } from 'react'\n\nexport const unstable_instant = { level: 'experimental-error' }\nexport const unstable_prefetch = 'force-runtime'\n\nexport async function generateMetadata(): Promise {\n await connection()\n return {\n title: 'Blocked by connection',\n }\n}\n\nexport default async function Page() {\n await cookies()\n return (\n

        \n

        \n This page has a generateMetadata that accesses connection. It's\n runtime-prefetchable, but metadata doesn", "suffix": " We also access connection in the page itself, because a runtime page\n with dynamic metadata is not allowed.\n

        \n \n \n \n
        \n )\n}\n\nasync function Dynamic() {\n await connection()\n retur", "middle": "'t block, so it's fine.\n

        \n

        \n ", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/head/valid-dynamic-metadata-in-runtime/page.tsx", "language": "tsx", "file_size": 923, "cut_index": 606, "middle_length": 52}} {"prefix": "import { cookies } from 'next/headers'\n\n// This would be valid if it used a runtime prefetch (because then it wouldn't block navigation),\n// but it's static, so it's invalid. As an extra sanity check, we put a runtime prefetch on the\n// layout above, and that should not make this error go away.\nexport const unstable_instant = { level: 'experimental-error' }\n\nexport async function generateViewport(): Promise {\n await cookies()\n return {\n themeColor: 'aliceblue',\n }\n}\n\nexport default function ", "suffix": "s a runtime generateViewport

        \n

        \n We also access runtime data in the page itself, because a fully static\n page with a runtime vieport is not allowed.\n

        \n \n \n \n
        \n )\n", "middle": "Page() {\n return (\n
        \n

        This page ha", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/head/invalid-runtime-viewport-in-static/page.tsx", "language": "tsx", "file_size": 954, "cut_index": 582, "middle_length": 52}} {"prefix": "le_instant = {\n level: 'experimental-error',\n unstable_samples: [{ cookies: [], searchParams: { foo: 'bar' } }],\n}\nexport const unstable_prefetch = 'force-runtime'\n\nexport default async function Page({\n searchParams,\n}: {\n searchParams: Promise>\n}) {\n const search = await searchParams\n return (\n

        \n
        \n

        Params don't need a suspense boundary when runtime-prefetched:

        \n
        Search: {JSON.stringify(search)}
        \n ", "suffix": "nt does:

        \n Loading...
        }>\n \n \n
      \n
    \n )\n}\n\nasync function Dynamic() {\n await connection()\n return
    Dynamic content from page
    \n}\n", "middle": "
    \n\n
    \n

    But dynamic conte", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/runtime/valid-no-suspense-around-search-params/page.tsx", "language": "tsx", "file_size": 914, "cut_index": 606, "middle_length": 52}} {"prefix": " { Suspense } from 'react'\n\nexport const unstable_instant = {\n level: 'experimental-error',\n unstable_samples: [{ cookies: [], params: { param: '123' } }],\n}\nexport const unstable_prefetch = 'force-runtime'\n\nexport default async function Page({\n params,\n}: {\n params: Promise<{ param: string }>\n}) {\n const { param } = await params\n return (\n

    \n
    \n

    Params don't need a suspense boundary when runtime-prefetched:

    \n
    Param value: {param}
    \n ", "suffix": "nt does:

    \n Loading...
    }>\n \n \n
    \n
    \n )\n}\n\nasync function Dynamic() {\n await connection()\n return
    Dynamic content from page
    \n}\n", "middle": "
    \n\n
    \n

    But dynamic conte", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/runtime/valid-no-suspense-around-params/[param]/page.tsx", "language": "tsx", "file_size": 867, "cut_index": 559, "middle_length": 52}} {"prefix": "kies } from 'next/headers'\n\nexport const unstable_instant = { level: 'experimental-error' }\nexport const unstable_prefetch = 'force-runtime'\n\n// This page HAS runtime prefetch enabled. cookies() is passed as a promise\n// input to a public \"use cache\" function. The cache doesn't read the cookies\n// in its body — they're only part of the cache key. After the cache resolves,\n// Date.now() is sync IO that should error because we're in a\n// runtime-prefetchable segment where cookies() has resolved at EarlyRuntim", "suffix": "would\n// resolve later, and Date.now() would happen at the Runtime stage where\n// canSyncInterrupt returns false — missing the error.\n\nasync function cachedFn(cookiePromise: Promise) {\n 'use cache'\n // Intentionally not reading the cookie promise", "middle": "e.\n//\n// This test validates that the cache input encoding resolves in the correct\n// runtime stage (EarlyRuntime for prefetchable segments). If the cache input\n// abort signal incorrectly waited for the Runtime stage, the cache ", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input/page.tsx", "language": "tsx", "file_size": 1412, "cut_index": 524, "middle_length": 229}} {"prefix": "} from 'next/headers'\nimport { Suspense } from 'react'\n\n// This layout does NOT have runtime prefetch — it's a static segment.\n// The RuntimeContent component accesses cookies() then Date.now().\n// In a static prefetch the render would never get past cookies() so the\n// sync IO is unreachable. In a runtime prefetch, cookies() would resolve\n// but this layout is not runtime-prefetchable — only the child page is.\n// So the sync IO here should not error.\n\nasync function RuntimeContent() {\n await cookies()\n c", "suffix": " sync IO after cookies: {now}

    \n}\n\nexport default function StaticLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n
    \n Loading...

    }>\n \n
    \n
    \n ", "middle": "onst now = Date.now()\n return

    Static layout with", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/runtime/valid-sync-io-in-static-parent/layout.tsx", "language": "tsx", "file_size": 870, "cut_index": 529, "middle_length": 52}} {"prefix": "'next/headers'\nimport { connection } from 'next/server'\nimport { Suspense } from 'react'\n\nexport const unstable_instant = { level: 'experimental-error' }\nexport const unstable_prefetch = 'force-runtime'\n\nexport default async function Page() {\n return (\n

    \n
    \n

    Runtime content doesn't need a suspense boundary:

    \n \n
    \n\n
    \n

    But dynamic content does:

    \n Loading...
    }>\n \n <", "suffix": "
    \n \n )\n}\n\nasync function Runtime() {\n await cookies()\n return
    Runtime content from page
    \n}\n\nasync function Dynamic() {\n await connection()\n return
    Dynamic content from page\n ", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/runtime/suspense-around-dynamic/page.tsx", "language": "tsx", "file_size": 811, "cut_index": 536, "middle_length": 14}} {"prefix": "t { Suspense, type ReactNode } from 'react'\nimport { ErrorInSSR } from './client'\nimport { connection } from 'next/server'\n\n// Make sure that the holes from this layout aren't factored in for validation\n// (otherwise, we'd check a navigation into it from the root layout and fail)\nexport const unstable_instant = false\n\nexport default async function Layout({ children }: { children: ReactNode }) {\n await connection() // Prevent the error from failing the prerender in build\n return (\n <>\n
    \n ", "suffix": " This layout errors in SSR, and the errors is caught by a Suspense\n boundary, but it blocks the children slot so it prevents validation.\n

    \n \n {children}\n \n \n ", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/static/invalid-client-error-in-parent-blocks-children/layout.tsx", "language": "tsx", "file_size": 803, "cut_index": 517, "middle_length": 14}} {"prefix": "omPackage } from 'my-pkg'\nimport { connection } from 'next/server'\n\n// Make sure that the holes from this layout aren't factored in for validation\n// (otherwise, we'd check a navigation into it from the root layout and fail)\nexport const unstable_instant = false\n\nexport default async function Layout({ children }: { children: ReactNode }) {\n await connection() // Prevent the error from failing the prerender in build\n return (\n <>\n
    \n

    \n This layout errors in SSR, and the error", "suffix": " blocks the children slot so it prevents validation.\n The error is thrown in a component from node_modules, which means that\n the component is ignore-listed away.\n

    \n \n {children}", "middle": "s is caught by a Suspense\n boundary, but it", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/static/invalid-error-in-node-modules-blocks-children/layout.tsx", "language": "tsx", "file_size": 962, "cut_index": 582, "middle_length": 52}} {"prefix": "ype { ReactNode } from 'react'\nimport { LazyClientWrapperWithNoSSR } from './lazy-client'\nimport { connection } from 'next/server'\n\n// Make sure that the holes from this layout aren't factored in for validation\n// (otherwise, we'd check a navigation into it from the root layout and fail)\nexport const unstable_instant = false\n\nexport default async function Layout({ children }: { children: ReactNode }) {\n await connection() // Prevent the error from failing the prerender in build\n return (\n <>\n \n {children}\n
    \n ", "middle": ">\n

    \n This layout renders a compon", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/static/invalid-csr-bailout-blocks-children/layout.tsx", "language": "tsx", "file_size": 835, "cut_index": 520, "middle_length": 52}} {"prefix": "import { cookies } from 'next/headers'\nimport { connection } from 'next/server'\nimport { Suspense } from 'react'\n\nexport const unstable_instant = { level: 'experimental-error' }\n\nexport default async function Page() {\n return (\n

    \n

    \n This page wraps all runtime/dynamic components in suspense, so it\n wouldn't block a navigation and should pass validation.\n

    \n
    \n

    Runtime content with a suspense boundary

    \n Loading...\n
    \n )\n}\n\nasync function Runtime() {\n await cookies()\n return
    Runtime content from page
    \n}\n\nasync function Dynamic() {\n await connection()\n return
    Dynamic content from page}>\n \n \n
    \n\n
    \n

    Dynamic content with a suspense boundary

    \n Loading...
    }>\n \n \n ", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/static/suspense-around-dynamic/page.tsx", "language": "tsx", "file_size": 1001, "cut_index": 512, "middle_length": 229}} {"prefix": "rt { Suspense, type ReactNode } from 'react'\nimport { ErrorInSSR } from './client'\nimport { connection } from 'next/server'\n\n// Make sure that the holes from this layout aren't factored in for validation\n// (otherwise, we'd check a navigation into it from the root layout and fail)\nexport const unstable_instant = false\n\nexport default async function Layout({ children }: { children: ReactNode }) {\n await connection() // Prevent the error from failing the prerender in build\n return (\n <>\n
    \n ", "suffix": "error is wrapped in Suspense and\n does not block the children slot, so it does not prevent us from\n validating the page.\n

    \n \n \n \n {children}\n
    \n \n", "middle": "

    \n This layout errors in SSR, but the ", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/static/valid-client-error-in-parent-does-not-block-validation/layout.tsx", "language": "tsx", "file_size": 830, "cut_index": 516, "middle_length": 52}} {"prefix": "ort { cookies } from 'next/headers'\nimport { connection } from 'next/server'\n\nexport const unstable_instant = { level: 'experimental-error' }\n\nexport default async function Page() {\n return (\n

    \n

    \n This page doesn't wrap runtime/dynamic components in suspense, but it\n has a loading.tsx above it. However, the page is inside a route group\n and the loading.tsx is on the parent URL segment. Validation considers\n the route group as a potential shared boundary where th", "suffix": "y report an error.\n

    \n
    \n \n
    \n
    \n \n
    \n
    \n )\n}\n\nasync function Runtime() {\n await cookies()\n return
    Runtime content from page
    \n}\n\nas", "middle": "e loading.tsx\n Suspense would already be revealed. In a more advanced system we would\n analyze siblings of the route group to determine if such a navigation is\n actually possible, but for now we conservativel", "meta": {"filepath": "test/e2e/app-dir/instant-validation/app/suspense-in-root/static/invalid-loading-above-route-group/(group)/page.tsx", "language": "tsx", "file_size": 1115, "cut_index": 515, "middle_length": 229}} {"prefix": "\n files: __dirname,\n skipDeployment: true,\n })\n if (skipped) return\n\n // Recursively read all .js files in a directory\n function getAllServerFiles(dir: string): string[] {\n const results: string[] = []\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true })\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name)\n if (entry.isDirectory()) {\n results.push(...getAllServerFiles(fullPath))\n } else if (entry.name.endsWith('.", "suffix": "t.testDir, '.next/server')\n const files = getAllServerFiles(serverDir)\n const contents = await Promise.all(\n files.map((f) => fs.promises.readFile(f, 'utf8'))\n )\n return contents.join('\\n')\n }\n\n // Verify that each page renders correctly", "middle": "js')) {\n results.push(fullPath)\n }\n }\n } catch {\n // directory doesn't exist\n }\n return results\n }\n\n async function getAllServerContent(): Promise {\n const serverDir = path.join(nex", "meta": {"filepath": "test/e2e/app-dir/dynamic-import-tree-shaking/dynamic-import-tree-shaking.test.ts", "language": "typescript", "file_size": 8590, "cut_index": 716, "middle_length": 229}} {"prefix": "assetPrefix', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n nextConfig: {\n assetPrefix: 'https://example.vercel.sh/',\n },\n })\n\n it('bundles should return 200 on served assetPrefix', async () => {\n const $ = await next.render$('/')\n\n let bundles = []\n for (const script of $('script').toArray()) {\n const { src } = script.attribs\n if (\n src?.includes('https://example.vercel.sh/_next/static') ||\n src?.includes('https://example.vercel.sh/_next/sta", "suffix": " }\n }\n\n expect(bundles.length).toBeGreaterThan(0)\n\n for (const src of bundles) {\n // Remove hostname to check if pathname is still used for serving the bundles\n const bundlePathWithoutHost = decodeURI(new URL(src).href)\n const ", "middle": "tic/immutable')\n ) {\n bundles.push(src)\n", "meta": {"filepath": "test/e2e/app-dir/asset-prefix-absolute/asset-prefix-absolute-no-path.test.ts", "language": "typescript", "file_size": 989, "cut_index": 582, "middle_length": 52}} {"prefix": "ort { nextTestSetup } from 'e2e-utils'\n\ndescribe('app-dir absolute assetPrefix', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n nextConfig: {\n assetPrefix: 'https://example.vercel.sh/custom-asset-prefix',\n },\n })\n\n it('bundles should return 200 on served assetPrefix', async () => {\n const $ = await next.render$('/')\n\n let bundles = []\n for (const script of $('script').toArray()) {\n const { src } = script.attribs\n if (\n src?.startsWith(\n 'htt", "suffix": "\n }\n\n expect(bundles.length).toBeGreaterThan(0)\n\n for (const src of bundles) {\n // Remove hostname to check if pathname is still used for serving the bundles\n const bundlePathWithoutHost = decodeURI(new URL(src).href)\n const { statu", "middle": "ps://example.vercel.sh/custom-asset-prefix/_next/static'\n ) ||\n src?.startsWith(\n 'https://example.vercel.sh/custom-asset-prefix/_next/static/immutable'\n )\n ) {\n bundles.push(src)\n }", "meta": {"filepath": "test/e2e/app-dir/asset-prefix-absolute/asset-prefix-absolute.test.ts", "language": "typescript", "file_size": 1092, "cut_index": 515, "middle_length": 229}} {"prefix": "r$(\n '/top-level?foo=foosearch',\n {},\n {\n headers: {\n fooheader: 'foo header value',\n cookie: 'foocookie=foo cookie value',\n },\n }\n )\n if (isNextDev) {\n // in dev we expect the entire page to be rendered at runtime\n expect($('#layout').text()).toBe('at runtime')\n expect($('#page').text()).toBe('at runtime')\n } else if (process.env.__NEXT_CACHE_COMPONENTS) {\n // in PPR we expect the shell to be rendered at build and the page to ", "suffix": " expect($('#layout').text()).toBe('at runtime')\n expect($('#page').text()).toBe('at runtime')\n }\n\n expect($('#headers .fooheader').text()).toBe('foo header value')\n expect($('#cookies .foocookie').text()).toBe('foo cookie value')\n expect($", "middle": "be rendered at runtime\n expect($('#layout').text()).toBe('at buildtime')\n expect($('#page').text()).toBe('at runtime')\n } else {\n // in static generation we expect the entire page to be rendered at runtime\n ", "meta": {"filepath": "test/e2e/app-dir/dynamic-data/dynamic-data.test.ts", "language": "typescript", "file_size": 15856, "cut_index": 921, "middle_length": 229}} {"prefix": "aders'\nimport { unstable_cache as cache } from 'next/cache'\n\nconst cookies = cache(() => nextCookies())\n\nexport default async function Page({ searchParams }) {\n return (\n
    \n
    \n This example uses `cookies()` but is configured with `dynamic = 'error'`\n which should cause the page to fail to build\n
    \n
    \n

    cookies

    \n {(await cookies()).getAll().map((cookie) => {\n const key = cookie.name\n let value = ", "suffix": " value = value.slice(0, 10) + '...'\n }\n return (\n
    \n

    {key}

    \n
    {value}
    \n
    \n )\n })}\n
    \n
    \n ", "middle": "cookie.value\n\n if (key === 'userCache') {\n ", "meta": {"filepath": "test/e2e/app-dir/dynamic-data/fixtures/cache-scoped/app/cookies/page.js", "language": "javascript", "file_size": 871, "cut_index": 559, "middle_length": 52}} {"prefix": " { headers as nextHeaders } from 'next/headers'\nimport { unstable_cache as cache } from 'next/cache'\n\nconst headers = cache(() => nextHeaders())\n\nexport default async function Page() {\n return (\n
    \n
    \n This example uses `headers()` but is configured with `dynamic = 'error'`\n which should cause the page to fail to build\n
    \n
    \n

    headers

    \n {Array.from(await headers())\n .entries()\n .map(([key, value", "suffix": " if (key === 'cookie') return null\n return (\n
    \n

    {key}

    \n
    {value}
    \n
    \n )\n })}\n
    \n
    \n )\n}\n", "middle": "]) => {\n ", "meta": {"filepath": "test/e2e/app-dir/dynamic-data/fixtures/cache-scoped/app/headers/page.js", "language": "javascript", "file_size": 788, "cut_index": 518, "middle_length": 14}} {"prefix": " } from 'next/headers'\nimport { connection } from 'next/server'\n\nimport { PageSentinel } from '../getSentinelValue'\n\nexport const dynamic = 'force-static'\n\nexport default async function Page({ searchParams }) {\n await connection()\n return (\n
    \n \n
    \n This example uses headers/cookies/connection/searchParams directly in a\n Page configured with `dynamic = 'force-static'`. This should cause the\n page to always statically render but without exposing", "suffix": "
    \n

    {key}

    \n
    {value}
    \n
    \n )\n })}\n
    \n
    \n

    cookies

    \n {(await cookies()).getAll().map((coo", "middle": " dynamic data\n
    \n
    \n

    headers

    \n {Array.from((await headers()).entries()).map(([key, value]) => {\n if (key === 'cookie') return null\n return (\n ", "meta": {"filepath": "test/e2e/app-dir/dynamic-data/fixtures/main/app/force-static/page.js", "language": "javascript", "file_size": 1717, "cut_index": 537, "middle_length": 229}} {"prefix": "use client'\n\nimport { PageSentinel } from '../getSentinelValue'\n\nexport default async function Page({ searchParams }) {\n return (\n
    \n \n
    \n This example uses headers/cookies/searchParams directly in a Page\n configured with `dynamic = 'force-dynamic'`. This should cause the page\n to always render dynamically regardless of dynamic APIs used\n
    \n
    \n

    headers

    \n

    This is a client Page so `h", "suffix": "

    searchParams

    \n {Object.entries(await searchParams).map(([key, value]) => {\n return (\n
    \n

    {key}

    \n
    {value}
    \n
    \n )\n ", "middle": "eaders()` is not available

    \n
    \n
    \n

    cookies

    {' '}\n

    This is a client Page so `cookies()` is not available

    \n
    \n
    \n ", "meta": {"filepath": "test/e2e/app-dir/dynamic-data/fixtures/main/app/client-page/page.js", "language": "javascript", "file_size": 1040, "cut_index": 513, "middle_length": 229}} {"prefix": " } from 'next/headers'\nimport { connection } from 'next/server'\n\nimport { PageSentinel } from '../getSentinelValue'\n\nexport default async function Page({ searchParams }) {\n await connection()\n return (\n
    \n \n
    \n This example uses headers/cookies/searchParams directly. In static\n generation we'd expect this to bail out to dynamic. In PPR we expect\n this to partially render the root layout only\n
    \n
    \n ", "suffix": " className={key}>{value}\n
    \n )\n })}\n
    \n
    \n

    cookies

    \n {(await cookies()).getAll().map((cookie) => {\n const key = cookie.name\n let value = c", "middle": "

    headers

    \n {Array.from((await headers()).entries()).map(([key, value]) => {\n if (key === 'cookie') return null\n return (\n
    \n

    {key}

    \n \n \n
    \n This example uses headers/cookies/connection/searchParams directly in a\n Page configured with `dynamic = 'force-dynamic'`. This should cause the\n page to always render dynamically regardless of dyn", "suffix": "
    \n

    {key}

    \n
    {value}
    \n
    \n )\n })}\n
    \n
    \n

    cookies

    \n {(await cookies()).getAll().map((co", "middle": "amic APIs used\n
    \n
    \n

    headers

    \n {Array.from((await headers()).entries()).map(([key, value]) => {\n if (key === 'cookie') return null\n return (\n ", "meta": {"filepath": "test/e2e/app-dir/dynamic-data/fixtures/main/app/force-dynamic/page.js", "language": "javascript", "file_size": 1718, "cut_index": 537, "middle_length": 229}} {"prefix": "tal-not-affect-parent', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should not affect parent display', async () => {\n const browser = await next.browser('/')\n const rect = await browser.eval(\n // https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect\n `document.querySelector('#div2').getBoundingClientRect()`\n )\n // Since the has `space-between`, if the shadow root takes up\n // the space, the x of #div2 will be 100 as is", "suffix": "not take up the space, as the total width of\n // the is 300 and as is a space-between, the #div2 will be placed\n // at the end of the and the x will be 200.\n\n // Before: <#div1 100> <#div2 100> \n // After: <#div", "middle": " the width of #div1.\n // If the shadow root does ", "meta": {"filepath": "test/e2e/app-dir/dev-overlay/portal-not-affect-parent/portal-not-affect-parent.test.ts", "language": "typescript", "file_size": 984, "cut_index": 582, "middle_length": 52}} {"prefix": "s } from 'child_process'\nimport { isNextDev, isNextStart, nextTestSetup } from 'e2e-utils'\nimport { findPort, killApp, retry } from 'next-test-utils'\n\ndescribe('interception-routes-output-export', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n skipStart: true,\n // Vercel deployment fails to build/deploy this fixture in CI; skip in deploy mode.\n skipDeployment: true,\n })\n\n it('should error when using interception routes with static export', async () => {\n if (isNextStart) {\n ", "suffix": " let stderr = ''\n let child: ChildProcess | undefined\n const port = await findPort()\n const exit = next.runCommand(['dev', '-p', String(port)], {\n onStderr(msg) {\n stderr += msg || ''\n },\n instance: (p) => {\n ", "middle": " const { exitCode, cliOutput } = await next.build()\n expect(cliOutput).toContain(\n 'Intercepting routes are not supported with static export.'\n )\n expect(exitCode).toBe(1)\n } else if (isNextDev) {\n ", "meta": {"filepath": "test/e2e/app-dir/interception-routes-output-export/interception-routes-output-export.test.ts", "language": "typescript", "file_size": 1540, "cut_index": 537, "middle_length": 229}} {"prefix": " { nextTestSetup } from 'e2e-utils'\n\ndescribe('with-exported-function-config', () => {\n const { next, isNextStart } = nextTestSetup({\n files: __dirname,\n })\n\n it('should have correct values in function config manifest', async () => {\n if (isNextStart) {\n const functionsConfigManifest = JSON.parse(\n await next.readFile('.next/server/functions-config-manifest.json')\n )\n\n expect(functionsConfigManifest).toEqual({\n functions: {\n '/api/page-route': {\n max", "suffix": " },\n '/app-route-edge': {\n maxDuration: 2,\n },\n '/app-ssr': {\n maxDuration: 3,\n },\n '/app-ssr-edge': {\n maxDuration: 4,\n },\n '/page': {\n maxDuratio", "middle": "Duration: 1,\n },\n '/app-layout': {\n maxDuration: 1,\n },\n '/app-layout/inner': {\n maxDuration: 2,\n },\n '/app-route': {\n maxDuration: 1,\n ", "meta": {"filepath": "test/e2e/app-dir/with-exported-function-config/with-exported-function-config.test.ts", "language": "typescript", "file_size": 1142, "cut_index": 518, "middle_length": 229}} {"prefix": "import { nextTestSetup } from 'e2e-utils'\n\ndescribe('resuming-head-runtime-search-param', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should not show resumable slots error when using runtime search params', async () => {\n const browser = await next.browser('/?foo=bar&test=123')\n\n // Check that the page renders correctly\n await browser.waitForElementByCss('p')\n const text = await browser.elementByCss('p').text()\n expect(text).toContain('hello world')\n\n // Wa", "suffix": "le')\n\n // Check server logs for the specific error message\n expect(next.cliOutput).not.toContain(\n \"Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering.\"\n )\n })\n}", "middle": "it for dynamic content to load (it's rendered inside the first p element)\n await browser.waitForElementByCss('p p')\n const dynamicText = await browser.elementByCss('p p').text()\n expect(dynamicText).toContain('Dynamic Ho", "meta": {"filepath": "test/e2e/app-dir/resuming-head-runtime-search-param/resuming-head-runtime-search-param.test.ts", "language": "typescript", "file_size": 999, "cut_index": 512, "middle_length": 229}} {"prefix": "lient'\n\nimport { useState } from 'react'\nimport { streamData } from './actions'\n\nexport default function Page() {\n const [chunks, setChunks] = useState(null)\n const [isStreaming, setIsStreaming] = useState(false)\n\n const handleClick = async () => {\n setChunks(null)\n setIsStreaming(true)\n\n const stream = await streamData(window.location.origin)\n const reader = stream.getReader()\n const decoder = new TextDecoder()\n\n try {\n while (true) {\n const { done, value }", "suffix": "der.releaseLock()\n setIsStreaming(false)\n }\n }\n\n return (\n
    \n \n\n {chunks && (\n ", "middle": " = await reader.read()\n if (done) {\n break\n }\n const chunk = decoder.decode(value, { stream: true })\n setChunks((prev) => (prev ? [...prev, chunk] : [chunk]))\n }\n } finally {\n rea", "meta": {"filepath": "test/e2e/app-dir/actions-streaming/app/readable-stream/page.tsx", "language": "tsx", "file_size": 1234, "cut_index": 518, "middle_length": 229}} {"prefix": "['--experimental-build-mode', 'compile'] })\n })\n afterEach(async () => {\n await next.stop()\n })\n } else {\n beforeAll(async () => {\n await next.start()\n })\n }\n\n let currentCliOutputIndex = 0\n beforeEach(() => {\n currentCliOutputIndex = next.cliOutput.length\n })\n\n function getCliOutputSinceMark(): string {\n if (next.cliOutput.length < currentCliOutputIndex) {\n currentCliOutputIndex = 0\n }\n return next.cliOutput.slice(currentCliOutputIndex)\n }\n\n const prerender", "suffix": "LIDATION_ERRORS_WAIT: Parameters[1] = {\n waitInMs: 500,\n }\n\n async function expectNoDevValidationErrors(\n browser: Playwright,\n url: string\n ): Promise {\n await waitForValidation(url, getCliOutputSinceMark)\n", "middle": " = async (pathname: string) => {\n const args = [\n '--experimental-build-mode',\n 'generate',\n '--debug-build-paths',\n `app${pathname}/page.tsx`,\n ]\n return await next.build({ args })\n }\n\n const NO_VA", "meta": {"filepath": "test/e2e/app-dir/instant-validation/instant-validation-parallel-slots.test.ts", "language": "typescript", "file_size": 33460, "cut_index": 1331, "middle_length": 229}} {"prefix": "tion.\n\n \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` accessed outside of \\`\\` prevents the route from being prerendered or the navigation from being instant, leading to a slower user experience.\n\n Ways to fix this:\n - Provide a placeholder with \\`\\` around the data access\n - If the runtime data is \\`params\\` and they're known, prerender them with \\`generateStaticParams\\`\n - Set \\`export const instant = false\\` ", "suffix": "idation failed for route \"/suspense-in-root/static/missing-suspense-around-runtime\".\n To get a more detailed stack trace and pinpoint the issue, try one of the following:\n - Start the app in development mode by running \\`next dev\\`, then ", "middle": "to allow a blocking route\n\n Learn more: https://nextjs.org/docs/messages/blocking-route\n at body ()\n at html ()\n at a ()\n Build-time instant val", "meta": {"filepath": "test/e2e/app-dir/instant-validation/instant-validation.test.ts", "language": "typescript", "file_size": 190702, "cut_index": 7068, "middle_length": 229}} {"prefix": "uspense } from 'react'\n\nexport default async function Layout({\n children,\n params,\n}: {\n children: React.ReactNode\n params: Promise<{\n layoutPaddingWidth: string\n layoutPaddingHeight: string\n pageWidth: string\n pageHeight: string\n }>\n}) {\n const { layoutPaddingHeight, layoutPaddingWidth, pageWidth, pageHeight } =\n await params\n return (\n \n loading...
    }>\n {children}\n {\n const { next, skipped } = nextTestSetup({\n files: __dirname,\n // No access to runtime logs when deployed.\n skipDeployment: true,\n })\n\n if (skipped) {\n return\n }\n\n it('should not call server actions with unused arguments', async () => {\n const browser = await next.browser('/')\n const cliOutputLength = next.cliOutput.length\n await browser.elementById('action-button').click()\n\n await retry(async () => {\n const actionLog = next.cliOutp", "suffix": "n')\n .find((line) => line.includes('Action called'))\n\n // We expect only 1 argument because the click event from the onClick\n // handler should be omitted as an unused argument.\n expect(actionLog).toBe('Action called with value: 42 (t", "middle": "ut\n .slice(cliOutputLength)\n .split('\\", "meta": {"filepath": "test/e2e/app-dir/actions-unused-args/actions-unused-args.test.ts", "language": "typescript", "file_size": 945, "cut_index": 606, "middle_length": 52}} {"prefix": "iousLogs = () => {\n currentCliOutputIndex = next.cliOutput.length\n }\n\n const getLogs = () => {\n return next.cliOutput.slice(currentCliOutputIndex)\n }\n\n beforeEach(() => {\n ignorePreviousLogs()\n })\n\n let buildLogs: string\n beforeAll(async () => {\n if (!isNextDev) {\n await next.build()\n buildLogs = next.cliOutput\n } else {\n buildLogs = '(no build logs in dev)'\n }\n await next.start()\n })\n\n describe('request APIs inside after()', () => {\n // TODO(after): test unaw", "suffix": "'cannot be called in a dynamic page', async () => {\n const path = '/request-apis/page-dynamic'\n await next.render(path)\n await retry(() => {\n const logs = getLogs()\n\n expect(logs).not.toContain(`[${path}] headers(): ok`)\n ", "middle": "aited calls, like this\n //\n // export default function Page() {\n // const promise = headers()\n // after(async () => {\n // const headerStore = await promise\n // })\n // return null\n // }\n\n it(", "meta": {"filepath": "test/e2e/app-dir/next-after-app-api-usage/index.test.ts", "language": "typescript", "file_size": 10638, "cut_index": 921, "middle_length": 229}} {"prefix": "kies, headers } from 'next/headers'\nimport { after, connection } from 'next/server'\n\nexport function testRequestAPIs(/** @type {string} */ route) {\n after(async () => {\n try {\n await headers()\n console.log(`[${route}] headers(): ok`)\n } catch (err) {\n console.error(`[${route}] headers(): error:`, err)\n }\n })\n\n after(() =>\n after(async () => {\n try {\n await headers()\n console.log(`[${route}] nested headers(): ok`)\n } catch (err) {\n console.error(`[", "suffix": "r:`, err)\n }\n })\n\n after(() =>\n after(async () => {\n try {\n await cookies()\n console.log(`[${route}] nested cookies(): ok`)\n } catch (err) {\n console.error(`[${route}] nested cookies(): error:`, err)\n }\n })\n ", "middle": "${route}] nested headers(): error:`, err)\n }\n })\n )\n\n after(async () => {\n try {\n await cookies()\n console.log(`[${route}] cookies(): ok`)\n } catch (err) {\n console.error(`[${route}] cookies(): erro", "meta": {"filepath": "test/e2e/app-dir/next-after-app-api-usage/app/request-apis/helpers.js", "language": "javascript", "file_size": 1457, "cut_index": 524, "middle_length": 229}} {"prefix": "{\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should match default and dynamic segment paths before catch-all', async () => {\n let browser = await next.browser('/en/nested')\n\n // we have a top-level catch-all but the /nested dir doesn't have a default/page until the /[foo]/[bar] segment\n // so we expect the top-level catch-all to render\n expect(await browser.elementById('children').text()).toBe(\n '/[locale]/[[...catchAll]]/page.tsx'\n )\n\n browser = await next.b", "suffix": " '/[locale]/nested/[foo]/[bar]/default.tsx'\n )\n\n // we expect the slot0 to match since there's a page defined at this segment\n expect(await browser.elementById('slot0').text()).toBe(\n '/[locale]/nested/[foo]/[bar]/@slot0/page.tsx'\n )\n\n ", "middle": "rowser('/en/nested/foo/bar')\n\n // we're now at the /[foo]/[bar] segment, so we expect the matched page to be the default (since there's no page defined)\n expect(await browser.elementById('nested-children').text()).toBe(\n ", "meta": {"filepath": "test/e2e/app-dir/parallel-routes-catchall-dynamic-segment/parallel-routes-catchall-dynamic-segment.test.ts", "language": "typescript", "file_size": 3683, "cut_index": 614, "middle_length": 229}} {"prefix": " { NextResponse } from 'next/server'\n\nexport async function middleware(request) {\n if (\n request.nextUrl.pathname.includes('payment') &&\n !request.nextUrl.pathname.includes('whoops')\n ) {\n if (request.nextUrl.searchParams.has('redirect')) {\n return NextResponse.redirect(new URL('/payment/whoops', request.url))\n }\n return NextResponse.rewrite(new URL('/payment/whoops', request.url))\n }\n if (\n request.nextUrl.pathname.includes('anotherRoute') &&\n !request.nextUrl.pathname.include", "suffix": "est.url))\n }\n}\n\nexport const config = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - favicon.i", "middle": "s('whoops')\n ) {\n if (request.nextUrl.searchParams.has('redirect')) {\n return NextResponse.redirect(new URL('/anotherRoute/whoops', request.url))\n }\n return NextResponse.rewrite(new URL('/anotherRoute/whoops', requ", "meta": {"filepath": "test/e2e/app-dir/middleware-rewrite-catchall-priority-with-parallel-route/middleware.js", "language": "javascript", "file_size": 1143, "cut_index": 518, "middle_length": 229}} {"prefix": "v jest */\nimport { nextTestSetup } from 'e2e-utils'\nimport {\n waitForRedbox,\n getRedboxDescription,\n} from '../../../../lib/next-test-utils'\n\ndescribe('after() in generateStaticParams - thrown errors', () => {\n const { next, skipped, isNextDev } = nextTestSetup({\n files: __dirname,\n skipStart: true,\n skipDeployment: true, // can't access build errors in deploy tests\n })\n\n if (skipped) return\n\n if (isNextDev) {\n it('shows the error overlay if an error is thrown inside after', async () => {\n", "suffix": "y cool error thrown inside after on route \"${route}\"`\n )\n })\n } else {\n it('fails the build if an error is thrown inside after', async () => {\n const buildResult = await next.build()\n expect(buildResult?.exitCode).toBe(1)\n\n const", "middle": " await next.start()\n const browser = await next.browser('/callback/1')\n await waitForRedbox(browser)\n const route = '/callback/[myParam]'\n expect(await getRedboxDescription(browser)).toContain(\n `M", "meta": {"filepath": "test/e2e/app-dir/next-after-app-static/generate-static-params-error/index.test.ts", "language": "typescript", "file_size": 1265, "cut_index": 524, "middle_length": 229}} {"prefix": "etup } from 'e2e-utils'\nimport * as Log from './utils/log'\nimport { setTimeout } from 'timers/promises'\n\n// This test relies on next.build() so it can't work in dev mode.\nconst _describe = isNextDev ? describe.skip : describe\n\n_describe('after() in static pages', () => {\n const { next, skipped } = nextTestSetup({\n files: __dirname,\n skipDeployment: true, // reading CLI logs to observe after\n skipStart: true,\n })\n\n if (skipped) return\n\n let currentCliOutputIndex = 0\n beforeEach(() => {\n curr", "suffix": "s\n currentCliOutputIndex = 0\n }\n return next.cliOutput.slice(currentCliOutputIndex)\n }\n\n const resetLogs = () => {\n currentCliOutputIndex = next.cliOutput.length\n }\n\n it('runs after during build', async () => {\n const buildResult = awa", "middle": "entCliOutputIndex = next.cliOutput.length\n })\n\n const getLogs = () => {\n if (next.cliOutput.length < currentCliOutputIndex) {\n // cliOutput shrank since we started the test, so something (like a `sandbox`) reset the log", "meta": {"filepath": "test/e2e/app-dir/next-after-app-static/build-time/build-time.test.ts", "language": "typescript", "file_size": 2230, "cut_index": 563, "middle_length": 229}} {"prefix": "('TypeScript type expressions in route segment config', () => {\n const { next, isNextStart } = nextTestSetup({\n files: __dirname,\n skipDeployment: true,\n })\n\n describe('app directory', () => {\n it('should pick up maxDuration declared with `as` type assertion', async () => {\n const $ = await next.render$('/as')\n expect($('main').text()).toBe('hello')\n })\n\n it('should pick up maxDuration declared with `as const` assertion', async () => {\n const $ = await next.render$('/as-cons", "suffix": " })\n })\n\n describe('pages directory', () => {\n it('should pick up maxDuration from config object declared with `as`', async () => {\n const $ = await next.render$('/config-as')\n expect($('main').text()).toBe('hello')\n })\n\n it('should ", "middle": "t')\n expect($('main').text()).toBe('hello')\n })\n\n it('should pick up maxDuration declared with `satisfies`', async () => {\n const $ = await next.render$('/satisfies')\n expect($('main').text()).toBe('hello')\n ", "meta": {"filepath": "test/e2e/app-dir/segment-config-ts/segment-config-ts.test.ts", "language": "typescript", "file_size": 2229, "cut_index": 563, "middle_length": 229}} {"prefix": "tTestSetup } from 'e2e-utils'\n\n// CSS data urls are only support in Turbopack\n;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(\n 'css-modules-data-urls',\n () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should apply rsc class name from data url correctly', async () => {\n const browser = await next.browser('/')\n\n const clientElementClass =\n (await browser.elementByCss('#client').getAttribute('class')) || ''\n\n expect(clientElementClass).n", "suffix": "ss('font-weight')\n\n expect(rscElement).toBe('700')\n })\n\n it('should apply client class name from data url correctly', async () => {\n const browser = await next.browser('/')\n\n const clientElementClass =\n (await browser.elementByC", "middle": "ot.toBe('')\n })\n\n it('should apply rsc styles from data url correctly', async () => {\n const browser = await next.browser('/')\n\n const rscElement = await browser\n .elementByCss('#rsc')\n .getComputedC", "meta": {"filepath": "test/e2e/app-dir/css-modules-data-urls/css-modules-data-urls.test.ts", "language": "typescript", "file_size": 1397, "cut_index": 524, "middle_length": 229}} {"prefix": "check } from 'next-test-utils'\n\ndescribe('interception-middleware-rewrite', () => {\n const { next, skipped } = nextTestSetup({\n files: __dirname,\n // TODO: remove after deployment handling is updated\n skipDeployment: true,\n })\n\n if (skipped) {\n return\n }\n\n it('should support intercepting routes with a middleware rewrite', async () => {\n const browser = await next.browser('/')\n\n await check(() => browser.elementByCss('#children').text(), 'root')\n\n await check(\n () =>\n br", "suffix": " 'not intercepted'\n )\n\n await check(() => browser.elementByCss('#modal').text(), 'default')\n })\n\n it('should continue to work after using browser back button and following another intercepting route', async () => {\n const browser = await nex", "middle": "owser\n .elementByCss('[href=\"/feed\"]')\n .click()\n .elementByCss('#modal')\n .text(),\n 'intercepted'\n )\n\n await check(\n () => browser.refresh().elementByCss('#children').text(),\n ", "meta": {"filepath": "test/e2e/app-dir/interception-middleware-rewrite/interception-middleware-rewrite.test.ts", "language": "typescript", "file_size": 2643, "cut_index": 563, "middle_length": 229}} {"prefix": "import { nextTestSetup } from 'e2e-utils'\n\ndescribe('next-image-src-with-query-without-local-patterns', () => {\n const { next, isNextDev, skipped } = nextTestSetup({\n files: __dirname,\n skipStart: true,\n skipDeployment: true,\n })\n\n if (skipped) {\n return\n }\n\n it('should throw error for relative image with query without localPatterns', async () => {\n if (isNextDev) {\n await next.start()\n await next.browser('/')\n expect(next.cliOutput).toContain(\n 'Image with src \"/te", "suffix": "build()\n expect(cliOutput).toContain(\n 'Image with src \"/test.png?v=1\" is using a query string which is not configured in images.localPatterns.\\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'\n )\n }\n ", "middle": "st.png?v=1\" is using a query string which is not configured in images.localPatterns.\\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'\n )\n } else {\n const { cliOutput } = await next.", "meta": {"filepath": "test/e2e/app-dir/next-image-src-with-query-without-local-patterns/next-image-src-with-query-without-local-patterns.test.ts", "language": "typescript", "file_size": 1003, "cut_index": 512, "middle_length": 229}} {"prefix": "/lib/next-test-utils'\nimport { createRedboxSnapshot } from '../../../lib/add-redbox-matchers'\n\ndescribe('instant validation - server errors', () => {\n const { next, skipped, isNextDev, isNextStart, isTurbopack } = nextTestSetup({\n files: __dirname,\n skipStart: true,\n skipDeployment: true,\n env: {\n NEXT_TEST_LOG_VALIDATION: '1',\n },\n })\n if (skipped) return\n\n if (isNextStart && !isTurbopack) {\n it.skip('TODO: snapshot tests for webpack', () => {})\n return\n }\n\n if (isNextStart)", "suffix": "tart()\n })\n }\n\n let currentCliOutputIndex = 0\n beforeEach(() => {\n currentCliOutputIndex = next.cliOutput.length\n })\n\n function getCliOutputSinceMark(): string {\n if (next.cliOutput.length < currentCliOutputIndex) {\n currentCliOutputInde", "middle": " {\n beforeAll(async () => {\n await next.build({ args: ['--experimental-build-mode', 'compile'] })\n })\n afterEach(async () => {\n await next.stop()\n })\n } else {\n beforeAll(async () => {\n await next.s", "meta": {"filepath": "test/e2e/app-dir/instant-validation/instant-validation-server-errors.test.ts", "language": "typescript", "file_size": 8269, "cut_index": 716, "middle_length": 229}} {"prefix": " // Should inject global css for .green selectors\n await check(\n async () =>\n await browser.eval(\n `window.getComputedStyle(document.querySelector('.green')).color`\n ),\n 'rgb(0, 128, 0)'\n )\n })\n\n it('should support css modules inside server layouts', async () => {\n const browser = await next.browser('/css/css-nested')\n await check(\n async () =>\n await browser.eval(\n `window.getCo", "suffix": "ss/css-external')\n await check(\n async () =>\n await browser.eval(\n `window.getComputedStyle(document.querySelector('main')).paddingTop`\n ),\n '80px'\n )\n })\n })\n\n describe('server ", "middle": "mputedStyle(document.querySelector('#server-cssm')).color`\n ),\n 'rgb(0, 128, 0)'\n )\n })\n\n it('should support external css imports', async () => {\n const browser = await next.browser('/c", "meta": {"filepath": "test/e2e/app-dir/app-css/index.test.ts", "language": "typescript", "file_size": 30827, "cut_index": 1331, "middle_length": 229}} {"prefix": "from 'e2e-utils'\n\ndescribe('interception-routes-multiple-catchall', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n describe('multi-param catch-all', () => {\n it('should intercept when navigating to the same path with route interception', async () => {\n const browser = await next.browser('/templates/multi/slug')\n await browser.elementByCss(\"[href='/showcase/multi/slug']\").click()\n await browser.waitForElementByCss('#intercepting-page')\n })\n\n it('should interc", "suffix": "ByCss('#intercepting-page')\n })\n\n it('should intercept when navigating to a multi-param path', async () => {\n const browser = await next.browser('/templates/multi/slug')\n await browser.elementByCss(\"[href='/showcase/another/slug']\").click()", "middle": "ept when navigating to a single param path', async () => {\n const browser = await next.browser('/templates/multi/slug')\n await browser.elementByCss(\"[href='/showcase/single']\").click()\n await browser.waitForElement", "meta": {"filepath": "test/e2e/app-dir/interception-routes-multiple-catchall/interception-routes-multiple-catchall.test.ts", "language": "typescript", "file_size": 1719, "cut_index": 537, "middle_length": 229}} {"prefix": "ort { isNextDev, nextTestSetup } from 'e2e-utils'\n\n// This test relies on next.build() so it can't work in dev mode.\nconst _describe = isNextDev ? describe.skip : describe\n\n_describe('after() in static pages - thrown errors', () => {\n const { next, skipped } = nextTestSetup({\n files: __dirname,\n skipStart: true,\n skipDeployment: true, // can't access build errors in deploy tests\n })\n\n if (skipped) return\n\n it('fails the build if an error is thrown inside after', async () => {\n const buildRes", "suffix": " expect(next.cliOutput).toContain(\n `My cool error thrown inside after on route \"${path}\"`\n )\n }\n\n {\n const path = '/page-throws-in-after/promise'\n expect(next.cliOutput).toContain(\n `Error occurred prerendering page \"", "middle": "ult = await next.build()\n expect(buildResult?.exitCode).toBe(1)\n\n {\n const path = '/page-throws-in-after/callback'\n expect(next.cliOutput).toContain(\n `Error occurred prerendering page \"${path}\"`\n )\n ", "meta": {"filepath": "test/e2e/app-dir/next-after-app-static/build-time-error/build-time-error.test.ts", "language": "typescript", "file_size": 1720, "cut_index": 537, "middle_length": 229}} {"prefix": "tTestSetup } from 'e2e-utils'\n\n// TODO(NAR-423): Migrate to Cache Components.\ndescribe.skip('ppr build errors', () => {\n ;(isNextStart ? describe : describe.skip)('production only', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n skipStart: true,\n })\n\n let cliOutput: string\n\n beforeAll(async () => {\n const output = await next.build()\n cliOutput = output.cliOutput\n })\n\n describe('within a suspense boundary', () => {\n it('should fail the build for unca", "suffix": "prerendering page \"/re-throwing-error\".'\n )\n })\n })\n\n describe('outside of a suspense boundary', () => {\n it('should fail the build for uncaught errors', async () => {\n expect(cliOutput).toContain(\n 'Error occurred pr", "middle": "ught prerender errors', async () => {\n expect(cliOutput).toContain(\n 'Error occurred prerendering page \"/regular-error-suspense-boundary\".'\n )\n expect(cliOutput).toContain(\n 'Error occurred ", "meta": {"filepath": "test/e2e/app-dir/ppr-errors/ppr-errors.test.ts", "language": "typescript", "file_size": 1559, "cut_index": 537, "middle_length": 229}} {"prefix": "estSetup } from 'e2e-utils'\n\ndescribe('Undefined default export', () => {\n const { next, isNextDev } = nextTestSetup({\n files: path.join(__dirname),\n skipStart: isNextStart,\n skipDeployment: true,\n })\n\n if (isNextDev) {\n it('should error if page component does not have default export', async () => {\n const browser = await next.browser('/specific-path/1')\n\n await expect(browser).toDisplayRedbox(`\n {\n \"code\": \"E45\",\n \"description\": \"The default export is not a Re", "suffix": "es not have default export', async () => {\n const browser = await next.browser('/specific-path/2')\n\n await expect(browser).toDisplayRedbox(`\n {\n \"code\": \"E45\",\n \"description\": \"The default export is not a React Component in ", "middle": "act Component in \"/specific-path/1/page\"\",\n \"environmentLabel\": null,\n \"label\": \"Runtime Error\",\n \"source\": null,\n \"stack\": [],\n }\n `)\n })\n\n it('should error if layout component do", "meta": {"filepath": "test/e2e/app-dir/undefined-default-export/undefined-default-export.test.ts", "language": "typescript", "file_size": 2647, "cut_index": 563, "middle_length": 229}} {"prefix": "import { nextTestSetup } from 'e2e-utils'\nimport cheerio from 'cheerio'\n\ndescribe('css-modules-pure-no-check', () => {\n const { isNextStart, next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should apply styles correctly', async () => {\n const browser = await next.browser('/')\n\n const elementWithGlobalStyles = await browser\n .elementByCss('#my-div')\n .getComputedCss('font-weight')\n\n expect(elementWithGlobalStyles).toBe('700')\n })\n\n if (isNextStart) {\n it('should have emitte", "suffix": "nk[0].attribs['href']\n\n const res = await next.fetch(cssHref)\n const cssCode = await res.text()\n\n expect(cssCode).toInclude(`.global{font-weight:700}`)\n expect(cssCode).toInclude(\n `::view-transition-old(root){animation-duration:", "middle": "d a CSS file', async () => {\n const html = await next.render('/')\n const $html = cheerio.load(html)\n\n const cssLink = $html('link[rel=\"stylesheet\"]')\n expect(cssLink.length).toBe(1)\n const cssHref = cssLi", "meta": {"filepath": "test/e2e/app-dir/css-modules-pure-no-check/css-modules-pure-no-check.test.ts", "language": "typescript", "file_size": 1025, "cut_index": 512, "middle_length": 229}} {"prefix": "mport { nextTestSetup } from 'e2e-utils'\n\ndescribe('Root Suspense Dynamic Rendering', () => {\n const { next, isNextStart } = nextTestSetup({\n files: __dirname + '/fixtures/default',\n skipDeployment: true,\n })\n\n // TODO: remove when there is a test for isNextDev === false\n it('placeholder to satisfy at least one test when isNextDev is false', async () => {\n expect(true).toBe(true)\n })\n\n if (isNextStart) {\n it('should handle dynamic content wrapped in Suspense above HTML structure', async ()", "suffix": "cted build to succeed for Suspense wrapping dynamic content above HTML',\n { cause: error }\n )\n }\n })\n\n it('should correctly mark route as dynamic', async () => {\n // The route should be marked as dynamic (ƒ) not static (○)\n ", "middle": " => {\n try {\n // Should render the page successfully\n const $ = await next.render$('/')\n expect($('body').text()).toContain('Hello World')\n } catch (error) {\n throw new Error(\n 'Expe", "meta": {"filepath": "test/e2e/app-dir/root-suspense-dynamic/root-suspense-dynamic.test.ts", "language": "typescript", "file_size": 1061, "cut_index": 513, "middle_length": 229}} {"prefix": "from 'e2e-utils'\n\ndescribe('app-dir - middleware rewrite with catch-all and parallel routes', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n describe('payment route', () => {\n it('should rewrite to the specific page instead of the catch-all with parallel route', async () => {\n const browser = await next.browser('/payment/test')\n const text = await browser.elementByCss('#specific-page').text()\n\n expect(text).toBe('payment whoops')\n expect(await browser.url()).", "suffix": "t text = await browser.elementByCss('#specific-page').text()\n\n expect(text).toBe('payment whoops')\n expect(await browser.url()).toBe(next.url + '/payment/whoops')\n })\n })\n\n describe('anotherRoute', () => {\n it('should rewrite to the speci", "middle": "toBe(next.url + '/payment/test')\n })\n\n it('should redirect to the specific page instead of the catch-all with parallel route', async () => {\n const browser = await next.browser('/payment/test?redirect=true')\n cons", "meta": {"filepath": "test/e2e/app-dir/middleware-rewrite-catchall-priority-with-parallel-route/middleware-rewrite-catchall-priority-with-parallel-route.test.ts", "language": "typescript", "file_size": 1751, "cut_index": 537, "middle_length": 229}} {"prefix": " 'e2e-utils'\nimport * as Log from './utils/log'\nimport { waitForNoRedbox, retry } from '../../../../lib/next-test-utils'\n\ndescribe('after() in generateStaticParams', () => {\n const { next, isNextDev, skipped } = nextTestSetup({\n files: __dirname,\n skipDeployment: true, // reading CLI logs to observe after\n skipStart: true,\n })\n\n if (skipped) return\n\n let currentCliOutputIndex = 0\n beforeEach(() => {\n currentCliOutputIndex = next.cliOutput.length\n })\n\n const getLogs = () => {\n if (next.", "suffix": "tIndex)\n }\n\n if (isNextDev) {\n it('runs after callbacks when visiting a page in dev', async () => {\n await next.start()\n const browser = await next.browser('/one/a')\n\n expect(await browser.elementByCss('body').text()).toBe('Param: a')\n ", "middle": "cliOutput.length < currentCliOutputIndex) {\n // cliOutput shrank since we started the test, so something (like a `sandbox`) reset the logs\n currentCliOutputIndex = 0\n }\n return next.cliOutput.slice(currentCliOutpu", "meta": {"filepath": "test/e2e/app-dir/next-after-app-static/generate-static-params/index.test.ts", "language": "typescript", "file_size": 2138, "cut_index": 563, "middle_length": 229}} {"prefix": "tTestSetup } from 'e2e-utils'\nimport { retry, waitFor } from 'next-test-utils'\n\ndescribe('actions-streaming', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n describe('actions returning a ReadableStream', () => {\n it('should properly stream the response without buffering', async () => {\n const browser = await next.browser('/readable-stream')\n await browser.elementById('stream-button').click()\n\n expect(await browser.elementById('stream-button').text()).toBe(\n ", "suffix": "ect(await browser.elementById('chunks').text()).toInclude(\n 'Lorem ipsum dolor sit'\n )\n\n // Finally, wait for the response to finish streaming.\n await waitFor(5000)\n await retry(\n async () => {\n expect(await brows", "middle": " 'Streaming...'\n )\n\n // If we're streaming properly, we should see the first chunks arrive\n // quickly.\n expect(await browser.elementByCss('h3').text()).toMatch(\n /Received \\d+ chunks/\n )\n exp", "meta": {"filepath": "test/e2e/app-dir/actions-streaming/actions-streaming.test.ts", "language": "typescript", "file_size": 1265, "cut_index": 524, "middle_length": 229}} {"prefix": "import { Suspense } from 'react'\nimport { connection } from 'next/server'\nimport { HydrationIndicator } from '../../hydration-indicator'\nimport waitForMarkerFile from '../../../waitForMarkerFile'\n\nexport default async function Page() {\n // Trigger the Suspense-around-body in the root layout so that no static shell is produced\n await connection()\n\n return (\n
    \n

    This is a page with no static shell + no streaming metadata

    \n
    \n

    Dynamic shell

    \n \n
    {`Random value: ${randomValue}`}
    \n \n
    \n Loading...
    }>\n \n \n
    \n \n )\n}\n\nasync function ", "meta": {"filepath": "test/e2e/app-dir/ppr-partial-hydration/app/without-shell/without-metadata/page.tsx", "language": "tsx", "file_size": 1021, "cut_index": 512, "middle_length": 229}} {"prefix": " { Suspense } from 'react'\nimport { connection } from 'next/server'\nimport { HydrationIndicator } from '../../hydration-indicator'\nimport waitForMarkerFile from '../../../waitForMarkerFile'\nimport type { Metadata } from 'next'\n\nexport async function generateMetadata(): Promise {\n await connection()\n return {\n title: 'Resume test',\n }\n}\n\nexport default async function Page() {\n // Trigger the Suspense-around-body in the root layout so that no static shell is produced\n await connection()\n\n r", "suffix": "se fallback={
    Loading...
    }>\n \n \n
    \n \n )\n}\n\nasync function SlowServerComponent() {\n await connection()\n await waitForMarkerFile()\n const randomValue = M", "middle": "eturn (\n
    \n

    This is a page with no static shell + with streaming metadata

    \n
    \n

    Dynamic shell

    \n \n
    \n {\n const { next, isNextDev, skipped } = nextTestSetup({\n files: __dirname,\n skipDeployment: true,\n skipStart: process.env.NEXT_TEST_MODE !== 'dev',\n })\n\n if (skipped) {\n return\n }\n\n if (isNextDev) {\n descr", "suffix": "h\n const browser = await next.browser('/below-dev-timeout')\n\n await expect(browser.elementByCss('#result').text()).resolves.toBe(\n 'cached'\n )\n\n const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))\n\n ex", "middle": "ibe('when a \"use cache\" fill is below the configured dev `useCacheTimeout`', () => {\n it('should not clamp the dev timeout and allow the cache fill to complete', async () => {\n const outputIndex = next.cliOutput.lengt", "meta": {"filepath": "test/e2e/app-dir/use-cache-configured-timeout/use-cache-configured-timeout.test.ts", "language": "typescript", "file_size": 2992, "cut_index": 563, "middle_length": 229}} {"prefix": ": any) {\n let result = ''\n onData = onData || (() => {})\n\n for await (const chunk of response.body) {\n result += chunk.toString()\n onData(chunk.toString(), result)\n }\n return result\n}\n\ndescribe('use-server-inserted-html', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies: {\n // TODO: Temporarily pinned due to https://github.com/styled-components/styled-components/issues/5667\n // which is breaking deployment tests\n 'styled-components': '6.3.9',\n ", "suffix": "x\n\n expect(head).toMatch(/{color:(\\s*)purple;?}/) // styled-jsx/style\n expect(head).toMatch(/{color:(\\s*)(?:hotpink|#ff69b4);?}/) // styled-jsx/css\n\n // from styled-components\n expect(head).toMatch(/{color:(\\s*)(?:blue|#00f);?}/)\n })\n\n it('sh", "middle": "'server-only': 'latest',\n },\n })\n\n it('should render initial styles of css-in-js in nodejs SSR correctly', async () => {\n const $ = await next.render$('/css-in-js')\n const head = $('head').html()\n\n // from styled-js", "meta": {"filepath": "test/e2e/app-dir/use-server-inserted-html/use-server-inserted-html.test.ts", "language": "typescript", "file_size": 3337, "cut_index": 614, "middle_length": 229}} {"prefix": "\n\nimport React from 'react'\nimport { StyleRegistry, createStyleRegistry } from 'styled-jsx'\nimport { ServerStyleSheet, StyleSheetManager } from 'styled-components'\nimport { useServerInsertedHTML } from 'next/navigation'\nimport { useState } from 'react'\n\nexport default function RootStyleRegistry({ children }) {\n const [jsxStyleRegistry] = useState(() => createStyleRegistry())\n const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())\n const styledJsxFlushEffect = () => {\n const styles", "suffix": "nstance.clearTag()\n return <>{styles}\n }\n\n // Allow multiple useServerInsertedHTML\n useServerInsertedHTML(() => {\n return <>{styledJsxFlushEffect()}\n })\n\n useServerInsertedHTML(() => {\n return <>{styledComponentsFlushEffect()}\n })\n\n", "middle": " = jsxStyleRegistry.styles()\n jsxStyleRegistry.flush()\n return <>{styles}\n }\n const styledComponentsFlushEffect = () => {\n const styles = styledComponentsStyleSheet.getStyleElement()\n styledComponentsStyleSheet.i", "meta": {"filepath": "test/e2e/app-dir/use-server-inserted-html/app/root-style-registry.js", "language": "javascript", "file_size": 1297, "cut_index": 524, "middle_length": 229}} {"prefix": "\n\nimport { Suspense } from 'react'\nimport styled from 'styled-components'\n\nexport function createDataFetcher(data, { timeout = 0, expire = 10 }) {\n let result\n let promise\n return function Data() {\n if (result) return result\n if (!promise)\n promise = new Promise((resolve) => {\n setTimeout(() => {\n result = data\n setTimeout(() => {\n result = undefined\n promise = undefined\n }, expire)\n resolve()\n }, timeout)\n })\n thr", "suffix": "pire: 4000,\n})\n\nfunction SuspenseyFooter() {\n readData()\n // generate large chunk of text to let the suspensey styling be inserted before the suspense script\n return (\n \n {'(generate-large-footer-text)'.repeat(30)}\n ", "middle": "ow promise\n }\n}\n\nconst Footer = styled.div`\n border: 1px solid orange;\n color: blue;\n`\n\nconst FootInner = styled.span`\n padding: 2px;\n color: orange;\n`\n\nconst readData = createDataFetcher('streaming', {\n timeout: 4000,\n ex", "meta": {"filepath": "test/e2e/app-dir/use-server-inserted-html/app/css-in-js/suspense/page.js", "language": "javascript", "file_size": 1314, "cut_index": 524, "middle_length": 229}} {"prefix": "t } from 'next/server'\n\n// We use this in combination with fallback rewrites to redirect all /:teamSlug URLs to /app-future/[locale]/:teamSlug\n// in order to avoid having to grab all existing pages at build and checking the path in middleware\nexport async function GET(\n request: NextRequest,\n {\n params,\n }: {\n params: Promise<{\n path: string\n }>\n }\n): Promise {\n request.nextUrl.pathname = `/app-future/en/${(await params).path}`\n return fetch(request.nextUrl, {\n headers: new ", "suffix": " cookie: request.headers.get('cookie') ?? '',\n }),\n }).then(async (res) => {\n const resHeaders = new Headers(res.headers)\n resHeaders.delete('content-encoding')\n return new Response(res.body, { status: res.status, headers: resHeaders })\n })\n", "middle": "Headers({\n ", "meta": {"filepath": "test/e2e/app-dir/front-redirect-issue/app/api/app-redirect/[path]/route.ts", "language": "typescript", "file_size": 808, "cut_index": 536, "middle_length": 14}} {"prefix": "tDev } from 'e2e-utils'\nimport { waitForRedbox, getRedboxSource, retry } from 'next-test-utils'\nimport * as Log from './utils/log'\n\n// using after is a compile-time error in build mode.\nconst _describe = isNextDev ? describe : describe.skip\n\n_describe('after() - pages', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n let currentCliOutputIndex = 0\n beforeEach(() => {\n currentCliOutputIndex = next.cliOutput.length\n })\n\n const getLogs = () => {\n return Log.readCliLogs(next.cli", "suffix": " redirect: 'follow',\n headers: {\n cookie: 'testCookie=testValue',\n },\n }\n )\n\n expect(res.status).toBe(200)\n await retry(() => {\n expect(getLogs()).toContainEqual({\n source: '[middleware] /middleware/redirec", "middle": "Output.slice(currentCliOutputIndex))\n }\n\n it('runs in middleware', async () => {\n const requestId = `${Date.now()}`\n const res = await next.fetch(\n `/middleware/redirect-source?requestId=${requestId}`,\n {\n ", "meta": {"filepath": "test/e2e/app-dir/next-after-pages/index.test.ts", "language": "typescript", "file_size": 2087, "cut_index": 563, "middle_length": 229}} {"prefix": "getRedboxSource } from 'next-test-utils'\n\ndescribe('CSS Import from node_modules', () => {\n const { next, skipped, isTurbopack, isRspack } = nextTestSetup({\n files: __dirname,\n skipStart: isNextStart,\n skipDeployment: true,\n dependencies: { sass: '1.54.0' },\n })\n\n if (skipped) {\n return\n }\n\n if (isNextStart) {\n it('should fail the build', async () => {\n const { exitCode, cliOutput } = await next.build()\n expect(exitCode).not.toBe(0)\n if (isRspack) {\n expect(cliOu", "suffix": "(/Build failed|Build error occurred/)\n })\n } else {\n it('should show a build error', async () => {\n const browser = await next.browser('/')\n\n await waitForRedbox(browser)\n const errorSource = await getRedboxSource(browser)\n\n if (", "middle": "tput).toMatch(\n /RspackResolver\\(NotFound\\(\\\\?\"nprogress\\/nprogress.css\\\\?\"\\)\\)/\n )\n } else {\n expect(cliOutput).toMatch(/Can't resolve '[^']*?nprogress[^']*?'/)\n }\n expect(cliOutput).toMatch", "meta": {"filepath": "test/e2e/app-dir/scss/npm-import-bad/npm-import-bad.test.ts", "language": "typescript", "file_size": 3101, "cut_index": 614, "middle_length": 229}} {"prefix": "tTestSetup } from 'e2e-utils'\nimport { colorToRgb } from 'next-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'Nested @import() Global Support ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies,\n nextConfig,\n })\n\n ", "suffix": "const browser = await next.browser('/')\n expect(\n await browser.elementByCss('.red-text').getComputedCss('color')\n ).toBe(colorToRgb('red'))\n expect(\n await browser.elementByCss('.blue-text').getComputedCss('color')\n ).toB", "middle": " it('should render the page', async () => {\n ", "meta": {"filepath": "test/e2e/app-dir/scss/nested-global/nested-global.test.ts", "language": "typescript", "file_size": 890, "cut_index": 547, "middle_length": 52}} {"prefix": "v jest */\n\nimport { nextTestSetup } from 'e2e-utils'\nimport { colorToRgb } from 'next-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n '3rd Party CSS Module Support ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies,\n n", "suffix": "Css('background-color')\n ).toBe(colorToRgb('blue'))\n\n // Baz\n expect(\n await browser\n .elementByCss('#verify-div .baz')\n .getComputedCss('background-color')\n ).toBe(colorToRgb('blue'))\n\n // Lol\n expect", "middle": "extConfig,\n })\n\n it('should render the module', async () => {\n const browser = await next.browser('/')\n // Bar\n expect(\n await browser\n .elementByCss('#verify-div .bar')\n .getComputed", "meta": {"filepath": "test/e2e/app-dir/scss/3rd-party-module/3rd-party-module.test.ts", "language": "typescript", "file_size": 1342, "cut_index": 524, "middle_length": 229}} {"prefix": "v jest */\n\nimport { nextTestSetup } from 'e2e-utils'\nimport { colorToRgb } from 'next-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'SCSS Support loader handling Preprocessor loader order ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirname,\n ", "suffix": "ies,\n nextConfig,\n })\n it('should render the module', async () => {\n const browser = await next.browser('/')\n expect(\n await browser.elementByCss('.red-text').getComputedCss('color')\n ).toBe(colorToRgb('red'))\n })\n }\n)\n", "middle": " dependenc", "meta": {"filepath": "test/e2e/app-dir/scss/loader-order/loader-order.test.ts", "language": "typescript", "file_size": 794, "cut_index": 524, "middle_length": 14}} {"prefix": "tTestSetup } from 'e2e-utils'\nimport { colorToRgb } from 'next-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'SCSS Support loader handling Data Urls ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies,\n nextConfig,\n ", "suffix": " {\n const browser = await next.browser('/')\n const redText = await browser.elementByCss('.red-text')\n expect(await redText.getComputedCss('color')).toBe(colorToRgb('red'))\n expect(await redText.getComputedCss('background-image')).toMatc", "middle": " })\n\n it('should render the module', async () =>", "meta": {"filepath": "test/e2e/app-dir/scss/data-url/data-url.test.ts", "language": "typescript", "file_size": 910, "cut_index": 547, "middle_length": 52}} {"prefix": "* eslint-env jest */\n\nimport { nextTestSetup } from 'e2e-utils'\nimport { colorToRgb } from 'next-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'Ordering with styled-jsx ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies,\n", "suffix": "ig,\n })\n\n it('should have the correct color (css ordering)', async () => {\n const browser = await next.browser('/')\n expect(\n await browser.elementByCss('.my-text').getComputedCss('color')\n ).toBe(colorToRgb('green'))\n })\n }", "middle": " nextConf", "meta": {"filepath": "test/e2e/app-dir/scss/with-styled-jsx/with-styled-jsx.test.ts", "language": "typescript", "file_size": 786, "cut_index": 513, "middle_length": 14}} {"prefix": "port { nextTestSetup } from 'e2e-utils'\nimport { colorToRgb, getUrlFromBackgroundImage } from 'next-test-utils'\n\n// TODO: Skipped as this test should set up the server to handle assetPrefix which it currently does not do.\ndescribe.skip('SCSS Support loader handling', () => {\n describe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },", "suffix": "extConfig,\n })\n\n it('should render the page', async () => {\n const browser = await next.browser('/')\n expect(\n await browser.elementByCss('.red-text').getComputedCss('color')\n ).toBe(colorToRgb('red'))\n\n const", "middle": "\n },\n },\n ])(\n 'CSS URL via `file-loader` and asset prefix (2) ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies,\n n", "meta": {"filepath": "test/e2e/app-dir/scss/url-global-asset-prefix-2/url-global-asset-prefix-2.test.ts", "language": "typescript", "file_size": 1567, "cut_index": 537, "middle_length": 229}} {"prefix": "port { nextTestSetup } from 'e2e-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])('unused scss', ({ dependencies, nextConfig }) => {\n describe('Body is not hidden when unused in Development ($dependencies)', () => {\n const { next, isNextDev } = nextTestSetup({\n files: __dirname,\n dependencies,\n ne", "suffix": "wser.eval(\n `window.getComputedStyle(document.querySelector('body')).display`\n )\n expect(currentDisplay).toBe('block')\n })\n })\n })\n\n describe('Body is not hidden when broken in Development', () => {\n const { next, isNext", "middle": "xtConfig,\n })\n\n ;(isNextDev ? describe : describe.skip)('development only', () => {\n it('should have body visible', async () => {\n const browser = await next.browser('/')\n const currentDisplay = await bro", "meta": {"filepath": "test/e2e/app-dir/scss/unused/unused.test.ts", "language": "typescript", "file_size": 1622, "cut_index": 537, "middle_length": 229}} {"prefix": "nv jest */\n\nimport { nextTestSetup } from 'e2e-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'Good CSS Import from node_modules ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies: {\n ...dependencies,\n nprogress: ", "suffix": "should render the page', async () => {\n const browser = await next.browser('/')\n expect(\n await browser\n .elementByCss('#nprogress .bar')\n .getComputedCss('background-color')\n ).toBe('rgb(34, 153, 221)')\n })\n }\n)", "middle": "'0.2.0',\n },\n nextConfig,\n })\n\n it('", "meta": {"filepath": "test/e2e/app-dir/scss/npm-import/npm-import.test.ts", "language": "typescript", "file_size": 832, "cut_index": 523, "middle_length": 52}} {"prefix": "/* eslint-env jest */\n\nimport { nextTestSetup } from 'e2e-utils'\nimport { colorToRgb } from 'next-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'Valid CSS Module Usage from within node_modules ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirna", "suffix": "ndencies,\n nextConfig,\n })\n\n it('should render the page', async () => {\n const browser = await next.browser('/')\n expect(\n await browser.elementByCss('#nm-div').getComputedCss('color')\n ).toBe(colorToRgb('red'))\n })\n }\n", "middle": "me,\n depe", "meta": {"filepath": "test/e2e/app-dir/scss/nm-module/nm-module.test.ts", "language": "typescript", "file_size": 784, "cut_index": 512, "middle_length": 14}} {"prefix": "ext-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'CSS Module Composes Usage (Basic) ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies,\n nextConfig,\n })\n\n it('should render the module', async () => {\n con", "suffix": " await browser.elementByCss('#verify-yellow').getComputedCss('color')\n ).toBe(colorToRgb('yellow'))\n expect(\n await browser\n .elementByCss('#verify-yellow')\n .getComputedCss('background-color')\n ).toBe(colorToR", "middle": "st browser = await next.browser('/')\n expect(\n ", "meta": {"filepath": "test/e2e/app-dir/scss/composes-basic/composes-basic.test.ts", "language": "typescript", "file_size": 939, "cut_index": 606, "middle_length": 52}} {"prefix": "int-env jest */\n\nimport { nextTestSetup } from 'e2e-utils'\nimport { colorToRgb } from 'next-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'Valid Nested CSS Module Usage from within node_modules ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirn", "suffix": " ).toBe(colorToRgb('red'))\n expect(\n await browser.elementByCss('#other3').getComputedCss('color')\n ).toBe(colorToRgb('black'))\n expect(\n await browser.elementByCss('#subclass').getComputedCss('color')\n ).toBe(colorToR", "middle": "ame,\n dependencies,\n nextConfig,\n })\n\n it('should render the page', async () => {\n const browser = await next.browser('/')\n expect(\n await browser.elementByCss('#other2').getComputedCss('color')\n ", "meta": {"filepath": "test/e2e/app-dir/scss/nm-module-nested/nm-module-nested.test.ts", "language": "typescript", "file_size": 1182, "cut_index": 518, "middle_length": 229}} {"prefix": "tTestSetup } from 'e2e-utils'\nimport { colorToRgb } from 'next-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'Good Nested CSS Import from node_modules ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies,\n nextConfig,\n", "suffix": " {\n const browser = await next.browser('/')\n expect(\n await browser.elementByCss('.red-text').getComputedCss('color')\n ).toBe(colorToRgb('red'))\n expect(\n await browser.elementByCss('.blue-text').getComputedCss('color')\n ", "middle": " })\n\n it('should render the page', async () =>", "meta": {"filepath": "test/e2e/app-dir/scss/npm-import-nested/npm-import-nested.test.ts", "language": "typescript", "file_size": 899, "cut_index": 547, "middle_length": 52}} {"prefix": "v jest */\n\nimport { nextTestSetup } from 'e2e-utils'\nimport { colorToRgb, getUrlFromBackgroundImage } from 'next-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'SCSS Support loader handling ($dependencies)',\n ({ dependencies, nextConfig }) => {\n describe('CSS URL via `file-loader`', () => {\n const", "suffix": "await browser.elementByCss('.red-text').getComputedCss('color')\n ).toBe(colorToRgb('red'))\n\n const background = await browser\n .elementByCss('.red-text')\n .getComputedCss('background-image')\n expect(background).toMatc", "middle": " { next } = nextTestSetup({\n files: __dirname,\n dependencies,\n nextConfig,\n })\n\n it('should render the page', async () => {\n const browser = await next.browser('/')\n expect(\n ", "meta": {"filepath": "test/e2e/app-dir/scss/url-global/url-global.test.ts", "language": "typescript", "file_size": 1400, "cut_index": 524, "middle_length": 229}} {"prefix": "port { isNextStart, nextTestSetup } from 'e2e-utils'\nimport { waitForRedbox, getRedboxSource } from 'next-test-utils'\n\n// Importing module CSS in _document is allowed in Turbopack\n;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(\n 'Invalid SCSS in _document',\n () => {\n const { next, skipped, isRspack } = nextTestSetup({\n files: __dirname,\n skipStart: isNextStart,\n skipDeployment: true,\n dependencies: { sass: '1.54.0' },\n })\n\n if (skipped) {\n return\n }\n\n i", "suffix": "ect(cliOutput).toContain('styles.module.scss')\n expect(cliOutput).toMatch(\n /CSS.*cannot.*be imported within.*pages[\\\\/]_document\\.js/\n )\n // Skip: Rspack loaders cannot access module issuer info for location details\n i", "middle": "f (isNextStart) {\n it('should fail to build', async () => {\n const { exitCode, cliOutput } = await next.build()\n expect(exitCode).not.toBe(0)\n expect(cliOutput).toContain('Failed to compile')\n exp", "meta": {"filepath": "test/e2e/app-dir/scss/invalid-module-document/invalid-module-document.test.ts", "language": "typescript", "file_size": 1887, "cut_index": 537, "middle_length": 229}} {"prefix": "Invalid CSS Global Module Usage in node_modules', () => {\n ;(isNextStart ? describe : describe.skip)('production only', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n skipStart: true,\n })\n\n it('should fail to build', async () => {\n const { exitCode, cliOutput } = await next.build()\n expect(exitCode).not.toBe(0)\n expect(cliOutput).toContain('Failed to compile')\n expect(cliOutput).toContain('node_modules/example/index.scss')\n expect(cliOutput).toMatc", "suffix": "hin.*node_modules/\n )\n // Skip: Rspack loaders cannot access module issuer info for location details\n if (!process.env.NEXT_RSPACK) {\n expect(cliOutput).toMatch(\n /Location:.*node_modules[\\\\/]example[\\\\/]index\\.mjs/\n )", "middle": "h(\n /Global CSS.*cannot.*be imported from wit", "meta": {"filepath": "test/e2e/app-dir/scss/invalid-global-module/invalid-global-module.test.ts", "language": "typescript", "file_size": 938, "cut_index": 606, "middle_length": 52}} {"prefix": "stSetup } from 'e2e-utils'\nimport { waitForRedbox, getRedboxSource } from 'next-test-utils'\n\ndescribe('Invalid Global CSS', () => {\n const { next, skipped, isTurbopack, isRspack } = nextTestSetup({\n files: __dirname,\n skipStart: isNextStart,\n skipDeployment: true,\n dependencies: { sass: '1.54.0' },\n })\n\n if (skipped) {\n return\n }\n\n if (isNextStart) {\n it('should fail to build', async () => {\n const { exitCode, cliOutput } = await next.build()\n expect(exitCode).not.toBe(0)\n ", "suffix": "orts.*?pages(\\/|\\\\)_app/\n )\n // Skip: Rspack loaders cannot access module issuer info for location details\n if (!process.env.NEXT_RSPACK) {\n expect(cliOutput).toMatch(/Location:.*pages[\\\\/]index\\.js/)\n }\n })\n } else {\n it(", "middle": " if (!isTurbopack) {\n expect(cliOutput).toContain('Failed to compile')\n }\n expect(cliOutput).toContain('styles/global.scss')\n expect(cliOutput).toMatch(\n /Please move all first-party global CSS imp", "meta": {"filepath": "test/e2e/app-dir/scss/invalid-global/invalid-global.test.ts", "language": "typescript", "file_size": 2728, "cut_index": 563, "middle_length": 229}} {"prefix": "v jest */\n\nimport { nextTestSetup } from 'e2e-utils'\nimport { colorToRgb, getUrlFromBackgroundImage } from 'next-test-utils'\n\ndescribe('SCSS Support loader handling', () => {\n describe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n ])(\n 'CSS URL via file-loader sass partial ($dependencies)',\n ({ dependencie", "suffix": "r('/')\n expect(\n await browser.elementByCss('.red-text').getComputedCss('color')\n ).toBe(colorToRgb('red'))\n\n const background = await browser\n .elementByCss('.red-text')\n .getComputedCss('background-image')\n", "middle": "s, nextConfig }) => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies,\n nextConfig,\n })\n\n it('should render the page', async () => {\n const browser = await next.browse", "meta": {"filepath": "test/e2e/app-dir/scss/url-global-partial/url-global-partial.test.ts", "language": "typescript", "file_size": 1434, "cut_index": 524, "middle_length": 229}} {"prefix": "t */\nimport { nextTestSetup } from 'e2e-utils'\nimport { colorToRgb } from 'next-test-utils'\n\nconst sassOptions = {\n loadPaths: ['./styles'],\n}\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: { sassOptions } },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n ...sassOptions,\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'Basic Module Include Paths Support ($dependencies)',\n ({ dependencies, nextConfig }) => {\n co", "suffix": "e,\n dependencies,\n nextConfig,\n })\n\n it('should render the module', async () => {\n const browser = await next.browser('/')\n expect(\n await browser.elementByCss('#verify-red').getComputedCss('color')\n ).toBe(colorToRgb(", "middle": "nst { next } = nextTestSetup({\n files: __dirnam", "meta": {"filepath": "test/e2e/app-dir/scss/basic-module-include-paths/basic-module-include-paths.test.ts", "language": "typescript", "file_size": 858, "cut_index": 529, "middle_length": 52}} {"prefix": "m 'e2e-utils'\nimport { colorToRgb, retry } from 'next-test-utils'\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: undefined },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n implementation: 'sass-embedded',\n },\n },\n },\n])('SCSS Support ($dependencies)', ({ dependencies, nextConfig }) => {\n const { next, isNextDev } = nextTestSetup({\n files: __dirname,\n dependencies,\n nextConfig,\n })\n describe('Has CSS in computed st", "suffix": "(colorToRgb('blue'))\n })\n })\n\n if (isNextDev) {\n describe('Can hot reload CSS without losing state', () => {\n it('should update CSS color without remounting ', async () => {\n const browser = await next.browser('/page1')\n\n ", "middle": "yles in Production', () => {\n it('should have CSS for page', async () => {\n const browser = await next.browser('/page2')\n\n expect(\n await browser.elementByCss('.blue-text').getComputedCss('color')\n ).toBe", "meta": {"filepath": "test/e2e/app-dir/scss/multi-page/multi-page.test.ts", "language": "typescript", "file_size": 2159, "cut_index": 563, "middle_length": 229}} {"prefix": " from 'e2e-utils'\nimport { colorToRgb } from 'next-test-utils'\n\nconst sassOptions = {\n additionalData: `\n $var: red;\n `,\n}\n\ndescribe.each([\n { dependencies: { sass: '1.54.0' }, nextConfig: { sassOptions } },\n {\n dependencies: { 'sass-embedded': '1.75.0' },\n nextConfig: {\n sassOptions: {\n ...sassOptions,\n implementation: 'sass-embedded',\n },\n },\n },\n])(\n 'Basic Module Additional Data Support ($dependencies)',\n ({ dependencies, nextConfig }) => {\n const { next } =", "suffix": "dencies,\n nextConfig,\n })\n\n it('should render the module', async () => {\n const browser = await next.browser('/')\n expect(\n await browser.elementByCss('#verify-red').getComputedCss('color')\n ).toBe(colorToRgb('red'))\n })", "middle": " nextTestSetup({\n files: __dirname,\n depen", "meta": {"filepath": "test/e2e/app-dir/scss/basic-module-additional-data/basic-module-additional-data.test.ts", "language": "typescript", "file_size": 874, "cut_index": 559, "middle_length": 52}} {"prefix": "nst path = require('path')\n\nmodule.exports = async function (content) {\n let dir = path.dirname(this.resourcePath)\n\n let read1 = await new Promise((res, rej) =>\n this.fs.readFile(path.join(dir, 'test.txt'), (err, data) => {\n if (err) return rej(err)\n res(data)\n })\n )\n let read2 = await new Promise((res, rej) =>\n this.fs.readFile(path.join(dir, 'test.txt'), 'utf8', (err, data) => {\n if (err) return rej(err)\n res(data)\n })\n )\n let read3 = await new Promise((res, rej) =>\n ", "suffix": "dFile(path.join(dir, 'test.mp4'), (err, data) => {\n if (err) return rej(err)\n res(data)\n })\n )\n return `module.exports = \"Buffer read: ${read1 instanceof Buffer ? read1.length : 0}, string read: '${read2.trim()}', binary read: ${read3.length", "middle": " this.fs.rea", "meta": {"filepath": "test/e2e/app-dir/webpack-loader-fs/test-file-loader.js", "language": "javascript", "file_size": 790, "cut_index": 514, "middle_length": 14}} {"prefix": " and over again'\n foo =\n 'This is the other repeating string. It should be about the same length'\n foo =\n 'I should just alternately repeat this and another string over and over again'\n foo =\n 'This is the other repeating string. It should be about the same length'\n foo =\n 'I should just alternately repeat this and another string over and over again'\n foo =\n 'This is the other repeating string. It should be about the same length'\n foo =\n 'I should just alterna", "suffix": "over again'\n foo =\n 'This is the other repeating string. It should be about the same length'\n foo =\n 'I should just alternately repeat this and another string over and over again'\n foo =\n 'This is the other repeating string. It shou", "middle": "tely repeat this and another string over and over again'\n foo =\n 'This is the other repeating string. It should be about the same length'\n foo =\n 'I should just alternately repeat this and another string over and ", "meta": {"filepath": "test/e2e/app-dir/chunk-loading/components/SuperShared.tsx", "language": "tsx", "file_size": 24368, "cut_index": 1331, "middle_length": 229}} {"prefix": "entsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'\n\ndescribe('app-dir trailingSlash handling', () => {\n const { next, isNextDev } = nextTestSetup({\n files: __dirname,\n buildArgs: [\n '--debug-build-paths',\n isCacheComponentsEnabled\n ? '!app/[lang]/legacy/page.js'\n : '!app/[lang]/cache-components/page.js',\n ],\n })\n\n it('should redirect route when requesting it directly', async () => {\n const res = await next.fetch('/a', {\n redirect: 'manual',\n })\n ex", "suffix": "o-a-trailing-slash').attr('href')).toBe('/a/')\n })\n\n it('should contain trailing slash to canonical url', async () => {\n const $ = await next.render$('/')\n expect($(`link[rel=\"canonical\"]`).attr('href')).toBe(\n 'http://trailingslash.com/'\n ", "middle": "pect(res.status).toBe(308)\n expect(new URL(res.headers.get('location'), next.url).pathname).toBe('/a/')\n })\n\n it('should render link with trailing slash', async () => {\n const $ = await next.render$('/')\n\n expect($('#t", "meta": {"filepath": "test/e2e/app-dir/trailingslash/trailingslash.test.ts", "language": "typescript", "file_size": 3752, "cut_index": 614, "middle_length": 229}} {"prefix": "from 'e2e-utils'\nimport { waitForNoRedbox } from 'next-test-utils'\n\ndescribe('global-not-found - basic', () => {\n const { next, isNextDev } = nextTestSetup({\n files: __dirname,\n })\n\n it('should render global-not-found for 404', async () => {\n const browser = await next.browser('/does-not-exist')\n if (isNextDev) {\n await waitForNoRedbox(browser)\n }\n\n const errorTitle = await browser.elementByCss('#global-error-title').text()\n expect(errorTitle).toBe('global-not-found')\n const not", "suffix": "next.render$('/does-not-exist')\n const errorTitle = $('#global-error-title').text()\n expect(errorTitle).toBe('global-not-found')\n const notFoundHtmlProp = $('html').attr('data-global-not-found')\n expect(notFoundHtmlProp).toBe('true')\n })\n\n it", "middle": "FoundHtmlProp = await browser\n .elementByCss('html')\n .getAttribute('data-global-not-found')\n expect(notFoundHtmlProp).toBe('true')\n })\n\n it('should ssr global-not-found for 404', async () => {\n const $ = await ", "meta": {"filepath": "test/e2e/app-dir/global-not-found/basic/global-not-found-basic.test.ts", "language": "typescript", "file_size": 1592, "cut_index": 537, "middle_length": 229}} {"prefix": "mport { nextTestSetup } from 'e2e-utils'\nimport { waitForNoRedbox } from 'next-test-utils'\n\ndescribe('global-not-found - no-root-layout', () => {\n const { next, isNextDev } = nextTestSetup({\n files: __dirname,\n })\n\n it('should render global-not-found for 404', async () => {\n const browser = await next.browser('/does-not-exist')\n if (isNextDev) {\n await waitForNoRedbox(browser)\n }\n\n const errorTitle = await browser.elementByCss('#global-error-title').text()\n expect(errorTitle).toBe(", "suffix": "sync () => {\n const $ = await next.render$('/does-not-exist')\n const errorTitle = $('#global-error-title').text()\n expect(errorTitle).toBe('global-not-found')\n const notFoundHtmlProp = $('html').attr('data-global-not-found')\n expect(notFound", "middle": "'global-not-found')\n const notFoundHtmlProp = await browser\n .elementByCss('html')\n .getAttribute('data-global-not-found')\n expect(notFoundHtmlProp).toBe('true')\n })\n\n it('should ssr global-not-found for 404', a", "meta": {"filepath": "test/e2e/app-dir/global-not-found/no-root-layout/no-root-layout.test.ts", "language": "typescript", "file_size": 1029, "cut_index": 513, "middle_length": 229}} {"prefix": "mport { nextTestSetup } from 'e2e-utils'\n\ndescribe('global-not-found - both-present', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should render global-not-found for 404 routes', async () => {\n const $ = await next.render$('/does-not-exist')\n expect($('html').attr('data-global-not-found')).toBe('true')\n expect($('#global-error-title').text()).toBe('global-not-found')\n\n const browser = await next.browser('/does-not-exist')\n expect(await browser.elementByCss('#gl", "suffix": "ng notFound() in a page', async () => {\n const browser = await next.browser('/call-not-found')\n expect(await browser.elementByCss('#not-found-boundary').text()).toBe(\n 'not-found.js'\n )\n expect(\n await browser.elementByCss('html').get", "middle": "obal-error-title').text()).toBe(\n 'global-not-found'\n )\n expect(\n await browser.elementByCss('html').getAttribute('data-global-not-found')\n ).toBe('true')\n })\n\n it('should render not-found boundary when calli", "meta": {"filepath": "test/e2e/app-dir/global-not-found/both-present/both-present.test.ts", "language": "typescript", "file_size": 1058, "cut_index": 513, "middle_length": 229}} {"prefix": " { nextTestSetup } from 'e2e-utils'\n\ndescribe(`mdx`, () => {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies: {\n '@next/mdx': 'canary',\n '@mdx-js/loader': '^2.2.1',\n },\n })\n\n describe('app directory', () => {\n it('should work in initial html', async () => {\n const $ = await next.render$('/')\n expect($('h1').text()).toBe('Hello World')\n expect($('p').text()).toBe('This is MDX!')\n })\n\n it('should work using browser', async () => {\n const br", "suffix": "ponents', async () => {\n const $ = await next.render$('/')\n expect($('h2').text()).toBe('This is a client component')\n })\n })\n\n describe('pages directory', () => {\n it('should work in initial html', async () => {\n const $ = await nex", "middle": "owser = await next.browser('/')\n expect(await browser.elementByCss('h1').text()).toBe('Hello World')\n expect(await browser.elementByCss('p').text()).toBe('This is MDX!')\n })\n\n it('should allow importing client com", "meta": {"filepath": "test/e2e/app-dir/mdx-no-mdx-components/mdx.test.ts", "language": "typescript", "file_size": 1136, "cut_index": 518, "middle_length": 229}} {"prefix": "import { nextTestSetup } from 'e2e-utils'\nimport { retry } from 'next-test-utils'\n\ndescribe('global-not-found - cache-components', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should render global-not-found for 404 routes', async () => {\n await next.fetch('/does-not-exist')\n expect(next.cliOutput).not.toContain(\n 'did not produce a static shell and Next.js was unable to determine a reason. This is a bug in Next.js'\n )\n })\n\n it('should render not-found boundary", "suffix": " => {\n expect(await browser.elementByCss('h1').text()).toBe('Global Not Found')\n })\n expect(next.cliOutput).not.toContain(\n 'did not produce a static shell and Next.js was unable to determine a reason. This is a bug in Next.js'\n )\n })\n}", "middle": " when calling notFound() in a page', async () => {\n const browser = await next.browser('/action')\n // submit form with #not-found-btn button\n await browser.elementByCss('#not-found-btn').click()\n\n await retry(async ()", "meta": {"filepath": "test/e2e/app-dir/global-not-found/cache-components/cache-components.test.ts", "language": "typescript", "file_size": 999, "cut_index": 512, "middle_length": 229}} {"prefix": " to work locally you need to use `pnpm next-with-deps dev|build`\n// Make sure you delete node_modules if you are editing the package otherwise it won't\n// reinstall and reflect your changes.\n\nimport ExportsDefault from 'my-external-esm-package/exports'\nimport * as ExportsNamed from 'my-external-esm-package/exports'\nimport { named as namedExports } from 'my-external-esm-package/exports'\n\nimport ImportsDefault from 'my-external-esm-package/imports'\nimport * as ImportsNamed from 'my-external-esm-package/import", "suffix": "external-esm-package/imports').then(\n (mod) => JSON.stringify(mod)\n)\n\nexport default function Client() {\n return (\n
    \n

    Client

    \n
    \n

    Exports

    \n
    \n

    Static

    \n
    \n )\n}", "meta": {"filepath": "test/e2e/app-dir/ppr-partial-hydration/app/with-shell/without-metadata/page.tsx", "language": "tsx", "file_size": 896, "cut_index": 547, "middle_length": 52}} {"prefix": " files: __dirname + '/fixtures/random/cache-components',\n skipDeployment: true,\n })\n\n if (skipped) {\n return\n }\n\n it('should not error when accessing middlware that use Math.random()', async () => {\n let res: Awaited>,\n $: Awaited>\n\n res = await next.fetch('/rewrite')\n expect(res.status).toBe(200)\n $ = await next.render$('/rewrite')\n expect($('[data-testid=\"content\"]').", "suffix": " expect(res.status).toBe(200)\n $ = await next.render$('/app/prerendered/unstable-cache')\n expect($('li').length).toBe(2)\n\n res = await next.fetch('/app/prerendered/use-cache')\n expect(res.status).toBe(200)\n $ = await nex", "middle": "text()).toBe('rewritten')\n })\n\n it('should not error when accessing pages that use Math.random() in App Router', async () => {\n let res, $\n\n res = await next.fetch('/app/prerendered/unstable-cache')\n ", "meta": {"filepath": "test/e2e/app-dir/node-extensions/node-extensions.random.test.ts", "language": "typescript", "file_size": 8865, "cut_index": 716, "middle_length": 229}} {"prefix": "fault Export\",\"named\":\"EXPORTS NEXT SERVER - Named Export\"},\"named\":\"EXPORTS NEXT SERVER - Named Export\"}\n named:\n \"EXPORTS NEXT SERVER - Named Export\"\n Dynamic\n {\"default\":{\"default\":\"EXPORTS NEXT SERVER - Default Export\",\"named\":\"EXPORTS NEXT SERVER - Named Export\"},\"named\":\"EXPORTS NEXT SERVER - Named Export\"}\n Imports\n Static\n Default:\n {\"default\":\"IMPORTS NEXT SERVER - Default E", "suffix": "RVER - Named Export\"}\n named:\n \"IMPORTS NEXT SERVER - Named Export\"\n Dynamic\n {\"default\":{\"default\":\"IMPORTS NEXT SERVER - Default Export\",\"named\":\"IMPORTS NEXT SERVER - Named Export\"},\"named\"", "middle": "xport\",\"named\":\"IMPORTS NEXT SERVER - Named Export\"}\n Namespace:\n {\"default\":{\"default\":\"IMPORTS NEXT SERVER - Default Export\",\"named\":\"IMPORTS NEXT SERVER - Named Export\"},\"named\":\"IMPORTS NEXT SE", "meta": {"filepath": "test/e2e/app-dir/next-condition/next-condition.test.ts", "language": "typescript", "file_size": 40260, "cut_index": 2151, "middle_length": 229}} {"prefix": "ext-with-deps dev|build`\n// Make sure you delete node_modules if you are editing the package otherwise it won't\n// reinstall and reflect your changes.\n\nimport ExportsDefault from 'my-external-cjs-package/exports'\nimport * as ExportsNamed from 'my-external-cjs-package/exports'\nimport { named as namedExports } from 'my-external-cjs-package/exports'\n\nimport ImportsDefault from 'my-external-cjs-package/imports'\nimport * as ImportsNamed from 'my-external-cjs-package/imports'\nimport { named as namedImports } from", "suffix": "mod) => JSON.stringify(mod)\n)\n\nimport Client from './client'\n\nexport default function Page() {\n return (\n <>\n
    \n

    Server

    \n
    \n

    Exports

    \n
    \n

    Static

    \n ", "middle": " 'my-external-cjs-package/imports'\n\nconst pendingDynamicExports = import('my-external-cjs-package/exports').then(\n (mod) => JSON.stringify(mod)\n)\n\nconst pendingDynamicImports = import('my-external-cjs-package/imports').then(\n (", "meta": {"filepath": "test/e2e/app-dir/next-condition/fixtures/render/app/external-cjs/page.tsx", "language": "tsx", "file_size": 2037, "cut_index": 563, "middle_length": 229}} {"prefix": "ge with correct UI elements', async () => {\n const browser = await next.browser('/trigger-error')\n\n // Trigger a client-side error\n await browser.elementByCss('#trigger-error').click()\n\n // Skip UI checks in dev mode (redbox overlay covers the error page)\n if (isNextDev) {\n await expect(browser).toDisplayRedbox(`\n {\n \"description\": \"Test client error\",\n \"environmentLabel\": null,\n \"label\": \"Runtime Error\",\n \"source\": \"app/trigger-error/page.js (9:11) ", "suffix": " }\n\n // In production mode, verify the client error page UI elements\n\n // Check that the SVG icon is present (32x32 size)\n const svgIcon = await browser.elementByCss('svg')\n expect(await svgIcon.getAttribute('width')).toBe('32')\n expect(a", "middle": "@ TriggerErrorPage\n > 9 | throw new Error('Test client error')\n | ^\",\n \"stack\": [\n \"TriggerErrorPage app/trigger-error/page.js (9:11)\",\n ],\n }\n `)\n return\n", "meta": {"filepath": "test/e2e/app-dir/default-error-page-ui/default-error-page-ui.test.ts", "language": "typescript", "file_size": 5122, "cut_index": 716, "middle_length": 229}} {"prefix": "remove this test when the feature is stable\ndescribe('global-not-found - not-present', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should render default 404 when global-not-found is not defined but enabled', async () => {\n const browser = await next.browser('/does-not-exist')\n const bodyText = await browser.elementByCss('body').text()\n expect(bodyText).toBe('404\\nThis page could not be found.')\n })\n\n it('should render custom not-found.js boundary when global-not-f", "suffix": "const browser = await next.browser('/call-not-found')\n const bodyText = await browser.elementByCss('body').text()\n const htmlLang = await browser.elementByCss('html').getAttribute('lang')\n // Render the root layout\n expect(htmlLang).toBe('en')\n", "middle": "ound is not defined but enabled', async () => {\n ", "meta": {"filepath": "test/e2e/app-dir/global-not-found/not-present/not-present.test.ts", "language": "typescript", "file_size": 980, "cut_index": 582, "middle_length": 52}} {"prefix": "ly you need to use `pnpm next-with-deps dev|build`\n// Make sure you delete node_modules if you are editing the package otherwise it won't\n// reinstall and reflect your changes.\n\nimport ExportsDefault from 'my-esm-package/exports'\nimport * as ExportsNamed from 'my-esm-package/exports'\nimport { named as namedExports } from 'my-esm-package/exports'\n\nimport ImportsDefault from 'my-esm-package/imports'\nimport * as ImportsNamed from 'my-esm-package/imports'\nimport { named as namedImports } from 'my-esm-package/im", "suffix": "m './client'\n\nexport default function Page() {\n return (\n <>\n
    \n

    Server

    \n
    \n

    Exports

    \n
    \n

    Static

    \n \n
    {JSON", "middle": "ports'\n\nconst pendingDynamicExports = import('my-esm-package/exports').then((mod) =>\n JSON.stringify(mod)\n)\n\nconst pendingDynamicImports = import('my-esm-package/imports').then((mod) =>\n JSON.stringify(mod)\n)\n\nimport Client fro", "meta": {"filepath": "test/e2e/app-dir/next-condition/fixtures/render/app/esm/page.tsx", "language": "tsx", "file_size": 1963, "cut_index": 537, "middle_length": 229}} {"prefix": "lient'\n\nimport { useState, useTransition } from 'react'\n\nexport function RevalidateButton({ lang }) {\n const [isPending, startTransition] = useTransition()\n const [result, setResult] = useState(null)\n\n function handleRevalidate(withSlash) {\n startTransition(async () => {\n try {\n const data = await fetch(\n `/api/revalidate/?lang=${lang}&withSlash=${withSlash}`\n ).then((res) => res.json())\n startTransition(() => {\n setResult(`Revalidated at: ${data.timestamp}`", "suffix": "abled={isPending}\n id=\"revalidate-button-with-slash\"\n >\n {isPending ? 'Revalidating...' : `Revalidate /${lang}/`}\n \n {\n setResult(`Error: ${e}`)\n })\n }\n })\n }\n\n return (\n
    \n {\n const { next } = nextTestSetup({\n files: __dirname,\n dependencies,\n nextConfig,\n })\n it(`should include font on the page`, async () => {\n const ", "suffix": " = await browser.eval(async function () {\n return document.fonts.ready.then((fonts) => {\n const includedFonts = []\n for (const font of fonts.values()) {\n includedFonts.push(font.family)\n }\n return inclu", "middle": "browser = await next.browser('/')\n const result", "meta": {"filepath": "test/e2e/app-dir/scss/external-url/external-url.test.ts", "language": "typescript", "file_size": 974, "cut_index": 582, "middle_length": 52}} {"prefix": "ion cachedConsoleCalls(outBadge: string, errBadge: string) {\n 'use cache'\n console.info(\n `${outBadge} /console-after-abort/server: template(one: %s, two: %s)`,\n 'one',\n 'two'\n )\n console.log(\n `${outBadge} /console-after-abort/server: This is a console page` +\n \". Don't match the codeframe.\"\n )\n console.warn(`${errBadge} /console-after-abort/server: not a template`, {\n foo: 'just-some-object',\n })\n // TODO(veil): Assert on inspected errors once we sourcemap errors replayed from ", "suffix": "ssert(\n true,\n `${errBadge} /console-after-abort/server: This is an assert message without a template`\n )\n}\n\nlet i = 0\nexport default async function ConsolePage() {\n const outBadge = `:::${i}:out:::`\n const errBadge = `:::${i++}:err:::`\n\n console", "middle": "Cache environment.\n // console.error(new Error('/console-after-abort/server: test'))\n console.assert(\n false,\n `${errBadge} /console-after-abort/server: This is an assert message with a %s`,\n 'template'\n )\n console.a", "meta": {"filepath": "test/e2e/app-dir/cache-components-console/fixtures/hide-logs-after-abort/app/console-after-abort/server/page.tsx", "language": "tsx", "file_size": 2218, "cut_index": 563, "middle_length": 229}} {"prefix": "e client'\n\nimport { use } from 'react'\n\nfunction log(outBadge: string, errBadge: string) {\n console.info(\n `${outBadge} /console-after-abort/client: template(one: %s, two: %s)`,\n 'one',\n 'two'\n )\n console.log(\n `${outBadge} /console-after-abort/client: This is a console page. Don't match the codeframe.`\n )\n console.warn(`${errBadge} /console-after-abort/client: not a template`, {\n foo: 'just-some-object',\n })\n console.error(new Error(`${errBadge} /console-after-abort/client: test`))\n ", "suffix": " without a template`\n )\n}\n\nexport default function ClientConsolePage({\n data,\n outBadge,\n errBadge,\n}: {\n data: Promise\n outBadge: string\n errBadge: string\n}) {\n console.log(\n `${outBadge} /console-after-abort/client: logging before prerend", "middle": "console.assert(\n false,\n `${errBadge} /console-after-abort/client: This is an assert message with a %s`,\n 'template'\n )\n console.assert(\n true,\n `${errBadge} /console-after-abort/client: This is an assert message", "meta": {"filepath": "test/e2e/app-dir/cache-components-console/fixtures/hide-logs-after-abort/app/console-after-abort/client/client.tsx", "language": "tsx", "file_size": 1117, "cut_index": 515, "middle_length": 229}} {"prefix": "mport * as path from 'path'\nimport { nextTestSetup, type Playwright } from 'e2e-utils'\n\nasync function assertNoConsoleErrors(browser: Playwright) {\n const logs = await browser.log()\n const warningsAndErrors = logs.filter((log) => {\n return log.source === 'warning' || log.source === 'error'\n })\n\n expect(warningsAndErrors).toEqual([])\n}\n\ndescribe('view-transitions', () => {\n const { next } = nextTestSetup({\n files: path.join(__dirname, 'fixtures/default'),\n })\n\n it('smoketest', async () => {\n ", "suffix": "rors(browser)\n\n // Click the link to navigate to page two\n // The first link causes a sliding transition\n // The second link causes a default transition (cross-fade)\n await browser.elementByCss('a[href=\"/transition-types/page-two\"]').click()\n\n ", "middle": "const browser = await next.browser('/basic')\n\n await assertNoConsoleErrors(browser)\n })\n\n it('transitionTypes smoketest', async () => {\n const browser = await next.browser('/transition-types')\n\n await assertNoConsoleEr", "meta": {"filepath": "test/e2e/app-dir/view-transitions/view-transitions.test.ts", "language": "typescript", "file_size": 1046, "cut_index": 513, "middle_length": 229}} {"prefix": "e-build-file', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n skipStart: !isNextDev,\n skipDeployment: true,\n env: {\n // Enable persistent caching even when the git working directory is\n // dirty (e.g. when developing Next.js itself). Without this, the\n // cache falls back to a temp directory and persistence/compaction\n // spans are not emitted.\n TURBO_ENGINE_IGNORE_DIRTY: '1',\n },\n })\n\n if (isNextStart) {\n it('should create .next/trace-build file ", "suffix": "\n expect(existsSync(traceBuildPath)).toBe(true)\n })\n\n it('should contain high-level build trace events', async () => {\n // Ensure we have a fresh build\n await next.build()\n\n const traceBuildPath = join(next.testDir, '.next/trace-b", "middle": "during production build', async () => {\n // Build the app to trigger trace generation\n await next.build()\n\n // Check that trace-build file exists\n const traceBuildPath = join(next.testDir, '.next/trace-build')", "meta": {"filepath": "test/e2e/app-dir/trace-build-file/trace-build-file.test.ts", "language": "typescript", "file_size": 6589, "cut_index": 716, "middle_length": 229}} {"prefix": "'\n\ndescribe('nx-handling', () => {\n const { next } = nextTestSetup({\n skipDeployment: true,\n files: __dirname,\n installCommand: 'npm i',\n buildCommand: 'npm run build',\n startCommand: isNextDev ? 'npm run dev' : 'npm run start',\n packageJson: {\n name: '@nx-next/source',\n version: '0.0.0',\n private: true,\n packageManager: 'npm@10.9.2',\n scripts: {\n // Nx's isolated plugin worker can race in CI and crash before Next.js\n // starts, so keep this fixture ", "suffix": " nx run next-nx-test:serve:production',\n },\n dependencies: {\n react: '19.0.0',\n 'react-dom': '19.0.0',\n '@nx/js': '21.1.3',\n '@nx/next': '21.1.3',\n '@nx/workspace': '21.1.3',\n '@swc-node/register': '~1.9.", "middle": "focused on Next.js integration.\n build:\n 'rm -rf dist; NX_ISOLATE_PLUGINS=false nx run next-nx-test:build',\n dev: 'NX_ISOLATE_PLUGINS=false nx run next-nx-test:dev',\n start: 'NX_ISOLATE_PLUGINS=false", "meta": {"filepath": "test/e2e/app-dir/nx-handling/nx-handling.test.ts", "language": "typescript", "file_size": 2125, "cut_index": 563, "middle_length": 229}} {"prefix": " strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth=\"2\"\n d=\"M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.", "suffix": " \n
    \n
    \n \n ", "middle": "438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z\"\n />\n \n You're up and running\n \n What's next?", "meta": {"filepath": "test/e2e/app-dir/nx-handling/apps/next-nx-test/app/page.tsx", "language": "tsx", "file_size": 20905, "cut_index": 1331, "middle_length": 229}} {"prefix": ", 'regular'),\n })\n\n if (isNextDev) {\n // dev doesn't support prefetch={true}, so this just performs a basic test to make sure data is reused for 30s\n it('should return fresh data every navigation', async () => {\n let browser = await next.browser('/', browserConfigWithFixedTime)\n\n // navigate to prefetch-auto page\n await browser.elementByCss('[href=\"/1\"]').click()\n\n let initialNumber = await browser.elementById('random-number').text()\n\n // Navigate back to the index, and then", "suffix": ".elementById('random-number').text()\n\n expect(newNumber).not.toBe(initialNumber)\n })\n } else {\n describe('prefetch={true}', () => {\n let browser: Playwright\n\n beforeEach(async () => {\n browser = await next.browser('/', browserC", "middle": " back to the prefetch-auto page\n await browser.elementByCss('[href=\"/\"]').click()\n await browser.eval(fastForwardTo, 5 * 1000)\n await browser.elementByCss('[href=\"/1\"]').click()\n\n let newNumber = await browser", "meta": {"filepath": "test/e2e/app-dir/app-client-cache/client-cache.defaults.test.ts", "language": "typescript", "file_size": 10715, "cut_index": 921, "middle_length": 229}} {"prefix": "res', 'regular'),\n nextConfig: {\n experimental: { staleTimes: { dynamic: 0 } },\n },\n env: {\n NEXT_TELEMETRY_DEBUG: '1',\n },\n })\n\n if (isNextDev) {\n // dev doesn't support prefetch={true}, so this just performs a basic test to make sure data is fresh on each navigation\n it('should trigger a loading state before fetching the page, followed by fresh data on every subsequent navigation', async () => {\n const browser = await next.browser('/', browserConfig", "suffix": "ing state is rendered\n await browser\n .elementByCss('[href=\"/1?timeout=1000\"]')\n .click()\n .waitForElementByCss('#loading')\n\n const initialRandomNumber = await browser\n .waitForElementByCss('#random-number'", "middle": "WithFixedTime)\n\n // Wait for initial prefetch to complete before clicking\n await browser.waitForIdleNetwork()\n\n // this test introduces an artificial delay in rendering the requested page, so we verify a load", "meta": {"filepath": "test/e2e/app-dir/app-client-cache/client-cache.experimental.test.ts", "language": "typescript", "file_size": 15322, "cut_index": 921, "middle_length": 229}} {"prefix": "s a basic test to make sure data is reused for 30s\n it('should renew the 30s cache once the data is revalidated', async () => {\n let browser = await next.browser('/', browserConfigWithFixedTime)\n\n // navigate to prefetch-auto page\n await browser.elementByCss('[href=\"/1\"]').click()\n await browser.waitForElementByCss('#random-number')\n\n let initialNumber = await browser.elementById('random-number').text()\n\n // Navigate back to the index, and then back to the prefetch-auto page", "suffix": "browser.waitForElementByCss('#random-number')\n\n let newNumber = await browser.elementById('random-number').text()\n\n // the number should be the same, as we navigated within 30s.\n expect(newNumber).toBe(initialNumber)\n\n // Fast forward t", "middle": "\n await browser.elementByCss('[href=\"/\"]').click()\n await browser.waitForElementByCss('[href=\"/1\"]')\n await browser.eval(fastForwardTo, 5 * 1000)\n await browser.elementByCss('[href=\"/1\"]').click()\n await ", "meta": {"filepath": "test/e2e/app-dir/app-client-cache/client-cache.original.test.ts", "language": "typescript", "file_size": 17684, "cut_index": 1331, "middle_length": 229}} {"prefix": "'\nimport path from 'path'\nimport type { Page as PlaywrightPage } from 'playwright'\n\n// TODO: This suite is flaky in production and deploy modes, skip until stabilized.\ndescribe.skip('app dir client cache with parallel routes', () => {\n const { next, isNextDev } = nextTestSetup({\n files: path.join(__dirname, 'fixtures', 'parallel-routes'),\n })\n\n if (isNextDev) {\n // dev doesn't support prefetch={true}\n it('should skip dev', () => {})\n return\n }\n\n async function reveal(browser: Playwright, hr", "suffix": "eveal the content.\n await reveal.click()\n\n // Return the anchor link element.\n return browser.elementByCss(`a[href=\"${href}\"]`)\n }\n\n describe('prefetch={true}', () => {\n it('should prefetch the full page', async () => {\n let page: Playwr", "middle": "ef: string) {\n // Get the reveal element and scroll it into view.\n const reveal = await browser.elementByCss(`[data-link-accordion=\"${href}\"]`)\n await reveal.scrollIntoViewIfNeeded()\n\n // Click the reveal element to r", "meta": {"filepath": "test/e2e/app-dir/app-client-cache/client-cache.parallel-routes.test.ts", "language": "typescript", "file_size": 4321, "cut_index": 614, "middle_length": 229}} {"prefix": "} from 'e2e-utils'\n\nexport const getPathname = (url: string) => {\n const urlObj = new URL(url)\n return urlObj.pathname\n}\n\nexport const browserConfigWithFixedTime = {\n beforePageLoad: (page) => {\n page.addInitScript(() => {\n const startTime = new Date()\n const fixedTime = new Date('2023-04-17T00:00:00Z')\n\n // Override the Date constructor\n // @ts-ignore\n // eslint-disable-next-line no-native-reassign\n Date = class extends Date {\n constructor() {\n super()\n ", "suffix": "ment the fixed time by the specified duration\n const currentTime = new Date()\n currentTime.setTime(currentTime.getTime() + ms)\n\n // Update the Date constructor to use the new fixed time\n // @ts-ignore\n // eslint-disable-next-line no-native-reassign\n ", "middle": " // @ts-ignore\n return new startTime.constructor(fixedTime)\n }\n\n static now() {\n return fixedTime.getTime()\n }\n }\n })\n },\n}\n\nexport const fastForwardTo = (ms) => {\n // Incre", "meta": {"filepath": "test/e2e/app-dir/app-client-cache/test-utils.ts", "language": "typescript", "file_size": 1633, "cut_index": 537, "middle_length": 229}} {"prefix": "turn (\n <>\n
    \n \n To Random Number - prefetch: true\n \n
    \n
    \n \n To Random Number - prefetch: true, slow\n \n
    \n
    \n To Random Number - prefetch: auto\n
    \n
    \n \n To Random Number 2 - prefetch: false\n \n \n To Random Number 2 - prefetch: false, slow\n \n
    \n
    \n \n To Random Number - prefetch: auto, slow\n \n
    \n
    \n \n
    \n \n
    \n \n To Random Number - prefetch: true\n \n
    \n
    \n \n To Random Number - prefetch: true, slow\n \n
    \n
    \n To Random Number - prefetch: auto\n
    \n
    \n \n To", "suffix": "
    \n
    \n \n To Random Number 2 - prefetch: false, slow\n \n
    \n
    \n \n To ", "middle": " Random Number 2 - prefetch: false\n \n ", "meta": {"filepath": "test/e2e/app-dir/app-client-cache/fixtures/regular/app/without-loading/page.js", "language": "javascript", "file_size": 970, "cut_index": 582, "middle_length": 52}} {"prefix": "rowser,\n 'description',\n 'this is the layout description'\n )\n })\n\n it('should support title template', async () => {\n const browser = await next.browser('/title-template')\n // Use the parent layout (root layout) instead of app/title-template/layout.tsx\n expect(await browser.eval(`document.title`)).toBe('Page')\n })\n\n it('should support stashed title in one layer of page and layout', async () => {\n const browser = await next.browser('/title-template/extra')\n ", "suffix": "title when no title is defined in page', async () => {\n const browser = await next.browser('/title-template/use-layout-title')\n expect(await browser.eval(`document.title`)).toBe(\n 'title template layout default'\n )\n })\n\n it('sho", "middle": " // Use the parent layout (app/title-template/layout.tsx) instead of app/title-template/extra/layout.tsx\n expect(await browser.eval(`document.title`)).toBe('Extra Page | Layout')\n })\n\n it('should use parent layout ", "meta": {"filepath": "test/e2e/app-dir/metadata/metadata.test.ts", "language": "typescript", "file_size": 32881, "cut_index": 1331, "middle_length": 229}} {"prefix": "ge() {\n return (\n <>\n

    {'BEGINNINGasdsadiasdhasuidhasdiuasduhiuihueiohjewiohjewiohj'}

    \n

    {'asdsadiasdhasuidhasdiuasasdsadduhiuihueiohjewiohjewiohj'}

    \n

    {'asdasd'}

    \n

    {'asdasdasadasdasd232344234234234'}

    \n

    {'asdsadiasdhasuidhasdiuasasdsadduhiuihueiohjewiohjewiohj'}

    \n

    {'asdasd'}

    \n

    {'asdasdasadasdasd232344234234234'}

    \n

    {'asdsadiasdhasuidhasdiuasasdsadduhiuihueiohjewiohjewiohj'}

    \n

    {'asdasd'}

    \n

    {'asdasdasada", "suffix": "4234'}

    \n

    {'asdsadiasdhasuidhasdiuasasdsadduhiuihueiohjewiohjewiohj'}

    \n

    {'asdasd'}

    \n

    {'asdasdasadasdasd232344234234234'}

    \n

    {'asdsadiasdhasuidhasdiuasasdsadduhiuihueiohjewiohjewiohj'}

    \n

    {'asdasd'}

    \n ", "middle": "sdasd232344234234234'}

    \n

    {'asdsadiasdhasuidhasdiuasduhiuihueiohjewiohjewiohj'}

    \n

    {'asdsadiasdhasuidhasdiuasasdsadduhiuihueiohjewiohjewiohj'}

    \n

    {'asdasd'}

    \n

    {'asdasdasadasdasd23234423423", "meta": {"filepath": "test/e2e/app-dir/metadata/app/large-shell/[slug]/page.tsx", "language": "tsx", "file_size": 5816, "cut_index": 716, "middle_length": 229}} {"prefix": " from 'react'\nimport type { Metadata } from 'next'\nimport Link from 'next/link'\nimport Client from './client'\n\nexport default function Page() {\n return (\n

    \n \n to index\n \n
    \n \n to /title-template/extra/inner\n \n \n
    \n )\n}\n\nexport const metadata: Metadata = {\n generator: 'next.js',\n applicationName: 'test',\n referrer: 'origi", "suffix": "dex, follow',\n alternates: {},\n pagination: {\n previous: '/basic?page=1',\n next: '/basic?page=3',\n },\n formatDetection: {\n email: false,\n address: false,\n telephone: false,\n // Properties set to `true` should not be included in `forma", "middle": "n-when-cross-origin',\n keywords: ['next.js', 'react', 'javascript'],\n authors: [{ name: 'huozhi' }, { name: 'tree', url: 'https://tree.com' }],\n manifest: '/api/manifest',\n creator: 'shu',\n publisher: 'vercel',\n robots: 'in", "meta": {"filepath": "test/e2e/app-dir/metadata/app/basic/page.tsx", "language": "tsx", "file_size": 1324, "cut_index": 524, "middle_length": 229}} {"prefix": "'\n\nexport const runtime = 'edge'\n\nexport default function Page() {\n return (\n
    \n \n to index\n \n
    \n \n to /title-template/extra/inner\n \n \n
    \n )\n}\n\nexport const metadata: Metadata = {\n generator: 'next.js',\n applicationName: 'test',\n referrer: 'origin-when-cross-origin',\n keywords: ['next.js', 'react', 'javascript'],\n autho", "suffix": "://tree.com' }],\n manifest: '/api/manifest',\n robots: 'index, follow',\n alternates: {},\n pagination: {\n previous: '/basic?page=1',\n next: '/basic?page=3',\n },\n formatDetection: {\n email: false,\n address: false,\n telephone: false,\n },\n", "middle": "rs: [{ name: 'huozhi' }, { name: 'tree', url: 'https", "meta": {"filepath": "test/e2e/app-dir/metadata/app/basic-edge/page.tsx", "language": "tsx", "file_size": 916, "cut_index": 606, "middle_length": 52}} {"prefix": " { nextTestSetup } from 'e2e-utils'\n\ndescribe('cache-components PPR bot static generation bypass', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should bypass static generation for DOM bot requests to avoid SSG_BAILOUT', async () => {\n const res = await next.fetch('/foo', {\n headers: {\n 'user-agent': 'Googlebot',\n },\n })\n // With cache components + PPR enabled, DOM bots should behave like regular users\n // and use the fallback cache mechanism. This", "suffix": "\n\n // Check that the page rendered successfully\n // With PPR, content is streamed via script tags\n expect(html).toContain('\\\\\"children\\\\\":\\\\\"foo\\\\\"')\n\n // Verify Math.random() was executed (check for a decimal number in the streamed content)\n ", "middle": " allows them to handle dynamic content\n // like Math.random() without triggering SSG_BAILOUT errors.\n expect(res.status).toBe(200)\n\n // Verify that the response contains the page content\n const html = await res.text()", "meta": {"filepath": "test/e2e/app-dir/cache-components-bot-ua/cache-components-bot-ua.test.ts", "language": "typescript", "file_size": 1175, "cut_index": 518, "middle_length": 229}} {"prefix": "retry } from 'next-test-utils'\n\ndescribe('interception-dynamic-segment-middleware', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should work when interception route is paired with a dynamic segment & middleware', async () => {\n const browser = await next.browser('/')\n\n await browser.elementByCss('[href=\"/foo/p/1\"]').click()\n await retry(async () => {\n expect(await browser.elementById('modal').text()).toMatch(/intercepted/)\n })\n await browser.refresh()\n ", "suffix": " )\n })\n })\n\n it('should intercept with back/forward navigation with middleware', async () => {\n // Test that interception works correctly with middleware and browser navigation\n const browser = await next.browser('/')\n\n // Navigate with ", "middle": "await retry(async () => {\n expect(await browser.elementById('modal').text()).toBe('default')\n })\n await retry(async () => {\n expect(await browser.elementById('children').text()).toMatch(\n /not intercepted/\n", "meta": {"filepath": "test/e2e/app-dir/interception-dynamic-segment-middleware/interception-dynamic-segment-middleware.test.ts", "language": "typescript", "file_size": 2168, "cut_index": 563, "middle_length": 229}} {"prefix": "routes-breadcrumbs', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should provide an unmatched catch-all route with params', async () => {\n const browser = await next.browser('/')\n await browser.elementByCss(\"[href='/artist1']\").click()\n\n const slot = await browser.waitForElementByCss('#slot')\n\n // verify page is rendering the params\n expect(await browser.elementByCss('h2').text()).toBe('Artist: artist1')\n\n // verify slot is rendering the params\n expect(aw", "suffix": "um2']\").click()\n\n await retry(async () => {\n // verify page is rendering the params\n expect(await browser.elementByCss('h2').text()).toBe('Album: album2')\n })\n\n // verify slot is rendering the params\n expect(await slot.text()).toConta", "middle": "ait slot.text()).toContain('Artist: artist1')\n expect(await slot.text()).toContain('Album: Select an album')\n expect(await slot.text()).toContain('Track: Select a track')\n\n await browser.elementByCss(\"[href='/artist1/alb", "meta": {"filepath": "test/e2e/app-dir/parallel-routes-breadcrumbs/parallel-routes-breadcrumbs.test.ts", "language": "typescript", "file_size": 3476, "cut_index": 614, "middle_length": 229}} {"prefix": "he layout manually\n;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(\n 'app-dir create root layout',\n () => {\n const isDev = (global as any).isNextDev\n\n if ((global as any).isNextDeploy) {\n it('should skip next deploy for now', () => {})\n return\n }\n\n if (isDev) {\n describe('page.js', () => {\n describe('root layout in app', () => {\n const { next } = nextTestSetup({\n files: {\n app: new FileRef(path.join(__dirname, 'app')),\n ", "suffix": "tput.length\n const browser = await next.browser('/route')\n\n expect(await browser.elementById('page-text').text()).toBe(\n 'Hello world!'\n )\n\n await check(\n () => stripAnsi(next.cliOutput.", "middle": " 'next.config.js': new FileRef(\n path.join(__dirname, 'next.config.js')\n ),\n },\n })\n\n it('create root layout', async () => {\n const outputIndex = next.cliOu", "meta": {"filepath": "test/e2e/app-dir/create-root-layout/create-root-layout.test.ts", "language": "typescript", "file_size": 7179, "cut_index": 716, "middle_length": 229}} {"prefix": "t { next, isNextDev, isNextStart } = nextTestSetup({\n files: __dirname,\n })\n\n it('should generate an opengraph image with a metadata route handler that uses \"use cache\"', async () => {\n const res = await next.fetch('/opengraph-image')\n expect(res.status).toBe(200)\n expect(res.headers.get('content-type')).toBe('image/png')\n\n if (isNextStart) {\n const [buildStatus] = next.cliOutput.match(/. \\/opengraph-image/)\n\n // TODO: Should always be `○ /opengraph-image`.\n expect(buildStatu", "suffix": "tch('/icon')\n expect(res.status).toBe(200)\n expect(res.headers.get('content-type')).toBe('image/png')\n\n if (isNextStart) {\n const [buildStatus] = next.cliOutput.match(/. \\/icon/)\n\n // TODO: Should always be `○ /icon`.\n expect(buildS", "middle": "s).toBeOneOf([\n '○ /opengraph-image',\n 'ƒ /opengraph-image',\n ])\n }\n })\n\n it('should generate an icon image with a metadata route handler that uses \"use cache\"', async () => {\n const res = await next.fe", "meta": {"filepath": "test/e2e/app-dir/use-cache-metadata-route-handler/use-cache-metadata-route-handler.test.ts", "language": "typescript", "file_size": 4948, "cut_index": 614, "middle_length": 229}} {"prefix": "rt { ImageResponse } from 'next/og'\n\nexport const alt = 'About Acme'\nexport const size = { width: 1200, height: 630 }\nexport const contentType = 'image/png'\n\nasync function fetchPostData() {\n 'use cache'\n\n return { title: 'Test', created: Date.now() }\n}\n\nexport default async function Image() {\n const post = await fetchPostData()\n\n return new ImageResponse(\n (\n \n

    {post.title}

    \n

    \n {new Date(post.created).toLocaleTimeString()}\n

    \n
    \n ),\n size\n )", "middle": " display: 'flex',\n alignItems: 'center',\n ", "meta": {"filepath": "test/e2e/app-dir/use-cache-metadata-route-handler/app/opengraph-image.tsx", "language": "tsx", "file_size": 827, "cut_index": 516, "middle_length": 52}} {"prefix": "retry } from 'next-test-utils'\n\ndescribe('next/script beforeInteractive inline payload escaping', () => {\n const { next } = nextTestSetup({\n files: __dirname,\n })\n\n it('should html-escape forwarded string props so they cannot break out of the inline __next_s script', async () => {\n const html = await next.render('/')\n\n // The attacker-controlled prop values must not appear verbatim in the HTML.\n // If they do, the `` inside terminates the inline __next_s push\n // script at the HTM", "suffix": "lineChildren=true'\n )\n expect(html).not.toContain('')\n\n // The fixture's exposes each result as a `data-*`\n // attribute on `[data-testid=\"xss-status\"]`. `data-ready=\"true\"`", "middle": "L tokenizer level and the trailing '\n )\n expect(html).not.toContain(\n '` breaks out of the script element at the\n// HTML tokenizer level, executes, and", "suffix": "acking-id=\"\"\n dangerouslySetInnerHTML={{\n // The body evaluates a `<` comparison so the global doubles as proof\n // of both \"did this run\" and \"did the HTML-escape preserve ", "middle": " the fingerprint it leaves on `window`\n// is picked up by .\nexport default function Page() {\n return (\n
    \n ` executed. Each would set a\n// `__xss*` global from its `` break-out.\n// 2. Whether each legitimate beforeInteractive `\n \n \n \n
    \n

    Page

    \n {children}\n ", "suffix": "links.map(({ href }) => (\n
  • \n {href} - link -{' '}\n anchor\n
  • \n ))}\n \n
    \n \n \n ", "middle": "

    Links

    \n