prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
mport type { FlightRouterState } from '../../../../shared/lib/app-router-types'
// The tree from the last state that was committed to the browser history
// (i.e., the last state for which HistoryUpdater's useInsertionEffect ran).
// This lets the server-patch reducer distinguish between retrying a
// navigation that ... | volve into (or be subsumed by) that new
// implementation.
let lastCommittedTree: FlightRouterState | null = null
export function getLastCommittedTree(): FlightRouterState | null {
return lastCommittedTree
}
export function setLastCommittedTree(tree: F | d a broader refactor of the navigation queue. The
// existing AppRouter action queue will eventually be replaced by a more
// reactive model that explicitly tracks pending vs committed navigation
// state. This file will likely e | {
"filepath": "packages/next/src/client/components/router-reducer/reducers/committed-state.ts",
"language": "typescript",
"file_size": 1053,
"cut_index": 513,
"middle_length": 229
} |
ct-server-dom-webpack/client'
import type {
ReadonlyReducerState,
ReducerState,
ServerActionAction,
} from '../router-reducer-types'
import { ScrollBehavior } from '../router-reducer-types'
import { assignLocation } from '../../../assign-location'
import { createHrefFromUrl } from '../create-href-from-url'
impor... | ./../../has-base-path'
import {
extractInfoFromServerReferenceId,
omitUnusedArgs,
} from '../../../../shared/lib/server-reference-info'
import { invalidateEntirePrefetchCache } from '../../segment-cache/cache'
import { startRevalidationCooldown } from | m '../../../flight-data-helpers'
import { getRedirectError } from '../../redirect'
import type { RedirectType } from '../../redirect-error'
import { removeBasePath } from '../../../remove-base-path'
import { hasBasePath } from '. | {
"filepath": "packages/next/src/client/components/router-reducer/reducers/server-action-reducer.ts",
"language": "typescript",
"file_size": 21027,
"cut_index": 1331,
"middle_length": 229
} |
type AppRouterInstance,
} from '../../shared/lib/app-router-context.shared-runtime'
import {
checkFormActionUrl,
createFormSubmitDestinationUrl,
DISALLOWED_FORM_PROPS,
hasReactClientActionAttributes,
hasUnsupportedSubmitterAttributes,
type FormProps,
} from '../form-shared'
import {
mountFormInstance,
... | // Validate `action`
if (process.env.NODE_ENV === 'development') {
if (isNavigatingForm) {
checkFormActionUrl(actionProp, 'action')
}
}
// Validate `prefetch`
if (process.env.NODE_ENV === 'development') {
if (
!(
pr | ce,
scroll,
prefetch: prefetchProp,
ref: externalRef,
...props
}: FormProps) {
const router = useContext(AppRouterContext)
const actionProp = props.action
const isNavigatingForm = typeof actionProp === 'string'
| {
"filepath": "packages/next/src/client/app-dir/form.tsx",
"language": "tsx",
"file_size": 6937,
"cut_index": 716,
"middle_length": 229
} |
arams'
import { ReflectAdapter } from '../../server/web/spec-extension/adapters/reflect'
import {
describeStringPropertyAccess,
wellKnownProperties,
} from '../../shared/lib/utils/reflect-utils'
interface CacheLifetime {}
const CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()
function makeDynamically... | lve(underlyingParams)
const proxiedProperties = new Set<string>()
Object.keys(underlyingParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underl | We don't use makeResolvedReactPromise here because params
// supports copying with spread and we don't want to unnecessarily
// instrument the promise with spreadable properties of ReactPromise.
const promise = Promise.reso | {
"filepath": "packages/next/src/client/request/params.browser.dev.ts",
"language": "typescript",
"file_size": 2751,
"cut_index": 563,
"middle_length": 229
} |
ices, type PlaywrightTestConfig } from '@playwright/test'
import type { NextOptionsConfig } from './next-options'
/**
* This is the default configuration generated by Playwright as of v1.43.0 with some modifications.
*
* - the `testMatch` property is configured to match all `*.spec.js` or `*.spec.ts` files within t... | retries: process.env.CI === 'true' ? 2 : 0,
reporter: [['list'], ['html', { open: 'never' }]],
use: {
baseURL: 'http://127.0.0.1:3000',
trace: 'on-first-retry',
},
projects: [
{
name: 'chromium',
use: { .. | red to run `next dev`.
*/
export const defaultPlaywrightConfig: PlaywrightTestConfig<NextOptionsConfig> =
{
testMatch: '{app,pages}/**/*.spec.{t,j}s',
fullyParallel: true,
forbidOnly: process.env.CI === 'true',
| {
"filepath": "packages/next/src/experimental/testmode/playwright/default-config.ts",
"language": "typescript",
"file_size": 1423,
"cut_index": 524,
"middle_length": 229
} |
ction,
ReadonlyReducerState,
ReducerState,
} from '../router-reducer-types'
import {
completeHardNavigation,
navigate as navigateUsingSegmentCache,
} from '../../segment-cache/navigation'
import { getStaleTimeMs } from '../../segment-cache/cache'
import { FreshnessPolicy } from '../ppr-navigations'
// These v... | tate,
action: NavigateAction
): ReducerState {
const { url, isExternalUrl, navigateType, scrollBehavior } = action
if (isExternalUrl) {
return completeHardNavigation(state, url, navigateType)
}
// Handles case where `<meta http-equiv="refre | cess.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME) * 1000
export const STATIC_STALETIME_MS = getStaleTimeMs(
Number(process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME)
)
export function navigateReducer(
state: ReadonlyReducerS | {
"filepath": "packages/next/src/client/components/router-reducer/reducers/navigate-reducer.ts",
"language": "typescript",
"file_size": 1716,
"cut_index": 537,
"middle_length": 229
} |
RuntimeErrorHandler } from '../../runtime-error-handler'
import { useWebSocketPing } from './web-socket'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
HMR_MESSAGE_SENT_TO_SERVER,
} from '../../../../server/dev/hot-reloader-types'
import type {
HmrMessageSentToBrowser,
TurbopackMessageSentToBrowser,
} from '../../../../... | T_HMR_REFRESH_HASH_COOKIE } from '../../../components/app-router-headers'
import {
publicAppRouterInstance,
type GlobalErrorState,
} from '../../../components/app-router-instance'
import { InvariantError } from '../../../../shared/lib/invariant-error'
| -metadata-types'
import { useUntrackedPathname } from '../../../components/navigation-untracked'
import reportHmrLatency from '../../report-hmr-latency'
import { TurbopackHmr } from '../turbopack-hot-reloader-common'
import { NEX | {
"filepath": "packages/next/src/client/dev/hot-reloader/app/hot-reloader-app.tsx",
"language": "tsx",
"file_size": 19178,
"cut_index": 1331,
"middle_length": 229
} |
nt-cache/navigation'
import type { FetchServerResponseResult } from './fetch-server-response'
export const ACTION_REFRESH = 'refresh'
export const ACTION_NAVIGATE = 'navigate'
export const ACTION_RESTORE = 'restore'
export const ACTION_SERVER_PATCH = 'server-patch'
export const ACTION_HMR_REFRESH = 'hmr-refresh'
expor... | the root.
*/
export interface RefreshAction {
type: typeof ACTION_REFRESH
/**
* Bypass invalidating the segment cache. Used by the Instant Navigation
* Testing API to preserve prefetched data when refreshing after an MPA
* navigation. Not ex | RouterState
serverResponse: FetchServerResponseResult
}) => void
/**
* Refresh triggers a refresh of the full page data.
* - fetches the Flight data and fills rsc at the root of the cache.
* - The router state is updated at | {
"filepath": "packages/next/src/client/components/router-reducer/router-reducer-types.ts",
"language": "typescript",
"file_size": 9065,
"cut_index": 716,
"middle_length": 229
} |
{ WorkerRequestHandler } from '../../server/lib/types'
import type { NodeRequestHandler } from '../../server/next-server'
import { withRequest, type TestRequestReader } from './context'
import { interceptFetch } from './fetch'
import { interceptHttpGet } from './httpget'
import type { IncomingMessage } from 'http'
con... | h(originalFetch)
const restoreHttpGet = interceptHttpGet(originalFetch)
// Cleanup.
return () => {
restoreFetch()
restoreHttpGet()
}
}
export function wrapRequestHandlerWorker(
handler: WorkerRequestHandler
): WorkerRequestHandler {
r | return null
}
if (typeof h === 'string') {
return h
}
return h[0] ?? null
},
}
export function interceptTestApis(): () => void {
const originalFetch = global.fetch
const restoreFetch = interceptFetc | {
"filepath": "packages/next/src/experimental/testmode/server.ts",
"language": "typescript",
"file_size": 1277,
"cut_index": 524,
"middle_length": 229
} |
reator } from 'postcss'
// Since the cssnano-preset-simple.js will be bundled into cssnano-simple
// during pre-compilation, we need to test against the source file directly
// @ts-expect-error -- untyped file
import cssnanoPresetSimple from './cssnano-preset-simple'
const cssnanoPlugin: PluginCreator<any> = (options... | s))
}
} else {
plugins.push(nanoPlugin)
}
}
return postcss(plugins)
}
cssnanoPlugin.postcss = true
function noopTemplate(strings: TemplateStringsArray, ...keys: string[]) {
const lastIndex = strings.length - 1
return (
stri | cessor, opts] = nanoPlugin
if (
typeof opts === 'undefined' ||
(typeof opts === 'object' && !opts.exclude) ||
(typeof opts === 'boolean' && opts === true)
) {
plugins.push(processor(opt | {
"filepath": "packages/next/src/bundles/cssnano-simple/cssnano-preset-simple.test.ts",
"language": "typescript",
"file_size": 3014,
"cut_index": 563,
"middle_length": 229
} |
//github.com/Timer/cssnano-simple/blob/master/src/index.js
/**
* This file is the actual "cssnano-simple" implementation, which will eventually be used
* by "next/src/build/cssnano-simple"
*/
const createSimplePreset = require('./cssnano-preset-simple')
module.exports = (opts = {}, postcss = require('postcss')) =... | .assign({}, { exclude: false }, val)
}
}
}
const options = Object.assign(
{},
excludeAll ? { rawCache: true } : undefined,
userOpts
)
const plugins = []
createSimplePreset(options).plugins.forEach((plugin) => {
if (Arr | operty(userOption)) continue
const val = userOpts[userOption]
if (!Boolean(val)) {
continue
}
if (Object.prototype.toString.call(val) === '[object Object]') {
userOpts[userOption] = Object | {
"filepath": "packages/next/src/bundles/cssnano-simple/index.js",
"language": "javascript",
"file_size": 1844,
"cut_index": 537,
"middle_length": 229
} |
'cookie' | 'query'
key: string
value?: string
}
| {
type: 'host'
key?: undefined
value: string
}
export type Route = {
// regex as string can have named or un-named matches
sourceRegex: string
// destination can have matches to replace in destination
// keyed by $1 for ... | L
}
export type ResolveRoutesParams = {
url: URL
buildId: string
basePath: string
requestBody: ReadableStream
headers: Headers
pathnames: string[]
i18n?: {
defaultLocale: string
domains?: Array<{
defaultLocale: string
dom | RL
headers: Headers
requestBody: ReadableStream
}
export type MiddlewareResult = {
bodySent?: boolean
requestHeaders?: Headers
responseHeaders?: Headers
redirect?: {
url: URL
status: number
}
rewrite?: UR | {
"filepath": "packages/next-routing/src/types.ts",
"language": "typescript",
"file_size": 2850,
"cut_index": 563,
"middle_length": 229
} |
lace $1 with first regex capture', async () => {
const params = createBaseParams({
url: new URL('https://example.com/blog/my-post'),
routes: {
beforeMiddleware: [],
beforeFiles: [
{
sourceRegex: '^/blog/([^/]+)$',
destination: '/posts/$1',
},
... | om/2024/01/post-title'),
routes: {
beforeMiddleware: [],
beforeFiles: [
{
sourceRegex: '^/([^/]+)/([^/]+)/([^/]+)$',
destination: '/archive/$1/$2/$3',
},
],
afterFiles: [],
| utes(params)
expect(result.resolvedPathname).toBe('/posts/my-post')
})
it('should replace multiple numbered captures $1, $2, $3', async () => {
const params = createBaseParams({
url: new URL('https://example.c | {
"filepath": "packages/next-routing/src/__tests__/captures.test.ts",
"language": "typescript",
"file_size": 23033,
"cut_index": 1331,
"middle_length": 229
} |
eader condition', async () => {
const headers = new Headers({
'x-user-role': 'admin',
})
const params = createBaseParams({
url: new URL('https://example.com/dashboard'),
headers,
routes: {
beforeMiddleware: [],
beforeFiles: [
{
sourceRegex: '^/d... | t resolveRoutes(params)
expect(result.resolvedPathname).toBe('/admin-dashboard')
})
it('should match route with cookie condition', async () => {
const headers = new Headers({
cookie: 'session=abc123; theme=dark',
})
const param | },
],
},
],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
pathnames: ['/admin-dashboard'],
})
const result = awai | {
"filepath": "packages/next-routing/src/__tests__/conditions.test.ts",
"language": "typescript",
"file_size": 17811,
"cut_index": 1331,
"middle_length": 229
} |
d: 'BUILD_ID',
basePath: '',
requestBody: createReadableStream(),
headers: new Headers(),
pathnames: [],
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
invokeMiddleware: async () => ({}),
... | destination: '/posts/$1',
},
],
dynamicRoutes: [
{
sourceRegex: '^/posts/(?<slug>[^/]+)$',
destination: '/posts/my-post', // Destination matches pathname
},
],
onMatch: [ | aseParams({
url: new URL('https://example.com/blog/my-post'),
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [
{
sourceRegex: '^/blog/([^/]+)$',
| {
"filepath": "packages/next-routing/src/__tests__/dynamic-after-rewrites.test.ts",
"language": "typescript",
"file_size": 13243,
"cut_index": 921,
"middle_length": 229
} |
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
invokeMiddleware: async () => ({ bodySent: false }),
}
const i18nConfig = {
defaultLocale: 'en',
locales: ['en', 'fr', 'de', 'ja'],
domains: [
{ domain: 'example.com', defaultLocal... | s({
...baseParams,
url: new URL('http://example.com/'),
headers: new Headers({
'accept-language': 'fr,en;q=0.9',
}),
i18n: i18nConfigNoDomains,
})
expect(result.redirect).toBeDefined()
ex | cales: ['en', 'fr', 'de', 'ja'],
}
describe('locale detection from accept-language header', () => {
it('should redirect to locale prefix when accept-language is set', async () => {
const result = await resolveRoute | {
"filepath": "packages/next-routing/src/__tests__/i18n-resolve-routes.test.ts",
"language": "typescript",
"file_size": 13499,
"cut_index": 921,
"middle_length": 229
} |
) => {
describe('detectDomainLocale', () => {
const domains = [
{ domain: 'example.com', defaultLocale: 'en', locales: ['en', 'en-US'] },
{ domain: 'example.fr', defaultLocale: 'fr' },
{ domain: 'example.de:3000', defaultLocale: 'de' },
]
it('should detect locale by hostname', () => {
... | fr')).toEqual(domains[1])
expect(detectDomainLocale(domains, 'other.com', 'en-US')).toEqual(
domains[0]
)
})
it('should return undefined for no match', () => {
expect(detectDomainLocale(domains, 'unknown.com')).toBeUndefi | hostname without port', () => {
expect(detectDomainLocale(domains, 'example.de')).toEqual(domains[2])
})
it('should detect locale by detected locale', () => {
expect(detectDomainLocale(domains, 'other.com', ' | {
"filepath": "packages/next-routing/src/__tests__/i18n.test.ts",
"language": "typescript",
"file_size": 8289,
"cut_index": 716,
"middle_length": 229
} |
om-header')).toBe('value')
expect(requestHeaders.get('content-type')).toBe('text/html')
expect(requestHeaders.get('x-custom-header')).toBe('value')
})
it('should set x-middleware-refresh when no routing headers present', () => {
const response = new Response(null, {
status: 200,
... | tatus: 200,
})
response.headers.append('set-cookie', 'cookie1=value1')
response.headers.append('set-cookie', 'cookie2=value2')
const requestHeaders = new Headers()
const url = new URL('https://example.com/test')
const | responseToMiddlewareResult(response, requestHeaders, url)
expect(result.bodySent).toBe(true)
})
it('should handle multiple values for the same header', () => {
const response = new Response(null, {
s | {
"filepath": "packages/next-routing/src/__tests__/middleware.test.ts",
"language": "typescript",
"file_size": 22032,
"cut_index": 1331,
"middle_length": 229
} |
uld normalize data URL before processing beforeMiddleware', async () => {
const params = createBaseParams({
url: new URL('https://example.com/_next/data/BUILD_ID/blog/post.json'),
basePath: '',
routes: {
beforeMiddleware: [],
beforeFiles: [
{
sourceRegex: '^/b... | json'
)
})
it('should normalize with basePath', async () => {
const params = createBaseParams({
url: new URL('https://example.com/base/_next/data/BUILD_ID/page.json'),
basePath: '/base',
routes: {
beforeMiddleware: [] | zeNextData: true,
},
pathnames: ['/_next/data/BUILD_ID/api/blog/post.json'],
})
const result = await resolveRoutes(params)
expect(result.resolvedPathname).toBe(
'/_next/data/BUILD_ID/api/blog/post. | {
"filepath": "packages/next-routing/src/__tests__/normalize-next-data.test.ts",
"language": "typescript",
"file_size": 24626,
"cut_index": 1331,
"middle_length": 229
} |
ndle 301 permanent redirect', async () => {
const params = createBaseParams({
url: new URL('https://example.com/old'),
routes: {
beforeMiddleware: [],
beforeFiles: [
{
sourceRegex: '^/old$',
destination: '/new',
status: 301,
heade... | defined()
expect(result.externalRewrite).toBeUndefined()
})
it('should handle 302 temporary redirect', async () => {
const params = createBaseParams({
url: new URL('https://example.com/temp'),
routes: {
beforeMiddleware: [] | const result = await resolveRoutes(params)
expect(result.redirect).toBeDefined()
expect(result.redirect?.status).toBe(301)
expect(result.redirect?.url.pathname).toBe('/new')
expect(result.resolvedPathname).toBeUn | {
"filepath": "packages/next-routing/src/__tests__/redirects.test.ts",
"language": "typescript",
"file_size": 19131,
"cut_index": 1331,
"middle_length": 229
} |
eateBaseParams({
url: new URL('https://example.com/old'),
routes: {
beforeMiddleware: [
{
sourceRegex: '^/old$',
destination: '/new',
status: 301,
headers: {
Location: '/new',
},
},
],
befor... | aseParams({
url: new URL('https://example.com/en/redirect-1'),
routes: {
beforeMiddleware: [
{
sourceRegex: '^/en/redirect-1(?:/)?$',
status: 307,
headers: {
Location: '/somewh | irect).toBeDefined()
expect(result.redirect?.status).toBe(301)
expect(result.redirect?.url.pathname).toBe('/new')
})
it('should stop at first matching redirect headers route', async () => {
const params = createB | {
"filepath": "packages/next-routing/src/__tests__/resolve-routes.test.ts",
"language": "typescript",
"file_size": 35161,
"cut_index": 2151,
"middle_length": 229
} |
d: 'BUILD_ID',
basePath: '',
requestBody: createReadableStream(),
headers: new Headers(),
pathnames: [],
routes: {
beforeMiddleware: [],
beforeFiles: [],
afterFiles: [],
dynamicRoutes: [],
onMatch: [],
fallback: [],
},
invokeMiddleware: async () => ({}),
... | micRoutes: [],
onMatch: [],
fallback: [],
},
pathnames: ['/posts'],
})
const result = await resolveRoutes(params)
expect(result.resolvedPathname).toBe('/posts')
expect(result.externalRewrite).toBeUndefined()
| mple.com/blog'),
routes: {
beforeMiddleware: [],
beforeFiles: [
{
sourceRegex: '^/blog$',
destination: '/posts',
},
],
afterFiles: [],
dyna | {
"filepath": "packages/next-routing/src/__tests__/rewrites.test.ts",
"language": "typescript",
"file_size": 14896,
"cut_index": 921,
"middle_length": 229
} |
'webpack'
// Shared between webpack 4 and 5:
function injectRefreshFunctions(
compilation: WebpackCompilation,
Template: typeof WebpackTemplate
) {
const hookVars: any = (compilation.mainTemplate.hooks as any).localVars
hookVars.tap('ReactFreshWebpackPlugin', (source: string) =>
Template.asString([
... | ate.indent('};')),
Template.indent('};'),
'}',
])
)
}
function webpack4(this: ReactFreshWebpackPlugin, compiler: WebpackCompiler) {
const { Template } = this
// Webpack 4 does not have a method to handle interception of module
// e |
Template.indent('self.$RefreshSig$ = function () {'),
Template.indent(Template.indent('return function (type) {')),
Template.indent(Template.indent(Template.indent('return type;'))),
Template.indent(Templ | {
"filepath": "packages/react-refresh-utils/ReactRefreshWebpackPlugin.ts",
"language": "typescript",
"file_size": 6722,
"cut_index": 716,
"middle_length": 229
} |
import type { LoaderDefinition } from 'webpack'
import RefreshModuleRuntime from './internal/ReactRefreshModule.runtime'
let refreshModuleRuntime = RefreshModuleRuntime.toString()
refreshModuleRuntime = refreshModuleRuntime
.slice(
refreshModuleRuntime.indexOf('{') + 1,
refreshModuleRuntime.lastIndexOf('}')
... | ,
`${source}\n\n;${
// Account for commonjs not supporting `import.meta
this.resourcePath.endsWith('.cjs')
? commonJsrefreshModuleRuntime
: refreshModuleRuntime
}`,
inputSourceMap
)
}
export default ReactRefreshLo | refreshModuleRuntime = refreshModuleRuntime.replace(
'import.meta.webpackHot',
'module.hot'
)
const ReactRefreshLoader: LoaderDefinition = function ReactRefreshLoader(
source,
inputSourceMap
) {
this.callback(
null | {
"filepath": "packages/react-refresh-utils/loader.ts",
"language": "typescript",
"file_size": 1002,
"cut_index": 512,
"middle_length": 229
} |
clare module 'react-refresh/runtime' {
export function injectIntoGlobalHook(...args: any[]): void
export function register(...args: any[]): void
export function createSignatureFunctionForTransform(...args: any[]): any
export function getFamilyByType(...args: any[]): any
export function isLikelyComponentType(.... | ignatureFunctionForTransform: typeof createSignatureFunctionForTransform
getFamilyByType: typeof getFamilyByType
isLikelyComponentType: typeof isLikelyComponentType
performReactRefresh: typeof performReactRefresh
}
export default RefreshRu | er
createS | {
"filepath": "packages/react-refresh-utils/react-refresh-runtime.d.ts",
"language": "typescript",
"file_size": 792,
"cut_index": 514,
"middle_length": 14
} |
RefreshRuntime from 'react-refresh/runtime'
import RefreshHelpers from './internal/helpers'
export type RefreshRuntimeGlobals = {
$RefreshReg$: (type: unknown, id: string) => void
$RefreshSig$: () => (type: unknown) => unknown
$RefreshInterceptModuleExecution$: (moduleId: string) => () => void
$RefreshHelpers... | $RefreshSig$
self.$RefreshReg$ = function (type, id) {
RefreshRuntime.register(type, webpackModuleId + ' ' + id)
}
self.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform
// Modeled after `useEffect` cleanup pattern:
// https | $RefreshHelpers$ = RefreshHelpers
// Register a helper for module execution interception
self.$RefreshInterceptModuleExecution$ = function (webpackModuleId) {
var prevRefreshReg = self.$RefreshReg$
var prevRefreshSig = self. | {
"filepath": "packages/react-refresh-utils/runtime.ts",
"language": "typescript",
"file_size": 1185,
"cut_index": 518,
"middle_length": 229
} |
obals
type Dictionary = { [key: string]: unknown }
declare const __webpack_module__: {
id: string
exports: unknown
hot: {
accept: () => void
dispose: (onDispose: (data: Dictionary) => void) => void
invalidate: () => void
data?: Dictionary
}
}
// This function gets unwrapped into global scope, ... | ned' &&
// No-JS mode does not inject these helpers:
'$RefreshHelpers$' in self
) {
// @ts-ignore __webpack_module__ is global
var currentExports = __webpack_module__.exports
// @ts-ignore __webpack_module__ is global
| cy CSS implementations will `eval` browser code in a Node.js context
// to extract CSS. For backwards compatibility, we need to check we're in a
// browser context before continuing.
if (
typeof self !== 'undefi | {
"filepath": "packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts",
"language": "typescript",
"file_size": 3745,
"cut_index": 614,
"middle_length": 229
} |
er, { exports: unknown | (() => Promise<unknown>) }>
}
// Extracts exports from a webpack module object.
function getModuleExports(moduleId: string) {
if (typeof moduleId === 'undefined') {
// `moduleId` is unavailable, which indicates that this module is not in the cache,
// which means we won't be able to ... | // We will warn the user (as this is likely a mistake) and assume they cannot be refreshed.
console.warn(
'[React Refresh] Failed to get exports for module: ' + moduleId + '.'
)
return {}
}
var exportsOrPromise = maybeModule.exports
| __.c[moduleId]
if (typeof maybeModule === 'undefined') {
// `moduleId` is available but the module in cache is unavailable,
// which indicates the module is somehow corrupted (e.g. broken Webpack `module` globals).
| {
"filepath": "packages/react-refresh-utils/internal/RspackReactRefresh.ts",
"language": "typescript",
"file_size": 3315,
"cut_index": 614,
"middle_length": 229
} |
n files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditio... | ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// This file is copied from the Metro JavaScrip | ANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR | {
"filepath": "packages/react-refresh-utils/internal/helpers.ts",
"language": "typescript",
"file_size": 5885,
"cut_index": 716,
"middle_length": 229
} |
(s):
// Edge 16, Firefox 60, Chrome 61, Safari 10.1
/**
* Available in:
* Edge: never
* Firefox: 61
* Chrome: 66
* Safari: 12
*
* https://caniuse.com/mdn-javascript_builtins_string_trimstart
* https://caniuse.com/mdn-javascript_builtins_string_trimend
*/
if (!('trimStart' in String.prototype)) {
String.prot... | rue,
get: function get() {
var m = /\((.*)\)/.exec(this.toString())
return m ? m[1] : undefined
},
})
}
/**
* Available in:
* Edge: never
* Firefox: 62
* Chrome: 69
* Safari: 12
*
* https://caniuse.com/array-flat
*/
// Copied | 63
* Chrome: 70
* Safari: 12.1
*
* https://caniuse.com/mdn-javascript_builtins_symbol_description
*/
if (!('description' in Symbol.prototype)) {
Object.defineProperty(Symbol.prototype, 'description', {
configurable: t | {
"filepath": "packages/next-polyfill-module/src/index.js",
"language": "javascript",
"file_size": 4504,
"cut_index": 614,
"middle_length": 229
} |
*/
// Keep in sync with eslint no-unwanted-polyfillio rule: https://github.com/vercel/next.js/blob/master/packages/eslint-plugin-next/lib/rules/no-unwanted-polyfillio.js
import 'core-js/features/array/at'
import 'core-js/features/array/copy-within'
import 'core-js/features/array/fill'
import 'core-js/features/array/fi... | /number/constructor'
import 'core-js/features/number/epsilon'
import 'core-js/features/number/is-finite'
import 'core-js/features/number/is-integer'
import 'core-js/features/number/is-nan'
import 'core-js/features/number/is-safe-integer'
import 'core-js/fe | /includes'
import 'core-js/features/array/iterator'
import 'core-js/features/array/of'
import 'core-js/features/function/has-instance'
import 'core-js/features/function/name'
import 'core-js/features/map'
import 'core-js/features | {
"filepath": "packages/next-polyfill-nomodule/src/index.js",
"language": "javascript",
"file_size": 2620,
"cut_index": 563,
"middle_length": 229
} |
lient'
import React, { useEffect } from 'react'
export type ScriptEmbed = {
html?: string | null
height?: string | number | null
width?: string | number | null
children?: React.ReactElement | React.ReactElement[]
dataNtpc?: string
}
export default function ThirdPartyScriptEmbed({
html,
height = null,
... | feature: `next-third-parties-${dataNtpc}`,
},
})
}
}, [dataNtpc])
return (
<>
{/* insert script children */}
{children}
{/* insert html */}
{html ? (
<div
style={{
heig | used for performance
// benchmarking it is low overhead and thus considered safe to use in production and it is a widely available
// existing API.
performance.mark('mark_feature_usage', {
detail: {
| {
"filepath": "packages/third-parties/src/ThirdPartyScriptEmbed.tsx",
"language": "tsx",
"file_size": 1244,
"cut_index": 518,
"middle_length": 229
} |
e global {
interface Window {
dataLayer?: Object[]
[key: string]: any
}
}
type JSONValue =
| string
| number
| boolean
| JSONValue[]
| { [key: string]: JSONValue }
type GTMParamsBaseParams = {
dataLayer?: { [key: string]: JSONValue }
dataLayerName?: string
auth?: string
preview?: string
... | : number | string
width?: number | string
mode: 'place' | 'view' | 'directions' | 'streetview' | 'search'
apiKey: string
style?: string
allowfullscreen?: boolean
loading?: 'eager' | 'lazy'
q?: string
id?: string
center?: string
zoom?: s | Url: string
}
export type GTMParams = GTMParamsWithId | GTMParamsWithScriptUrl
export type GAParams = {
gaId: string
dataLayerName?: string
debugMode?: boolean
nonce?: string
}
export type GoogleMapsEmbed = {
height? | {
"filepath": "packages/third-parties/src/types/google.ts",
"language": "typescript",
"file_size": 1209,
"cut_index": 518,
"middle_length": 229
} |
luate import 'client only'
import React, { useEffect } from 'react'
import Script from 'next/script'
import type { GAParams } from '../types/google'
declare global {
interface Window {
dataLayer?: Object[]
}
}
let currDataLayerName: string | undefined = undefined
export function GoogleAnalytics(props: GAPar... | ng API.
// The performance measurement will be handled by Chrome Aurora
performance.mark('mark_feature_usage', {
detail: {
feature: 'next-third-parties-ga',
},
})
}, [])
return (
<>
<Script
id="_next- | erformance.mark is being used as a feature use signal. While it is traditionally used for performance
// benchmarking it is low overhead and thus considered safe to use in production and it is a widely available
// existi | {
"filepath": "packages/third-parties/src/google/ga.tsx",
"language": "tsx",
"file_size": 1918,
"cut_index": 537,
"middle_length": 229
} |
import React, { useEffect } from 'react'
import Script from 'next/script'
import type { GTMParams } from '../types/google'
let currDataLayerName = 'dataLayer'
export function GoogleTagManager(props: GTMParams) {
const {
gtmId,
gtmScriptUrl,
dataLayerName = 'dataLayer',
auth,
preview,
dataL... | chParams.set('gtm_preview', preview)
scriptUrl.searchParams.set('gtm_cookies_win', 'x')
}
useEffect(() => {
// performance.mark is being used as a feature use signal. While it is traditionally used for performance
// benchmarking it is low | earchParams.set('id', gtmId)
}
if (dataLayerName !== 'dataLayer') {
scriptUrl.searchParams.set('l', dataLayerName)
}
if (auth) {
scriptUrl.searchParams.set('gtm_auth', auth)
}
if (preview) {
scriptUrl.sear | {
"filepath": "packages/third-parties/src/google/gtm.tsx",
"language": "tsx",
"file_size": 2239,
"cut_index": 563,
"middle_length": 229
} |
import React from 'react'
import type { ScriptProps } from 'next/script'
import Script from 'next/script'
import { YouTubeEmbed as TPCYouTubeEmbed } from 'third-party-capital'
import ThirdPartyScriptEmbed from '../ThirdPartyScriptEmbed'
import type { YouTubeEmbed as YouTubeEmbedTypes } from '../types/google'
const sc... | {scripts?.map((script) => (
<Script
key={script.url}
src={script.url}
strategy={scriptStrategy[script.strategy] as ScriptProps['strategy']}
stylesheets={stylesheets}
/>
))}
</ThirdPartyScrip | nst { html, scripts, stylesheets } = TPCYouTubeEmbed(props)
return (
<ThirdPartyScriptEmbed
height={props.height || null}
width={props.width || null}
html={html}
dataNtpc="YouTubeEmbed"
>
| {
"filepath": "packages/third-parties/src/google/youtube-embed.tsx",
"language": "tsx",
"file_size": 1011,
"cut_index": 512,
"middle_length": 229
} |
mber
size: number
compressed_size: number
}
export interface AnalyzeOutputFile {
filename: string
}
export interface AnalyzeLayer {
name: string
}
interface EdgesDataReference {
offset: number
length: number
}
interface AnalyzeDataHeader {
sources: AnalyzeSource[]
chunk_parts: AnalyzeChunkPart[]
o... |
/**
* Represents the global modules data that is shared across all routes
*/
export class ModulesData {
private modulesHeader: ModulesDataHeader
private modulesBinaryData: DataView
private pathToModuleIndex: Map<string, ModuleIndex[]>
construct | ace ModulesDataHeader {
modules: AnalyzeModule[]
module_dependents: EdgesDataReference
async_module_dependents: EdgesDataReference
module_dependencies: EdgesDataReference
async_module_dependencies: EdgesDataReference
}
| {
"filepath": "apps/bundle-analyzer/lib/analyze-data.ts",
"language": "typescript",
"file_size": 12618,
"cut_index": 921,
"middle_length": 229
} |
t: LayoutRect): LayoutRect[] {
if (sizes.length === 0) return []
if (sizes.length === 1) return [rect]
const totalSize = sizes.reduce((a, b) => a + b, 0)
const normalizedSizes = sizes.map(
(s) => (s / totalSize) * rect.width * rect.height
)
const result: LayoutRect[] = []
let remaining = [...normali... | sum += size
if (vertical) {
const width = (currentRect.width * sum) / totalRemaining
if (width > (currentRect.height / picked.length) * 0.9) {
break
}
} else {
const height = (currentRect.height * s | if taller
const vertical = currentRect.width >= currentRect.height
// Pick items until sum > total / count
const picked: number[] = []
let sum = 0
for (const size of remaining) {
picked.push(size)
| {
"filepath": "apps/bundle-analyzer/lib/layout-treemap.ts",
"language": "typescript",
"file_size": 3496,
"cut_index": 614,
"middle_length": 229
} |
ries from the current route's sources.
*
* It's a heuristic approach that looks for known entry module idents
* and traces their dependencies to find active modules.
*
* I don't like it as it has too much assumptions about next.js internals.
* It would be better if the source map contains idents instead of only p... | st/esm/build/templates/edge-app-route.js',
'next/dist/esm/build/templates/app-page.js',
'next/dist/esm/build/templates/edge-ssr-app.js',
'next/dist/esm/build/templates/middleware.js',
'[next]/entry/page-loader.ts',
]
const potentialEntr | s/pages.js',
'next/dist/esm/build/templates/pages-api.js',
'next/dist/esm/build/templates/pages-edge-api.js',
'next/dist/esm/build/templates/edge-ssr.js',
'next/dist/esm/build/templates/app-route.js',
'next/di | {
"filepath": "apps/bundle-analyzer/lib/module-graph.ts",
"language": "typescript",
"file_size": 4943,
"cut_index": 614,
"middle_length": 229
} |
rt interface LayoutRect {
x: number
y: number
width: number
height: number
}
export interface LayoutNodeInfo {
name: string
size: number
server?: boolean
client?: boolean
}
export interface LayoutNode extends LayoutNodeInfo {
size: number
rect: LayoutRect
type: 'file' | 'directory' | 'collapsed-... | sed',
Uncompressed = 'uncompressed',
}
function precomputeSourceMetadata(
analyzeData: AnalyzeData,
filterSource?: (sourceIndex: SourceIndex) => boolean
): SourceMetadata[] {
const sourceCount = analyzeData.sourceCount()
const metadata: SourceMe |
asset?: boolean
sourceIndex?: SourceIndex // Track which source this node represents
}
interface SourceMetadata {
filtered: boolean
size: number
compressedSize: number
}
export enum SizeMode {
Compressed = 'compres | {
"filepath": "apps/bundle-analyzer/lib/treemap-layout.ts",
"language": "typescript",
"file_size": 7697,
"cut_index": 716,
"middle_length": 229
} |
{ twMerge } from 'tailwind-merge'
import { SpecialModule } from './types'
import { NetworkError } from './errors'
import { AnalyzeData, SourceIndex } from './analyze-data'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export async function fetchStrict(url: string): Promise<Response> ... | tSpecialModuleType(
analyzeData: AnalyzeData | undefined,
sourceIndex: SourceIndex | null
): SpecialModule | null {
if (!analyzeData || sourceIndex == null) return null
const path = analyzeData.source(sourceIndex)?.path || ''
if (path.endsWith(' | d to fetch ${url}: ${res.status} ${res.statusText}`)
}
return res
}
export async function jsonFetcher<T>(url: string): Promise<T> {
const res = await fetchStrict(url)
return res.json() as Promise<T>
}
export function ge | {
"filepath": "apps/bundle-analyzer/lib/utils.ts",
"language": "typescript",
"file_size": 2072,
"cut_index": 563,
"middle_length": 229
} |
import { RefreshCw, AlertTriangle } from 'lucide-react'
import { NetworkError } from '@/lib/errors'
interface ErrorStateProps {
error: unknown
onRetry?: () => void
}
export function ErrorState({ error }: ErrorStateProps) {
const isNetwork = error instanceof NetworkError
const title = isNetwork ? 'Server Con... | ter w-16 h-16 rounded-full bg-destructive/10 text-destructive mb-2">
<AlertTriangle className="w-8 h-8" />
</div>
<div>
<h3 className="text-lg font-semibold text-foreground mb-2">
{title}
</h3>
| ? 'An unexpected error occurred.')
return (
<div className="flex-1 flex items-center justify-center">
<div className="text-center space-y-4 max-w-md px-6">
<div className="inline-flex items-center justify-cen | {
"filepath": "apps/bundle-analyzer/components/error-state.tsx",
"language": "tsx",
"file_size": 1501,
"cut_index": 524,
"middle_length": 229
} |
eEffect, useRef, useState } from 'react'
import { Input } from '@/components/ui/input'
import { Kbd } from '@/components/ui/kbd'
interface FileSearchProps {
value: string
onChange: (value: string) => void
}
export function FileSearch({ value, onChange }: FileSearchProps) {
const [focused, setFocused] = useState... | e.preventDefault()
onChange('')
inputRef.current?.blur()
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [onChange])
const handleFocu | A'].includes((e.target as HTMLElement).tagName)
) {
e.preventDefault()
inputRef.current?.focus()
} else if (
e.key === 'Escape' &&
document.activeElement === inputRef.current
) {
| {
"filepath": "apps/bundle-analyzer/components/file-search.tsx",
"language": "tsx",
"file_size": 1595,
"cut_index": 537,
"middle_length": 229
} |
no-extraneous-dependencies */
module.exports = function () {
return {
BasicEvaluatedExpression: require('webpack/lib/javascript/BasicEvaluatedExpression'),
ConcatenatedModule: require('webpack/lib/optimize/ConcatenatedModule'),
makePathsAbsolute: require('webpack/lib/util/identifier').makePathsAbsolute,
... | LibraryTemplatePlugin'),
LimitChunkCountPlugin: require('webpack/lib/optimize/LimitChunkCountPlugin'),
WebWorkerTemplatePlugin: require('webpack/lib/webworker/WebWorkerTemplatePlugin'),
ExternalsPlugin: require('webpack/lib/ExternalsPlugin'),
| odeTemplatePlugin'),
RuntimeGlobals: require('webpack/lib/RuntimeGlobals'),
SourceMapDevToolModuleOptionsPlugin: require('webpack/lib/SourceMapDevToolModuleOptionsPlugin'),
LibraryTemplatePlugin: require('webpack/lib/ | {
"filepath": "packages/next/src/bundles/webpack/bundle5.js",
"language": "javascript",
"file_size": 1521,
"cut_index": 537,
"middle_length": 229
} |
bal __resourceQuery */
"use strict";
var urlBase = decodeURIComponent(__resourceQuery.slice(1));
/**
* @param {{ data: string, onError: (err: Error) => void, active: boolean, module: module }} options options
* @returns {() => void} function to destroy response
*/
exports.keepAlive = function (options) {
var dat... | orHandler);
if (!active && !module.hot) {
console.log(
"Hot Module Replacement is not enabled. Waiting for process restart..."
);
}
}
);
/**
* @param {Error} err error
*/
function errorHandler(err) {
err.message =
"Problem | rlBase.startsWith("https") ? require("https") : require("http")
).request(
urlBase + data,
{
agent: false,
headers: { accept: "text/event-stream" }
},
function (res) {
response = res;
response.on("error", err | {
"filepath": "packages/next/src/bundles/webpack/packages/lazy-compilation-node.js",
"language": "javascript",
"file_size": 1187,
"cut_index": 518,
"middle_length": 229
} |
ned
if (process.env.NEXT_RSPACK) {
Object.assign(exports, getRspackCore())
Object.assign(exports, {
StringXor: require('./bundle5')().StringXor,
})
} else if (process.env.NEXT_PRIVATE_LOCAL_WEBPACK) {
Object.assign(exports, {
// eslint-disable-next-line import/no-extraneous-dependencies
BasicEvalua... | ndencies
ModuleFilenameHelpers: require('webpack/lib/ModuleFilenameHelpers'),
// eslint-disable-next-line import/no-extraneous-dependencies
NodeTargetPlugin: require('webpack/lib/node/NodeTargetPlugin'),
// eslint-disable-next-line import/n | ze/ConcatenatedModule'),
// eslint-disable-next-line import/no-extraneous-dependencies
makePathsAbsolute: require('webpack/lib/util/identifier').makePathsAbsolute,
// eslint-disable-next-line import/no-extraneous-depe | {
"filepath": "packages/next/src/bundles/webpack/packages/webpack.js",
"language": "javascript",
"file_size": 2147,
"cut_index": 563,
"middle_length": 229
} |
*/
function eslintParser() {
return require('@babel/eslint-parser')
}
function pluginProposalClassProperties() {
return require('@babel/plugin-transform-class-properties')
}
function pluginProposalExportNamespaceFrom() {
return require('@babel/plugin-transform-export-namespace-from')
}
function pluginProposa... | return require('@babel/plugin-syntax-import-attributes')
}
function pluginSyntaxJsx() {
return require('@babel/plugin-syntax-jsx')
}
function pluginSyntaxTypescript() {
return require('@babel/plugin-syntax-typescript')
}
function pluginTransformDef | )
}
function pluginSyntaxBigint() {
return require('@babel/plugin-syntax-bigint')
}
function pluginSyntaxDynamicImport() {
return require('@babel/plugin-syntax-dynamic-import')
}
function pluginSyntaxImportAttributes() {
| {
"filepath": "packages/next/src/bundles/babel/packages-bundle.js",
"language": "javascript",
"file_size": 2112,
"cut_index": 563,
"middle_length": 229
} |
gnore-webpack-plugin/blob/e35ce41d9606a92a455ef247f509a1c2ccab5778/src/index.ts
// eslint-disable-next-line import/no-extraneous-dependencies -- this is a dev-only file
const webpack = require('@rspack/core')
// Following the naming conventions from
// https://tc39.es/source-map/#source-map-format
const IGNORE_LIST =... | evTools to automatically ignore-list sources.
*/
module.exports = class DevToolsIgnorePlugin {
options
constructor(options = {}) {
this.options = {
shouldIgnorePath: options.shouldIgnorePath ?? defaultShouldIgnorePath,
isSourceMapAsset | ourceMapAsset(name) {
return name.endsWith('.map')
}
/**
* This plugin adds a field to source maps that identifies which sources are
* vendored or runtime-injected (aka third-party) sources. These are consumed by
* Chrome D | {
"filepath": "packages/next/webpack-plugins/devtools-ignore-list-plugin.js",
"language": "javascript",
"file_size": 2531,
"cut_index": 563,
"middle_length": 229
} |
SearchParams } from 'next/navigation'
declare module 'next/navigation' {
/**
* Get a read-only URLSearchParams object. For example searchParams.get('foo') would return 'bar' when ?foo=bar
* Learn more about URLSearchParams here: https://developer.mozilla.org/docs/Web/API/URLSearchParams
*
* If used from ... | me(): string | null
/**
* Get the current parameters. For example useParams() on /dashboard/[team]
* where pathname is /dashboard/nextjs would return { team: 'nextjs' }
*
* If used from `pages/`, the hook will return `null`.
*/
export f | ple, if the URL is
* https://example.com/foo?bar=baz, the pathname would be /foo.
*
* If the hook is accessed from `pages/`, the pathname may be `null` when the
* router is not ready.
*/
export function usePathna | {
"filepath": "packages/next/navigation-types/compat/navigation.d.ts",
"language": "typescript",
"file_size": 1852,
"cut_index": 537,
"middle_length": 229
} |
use
* structural types rather than importing from a specific Playwright package
* so this works with any version of playwright, playwright-core, or
* @playwright/test.
*/
interface PlaywrightBrowserContext {
addCookies(
cookies: Array<{
name: string
value: string
url?: string
domain?: ... | hin this scope,
* navigations render the prefetched UI immediately and wait for the
* callback to complete before streaming in dynamic data.
*
* Uses the cookie-based protocol: setting the cookie acquires the
* navigation lock (via CookieStore change | ring
}): Promise<void>
}
interface PlaywrightPage {
url(): string
context(): PlaywrightBrowserContext
}
const INSTANT_COOKIE = 'next-instant-navigation-testing'
/**
* Runs a function with instant navigation enabled. Wit | {
"filepath": "packages/next-playwright/src/index.ts",
"language": "typescript",
"file_size": 4639,
"cut_index": 614,
"middle_length": 229
} |
(source)
* Source: https://v0.dev/chat/eslint-cast-imports-CDvQ3iWC1Mo
*/
module.exports = {
name: 'typechecked-require',
meta: {
type: 'problem',
docs: {
description:
'Enforce require() calls to be cast as typeof import(). ' +
'Rule can be disabled for require(cjs) or for files not... |
},
create(context) {
function checkRequireCall(node) {
// Check if this is a require() call
if (
node.type !== 'CallExpression' ||
node.callee.type !== 'Identifier' ||
node.callee.name !== 'require' ||
| e cast as `typeof import(source)`',
mismatchedSource:
'Source in `require(source)` must match source in `import(source)`.\n' +
'Require: "{{requireSource}}"\n' +
' Import: "{{importSource}}"',
}, | {
"filepath": "packages/eslint-plugin-internal/src/eslint-typechecked-require.js",
"language": "javascript",
"file_size": 4035,
"cut_index": 614,
"middle_length": 229
} |
ents/links'
import { isLocalURL } from '../../shared/lib/router/utils/is-local-url'
import {
FetchStrategy,
type PrefetchTaskFetchStrategy,
} from '../components/segment-cache/types'
import { errorOnce } from '../../shared/lib/utils/error-once'
type Url = string | UrlObject
type RequiredKeys<T> = {
[K in keyof T... | k href="/dashboard">Dashboard</Link>
*
* // Navigate to /about?name=test:
* <Link href={{ pathname: '/about', query: { name: 'test' } }}>
* About
* </Link>
* ```
*
* @remarks
* - For external URLs, use a fully qualified URL suc | ult: () => void }) => void
type InternalLinkProps = {
/**
* **Required**. The path or URL to navigate to. It can also be an object (similar to `URL`).
*
* @example
* ```tsx
* // Navigate to /dashboard:
* <Lin | {
"filepath": "packages/next/src/client/app-dir/link.tsx",
"language": "tsx",
"file_size": 24277,
"cut_index": 1331,
"middle_length": 229
} |
type { NextConfig } from 'next'
import type { Options } from '@mdx-js/loader'
import type { RuleSetConditionAbsolute } from 'webpack'
type WithMDX = (config: NextConfig) => NextConfig
type PluggableListName = 'remarkPlugins' | 'rehypePlugins' | 'recmaPlugins'
declare namespace nextMDX {
interface NextMDXOptions {... | | (
| string
| [name: string, ...options: any[]]
| NonNullable<Options[Key]>[number]
)[]
| Options[Key]
: Options[Key]
}
}
}
/**
* Use [MDX](https://github.c | nsion?: RuleSetConditionAbsolute
/**
* The options to pass to MDX.
*
* @see https://mdxjs.com/packages/mdx/#api
*/
options?: {
[Key in keyof Options]: Key extends PluggableListName
?
| {
"filepath": "packages/next-mdx/index.d.ts",
"language": "typescript",
"file_size": 1158,
"cut_index": 518,
"middle_length": 229
} |
pathToFileURL } = require('node:url')
function interopDefault(mod) {
return mod.default || mod
}
async function importPluginForPath(pluginPath, projectRoot) {
const path = require.resolve(pluginPath, { paths: [projectRoot] })
return interopDefault(
// "use pathToFileUrl to make esm import()s work with abso... | importPluginForPath(plugin[0], projectRoot)
}
if (typeof plugin === 'string') {
plugin = await importPluginForPath(plugin, projectRoot)
}
return plugin
}
async function getOptions(options, projectRoot) {
const {
recmaPlugins = [],
r | 57bd20be9
await import(process.platform === 'win32' ? pathToFileURL(path) : path)
)
}
async function importPlugin(plugin, projectRoot) {
if (Array.isArray(plugin) && typeof plugin[0] === 'string') {
plugin[0] = await | {
"filepath": "packages/next-mdx/mdx-js-loader.js",
"language": "javascript",
"file_size": 2205,
"cut_index": 563,
"middle_length": 229
} |
act from 'eslint-plugin-react'
import reactHooks from 'eslint-plugin-react-hooks'
import tsEslint from 'typescript-eslint'
// import * as ... for plugins without default export
import * as importPlugin from 'eslint-plugin-import'
import * as jsxA11yPlugin from 'eslint-plugin-jsx-a11y'
// utils
import globals from 'glo... | : {
requireConfigFile: false,
sourceType: 'module',
allowImportExportEverywhere: true,
// TODO: Is this needed?
babelOptions: {
presets: ['next/babel'],
caller: {
// Eslint supports to | '],
plugins: {
react,
'react-hooks': reactHooks,
import: importPlugin,
'jsx-a11y': jsxA11yPlugin,
'@next/next': next,
},
languageOptions: {
parser: eslintParser,
parserOptions | {
"filepath": "packages/eslint-config-next/src/index.ts",
"language": "typescript",
"file_size": 3316,
"cut_index": 614,
"middle_length": 229
} |
faultLocale: string
domains?: I18nDomain[]
localeDetection?: false
locales: string[]
}
/**
* Detects the domain locale based on hostname or detected locale
*/
export function detectDomainLocale(
domains: I18nDomain[] | undefined,
hostname: string | undefined,
detectedLocale?: string
): I18nDomain | undef... | n.locales?.some(
(locale) => locale.toLowerCase() === normalizedLocale
)
) {
return domain
}
}
return undefined
}
/**
* Normalizes a pathname by removing the locale prefix if present
*/
export function normalizeLocalePat | Remove port if present
const domainHostname = domain.domain.split(':', 1)[0].toLowerCase()
if (
normalizedHostname === domainHostname ||
normalizedLocale === domain.defaultLocale.toLowerCase() ||
domai | {
"filepath": "packages/next-routing/src/i18n.ts",
"language": "typescript",
"file_size": 6819,
"cut_index": 716,
"middle_length": 229
} |
uch as header overrides, rewrites, redirects, and refresh signals.
*
* @param response - The Response object returned from middleware
* @param requestHeaders - The request Headers object to be mutated
* @param url - The original request URL
* @returns A MiddlewareResult object with processed headers and routing in... | convert to array
const existing = middlewareHeaders[key]
if (Array.isArray(existing)) {
existing.push(value)
} else {
middlewareHeaders[key] = [existing as string, value]
}
} else {
middlewareHeaders[key] = | response headers to a mutable record
const middlewareHeaders: Record<string, string | string[] | undefined> = {}
response.headers.forEach((value, key) => {
if (middlewareHeaders[key]) {
// If header already exists, | {
"filepath": "packages/next-routing/src/middleware.ts",
"language": "typescript",
"file_size": 6957,
"cut_index": 716,
"middle_length": 229
} |
ecord<string, string>
regexMatches?: RegExpMatchArray
hasCaptures?: Record<string, string>
} {
// Check if source regex matches the pathname
const regex = new RegExp(route.sourceRegex, caseSensitive ? '' : 'i')
const regexMatches = url.pathname.match(regex)
if (!regexMatches) {
return { matched: false ... | Destination(route.destination, regexMatches, hasResult.captures)
: undefined
const resolvedHeaders = route.headers
? Object.fromEntries(
Object.entries(route.headers).map(([key, value]) => [
replaceDestination(key, regexMatches, | const missingMatched = checkMissingConditions(route.missing, url, headers)
if (!missingMatched) {
return { matched: false }
}
// Replace placeholders in destination
const destination = route.destination
? replace | {
"filepath": "packages/next-routing/src/resolve-routes.ts",
"language": "typescript",
"file_size": 35901,
"cut_index": 2151,
"middle_length": 229
} |
idateModuleHandlers$ = undefined;
var __webpack_require__ = undefined;
module.exports = function () {
var currentModuleData = {};
var installedModules = $moduleCache$;
// module and require creation
var currentChildModule;
var currentParents = [];
// status
var registeredStatusHandlers = [];
var currentStatu... | e);
module.parents = currentParents;
module.children = [];
currentParents = [];
options.require = require;
});
$hmrDownloadUpdateHandlers$ = {};
$hmrInvalidateModuleHandlers$ = {};
function createRequire(require, moduleId) {
var me = instal | leData$ = currentModuleData;
$interceptModuleExecution$.push(function (options) {
var module = options.module;
var require = createRequire(options.require, options.id);
module.hot = createModuleHotObject(options.id, modul | {
"filepath": "packages/next/src/bundles/webpack/packages/HotModuleReplacement.runtime.js",
"language": "javascript",
"file_size": 10229,
"cut_index": 921,
"middle_length": 229
} |
peof EventSource !== "function") {
throw new Error(
"Environment doesn't support lazy compilation (requires EventSource)"
);
}
var urlBase = decodeURIComponent(__resourceQuery.slice(1));
/** @type {EventSource | undefined} */
var activeEventSource;
var activeKeys = new Map();
var errorHandlers = new Set();
var up... | vent) {
errorHandlers.forEach(function (onError) {
onError(
new Error(
"Problem communicating active modules to the server: " +
event.message +
" " +
event.filename +
":" +
event.lineno +
":" +
| eKeys.keys()).join("@")
);
/**
* @this {EventSource}
* @param {Event & { message?: string, filename?: string, lineno?: number, colno?: number, error?: Error }} event event
*/
activeEventSource.onerror = function (e | {
"filepath": "packages/next/src/bundles/webpack/packages/lazy-compilation-web.js",
"language": "javascript",
"file_size": 2052,
"cut_index": 563,
"middle_length": 229
} |
is conditionally added/removed to next-env.d.ts
// if the static image import handling is enabled
declare module '*.png' {
const content: import('../dist/shared/lib/image-external').StaticImageData
export default content
}
declare module '*.svg' {
/**
* Use `any` to avoid conflicts with
* `@svgr/webpack... | ort('../dist/shared/lib/image-external').StaticImageData
export default content
}
declare module '*.webp' {
const content: import('../dist/shared/lib/image-external').StaticImageData
export default content
}
declare module '*.avif' {
const cont | rnal').StaticImageData
export default content
}
declare module '*.jpeg' {
const content: import('../dist/shared/lib/image-external').StaticImageData
export default content
}
declare module '*.gif' {
const content: imp | {
"filepath": "packages/next/image-types/global.d.ts",
"language": "typescript",
"file_size": 1364,
"cut_index": 524,
"middle_length": 229
} |
'path'
import * as dotenv from 'dotenv'
import { expand as dotenvExpand } from 'dotenv-expand'
export type Env = { [key: string]: string | undefined }
export type LoadedEnvFiles = Array<{
path: string
contents: string
env: Env
}>
export let initialEnv: Env | undefined = undefined
let combinedEnv: Env | undefine... | // Allow mutating internal Next.js env variables after the server has initiated.
// This is necessary for dynamic things like the IPC server port.
if (!key.startsWith('__NEXT_PRIVATE')) {
if (sourceEnv[key] === undefined || sourceEnv[key] = | Env) {
Object.assign(initialEnv || {}, newEnv)
}
type Log = {
info: (...args: any[]) => void
error: (...args: any[]) => void
}
function replaceProcessEnv(sourceEnv: Env) {
Object.keys(process.env).forEach((key) => {
| {
"filepath": "packages/next-env/index.ts",
"language": "typescript",
"file_size": 5002,
"cut_index": 614,
"middle_length": 229
} |
-to-import', rule, {
valid: [
// ✅ Correct usage - basic modules
{
code: `const fs = require('fs') as typeof import('fs')`,
filename: 'test.ts',
},
{
code: `const path = require('path') as typeof import('path')`,
filename: 'test.ts',
},
{
c... | },
// ✅ Correct usage - relative imports
{
code: `const utils = require('./utils') as typeof import('./utils')`,
filename: 'test.ts',
},
{
code: `const config = require('../config/database') as typeof import | equire('@types/lodash') as typeof import('@types/lodash')`,
filename: 'test.ts',
},
{
code: `const react = require('@types/react') as typeof import('@types/react')`,
filename: 'test.ts',
| {
"filepath": "packages/eslint-plugin-internal/src/eslint-typechecked-require.test.js",
"language": "javascript",
"file_size": 10843,
"cut_index": 921,
"middle_length": 229
} |
om '../cli/next-info.js'
import type { NextDevOptions } from '../cli/next-dev.js'
import type { NextAnalyzeOptions } from '../cli/next-analyze.js'
import type { NextBuildOptions } from '../cli/next-build.js'
import type { NextTypegenOptions } from '../cli/next-typegen.js'
import type { NextPostBuildOptions } from '../c... | "${process.env.__NEXT_REQUIRED_NODE_VERSION_RANGE}" is required.`
)
process.exit(1)
}
process.env.NEXT_PRIVATE_START_TIME = Date.now().toString()
for (const dependency of ['react', 'react-dom']) {
try {
// When 'npm link' is used it checks the | satisfies(
process.versions.node,
process.env.__NEXT_REQUIRED_NODE_VERSION_RANGE!,
{ includePrerelease: true }
)
) {
console.error(
`You are using Node.js ${process.versions.node}. For Next.js, Node.js version | {
"filepath": "packages/next/src/bin/next.ts",
"language": "typescript",
"file_size": 24147,
"cut_index": 1331,
"middle_length": 229
} |
in the destination string
* with matches from the regex and has conditions
*/
export function replaceDestination(
destination: string,
regexMatches: RegExpMatchArray | null,
hasCaptures: Record<string, string>
): string {
let result = destination
// Replace numbered captures from regex ($1, $2, etc.)
if... | lace(new RegExp(`\\$${name}`, 'g'), value ?? '')
}
}
}
// Replace named captures from has conditions
for (const [name, value] of Object.entries(hasCaptures)) {
result = result.replace(new RegExp(`\\$${name}`, 'g'), value)
}
return | lt = result.replace(new RegExp(`\\$${i}`, 'g'), value)
}
// Replace named groups ($name)
if (regexMatches.groups) {
for (const [name, value] of Object.entries(regexMatches.groups)) {
result = result.rep | {
"filepath": "packages/next-routing/src/destination.ts",
"language": "typescript",
"file_size": 2521,
"cut_index": 563,
"middle_length": 229
} |
data URL by removing /_next/data/{buildId}/ prefix and .json extension
* ${basePath}/_next/data/$buildId/$path.json -> ${basePath}/$path
*/
export function normalizeNextDataUrl(
url: URL,
basePath: string,
buildId: string
): URL {
const newUrl = new URL(url.toString())
let pathname = newUrl.pathname
// ... | }
if (pathAfterData === 'index') {
pathname = basePath || '/'
} else {
pathname = basePath ? `${basePath}/${pathAfterData}` : `/${pathAfterData}`
}
newUrl.pathname = pathname
}
return newUrl
}
/**
* Denormalizes URL | dId}/ part, keeping what comes after
let pathAfterData = pathname.slice(dataPrefix.length)
// Remove .json extension if present
if (pathAfterData.endsWith('.json')) {
pathAfterData = pathAfterData.slice(0, -5)
| {
"filepath": "packages/next-routing/src/next-data.ts",
"language": "typescript",
"file_size": 1960,
"cut_index": 537,
"middle_length": 229
} |
pes')
}
function core() {
return require('@babel/core')
}
function coreLibConfig() {
return require('@babel/core/lib/config')
}
function coreLibNormalizeFile() {
return require('@babel/core/lib/transformation/normalize-file')
}
function coreLibNormalizeOpts() {
return require('@babel/core/lib/transformation... | intParser() {
return require('next/dist/compiled/babel-packages').eslintParser()
}
function pluginProposalClassProperties() {
return require('next/dist/compiled/babel-packages').pluginProposalClassProperties()
}
function pluginProposalExportNamespace | lib/transformation/plugin-pass')
}
function traverse() {
return require('@babel/traverse')
}
function generator() {
return require('@babel/generator')
}
function parser() {
return require('@babel/parser')
}
function esl | {
"filepath": "packages/next/src/bundles/babel/bundle.js",
"language": "javascript",
"file_size": 3501,
"cut_index": 614,
"middle_length": 229
} |
xport type Step = <T>(title: string, body: () => Promise<T>) => Promise<T>
/**
* When `@playwright/test` is installed and we're running inside the Playwright
* test runner, wraps the body in a `test.step()` so it appears as a labeled
* step in the Playwright UI. Otherwise just executes the body directly.
*/
let st... | running under Jest), fall back to executing the body
// directly without step labels.
if (
e instanceof Error &&
e.message.includes('can only be called from a test')
) {
return body()
}
| pw.test.step
step = async (title, body) => {
try {
return await playwrightStep(title, body)
} catch (e) {
// If test.step fails because we're not inside the Playwright test
// runner (e.g., | {
"filepath": "packages/next-playwright/src/step.ts",
"language": "typescript",
"file_size": 1053,
"cut_index": 513,
"middle_length": 229
} |
= require('crypto')
const markdownExtensions = [
'md',
'markdown',
'mdown',
'mkdn',
'mkd',
'mdwn',
'mkdown',
'ron',
]
const mdx = ['.mdx']
const md = markdownExtensions.map((/** @type {string} */ d) => '.' + d)
const own = {}.hasOwnProperty
const marker = {}
const cache = new WeakMap()
/*
* From n... | mStrikethrough: true,
gfmTable: true,
gfmTaskListItem: true,
},
}
break
case 'commonMark':
default:
parse = { gfmStrikethroughSingleTilde: true, mathTextSingleDollar: true }
break
}
return {
| ns
let parse = undefined
switch (mdxType) {
case 'gfm':
parse = {
constructs: {
gfmAutolinkLiteral: true,
gfmFootnoteDefinition: true,
gfmLabelStartFootnote: true,
gf | {
"filepath": "packages/next-mdx/mdx-rs-loader.js",
"language": "javascript",
"file_size": 4240,
"cut_index": 614,
"middle_length": 229
} |
defined;
var $hmrInvalidateModuleHandlers$ = undefined;
var __webpack_require__ = undefined;
module.exports = function () {
var currentUpdateChunks;
var currentUpdate;
var currentUpdateRemovedChunks;
var currentUpdateRuntime;
function applyHandler(options) {
if ($ensureChunkHandlers$) delete $ensureChunkHandler... | var module = $moduleCache$[moduleId];
if (
!module ||
(module.hot._selfAccepted && !module.hot._selfInvalidated)
)
continue;
if (module.hot._selfDeclined) {
return {
type: "self-declined",
chain: chain,
mod | = outdatedModules.map(function (id) {
return {
chain: [id],
id: id
};
});
while (queue.length > 0) {
var queueItem = queue.pop();
var moduleId = queueItem.id;
var chain = queueItem.chain;
| {
"filepath": "packages/next/src/bundles/webpack/packages/JavascriptHotModuleReplacement.runtime.js",
"language": "javascript",
"file_size": 13235,
"cut_index": 921,
"middle_length": 229
} |
ts =
({ enabled = true, logLevel, openAnalyzer, analyzerMode } = {}) =>
(nextConfig = {}) => {
if (!enabled) {
return nextConfig
}
if (process.env.TURBOPACK) {
console.warn(
'The Next Bundle Analyzer is not compatible with Turbopack builds, no report will be generated.\n\n' +
... | onfig, options) {
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
config.plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: analyzerMode || 'static',
logLevel,
openAnalyz | 'To run this analysis pass the `--webpack` flag to `next build`'
)
return nextConfig
}
const extension = analyzerMode === 'json' ? '.json' : '.html'
return Object.assign({}, nextConfig, {
webpack(c | {
"filepath": "packages/next-bundle-analyzer/index.js",
"language": "javascript",
"file_size": 1443,
"cut_index": 524,
"middle_length": 229
} |
onValue is undefined, returns the key's value if it exists.
* If conditionValue is defined, it can be a regex string or a direct match.
*/
function matchesCondition(
actualValue: string | undefined,
conditionValue: string | undefined
): {
matched: boolean
capturedValue?: string
namedCaptures?: Record<string... | const match =
actualValue.match(exactRegex) ?? actualValue.match(fallbackRegex)
if (match) {
const namedCaptures: Record<string, string> = {}
if (match.groups) {
for (const [key, value] of Object.entries(match.groups)) {
| ndefined) {
return { matched: true, capturedValue: actualValue }
}
// Try to match as regex first
try {
const exactRegex = new RegExp(`^(?:${conditionValue})$`)
const fallbackRegex = new RegExp(conditionValue)
| {
"filepath": "packages/next-routing/src/matchers.ts",
"language": "typescript",
"file_size": 4340,
"cut_index": 614,
"middle_length": 229
} |
Config = {}) => {
const extension = pluginOptions.extension || /\.mdx$/
const userProvidedMdxOptions = pluginOptions.options
const mdxRsOptions = inputConfig?.experimental?.mdxRs
const loader = mdxRsOptions
? {
loader: require.resolve('./mdx-rs-loader'),
options: {
... | ...userProvidedMdxOptions,
},
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
...inputConfig,
webpack(config, options) {
config.resolve.alias['next-mdx-import-source-file'] = | ...(mdxRsOptions === true ? {} : mdxRsOptions),
},
}
: {
loader: require.resolve('./mdx-js-loader'),
options: {
providerImportSource: 'next-mdx-import-source-file',
| {
"filepath": "packages/next-mdx/index.js",
"language": "javascript",
"file_size": 2748,
"cut_index": 563,
"middle_length": 229
} |
{ Metadata } from 'next'
import type React from 'react'
import './globals.css'
export const metadata: Metadata = {
title: 'Next.js Bundle Analyzer',
description:
'Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis',
}
export default function RootLayout({
childre... | prevent flash of incorrect theme
dangerouslySetInnerHTML={{
__html: `
(function() {
const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
document.do | he theme before React hydates. This is to prevent a flash
// of incorrect theme.
suppressHydrationWarning
>
<head>
<script
// biome-ignore lint/security/noDangerouslySetInnerHtml: Needed to | {
"filepath": "apps/bundle-analyzer/app/layout.tsx",
"language": "tsx",
"file_size": 1425,
"cut_index": 524,
"middle_length": 229
} |
__next_internal_action_entry_do_not_use__ {"c0dd5bb6fef67f5ab84327f5164ac2c3111a159337":{"name":"$$RSC_SERVER_CACHE_0"}} */ import { registerServerReference } from "private-next-rsc-server-reference";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
import { cache as $$reactCache__ } from "react";
i... | 4ac2c3111a159337", 0, $$RSC_SERVER_CACHE_0_INNER, Array.prototype.slice.call(arguments, 0, 1));
});
registerServerReference($$RSC_SERVER_CACHE_0, "c0dd5bb6fef67f5ab84327f5164ac2c3111a159337", null);
Object["defineProperty"]($$RSC_SERVER_CACHE_0, "name", {
| ync function Cached({ children }) {
return <div className={inter.className}>{children}</div>;
};
export var $$RSC_SERVER_CACHE_0 = $$reactCache__(function Cached() {
return $$cache__("default", "c0dd5bb6fef67f5ab84327f516 | {
"filepath": "crates/next-custom-transforms/tests/fixture/next-font-with-directive/use-cache/output.js",
"language": "javascript",
"file_size": 1066,
"cut_index": 515,
"middle_length": 229
} |
cel/commerce/blob/18167d22f31fce6c90f98912e514243236200989/components/layout/search/filter/dropdown.tsx#L16
'use client'
import { usePathname, useSearchParams } from 'next/navigation'
import { useEffect, useRef, useState } from 'react'
import { ChevronDownIcon } from '@heroicons/react/24/outline'
import { FilterItem... | (false)
}
}
window.addEventListener('click', handleClickOutside)
return () => window.removeEventListener('click', handleClickOutside)
}, [])
useEffect(() => {
list.forEach((listItem) => {
if (
('path' in listItem & | const [openSelect, setOpenSelect] = useState(false)
const ref = useRef(null)
useEffect(() => {
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
setOpenSelect | {
"filepath": "crates/next-custom-transforms/tests/fixture/optimize_server_react/2/input.js",
"language": "javascript",
"file_size": 1936,
"cut_index": 537,
"middle_length": 229
} |
f31fce6c90f98912e514243236200989/components/layout/search/filter/dropdown.tsx#L16
'use client';
import { usePathname, useSearchParams } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { ChevronDownIcon } from '@heroicons/react/24/outline';
import { FilterItem } from './item';
export ... | )=>{
if (ref.current && !ref.current.contains(event.target)) {
setOpenSelect(false);
}
};
window.addEventListener('click', handleClickOutside);
return ()=>window.removeEventListener('click', h | ];
const [openSelect, setOpenSelect] = [
false,
()=>null
];
const ref = useRef(null);
process.env.__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE && useEffect(()=>{
const handleClickOutside = (event | {
"filepath": "crates/next-custom-transforms/tests/fixture/optimize_server_react/2/output.js",
"language": "javascript",
"file_size": 2045,
"cut_index": 563,
"middle_length": 229
} |
https from 'https'
import timer from '@szmarczak/http-timer'
// a wrapper around genAsyncRequest that will retry the request 5 times if it fails
export async function genRetryableRequest(url) {
let retries = 0
while (retries < 10) {
try {
return await genAsyncRequest(url)
} catch (err) {}
retrie... | esponse.on('end', () => {
if (response.statusCode !== 200) {
reject(new Error(`Failed to fetch ${url}`))
}
resolve({
...response.timings.phases,
cold: !body.includes('HOT'),
})
})
re | n new Promise((resolve, reject) => {
const request = https.get(url)
timer(request)
request.on('response', (response) => {
let body = ''
response.on('data', (data) => {
body += data
})
r | {
"filepath": "bench/vercel/gen-request.js",
"language": "javascript",
"file_size": 1136,
"cut_index": 518,
"middle_length": 229
} |
rt { useEffect, useLayoutEffect, useMemo } from 'react';
import React from 'react';
export default function App() {
process.env.__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE && useEffect(()=>{
console.log('Hello World');
}, []);
process.env.__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE && useLayoutEffect(()=>{
... | t(()=>{}, getArray());
const a = useMemo(()=>{
return 1;
}, []);
process.env.__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE && React.useEffect(()=>{
console.log('Hello World');
});
return <div>
<h1>Hello World</h1>
</div> | runSideEffect(),
2
]);
useEffec | {
"filepath": "crates/next-custom-transforms/tests/fixture/optimize_server_react/1/output.js",
"language": "javascript",
"file_size": 828,
"cut_index": 516,
"middle_length": 52
} |
import { useEffect, useLayoutEffect, useMemo } from 'react';
import * as React from 'react';
export default function App() {
process.env.__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE && useEffect(()=>{
console.log('Hello World');
}, []);
process.env.__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE && useLayoutEffect(()=>{... | runSideEffect(),
2
]);
useEffect(()=>{}, getArray());
const a = useMemo(()=>{
return 1;
}, []);
React.useEffect(()=>{
console.log('Hello World');
});
return <div>
<h1>Hello World</h1>
</div>;
}
| 1,
| {
"filepath": "crates/next-custom-transforms/tests/fixture/optimize_server_react/7/output.js",
"language": "javascript",
"file_size": 782,
"cut_index": 512,
"middle_length": 14
} |
le 'database' {
export const db: {
serialize<T>(cb: () => T): T
run(
statement: string,
args: Record<string, any>,
onComplete: (this: { lastID: string }, error?: Error) => void
): void
}
}
declare module 'db' {
export default function deleteFromDb(arg: any, ...args: any[]): Promise<... | from 'react'
export function Button(
props: {
action: () => Promise<any>
} & React.ComponentProps<'button'>
): React.ReactNode
export function Form(
props: React.PropsWithChildren<{ action: () => Promise<any> }>
): React.ReactN | declare module 'anything' {
const ANYTHING: any
export default ANYTHING
}
declare module 'foo' {
const f: any
export default f
export const f1: any
export const f2: any
}
declare module 'components' {
import React | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/modules.d.ts",
"language": "typescript",
"file_size": 1254,
"cut_index": 524,
"middle_length": 229
} |
le 'private-next-rsc-action-encryption' {
export function encryptActionBoundArgs(
actionId: string,
...args: any[]
): Promise<string>
export function decryptActionBoundArgs(
actionId: string,
encryptedPromise: Promise<string>
): Promise<any[]>
}
declare module 'private-next-rsc-server-referenc... | id: string,
callServer: any,
encodeFormAction?: any,
findSourceMapURL?: any,
functionName?: string
) => (...args: unknown[]) => Promise<unknown>
}
declare module 'private-next-rsc-action-validate' {
function ensureServerEntryExports(a | tion-client-wrapper' {
export function callServer(
actionId: string,
actionArgs: unknown[]
): Promise<unknown>
export function findSourceMapURL(filename: string): string | null
const createServerReference: (
| {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/next.d.ts",
"language": "typescript",
"file_size": 1274,
"cut_index": 524,
"middle_length": 229
} |
f3a714ffdef1bf9651d":{"name":"default"}} */ import { registerServerReference } from "private-next-rsc-server-reference";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
import { cache as $$reactCache__ } from "react";
// @ts-ignore
import { withSlug } from './with-slug';
const Page = withSlug(funct... | 64bf709f3a714ffdef1bf9651d", 0, Page, Array.prototype.slice.call(arguments));
});
registerServerReference($$RSC_SERVER_CACHE_default, "ffc18c215a6b7cdc64bf709f3a714ffdef1bf9651d", null);
Object["defineProperty"]($$RSC_SERVER_CACHE_default, "nam | return $$cache__("default", "ffc18c215a6b7cdc | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/64/output.js",
"language": "javascript",
"file_size": 971,
"cut_index": 582,
"middle_length": 52
} |
ctionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
/* __next_internal_action_entry_do_not_use__ {"606a88810ecce4a4e8b59d53b8327d7e98bbf251d7":{"name":"$$RSC_SERVER_ACTION_0"}} */ import { Button } from 'components';
export const $$RSC_SERVER_ACTION_0 = async function action($$ACTION_CLO... | 0ecce4a4e8b59d53b8327d7e98bbf251d7", null);
export function Item({ value }) {
return <>
<Button action={$$RSC_SERVER_ACTION_0.bind(null, encryptActionBoundArgs("606a88810ecce4a4e8b59d53b8327d7e98bbf251d7", value))}>
Multiple
</Butto | sterServerReference($$RSC_SERVER_ACTION_0, "606a8881 | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/19/output.js",
"language": "javascript",
"file_size": 928,
"cut_index": 606,
"middle_length": 52
} |
// @ts-ignore
import { getStuff, wrap, type Stuff } from './foo'
export { getData, type Data } from './data'
export const getCachedData = async (): Stuff => {
// This is not using the wrapped version of getStuff, as we're only
// runtime-wrapping what flows out of the module, not into it. Would one
// expect th... | iv>Sync</div>)
export const wrapped = wrap(
async () => 'foo',
async () => 'bar',
async () => async () => 'baz',
() => 'sync'
)
export default Layout
export { Other, getStuff, staticallyKnownFunction }
async function staticallyKnownFunction() {} | wrap(() => <d | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/63/input.tsx",
"language": "tsx",
"file_size": 795,
"cut_index": 524,
"middle_length": 14
} |
acff246876a467753785a92d1f95ac6fe32c9b9":{"name":"Other"},"ff27fadf3eeb97c777cea9f14a407b5c0b42ac65bb":{"name":"aliased"},"ff438bb59117ff1af890c80ca3e39d9e888fc93033":{"name":"wrapped"},"ff84effee663e5ce4e0948b55df129a8df904c67aa":{"name":"Sync"},"ff8fa22f08e492db15701f58a1458cc4ebf782f855":{"name":"getData"},"ff980f8c... | import { getData } from './data';
const $$RSC_SERVER_CACHE_0_INNER = async function getCachedData() {
// This is not using the wrapped version of getStuff, as we're only
// runtime-wrapping what flows out of the module, not into it. Would one
/ | erence";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
import { cache as $$reactCache__ } from "react";
// @ts-ignore
import { getStuff, wrap, type Stuff } from './foo';
export { type Data } from './data';
| {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/63/output.tsx",
"language": "tsx",
"file_size": 6265,
"cut_index": 716,
"middle_length": 229
} |
not_use__ {"f03128060c414d59f8552e4788b846c0d2b7f74743":{"name":"$$RSC_SERVER_CACHE_0"}} */ import { registerServerReference } from "private-next-rsc-server-reference";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
import { cache as $$reactCache__ } from "react";
const $$RSC_SERVER_CACHE_0_INNER ... | $$cache__("default", "f03128060c414d59f8552e4788b846c0d2b7f74743", 0, $$RSC_SERVER_CACHE_0_INNER, Array.prototype.slice.call(arguments, 0, 3));
});
registerServerReference($$RSC_SERVER_CACHE_0, "f03128060c414d59f8552e4788b846c0d2b7f74743", null);
export de | ER_CACHE_0 = $$reactCache__(function() {
return | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/49/output.js",
"language": "javascript",
"file_size": 883,
"cut_index": 547,
"middle_length": 52
} |
a8d21b6362b4cc8f5b15560525095bc48dba80":{"name":"$$RSC_SERVER_CACHE_3"},"803128060c414d59f8552e4788b846c0d2b7f74743":{"name":"$$RSC_SERVER_CACHE_0"},"8069348c79fce073bae2f70f139565a2fda1c74c74":{"name":"$$RSC_SERVER_CACHE_2"},"80951c375b4a6a6e89d67b743ec5808127cfde405d":{"name":"$$RSC_SERVER_CACHE_1"}} */ import { regi... | CACHE_0_INNER, []);
});
registerServerReference($$RSC_SERVER_CACHE_0, "803128060c414d59f8552e4788b846c0d2b7f74743", null);
Object["defineProperty"]($$RSC_SERVER_CACHE_0, "name", {
value: "foo"
});
const foo = $$RSC_SERVER_CACHE_0;
export { bar };
const | C_SERVER_CACHE_0_INNER = async function foo() {
return 'foo';
};
export var $$RSC_SERVER_CACHE_0 = $$reactCache__(function foo() {
return $$cache__("default", "803128060c414d59f8552e4788b846c0d2b7f74743", 0, $$RSC_SERVER_ | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/34/output.js",
"language": "javascript",
"file_size": 2613,
"cut_index": 563,
"middle_length": 229
} |
l_action_entry_do_not_use__ {"0090b5db271335765a4b0eab01f044b381b5ebd5cd":{"name":"$$RSC_SERVER_ACTION_1"},"706a88810ecce4a4e8b59d53b8327d7e98bbf251d7":{"name":"$$RSC_SERVER_ACTION_0"}} */ import { validator } from 'auth';
import { Button } from 'components';
export const $$RSC_SERVER_ACTION_0 = async function myAction... | >Delete</Button>;
}
export const $$RSC_SERVER_ACTION_1 = async function() {};
registerServerReference($$RSC_SERVER_ACTION_1, "0090b5db271335765a4b0eab01f044b381b5ebd5cd", null);
// TODO: should use `action` as function name?
export const action = validator | nction Page() {
return <Button action={myAction} | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/2/output.js",
"language": "javascript",
"file_size": 939,
"cut_index": 606,
"middle_length": 52
} |
ort { registerServerReference } from "private-next-rsc-server-reference";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
import { cache as $$reactCache__ } from "react";
const $$RSC_SERVER_CACHE_0_INNER = async function foo() {};
export var $$RSC_SERVER_CACHE_0 = $$reactCache__(function foo() {
... | 4b0eab01f044b381b5ebd5cd", null);
/* __next_internal_action_entry_do_not_use__ {"0090b5db271335765a4b0eab01f044b381b5ebd5cd":{"name":"$$RSC_SERVER_ACTION_1"},"803128060c414d59f8552e4788b846c0d2b7f74743":{"name":"$$RSC_SERVER_CACHE_0"}} */ export const obj | 6c0d2b7f74743", null);
Object["defineProperty"]($$RSC_SERVER_CACHE_0, "name", {
value: "foo"
});
export const $$RSC_SERVER_ACTION_1 = async function bar() {};
registerServerReference($$RSC_SERVER_ACTION_1, "0090b5db271335765a | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/53/output.js",
"language": "javascript",
"file_size": 1069,
"cut_index": 515,
"middle_length": 229
} |
788b846c0d2b7f74743":{"name":"$$RSC_SERVER_CACHE_0"}} */ import { registerServerReference } from "private-next-rsc-server-reference";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
import { cache as $$reactCache__ } from "react";
// Expect no error here, this is allowed to be sync because it's not... | eturn $$cache__("default", "803128060c414d59f8552e4788b846c0d2b7f74743", 0, $$RSC_SERVER_CACHE_0_INNER, []);
});
registerServerReference($$RSC_SERVER_CACHE_0, "803128060c414d59f8552e4788b846c0d2b7f74743", null);
Object["defineProperty"]($$RSC_SERVER_CACHE_ | RVER_CACHE_0 = $$reactCache__(function bar() {
r | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/45/output.js",
"language": "javascript",
"file_size": 963,
"cut_index": 582,
"middle_length": 52
} |
a8d21b6362b4cc8f5b15560525095bc48dba80":{"name":"$$RSC_SERVER_CACHE_3"},"803128060c414d59f8552e4788b846c0d2b7f74743":{"name":"$$RSC_SERVER_CACHE_0"},"80951c375b4a6a6e89d67b743ec5808127cfde405d":{"name":"$$RSC_SERVER_CACHE_1"},"c069348c79fce073bae2f70f139565a2fda1c74c74":{"name":"$$RSC_SERVER_CACHE_2"}} */ import { regi... | ER_CACHE_0_INNER, []);
});
registerServerReference($$RSC_SERVER_CACHE_0, "803128060c414d59f8552e4788b846c0d2b7f74743", null);
Object["defineProperty"]($$RSC_SERVER_CACHE_0, "name", {
value: "foo"
});
export var foo = $$RSC_SERVER_CACHE_0;
const $$RSC_S | C_SERVER_CACHE_0_INNER = async function foo() {
return 'data A';
};
export var $$RSC_SERVER_CACHE_0 = $$reactCache__(function foo() {
return $$cache__("default", "803128060c414d59f8552e4788b846c0d2b7f74743", 0, $$RSC_SERV | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/36/output.js",
"language": "javascript",
"file_size": 2543,
"cut_index": 563,
"middle_length": 229
} |
ternal_action_entry_do_not_use__ {"ffab21efdafbe611287bc25c0462b1e0510d13e48b":{"name":"foo"},"ffac840dcaf5e8197cb02b7f3a43c119b7a770b272":{"name":"bar"}} */ import { registerServerReference } from "private-next-rsc-server-reference";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
import { cache a... | terServerReference($$RSC_SERVER_CACHE_foo, "ffab21efdafbe611287bc25c0462b1e0510d13e48b", null);
Object["defineProperty"]($$RSC_SERVER_CACHE_foo, "name", {
value: "foo"
});
}
export { $$RSC_SERVER_CACHE_foo as foo };
let $$RSC_SERVER_CACHE_b | of foo === "function") {
$$RSC_SERVER_CACHE_foo = $$reactCache__(function() {
return $$cache__("default", "ffab21efdafbe611287bc25c0462b1e0510d13e48b", 0, foo, Array.prototype.slice.call(arguments));
});
regis | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/68/output.tsx",
"language": "tsx",
"file_size": 1488,
"cut_index": 524,
"middle_length": 229
} |
) {
const b = 1
return (
<Client
// Should be 1 110000 0, which is "e0" in hex (counts as two params,
// because of the encrypted bound args param)
fn1={async (c) => {
'use cache'
return a + b + c
}}
// Should be 1 100000 0, which is "c0" in hex (counts as one par... | ed bound args param)
fn3={async (c) => {
'use server'
return a + b + c
}}
// Should be 0 100000 0, which is "40" in hex (counts as one param,
// because of the encrypted bound args param)
fn4={async function ( | ounts as two params,
// because of the encrypt | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/52/input.js",
"language": "javascript",
"file_size": 959,
"cut_index": 582,
"middle_length": 52
} |
ndArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
import { cache as $$reactCache__ } from "react";
/* __next_internal_action_entry_do_not_use__ {"409ed0cc47abc4e1c64320cf42b74ae60b58c40f00":{"name":"$$RSC_SERVER_ACTION_3"},"6... | nd args param)
fn1([$$ACTION_ARG_0, $$ACTION_ARG_1], c) {
return $$ACTION_ARG_0 + $$ACTION_ARG_1 + c;
};
export var $$RSC_SERVER_CACHE_0 = $$reactCache__(function fn1() {
return $$cache__("default", "e03128060c414d59f8552e4788b846c0d2b7f74743", 2, | 4743":{"name":"$$RSC_SERVER_CACHE_0"}} */ import { Client } from 'components';
const $$RSC_SERVER_CACHE_0_INNER = async function // Should be 1 110000 0, which is "e0" in hex (counts as two params,
// because of the encrypted bou | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/52/output.js",
"language": "javascript",
"file_size": 3523,
"cut_index": 614,
"middle_length": 229
} |
ference } from "private-next-rsc-server-reference";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
import { cache as $$reactCache__ } from "react";
/* __next_internal_action_entry_do_not_use__ {"40... | , $$ACTION_CLOSURE_BOUND);
console.log(secret, $$ACTION_ARG_0);
};
registerServerReference($$RSC_SERVER_ACTION_0, "406a88810ecce4a4e8b59d53b8327d7e98bbf251d7", null);
const $$RSC_SERVER_CACHE_1_INNER = async function getCachedRandom(x, children) {
|
const secret = 'my password is qwerty123';
export const $$RSC_SERVER_ACTION_0 = async function action($$ACTION_CLOSURE_BOUND) {
var [$$ACTION_ARG_0] = await decryptActionBoundArgs("406a88810ecce4a4e8b59d53b8327d7e98bbf251d7" | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/43/output.js",
"language": "javascript",
"file_size": 1705,
"cut_index": 537,
"middle_length": 229
} |
$$cache__ } from "private-next-rsc-cache-wrapper";
import { cache as $$reactCache__ } from "react";
// shadow the builtin Array global (used in the transform output)
/* __next_internal_action_entry_do_not_use__ {"c03128060c414d59f8552e4788b846c0d2b7f74743":{"name":"$$RSC_SERVER_CACHE_0"}} */ const Array1 = {};
const $... | NNER, Array.prototype.slice.call(arguments, 0, 1));
});
registerServerReference($$RSC_SERVER_CACHE_0, "c03128060c414d59f8552e4788b846c0d2b7f74743", null);
Object["defineProperty"]($$RSC_SERVER_CACHE_0, "name", {
value: "action"
});
export var action = | 552e4788b846c0d2b7f74743", 0, $$RSC_SERVER_CACHE_0_I | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/70/output.js",
"language": "javascript",
"file_size": 936,
"cut_index": 606,
"middle_length": 52
} |
{ registerServerReference } from "private-next-rsc-server-reference";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
/* __next_internal_action_entry_do_not_use__ {"406a88810ecce4a4e8b59d53b8327d7e98bbf251d7":{"name":"$$RSC_SERVER_ACTION_0"}} */ import { Button } fr... | $ACTION_ARG_1);
await deleteFromDb({
id3: $$ACTION_ARG_2
});
await deleteFromDb($$ACTION_ARG_3);
};
registerServerReference($$RSC_SERVER_ACTION_0, "406a88810ecce4a4e8b59d53b8327d7e98bbf251d7", null);
export function Item({ id1, id2, id3 | 1, $$ACTION_ARG_2, $$ACTION_ARG_3] = await decryptActionBoundArgs("406a88810ecce4a4e8b59d53b8327d7e98bbf251d7", $$ACTION_CLOSURE_BOUND);
await deleteFromDb($$ACTION_ARG_0);
await deleteFromDb(v1);
await deleteFromDb($ | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/5/output.js",
"language": "javascript",
"file_size": 1238,
"cut_index": 518,
"middle_length": 229
} |
use server'
import { db } from 'database'
export const createItem = async (title) => {
return new Promise((resolve, reject) => {
db.serialize(() => {
db.run(
`INSERT INTO items (title) VALUES ($title)`,
{ $title: title },
function () {
// arguments is allowed here
... | test() {
const MyClass = class {
x = 1
foo() {
// this is allowed here
return this.x
}
bar = () => {
// this is allowed here
return this.x
}
}
const myObj = new MyClass()
return myObj.foo() + myObj.bar()
| sync function | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/59/input.js",
"language": "javascript",
"file_size": 785,
"cut_index": 513,
"middle_length": 14
} |
ternal_action_entry_do_not_use__ {"00b98e10c56c1bee7af6ff753c91a4c70ab0419f0a":{"name":"test"},"407a40999f9833d2bb66a82d6a20a7f2a7810315f8":{"name":"createItem"}} */ import { registerServerReference } from "private-next-rsc-server-reference";
import { db } from 'database';
export const createItem = async (title)=>{
... | his.lastID);
});
});
});
};
export async function test() {
const MyClass = class {
x = 1;
foo() {
// this is allowed here
return this.x;
}
bar = ()=>{
// this i | // arguments is allowed here
const [err] = arguments;
if (err) {
reject(err);
}
// this is allowed here
resolve(t | {
"filepath": "crates/next-custom-transforms/tests/fixture/server-actions/server-graph/59/output.js",
"language": "javascript",
"file_size": 1447,
"cut_index": 524,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.