Commit 2471a697 authored by Jimmy Lai's avatar Jimmy Lai

Refactor markdown integration seams

parent ddc5b072
import {
MARKDOWN_COMPONENT_MARKER_TAG,
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP,
MARKDOWN_SEGMENT_MARKER_TAG,
} from './constants'
export type MarkdownBaseNode = {
hidden?: boolean
}
export type MarkdownTextNode = MarkdownBaseNode & {
kind: 'text'
rawText: string
}
export type MarkdownRawHtmlNode = MarkdownBaseNode & {
kind: 'raw-html'
html: string
}
export type MarkdownElementNode = MarkdownBaseNode & {
kind: 'element'
tagName: string
attributes: Record<string, string>
childNodes: MarkdownNode[]
}
export type MarkdownSegmentMarkerNode = MarkdownElementNode & {
tagName: typeof MARKDOWN_SEGMENT_MARKER_TAG
}
export type MarkdownComponentMarkerNode = MarkdownElementNode & {
tagName: typeof MARKDOWN_COMPONENT_MARKER_TAG
}
export type MarkdownFragmentNode = MarkdownBaseNode & {
kind: 'fragment'
childNodes: MarkdownNode[]
}
export type MarkdownNode =
| MarkdownTextNode
| MarkdownRawHtmlNode
| MarkdownElementNode
| MarkdownFragmentNode
export type MarkdownContainer = {
childNodes: MarkdownNode[]
}
export type MarkdownParentNode =
| MarkdownContainer
| MarkdownElementNode
| MarkdownFragmentNode
export function createMarkdownText(value: string): MarkdownTextNode {
return {
kind: 'text',
rawText: value,
hidden: false,
}
}
export function createRawHtmlNode(html: string): MarkdownRawHtmlNode {
return {
kind: 'raw-html',
html,
hidden: false,
}
}
export function createMarkdownFragment(): MarkdownFragmentNode {
return {
kind: 'fragment',
childNodes: [],
hidden: false,
}
}
export function createMarkdownElement(
type: string,
props: Record<string, any>
): MarkdownElementNode {
return {
kind: 'element',
tagName: type.toLowerCase(),
attributes: createReactAttributes(props),
childNodes: getDangerouslySetInnerHTMLNodes(props),
hidden: false,
}
}
export function hasDangerouslySetInnerHTML(
props: Record<string, any>
): boolean {
return (
!!props.dangerouslySetInnerHTML &&
typeof props.dangerouslySetInnerHTML === 'object' &&
typeof props.dangerouslySetInnerHTML.__html === 'string'
)
}
export function getDangerouslySetInnerHTMLNodes(
props: Record<string, any>
): MarkdownNode[] {
if (!hasDangerouslySetInnerHTML(props)) {
return []
}
return [createRawHtmlNode(props.dangerouslySetInnerHTML.__html)]
}
export function appendMarkdownChild(
parent: MarkdownParentNode,
child: MarkdownNode
): void {
const index = parent.childNodes.indexOf(child)
if (index !== -1) {
parent.childNodes.splice(index, 1)
}
parent.childNodes.push(child)
}
export function insertMarkdownChild(
parent: MarkdownParentNode,
child: MarkdownNode,
beforeChild: MarkdownNode
): void {
const existingIndex = parent.childNodes.indexOf(child)
if (existingIndex !== -1) {
parent.childNodes.splice(existingIndex, 1)
}
const beforeIndex = parent.childNodes.indexOf(beforeChild)
if (beforeIndex === -1) {
parent.childNodes.push(child)
return
}
parent.childNodes.splice(beforeIndex, 0, child)
}
export function removeMarkdownChild(
parent: MarkdownParentNode,
child: MarkdownNode
): void {
const index = parent.childNodes.indexOf(child)
if (index !== -1) {
parent.childNodes.splice(index, 1)
}
}
export function createAttributes(
node: MarkdownElementNode
): Record<string, string> {
return { ...node.attributes }
}
export function createReactAttributes(
props: Record<string, unknown>
): Record<string, string> {
const attributes: Record<string, string> = {}
for (const [key, value] of Object.entries(props)) {
if (
key === 'children' ||
key === 'dangerouslySetInnerHTML' ||
key === 'ref' ||
key === 'suppressHydrationWarning' ||
key === MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP
) {
continue
}
if (value == null || value === false || typeof value === 'function') {
continue
}
const attributeName =
key === 'className' ? 'class' : key === 'htmlFor' ? 'for' : key
if (typeof value === 'boolean') {
attributes[attributeName] = 'true'
continue
}
if (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'bigint'
) {
attributes[attributeName] = String(value)
continue
}
if (attributeName === 'style' && typeof value === 'object') {
const style = Object.entries(value as Record<string, unknown>)
.filter(([, styleValue]) => styleValue != null && styleValue !== '')
.map(([styleKey, styleValue]) => `${kebabCase(styleKey)}:${styleValue}`)
.join(';')
if (style) {
attributes.style = style
}
continue
}
if (Array.isArray(value)) {
attributes[attributeName] = value.join(' ')
}
}
return attributes
}
export function getTextContent(node: MarkdownNode): string {
if (node.hidden) {
return ''
}
if (isTextNode(node)) {
return node.rawText
}
if (isRawHtmlNode(node)) {
return node.html
}
return (node.childNodes ?? []).map((child) => getTextContent(child)).join('')
}
export function isElementNode(
node: MarkdownNode | null | undefined
): node is MarkdownElementNode {
return !!node && node.kind === 'element'
}
export function isTextNode(
node: MarkdownNode | null | undefined
): node is MarkdownTextNode {
return !!node && node.kind === 'text'
}
export function isRawHtmlNode(
node: MarkdownNode | null | undefined
): node is MarkdownRawHtmlNode {
return !!node && node.kind === 'raw-html'
}
export function isFragmentNode(
node: MarkdownNode | null | undefined
): node is MarkdownFragmentNode {
return !!node && node.kind === 'fragment'
}
export function isSegmentMarker(
node: MarkdownNode
): node is MarkdownSegmentMarkerNode {
return isElementNode(node) && node.tagName === MARKDOWN_SEGMENT_MARKER_TAG
}
export function isComponentMarker(
node: MarkdownNode
): node is MarkdownComponentMarkerNode {
return isElementNode(node) && node.tagName === MARKDOWN_COMPONENT_MARKER_TAG
}
export function getDirectChildSegments(
nodes: MarkdownNode[] | undefined
): MarkdownElementNode[] {
const segments: MarkdownElementNode[] = []
const visit = (childNodes: MarkdownNode[] | undefined) => {
for (const child of childNodes ?? []) {
if (isFragmentNode(child)) {
visit(child.childNodes)
continue
}
if (!isElementNode(child)) {
continue
}
if (isSegmentMarker(child)) {
segments.push(child)
continue
}
visit(child.childNodes)
}
}
visit(nodes)
return segments
}
export function getSingleCodeChild(
node: MarkdownElementNode
): MarkdownElementNode | null {
const elements = node.childNodes.filter(isElementNode)
if (elements.length === 1 && elements[0].tagName === 'code') {
return elements[0]
}
return null
}
export function findDescendantElements(
node: MarkdownElementNode,
tagName: string
): MarkdownElementNode[] {
const results: MarkdownElementNode[] = []
const visit = (childNodes: MarkdownNode[]) => {
for (const child of childNodes) {
if (isFragmentNode(child)) {
visit(child.childNodes)
continue
}
if (!isElementNode(child)) {
continue
}
if (child.tagName === tagName) {
results.push(child)
}
visit(child.childNodes)
}
}
visit(node.childNodes)
return results
}
function kebabCase(value: string): string {
return value.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)
}
export const MARKDOWN_COMPONENT_MARKER_TAG = 'react-markdown-component-marker'
export const MARKDOWN_SEGMENT_MARKER_TAG = 'react-markdown-segment-marker'
export const MARKDOWN_INTERACTIVE_ATTR = 'data-react-markdown-interactive'
export const MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP =
'__nextMarkdownBehavior'
export const MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_OMIT = 'omit'
export const MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH = 'passthrough'
export type MarkdownInternalComponentBehavior =
| typeof MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_OMIT
| typeof MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH
export function getMarkdownInternalComponentBehavior(
props: Record<string, unknown>
): MarkdownInternalComponentBehavior | undefined {
const behavior = props[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]
if (
behavior === MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_OMIT ||
behavior === MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH
) {
return behavior
}
return undefined
}
import type React from 'react'
export const MARKDOWN_COMPONENT_MARKER_TAG = 'react-markdown-component-marker'
export const MARKDOWN_SEGMENT_MARKER_TAG = 'react-markdown-segment-marker'
export const MARKDOWN_INTERACTIVE_ATTR = 'data-react-markdown-interactive'
export {
MARKDOWN_COMPONENT_MARKER_TAG,
MARKDOWN_INTERACTIVE_ATTR,
MARKDOWN_SEGMENT_MARKER_TAG,
} from './constants'
export function markReactNode(node: React.ReactNode): React.ReactNode {
return node
......@@ -17,4 +19,4 @@ export type {
MarkdownComponentContext,
MarkdownComponents,
MarkdownSegmentDefinition,
} from './index'
} from './types'
This diff is collapsed.
This diff is collapsed.
import React from 'react'
import {
appendMarkdownChild,
createMarkdownElement,
createMarkdownFragment,
createMarkdownText,
insertMarkdownChild,
removeMarkdownChild,
type MarkdownContainer,
type MarkdownElementNode,
type MarkdownFragmentNode,
type MarkdownNode,
type MarkdownParentNode,
type MarkdownTextNode,
} from './ast'
const Reconciler =
// eslint-disable-next-line @next/internal/typechecked-require -- Runtime dependency for the standalone renderer package.
require('react-reconciler') as any
const { ConcurrentRoot, DefaultEventPriority } =
// eslint-disable-next-line @next/internal/typechecked-require -- Runtime dependency for the standalone renderer package.
require('react-reconciler/constants') as {
ConcurrentRoot: number
DefaultEventPriority: number
}
const NO_HOST_CONTEXT = {}
const NOOP = () => {}
let currentUpdatePriority = DefaultEventPriority
const MarkdownTreeReconciler = Reconciler({
now: Date.now,
getRootHostContext() {
return NO_HOST_CONTEXT
},
getChildHostContext() {
return NO_HOST_CONTEXT
},
getPublicInstance(instance: MarkdownNode) {
return instance
},
prepareForCommit() {
return null
},
resetAfterCommit() {},
createInstance(type: string, props: Record<string, any>) {
return createMarkdownElement(type, props)
},
appendInitialChild(parent: MarkdownParentNode, child: MarkdownNode) {
appendMarkdownChild(parent, child)
},
finalizeInitialChildren() {
return false
},
shouldSetTextContent() {
return false
},
createTextInstance(text: string) {
return createMarkdownText(text)
},
scheduleTimeout: setTimeout,
cancelTimeout: clearTimeout,
noTimeout: -1,
isPrimaryRenderer: false,
supportsMutation: true,
supportsPersistence: false,
supportsHydration: false,
getInstanceFromNode() {
return null
},
preparePortalMount() {},
setCurrentUpdatePriority(priority: number) {
currentUpdatePriority = priority
},
getCurrentUpdatePriority() {
return currentUpdatePriority
},
resolveUpdatePriority() {
return currentUpdatePriority || DefaultEventPriority
},
trackSchedulerEvent() {},
resolveEventType() {
return null
},
resolveEventTimeStamp() {
return Date.now()
},
shouldAttemptEagerTransition() {
return false
},
detachDeletedInstance() {},
maySuspendCommit: false,
maySuspendCommitOnUpdate: false,
maySuspendCommitInSyncRender: false,
preloadInstance() {},
startSuspendingCommit() {},
suspendInstance() {},
suspendOnActiveViewTransition: false,
waitForCommitToBeReady() {
return null
},
getSuspendedCommitReason() {
return null
},
NotPendingTransition: null,
HostTransitionContext: {
_currentValue: null,
_currentValue2: null,
_threadCount: 0,
Provider: null,
Consumer: null,
},
resetFormInstance() {},
bindToConsole(methodName: keyof Console) {
const value = console[methodName] as unknown
return typeof value === 'function'
? (value as (...args: any[]) => void).bind(console)
: console.error.bind(console)
},
supportsMicrotasks: true,
scheduleMicrotask: queueMicrotask,
supportsTestSelectors: false,
findFiberRoot() {
return null
},
getBoundingRect() {
return { x: 0, y: 0, width: 0, height: 0 }
},
getTextContent() {
return ''
},
isHiddenSubtree() {
return false
},
matchAccessibilityRole() {
return false
},
setFocusIfFocusable() {
return false
},
setupIntersectionObserver() {
return NOOP
},
appendChild(parent: MarkdownParentNode, child: MarkdownNode) {
appendMarkdownChild(parent, child)
},
appendChildToContainer(container: MarkdownContainer, child: MarkdownNode) {
appendMarkdownChild(container, child)
},
commitTextUpdate(
textInstance: MarkdownTextNode,
_oldText: string,
newText: string
) {
textInstance.rawText = String(newText)
},
commitMount() {},
commitUpdate(
instance: MarkdownElementNode,
_payload: unknown,
type: string,
_oldProps: Record<string, any>,
newProps: Record<string, any>
) {
instance.tagName = type.toLowerCase()
instance.attributes = createMarkdownElement(type, newProps).attributes
instance.childNodes = createMarkdownElement(type, newProps).childNodes
},
insertBefore(
parent: MarkdownParentNode,
child: MarkdownNode,
beforeChild: MarkdownNode
) {
insertMarkdownChild(parent, child, beforeChild)
},
insertInContainerBefore(
container: MarkdownContainer,
child: MarkdownNode,
beforeChild: MarkdownNode
) {
insertMarkdownChild(container, child, beforeChild)
},
removeChild(parent: MarkdownParentNode, child: MarkdownNode) {
removeMarkdownChild(parent, child)
},
removeChildFromContainer(container: MarkdownContainer, child: MarkdownNode) {
removeMarkdownChild(container, child)
},
resetTextContent() {},
hideInstance(instance: MarkdownElementNode | MarkdownFragmentNode) {
instance.hidden = true
},
hideTextInstance(instance: MarkdownTextNode) {
instance.hidden = true
},
unhideInstance(instance: MarkdownElementNode | MarkdownFragmentNode) {
instance.hidden = false
},
unhideTextInstance(instance: MarkdownTextNode) {
instance.hidden = false
},
applyViewTransitionName() {},
restoreViewTransitionName() {},
cancelViewTransitionName() {},
cancelRootViewTransitionName() {},
restoreRootViewTransitionName() {},
measureInstance() {
return null
},
measureClonedInstance() {
return null
},
wasInstanceInViewport() {
return true
},
hasInstanceChanged() {
return false
},
hasInstanceAffectedParent() {
return false
},
startViewTransition() {},
stopViewTransition() {},
addViewTransitionFinishedListener() {},
createViewTransitionInstance() {
return null
},
clearContainer(container: MarkdownContainer) {
container.childNodes.length = 0
},
createFragmentInstance() {
return createMarkdownFragment()
},
updateFragmentInstanceFiber() {},
commitNewChildToFragmentInstance(
parent: MarkdownFragmentNode,
child: MarkdownNode
) {
appendMarkdownChild(parent, child)
},
deleteChildFromFragmentInstance(
parent: MarkdownFragmentNode,
child: MarkdownNode
) {
removeMarkdownChild(parent, child)
},
cloneInstance(instance: MarkdownElementNode) {
return {
...instance,
attributes: { ...instance.attributes },
childNodes: [...instance.childNodes],
}
},
})
export function renderReactNodeToMarkdownNodes(
node: React.ReactNode
): MarkdownNode[] {
const container: MarkdownContainer = { childNodes: [] }
let renderError: unknown = null
const onError = (error: unknown) => {
renderError ??= error
}
const root = MarkdownTreeReconciler.createContainer(
container,
ConcurrentRoot,
null,
false,
null,
'',
onError,
onError,
onError,
null
)
try {
withServerStyleHooksDisabled(() => {
MarkdownTreeReconciler.updateContainerSync(node, root, null, null)
MarkdownTreeReconciler.flushSyncWork()
})
} catch (error) {
renderError ??= error
}
if (renderError) {
throw renderError
}
return container.childNodes
}
function withServerStyleHooksDisabled<T>(callback: () => T): T {
const clientInternals = (React as any)
.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE as
| { H: unknown }
| undefined
if (!clientInternals) {
return callback()
}
const descriptor = Object.getOwnPropertyDescriptor(clientInternals, 'H')
let currentDispatcher = (clientInternals as { H: unknown }).H
Object.defineProperty(clientInternals, 'H', {
configurable: true,
enumerable: true,
get() {
return currentDispatcher
},
set(value) {
currentDispatcher = maskEffectHooks(value)
},
})
try {
;(clientInternals as { H: unknown }).H = currentDispatcher
return callback()
} finally {
if (descriptor) {
Object.defineProperty(clientInternals, 'H', descriptor)
} else {
Object.defineProperty(clientInternals, 'H', {
configurable: true,
enumerable: true,
writable: true,
value: currentDispatcher,
})
}
}
}
function maskEffectHooks(dispatcher: unknown): unknown {
if (!dispatcher || typeof dispatcher !== 'object') {
return dispatcher
}
return {
...(dispatcher as Record<string, unknown>),
useEffect: NOOP,
useInsertionEffect: NOOP,
useLayoutEffect: NOOP,
useImperativeHandle: NOOP,
}
}
This diff is collapsed.
export type MarkdownComponentContext = {
tagName?: string
componentName?: string
attributes: Record<string, string>
children: string
textContent: string
renderDefault: () => string
}
export type MarkdownComponent = (
context: MarkdownComponentContext
) => string | null | undefined
export type MarkdownComponents = Record<string, MarkdownComponent>
export type MarkdownSegmentDefinition = {
id: string
props: any
components?: MarkdownComponents
render?: (
props: any,
helpers: {
content: string
children: string
}
) => string | Promise<string> | null | undefined
}
......@@ -1088,5 +1088,6 @@
"1087": "Failed to parse \"%s\":\\n%s%s",
"1088": "Expected RSC navigation response to have a body",
"1089": "RSC fetch failed after all retry attempts",
"1090": "Markdown output is not supported in the Edge runtime."
"1090": "Markdown output is not supported in the Edge runtime.",
"1091": "Expected InitialRSCPayload to include seed data for markdown rendering."
}
......@@ -10,6 +10,8 @@ import { recursiveReadDir } from '../../lib/recursive-readdir'
import { isDynamicRoute } from '../../shared/lib/router/utils'
import type { Revalidate } from '../../server/lib/cache-control'
import type { NextConfigComplete } from '../../server/config-shared'
import { getNegotiatedDocumentPathname } from '../../server/document-representation'
import { markdownDocumentRepresentation } from '../../server/markdown/representation'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { AdapterOutputType, type PHASE_TYPE } from '../../shared/lib/constants'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
......@@ -307,12 +309,6 @@ export interface AdapterOutputs {
staticFiles: Array<AdapterOutput['STATIC_FILE']>
}
const MARKDOWN_OUTPUT_SUFFIX = '.markdown'
function getMarkdownOutputPathname(pathname: string): string {
return `${normalizePagePath(pathname)}${MARKDOWN_OUTPUT_SUFFIX}`
}
type RewriteItem = {
source: string
sourceRegex: string
......@@ -871,6 +867,48 @@ export async function handleBuildComplete({
const route = normalizePagePath(page)
const pageFile = path.join(pagesDistDir, `${route}.js`)
const functionConfig = functionsConfigManifest.functions[route] || {}
let sourcePage = route.replace(/^\//, '')
sourcePage = sourcePage === 'api' ? 'api/index' : sourcePage
const baseConfig = {
maxDuration: functionConfig.maxDuration,
preferredRegion: functionConfig.regions,
}
const createStaticMarkdownFileOutput = async (
pathname: string
): Promise<AdapterOutput['STATIC_FILE'] | null> => {
if (!functionConfig.markdown) {
return null
}
const staticHtmlPath = path.join(
pagesDistDir,
`${normalizePagePath(pathname)}.html`
)
const markdownFilePath = staticHtmlPath.replace(
/\.html$/,
markdownDocumentRepresentation.outputSuffix
)
return {
id: getNegotiatedDocumentPathname(
markdownDocumentRepresentation,
pathname
),
pathname: getNegotiatedDocumentPathname(
markdownDocumentRepresentation,
pathname
),
type: AdapterOutputType.STATIC_FILE,
filePath: markdownFilePath,
immutableHash: undefined,
}
}
const pageTraceFile = `${pageFile}.nft.json`
// if it's an auto static optimized page it's just
// a static file
......@@ -893,6 +931,12 @@ export async function handleBuildComplete({
outputs.staticFiles.push(localeOutput)
const markdownOutput =
await createStaticMarkdownFileOutput(localePage)
if (markdownOutput) {
outputs.staticFiles.push(markdownOutput)
}
if (appPageKeys && appPageKeys.length > 0) {
outputs.staticFiles.push({
id: `${localePage}.rsc`,
......@@ -914,6 +958,11 @@ export async function handleBuildComplete({
outputs.staticFiles.push(staticOutput)
const markdownOutput = await createStaticMarkdownFileOutput(route)
if (markdownOutput) {
outputs.staticFiles.push(markdownOutput)
}
if (appPageKeys && appPageKeys.length > 0) {
outputs.staticFiles.push({
id: `${page}.rsc`,
......@@ -928,7 +977,6 @@ export async function handleBuildComplete({
continue
}
const pageTraceFile = `${pageFile}.nft.json`
const assets = await handleTraceFiles(pageTraceFile, 'pages').catch(
(err) => {
if (err.code !== 'ENOENT' || (page !== '/404' && page !== '/500')) {
......@@ -937,15 +985,6 @@ export async function handleBuildComplete({
return {} as Record<string, string>
}
)
const functionConfig = functionsConfigManifest.functions[route] || {}
let sourcePage = route.replace(/^\//, '')
sourcePage = sourcePage === 'api' ? 'api/index' : sourcePage
const baseConfig = {
maxDuration: functionConfig.maxDuration,
preferredRegion: functionConfig.regions,
}
const output: AdapterOutput['PAGES'] | AdapterOutput['PAGES_API'] = {
id: route,
type: page.startsWith('/api')
......@@ -964,7 +1003,10 @@ export async function handleBuildComplete({
outputs.pages.push(output)
if (functionConfig.markdown) {
const markdownPathname = getMarkdownOutputPathname(route)
const markdownPathname = getNegotiatedDocumentPathname(
markdownDocumentRepresentation,
route
)
outputs.pages.push({
...output,
pathname: markdownPathname,
......@@ -1010,7 +1052,10 @@ export async function handleBuildComplete({
})
if (functionConfig.markdown) {
const markdownPathname = getMarkdownOutputPathname(localePage)
const markdownPathname = getNegotiatedDocumentPathname(
markdownDocumentRepresentation,
localePage
)
outputs.pages.push({
...output,
pathname: markdownPathname,
......@@ -1150,7 +1195,8 @@ export async function handleBuildComplete({
config: baseConfig,
})
if (functionConfig.markdown) {
const markdownPathname = getMarkdownOutputPathname(
const markdownPathname = getNegotiatedDocumentPathname(
markdownDocumentRepresentation,
output.pathname
)
outputs.appPages.push({
......
......@@ -222,7 +222,8 @@ function checkExports(
hasLeadingNonDirectiveNode = true
}
if (
node.type === 'ExportDeclaration' &&
(node.type === 'ExportDeclaration' ||
node.type === 'ExportNamedDeclaration') &&
node.declaration?.type === 'VariableDeclaration'
) {
for (const declaration of node.declaration?.declarations) {
......@@ -239,7 +240,8 @@ function checkExports(
}
if (
node.type === 'ExportDeclaration' &&
(node.type === 'ExportDeclaration' ||
node.type === 'ExportNamedDeclaration') &&
node.declaration?.type === 'FunctionDeclaration' &&
exportsSet.has(node.declaration.identifier?.value)
) {
......@@ -252,7 +254,8 @@ function checkExports(
}
if (
node.type === 'ExportDeclaration' &&
(node.type === 'ExportDeclaration' ||
node.type === 'ExportNamedDeclaration') &&
node.declaration?.type === 'FunctionDeclaration' &&
node.declaration.identifier?.value === 'generateMarkdown'
) {
......@@ -260,7 +263,8 @@ function checkExports(
}
if (
node.type === 'ExportDeclaration' &&
(node.type === 'ExportDeclaration' ||
node.type === 'ExportNamedDeclaration') &&
node.declaration?.type === 'VariableDeclaration'
) {
const id = node.declaration?.declarations[0]?.id.value
......
......@@ -3467,7 +3467,7 @@ export default async function build(
page: string,
file: string,
isSsg: boolean,
ext: 'html' | 'json',
ext: 'html' | 'json' | 'markdown',
additionalSsgFile = false
) => {
return staticGenerationSpan
......@@ -3502,6 +3502,7 @@ export default async function build(
.replace(/\\/g, '/')
if (
ext !== 'markdown' &&
!isSsg &&
!(
// don't add static status page to manifest if it's
......@@ -3570,7 +3571,7 @@ export default async function build(
updatedRelativeDest
)
if (!isSsg) {
if (ext !== 'markdown' && !isSsg) {
pagesManifest[curPath] = updatedRelativeDest
}
await fs.mkdir(path.dirname(updatedDest), {
......@@ -3719,9 +3720,14 @@ export default async function build(
// fallback is enabled. Below, we handle the specific prerenders
// of these.
const hasHtmlOutput = !(isSsg && isDynamic && !isStaticSsgFallback)
const hasMarkdownOutput =
functionsConfigManifest.functions[page]?.markdown === true
if (hasHtmlOutput) {
await moveExportedPage(page, page, file, isSsg, 'html')
if (hasMarkdownOutput) {
await moveExportedPage(page, page, file, isSsg, 'markdown')
}
}
if (isSsg) {
......@@ -3789,6 +3795,16 @@ export default async function build(
'html',
true
)
if (hasMarkdownOutput) {
await moveExportedPage(
page,
route.pathname,
pageFile,
isSsg,
'markdown',
true
)
}
await moveExportedPage(
page,
route.pathname,
......
......@@ -7,127 +7,16 @@ import path from 'path'
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { debug } from 'next/dist/compiled/debug'
import type { ResolvedBaseUrl } from '../../load-jsconfig'
import {
isString,
matchPatternOrExact,
matchedText,
pathIsRelative,
patternText,
} from '../../../lib/jsconfig-path-matcher'
const log = debug('next:jsconfig-paths-plugin')
export interface Pattern {
prefix: string
suffix: string
}
const asterisk = 0x2a
export function hasZeroOrOneAsteriskCharacter(str: string): boolean {
let seenAsterisk = false
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) === asterisk) {
if (!seenAsterisk) {
seenAsterisk = true
} else {
// have already seen asterisk
return false
}
}
}
return true
}
/**
* Determines whether a path starts with a relative path component (i.e. `.` or `..`).
*/
export function pathIsRelative(testPath: string): boolean {
return /^\.\.?($|[\\/])/.test(testPath)
}
export function tryParsePattern(pattern: string): Pattern | undefined {
// This should be verified outside of here and a proper error thrown.
const indexOfStar = pattern.indexOf('*')
return indexOfStar === -1
? undefined
: {
prefix: pattern.slice(0, indexOfStar),
suffix: pattern.slice(indexOfStar + 1),
}
}
function isPatternMatch({ prefix, suffix }: Pattern, candidate: string) {
return (
candidate.length >= prefix.length + suffix.length &&
candidate.startsWith(prefix) &&
candidate.endsWith(suffix)
)
}
/** Return the object corresponding to the best pattern to match `candidate`. */
export function findBestPatternMatch<T>(
values: readonly T[],
getPattern: (value: T) => Pattern,
candidate: string
): T | undefined {
let matchedValue: T | undefined
// use length of prefix as betterness criteria
let longestMatchPrefixLength = -1
for (const v of values) {
const pattern = getPattern(v)
if (
isPatternMatch(pattern, candidate) &&
pattern.prefix.length > longestMatchPrefixLength
) {
longestMatchPrefixLength = pattern.prefix.length
matchedValue = v
}
}
return matchedValue
}
/**
* patternStrings contains both pattern strings (containing "*") and regular strings.
* Return an exact match if possible, or a pattern match, or undefined.
* (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
*/
export function matchPatternOrExact(
patternStrings: readonly string[],
candidate: string
): string | Pattern | undefined {
const patterns: Pattern[] = []
for (const patternString of patternStrings) {
if (!hasZeroOrOneAsteriskCharacter(patternString)) continue
const pattern = tryParsePattern(patternString)
if (pattern) {
patterns.push(pattern)
} else if (patternString === candidate) {
// pattern was matched as is - no need to search further
return patternString
}
}
return findBestPatternMatch(patterns, (_) => _, candidate)
}
/**
* Tests whether a value is string
*/
export function isString(text: unknown): text is string {
return typeof text === 'string'
}
/**
* Given that candidate matches pattern, returns the text matching the '*'.
* E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
*/
export function matchedText(pattern: Pattern, candidate: string): string {
return candidate.substring(
pattern.prefix.length,
candidate.length - pattern.suffix.length
)
}
export function patternText({ prefix, suffix }: Pattern): string {
return `${prefix}*${suffix}`
}
/**
* Calls the iterator function for each entry of the array
* until the first result or error is reached
......
......@@ -44,6 +44,11 @@ import {
NavigationPromisesContext,
type NavigationPromises,
} from '../../shared/lib/hooks-client-context.shared-runtime'
import {
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_OMIT,
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP,
} from '../../lib/constants'
import { getParamValueFromCacheKey } from '../route-params'
import type { Params } from '../../server/request/params'
import { isDeferredRsc } from './router-reducer/ppr-navigations'
......@@ -746,12 +751,24 @@ export default function OuterLayoutRouter({
const pagePrefix = normalizeAppPath(url)
segmentViewStateNode = (
<SegmentViewStateNode key={pagePrefix} page={pagePrefix} />
<SegmentViewStateNode
key={pagePrefix}
page={pagePrefix}
{...{
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_OMIT,
}}
/>
)
segmentBoundaryTriggerNode = (
<>
<SegmentBoundaryTriggerNode />
<SegmentBoundaryTriggerNode
{...{
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_OMIT,
}}
/>
</>
)
}
......@@ -863,7 +880,13 @@ export default function OuterLayoutRouter({
require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')
child = (
<SegmentStateProvider key={stateKey}>
<SegmentStateProvider
key={stateKey}
{...{
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
}}
>
{child}
{segmentViewBoundaries}
</SegmentStateProvider>
......
......@@ -477,6 +477,8 @@ async function exportAppImpl(
isBuildTimePrerendering: true,
assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
distDir,
projectDir: dir,
tsconfigPath: nextConfig.typescript.tsconfigPath,
basePath: nextConfig.basePath,
cacheComponents: nextConfig.cacheComponents ?? false,
trailingSlash: nextConfig.trailingSlash,
......@@ -501,6 +503,7 @@ async function exportAppImpl(
images: nextConfig.images,
htmlLimitedBots: nextConfig.htmlLimitedBots.source,
experimental: {
markdown: nextConfig.experimental.markdown,
clientTraceMetadata: nextConfig.experimental.clientTraceMetadata,
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
......
......@@ -14,14 +14,19 @@ import type {
MockedRequest,
MockedResponse,
} from '../../server/lib/mock-request'
import { createRequestResponseMocks } from '../../server/lib/mock-request'
import {
HTML_CONTENT_TYPE_HEADER,
NEXT_DATA_SUFFIX,
SERVER_PROPS_EXPORT_ERROR,
} from '../../lib/constants'
import { getMarkdownRouteConfig } from '../../server/markdown/config'
import { markdownDocumentRepresentation } from '../../server/markdown/representation'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { interopDefault } from '../../lib/interop-default'
import { lazyRenderPagesPage } from '../../server/route-modules/pages/module.render'
import type { MultiFileWriter } from '../../lib/multi-file-writer'
import { getRequestMeta, setRequestMeta } from '../../server/request-meta'
/**
* Renders & exports a page associated with the /pages directory
......@@ -107,6 +112,50 @@ export async function exportPagesPage(
}
}
const markdownRoute = getMarkdownRouteConfig(
renderOpts.ComponentMod as {
markdown?: unknown
generateMarkdown?: unknown
}
)
if (renderOpts.experimental.markdown === true && markdownRoute.enabled) {
const markdownFilepath = htmlFilepath.replace(/\.html$/, '.markdown')
const { req: markdownReq, res: markdownRes } = createRequestResponseMocks({
url: req.url || path,
method: 'GET',
headers: {
...req.headers,
accept: markdownDocumentRepresentation.contentType,
},
})
markdownRes.statusCode = res.statusCode
setRequestMeta(markdownReq, { ...getRequestMeta(req) })
const markdownRenderOpts =
typeof renderOpts.Component === 'string'
? {
...renderOpts,
Component: interopDefault(renderOpts.ComponentMod),
}
: renderOpts
const markdownResult = await lazyRenderPagesPage(
markdownReq,
markdownRes,
page,
searchAndDynamicParams,
markdownRenderOpts,
sharedContext,
renderContext
)
if (markdownResult && !markdownResult.isNull) {
fileWriter.append(markdownFilepath, markdownResult.toUnchunkedString())
}
}
const ssgNotFound = renderResult?.metadata.isNotFound
const html =
......
......@@ -63,6 +63,10 @@ export const DOT_NEXT_ALIAS = 'private-dot-next'
export const ROOT_DIR_ALIAS = 'private-next-root-dir'
export const APP_DIR_ALIAS = 'private-next-app-dir'
export const MARKDOWN_COMPONENTS_ALIAS = 'next-markdown-import-source-file'
export const MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP =
'__nextMarkdownBehavior'
export const MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_OMIT = 'omit'
export const MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH = 'passthrough'
export const RSC_MOD_REF_PROXY_ALIAS = 'private-next-rsc-mod-ref-proxy'
export const RSC_ACTION_VALIDATE_ALIAS = 'private-next-rsc-action-validate'
export const RSC_ACTION_PROXY_ALIAS = 'private-next-rsc-server-reference'
......
/**
* Runtime-safe subset of Next's jsconfig/tsconfig path matching logic.
* Based on the same TypeScript path pattern handling used by the webpack plugin.
*/
export interface Pattern {
prefix: string
suffix: string
}
const asterisk = 0x2a
export function hasZeroOrOneAsteriskCharacter(str: string): boolean {
let seenAsterisk = false
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) === asterisk) {
if (!seenAsterisk) {
seenAsterisk = true
} else {
return false
}
}
}
return true
}
export function pathIsRelative(testPath: string): boolean {
return /^\.\.?($|[\\/])/.test(testPath)
}
export function tryParsePattern(pattern: string): Pattern | undefined {
const indexOfStar = pattern.indexOf('*')
return indexOfStar === -1
? undefined
: {
prefix: pattern.slice(0, indexOfStar),
suffix: pattern.slice(indexOfStar + 1),
}
}
function isPatternMatch({ prefix, suffix }: Pattern, candidate: string) {
return (
candidate.length >= prefix.length + suffix.length &&
candidate.startsWith(prefix) &&
candidate.endsWith(suffix)
)
}
export function findBestPatternMatch<T>(
values: readonly T[],
getPattern: (value: T) => Pattern,
candidate: string
): T | undefined {
let matchedValue: T | undefined
let longestMatchPrefixLength = -1
for (const value of values) {
const pattern = getPattern(value)
if (
isPatternMatch(pattern, candidate) &&
pattern.prefix.length > longestMatchPrefixLength
) {
longestMatchPrefixLength = pattern.prefix.length
matchedValue = value
}
}
return matchedValue
}
export function matchPatternOrExact(
patternStrings: readonly string[],
candidate: string
): string | Pattern | undefined {
const patterns: Pattern[] = []
for (const patternString of patternStrings) {
if (!hasZeroOrOneAsteriskCharacter(patternString)) continue
const pattern = tryParsePattern(patternString)
if (pattern) {
patterns.push(pattern)
} else if (patternString === candidate) {
return patternString
}
}
return findBestPatternMatch(patterns, (_) => _, candidate)
}
export function isString(text: unknown): text is string {
return typeof text === 'string'
}
export function matchedText(pattern: Pattern, candidate: string): string {
return candidate.substring(
pattern.prefix.length,
candidate.length - pattern.suffix.length
)
}
export function patternText({ prefix, suffix }: Pattern): string {
return `${prefix}*${suffix}`
}
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { requireMarkdownComponents } from './require-markdown-components'
describe('requireMarkdownComponents', () => {
it('resolves markdown-components from the configured project dir', async () => {
const tmpDir = await mkdtemp(join(tmpdir(), 'nextjs-markdown-components-'))
const appDir = join(tmpDir, 'apps', 'web')
await mkdir(appDir, { recursive: true })
await writeFile(
join(tmpDir, 'markdown-components.ts'),
createMarkdownComponentsModule('root')
)
await writeFile(
join(appDir, 'markdown-components.ts'),
createMarkdownComponentsModule('app')
)
const components = await requireMarkdownComponents({
dir: appDir,
dev: false,
})
expect(components.p?.(createMarkdownComponentContext('value'))).toBe(
'app:value'
)
})
it('resolves markdown-components imports through configured tsconfig paths', async () => {
const tmpDir = await mkdtemp(join(tmpdir(), 'nextjs-markdown-components-'))
const srcDir = join(tmpDir, 'src')
await mkdir(srcDir, { recursive: true })
await writeFile(
join(tmpDir, 'jsconfig.json'),
JSON.stringify({
compilerOptions: {
baseUrl: '.',
paths: {
'@/*': ['src/*'],
},
},
})
)
await writeFile(join(srcDir, 'label.ts'), `export const label = 'alias'\n`)
await writeFile(
join(tmpDir, 'markdown-components.ts'),
`
import { label } from '@/label'
export function useMarkdownComponents() {
return {
p({ children }) {
return \`\${label}:\${children}\`
},
}
}
`
)
const components = await requireMarkdownComponents({
dir: tmpDir,
dev: false,
})
expect(components.p?.(createMarkdownComponentContext('value'))).toBe(
'alias:value'
)
})
it('reloads markdown-components from disk on every request in development', async () => {
const tmpDir = await mkdtemp(join(tmpdir(), 'nextjs-markdown-components-'))
const filePath = join(tmpDir, 'markdown-components.ts')
await writeFile(filePath, createMarkdownComponentsModule('first'))
const firstLoad = await requireMarkdownComponents({
dir: tmpDir,
dev: true,
})
expect(firstLoad.p?.(createMarkdownComponentContext('value'))).toBe(
'first:value'
)
await writeFile(filePath, createMarkdownComponentsModule('second'))
const secondLoad = await requireMarkdownComponents({
dir: tmpDir,
dev: true,
})
expect(secondLoad.p?.(createMarkdownComponentContext('value'))).toBe(
'second:value'
)
})
})
function createMarkdownComponentsModule(prefix: string): string {
return `
export function useMarkdownComponents() {
return {
p({ children }) {
return '${prefix}:' + children
},
}
}
`
}
function createMarkdownComponentContext(children: string) {
return {
attributes: {},
children,
textContent: children,
renderDefault() {
return children
},
}
}
import type { MarkdownComponents } from '@next/markdown'
import { existsSync, readFileSync, statSync } from 'node:fs'
import Module from 'node:module'
import { dirname, extname, isAbsolute, join, resolve } from 'node:path'
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import { loadUserModule } from './user-module-loader'
type MarkdownComponentsModule = {
default?: {
......@@ -22,187 +23,27 @@ const MARKDOWN_COMPONENTS_CANDIDATES = [
'markdown-components.js',
]
const USER_MODULE_EXTENSIONS = [
'.ts',
'.tsx',
'.js',
'.jsx',
'.mjs',
'.cjs',
'.mts',
'.cts',
]
const userModuleCache = new Map<string, unknown>()
function getMarkdownComponentsPath(cwd: string): string | null {
for (const candidate of MARKDOWN_COMPONENTS_CANDIDATES) {
const filePath = join(cwd, candidate)
if (existsSync(filePath)) {
return filePath
}
}
return null
type RequireMarkdownComponentsOptions = {
dir: string
tsconfigPath?: string
dev?: boolean
}
function isFile(filePath: string): boolean {
try {
return statSync(filePath).isFile()
} catch {
return false
}
}
function resolveUserModulePath(
fromFilename: string,
request: string
): string | null {
if (!request.startsWith('.') && !isAbsolute(request)) {
return null
}
const basePath = request.startsWith('.')
? resolve(dirname(fromFilename), request)
: request
if (isFile(basePath)) {
return basePath
}
for (const extension of USER_MODULE_EXTENSIONS) {
if (isFile(basePath + extension)) {
return basePath + extension
}
}
for (const extension of USER_MODULE_EXTENSIONS) {
const indexPath = join(basePath, `index${extension}`)
if (isFile(indexPath)) {
return indexPath
}
}
return null
}
function shouldEnableJsxTransform(filename: string): boolean {
const extension = extname(filename)
return extension === '.jsx' || extension === '.tsx'
}
function shouldUseTypeScriptParser(filename: string): boolean {
const extension = extname(filename)
return (
extension === '.ts' ||
extension === '.tsx' ||
extension === '.cts' ||
extension === '.mts'
)
}
function transformModule(code: string, filename: string): string {
// eslint-disable-next-line no-eval -- We need runtime `require` here so the Node-only SWC loader isn't statically bundled into edge-facing codepaths.
const dynamicRequire = eval('require') as NodeJS.Require
const { transformSync } = dynamicRequire(
'next/dist/build/swc'
) as typeof import('../build/swc')
const parser = shouldUseTypeScriptParser(filename)
? {
syntax: 'typescript' as const,
tsx: shouldEnableJsxTransform(filename),
}
: {
syntax: 'ecmascript' as const,
jsx: shouldEnableJsxTransform(filename),
}
return transformSync(code, {
filename,
jsc: {
parser,
transform: shouldEnableJsxTransform(filename)
? {
react: {
runtime: 'automatic',
},
}
: undefined,
},
module: {
type: 'commonjs',
},
isModule: 'unknown',
env: {
targets: {
node: process.versions.node ?? '20.19.0',
},
},
}).code
}
function executeUserModule(filePath: string): unknown {
const cached = userModuleCache.get(filePath)
if (cached) {
return cached
}
const source = readFileSync(filePath, 'utf8')
const transformed = transformModule(source, filePath)
const moduleRecord = { exports: {} as unknown }
userModuleCache.set(filePath, moduleRecord.exports)
const createRequire = Module.createRequire(filePath)
const localRequire = (request: string) => {
const resolvedUserModulePath = resolveUserModulePath(filePath, request)
if (resolvedUserModulePath) {
return executeUserModule(resolvedUserModulePath)
}
return createRequire(request)
}
// eslint-disable-next-line no-new-func -- We compile user-provided markdown-components modules to CommonJS and execute them in an isolated local module scope.
const wrapped = new Function(
'exports',
'require',
'module',
'__filename',
'__dirname',
transformed
) as (
exports: unknown,
require: (request: string) => unknown,
module: { exports: unknown },
__filename: string,
__dirname: string
) => void
wrapped(
moduleRecord.exports,
localRequire,
moduleRecord,
filePath,
dirname(filePath)
)
userModuleCache.set(filePath, moduleRecord.exports)
return moduleRecord.exports
}
function loadMarkdownComponentsModule(
filePath: string
): MarkdownComponentsModule {
return executeUserModule(filePath) as MarkdownComponentsModule
}
export function requireMarkdownComponents(): MarkdownComponents {
const filePath = getMarkdownComponentsPath(process.cwd())
export async function requireMarkdownComponents({
dir,
tsconfigPath,
dev,
}: RequireMarkdownComponentsOptions): Promise<MarkdownComponents> {
const filePath = getMarkdownComponentsPath(dir)
if (!filePath) {
return {}
}
const mod = loadMarkdownComponentsModule(filePath)
const mod = (await loadUserModule(filePath, {
dir,
tsconfigPath,
dev,
})) as MarkdownComponentsModule
const loadMarkdownComponents =
mod.useMarkdownComponents ?? mod.default?.useMarkdownComponents
......@@ -212,3 +53,14 @@ export function requireMarkdownComponents(): MarkdownComponents {
return loadMarkdownComponents()
}
function getMarkdownComponentsPath(dir: string): string | null {
for (const candidate of MARKDOWN_COMPONENTS_CANDIDATES) {
const filePath = join(dir, candidate)
if (existsSync(filePath)) {
return filePath
}
}
return null
}
import { readFileSync, statSync } from 'node:fs'
import Module from 'node:module'
import { dirname, extname, isAbsolute, join, resolve } from 'node:path'
import type { ResolvedBaseUrl } from '../build/load-jsconfig'
import {
isString,
matchPatternOrExact,
matchedText,
pathIsRelative,
patternText,
} from './jsconfig-path-matcher'
const USER_MODULE_EXTENSIONS = [
'.ts',
'.tsx',
'.js',
'.jsx',
'.mjs',
'.cjs',
'.mts',
'.cts',
]
type UserModuleLoaderOptions = {
dir: string
tsconfigPath?: string
dev?: boolean
}
type UserModuleCacheEntry = {
exports: unknown
dependencies: ReadonlySet<string>
}
type UserModuleResolutionConfig = {
paths: Record<string, string[]>
resolvedBaseUrl: ResolvedBaseUrl
}
const userModuleCache = new Map<string, UserModuleCacheEntry>()
const userModuleResolutionCache = new Map<string, UserModuleResolutionConfig>()
export async function loadUserModule(
filePath: string,
options: UserModuleLoaderOptions
): Promise<unknown> {
const resolutionConfig = await getUserModuleResolutionConfig(options)
return executeUserModule(filePath, options, resolutionConfig).exports
}
function executeUserModule(
filePath: string,
options: UserModuleLoaderOptions,
resolutionConfig: UserModuleResolutionConfig
): UserModuleCacheEntry {
if (!options.dev) {
const cached = userModuleCache.get(filePath)
if (cached) {
return cached
}
}
const source = readFileSync(filePath, 'utf8')
const transformed = transformModule(source, filePath)
const moduleRecord = { exports: {} as unknown }
const dependencies = new Set<string>([filePath])
const createRequire = Module.createRequire(filePath)
const localRequire = (request: string) => {
const resolvedUserModulePath = resolveUserModuleRequest(
filePath,
request,
resolutionConfig
)
if (resolvedUserModulePath) {
const dependencyEntry = executeUserModule(
resolvedUserModulePath,
options,
resolutionConfig
)
dependencyEntry.dependencies.forEach((dependency) => {
dependencies.add(dependency)
})
return dependencyEntry.exports
}
return createRequire(request)
}
// eslint-disable-next-line no-new-func -- We compile user-provided modules to CommonJS and execute them in an isolated local module scope.
const wrapped = new Function(
'exports',
'require',
'module',
'__filename',
'__dirname',
transformed
) as (
exports: unknown,
require: (request: string) => unknown,
module: { exports: unknown },
__filename: string,
__dirname: string
) => void
wrapped(
moduleRecord.exports,
localRequire,
moduleRecord,
filePath,
dirname(filePath)
)
const entry: UserModuleCacheEntry = {
exports: moduleRecord.exports,
dependencies,
}
if (!options.dev) {
userModuleCache.set(filePath, entry)
}
return entry
}
async function getUserModuleResolutionConfig(
options: UserModuleLoaderOptions
): Promise<UserModuleResolutionConfig> {
const cacheKey = `${options.dir}:${options.tsconfigPath || ''}`
if (!options.dev) {
const cached = userModuleResolutionCache.get(cacheKey)
if (cached) {
return cached
}
}
const config = loadRuntimeJsConfig(options.dir, options.tsconfigPath)
if (!options.dev) {
userModuleResolutionCache.set(cacheKey, config)
}
return config
}
function loadRuntimeJsConfig(
dir: string,
tsconfigPath?: string
): UserModuleResolutionConfig {
const tsConfigFileName = tsconfigPath || 'tsconfig.json'
const resolvedTsConfigPath = join(dir, tsConfigFileName)
const resolvedJsConfigPath = join(dir, 'jsconfig.json')
let implicitBaseurl: string | undefined
let compilerOptions: Record<string, unknown> | undefined
if (isFile(resolvedTsConfigPath)) {
compilerOptions = parseJsonConfigFile(resolvedTsConfigPath).compilerOptions
implicitBaseurl = dirname(resolvedTsConfigPath)
} else if (isFile(resolvedJsConfigPath)) {
compilerOptions = parseJsonConfigFile(resolvedJsConfigPath).compilerOptions
implicitBaseurl = dirname(resolvedJsConfigPath)
}
let resolvedBaseUrl: ResolvedBaseUrl
if (typeof compilerOptions?.baseUrl === 'string') {
resolvedBaseUrl = {
baseUrl: resolve(dir, compilerOptions.baseUrl),
isImplicit: false,
}
} else if (implicitBaseurl) {
resolvedBaseUrl = {
baseUrl: implicitBaseurl,
isImplicit: true,
}
}
return {
paths:
(compilerOptions?.paths as Record<string, string[]>) ??
Object.create(null),
resolvedBaseUrl,
}
}
function parseJsonConfigFile(filePath: string): {
compilerOptions?: Record<string, unknown>
} {
const JSON5 =
require('next/dist/compiled/json5') as typeof import('next/dist/compiled/json5')
const contents = readFileSync(filePath, 'utf8')
if (contents.trim() === '') {
return {}
}
return JSON5.parse(contents) as { compilerOptions?: Record<string, unknown> }
}
function resolveUserModuleRequest(
fromFilename: string,
request: string,
resolutionConfig: UserModuleResolutionConfig
): string | null {
if (request.startsWith('.')) {
return resolveAbsoluteUserModulePath(
resolve(dirname(fromFilename), request)
)
}
if (isAbsolute(request)) {
return resolveAbsoluteUserModulePath(request)
}
const aliasResolvedPath = resolveJsConfigModulePath(request, resolutionConfig)
if (aliasResolvedPath) {
return aliasResolvedPath
}
return null
}
function resolveJsConfigModulePath(
request: string,
resolutionConfig: UserModuleResolutionConfig
): string | null {
const { paths, resolvedBaseUrl } = resolutionConfig
if (!resolvedBaseUrl || pathIsRelative(request) || isAbsolute(request)) {
return null
}
const pathKeys = Object.keys(paths)
if (pathKeys.length > 0) {
const matchedPattern = matchPatternOrExact(pathKeys, request)
if (matchedPattern) {
const matchedStar = isString(matchedPattern)
? undefined
: matchedText(matchedPattern, request)
const matchedPatternText = isString(matchedPattern)
? matchedPattern
: patternText(matchedPattern)
for (const substitution of paths[matchedPatternText] || []) {
const candidatePath = matchedStar
? substitution.replace('*', matchedStar)
: substitution
if (candidatePath.endsWith('.d.ts')) {
continue
}
const resolvedPath = resolveAbsoluteUserModulePath(
resolve(resolvedBaseUrl.baseUrl, candidatePath)
)
if (resolvedPath) {
return resolvedPath
}
}
}
}
if (resolvedBaseUrl.isImplicit) {
return null
}
return resolveAbsoluteUserModulePath(
resolve(resolvedBaseUrl.baseUrl, request)
)
}
function resolveAbsoluteUserModulePath(basePath: string): string | null {
if (isFile(basePath)) {
return basePath
}
for (const extension of USER_MODULE_EXTENSIONS) {
if (isFile(basePath + extension)) {
return basePath + extension
}
}
for (const extension of USER_MODULE_EXTENSIONS) {
const indexPath = join(basePath, `index${extension}`)
if (isFile(indexPath)) {
return indexPath
}
}
return null
}
function shouldEnableJsxTransform(filename: string): boolean {
const extension = extname(filename)
return extension === '.jsx' || extension === '.tsx'
}
function shouldUseTypeScriptParser(filename: string): boolean {
const extension = extname(filename)
return (
extension === '.ts' ||
extension === '.tsx' ||
extension === '.cts' ||
extension === '.mts'
)
}
function transformModule(code: string, filename: string): string {
// eslint-disable-next-line no-eval -- We need runtime `require` here so the Node-only SWC loader isn't statically bundled into edge-facing codepaths.
const dynamicRequire = eval('require') as NodeJS.Require
const { transformSync } = dynamicRequire(
'next/dist/build/swc'
) as typeof import('../build/swc')
const parser = shouldUseTypeScriptParser(filename)
? {
syntax: 'typescript' as const,
tsx: shouldEnableJsxTransform(filename),
}
: {
syntax: 'ecmascript' as const,
jsx: shouldEnableJsxTransform(filename),
}
return transformSync(code, {
filename,
jsc: {
parser,
transform: shouldEnableJsxTransform(filename)
? {
react: {
runtime: 'automatic',
},
}
: undefined,
},
module: {
type: 'commonjs',
},
isModule: 'unknown',
env: {
targets: {
node: process.versions.node ?? '20.19.0',
},
},
}).code
}
function isFile(filePath: string): boolean {
try {
return statSync(filePath).isFile()
} catch {
return false
}
}
......@@ -11,6 +11,10 @@ import {
} from 'react'
import { useLayoutEffect } from 'react'
import { dispatcher } from 'next/dist/compiled/next-devtools'
import {
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_OMIT,
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP,
} from '../../../lib/constants'
import { notFound } from '../../../client/components/not-found'
export type SegmentBoundaryType =
......@@ -29,13 +33,17 @@ export type SegmentNodeState = {
setBoundaryType: (type: SegmentBoundaryType | null) => void
}
type MarkdownInternalBehaviorProps = {
__nextMarkdownBehavior?: 'omit' | 'passthrough'
}
function SegmentTrieNode({
type,
pagePath,
}: {
type: string
pagePath: string
}): React.ReactNode {
} & MarkdownInternalBehaviorProps): React.ReactNode {
const { boundaryType, setBoundaryType } = useSegmentState()
const nodeState: SegmentNodeState = useMemo(() => {
return {
......@@ -72,7 +80,9 @@ function LoadingSegmentNode(): React.ReactNode {
return null
}
export function SegmentViewStateNode({ page }: { page: string }) {
export function SegmentViewStateNode({
page,
}: { page: string } & MarkdownInternalBehaviorProps) {
useLayoutEffect(() => {
dispatcher.segmentExplorerUpdateRouteState(page)
return () => {
......@@ -82,7 +92,9 @@ export function SegmentViewStateNode({ page }: { page: string }) {
return null
}
export function SegmentBoundaryTriggerNode() {
export function SegmentBoundaryTriggerNode(
_props: MarkdownInternalBehaviorProps
) {
const { boundaryType } = useSegmentState()
let segmentNode: React.ReactNode = null
if (boundaryType === 'loading') {
......@@ -103,9 +115,17 @@ export function SegmentViewNode({
type: string
pagePath: string
children?: ReactNode
}): React.ReactNode {
} & MarkdownInternalBehaviorProps): React.ReactNode {
const segmentNode = (
<SegmentTrieNode key={type} type={type} pagePath={pagePath} />
<SegmentTrieNode
key={type}
type={type}
pagePath={pagePath}
{...{
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_OMIT,
}}
/>
)
return (
......@@ -124,7 +144,9 @@ const SegmentStateContext = createContext<{
setBoundaryType: () => {},
})
export function SegmentStateProvider({ children }: { children: ReactNode }) {
export function SegmentStateProvider({
children,
}: { children: ReactNode } & MarkdownInternalBehaviorProps) {
const [boundaryType, setBoundaryType] = useState<SegmentBoundaryType | null>(
null
)
......
......@@ -35,6 +35,10 @@ import type {
UseCachePageProps,
} from '../use-cache/use-cache-wrapper'
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
import {
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP,
} from '../../lib/constants'
import {
BOUNDARY_PREFIX,
BOUNDARY_SUFFIX,
......@@ -447,7 +451,7 @@ async function createComponentTreeInternal(
// Resolve the segment param
const isSegmentViewEnabled =
!!process.env.__NEXT_DEV_SERVER && !ctx.markdownSegmentByComponent
!!process.env.__NEXT_DEV_SERVER && !ctx.markdownSegmentRegistry
const dir =
(process.env.NEXT_RUNTIME === 'edge'
? process.env.__NEXT_EDGE_PROJECT_DIR
......@@ -596,6 +600,8 @@ async function createComponentTreeInternal(
? createElement(
SegmentViewNode,
{
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
type: 'error',
pagePath: errorFilePath,
},
......@@ -613,21 +619,29 @@ async function createComponentTreeInternal(
null,
notFoundFilePath &&
createElement(SegmentViewNode, {
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
type: `${BOUNDARY_PREFIX}not-found`,
pagePath: notFoundFilePath + fileNameSuffix,
}),
loadingFilePath &&
createElement(SegmentViewNode, {
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
type: `${BOUNDARY_PREFIX}loading`,
pagePath: loadingFilePath + fileNameSuffix,
}),
errorFilePath &&
createElement(SegmentViewNode, {
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
type: `${BOUNDARY_PREFIX}error`,
pagePath: errorFilePath + fileNameSuffix,
}),
globalErrorFilePath &&
createElement(SegmentViewNode, {
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
type: `${BOUNDARY_PREFIX}global-error`,
pagePath: isNextjsBuiltinFilePath(globalErrorFilePath)
? `${BUILTIN_PREFIX}global-error.js${fileNameSuffix}`
......@@ -648,6 +662,8 @@ async function createComponentTreeInternal(
? createElement(
SegmentViewNode,
{
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
type: 'template',
pagePath: templateFilePath,
},
......@@ -670,7 +686,7 @@ async function createComponentTreeInternal(
)
// Convert the parallel route map into an object after all promises have been resolved.
const isMarkdownRender = !!ctx.markdownSegmentByComponent
const isMarkdownRender = !!ctx.markdownSegmentRegistry
let parallelRouteProps: { [key: string]: React.ReactNode } = {}
let parallelRouteCacheNodeSeedData: {
[key: string]: CacheNodeSeedData | null
......@@ -693,6 +709,8 @@ async function createComponentTreeInternal(
loadingElement = createElement(
SegmentViewNode,
{
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
key: cacheNodeKey + '-loading',
type: 'loading',
pagePath: loadingFilePath,
......@@ -859,9 +877,9 @@ async function createComponentTreeInternal(
}
}
if (ctx.markdownSegmentByComponent) {
if (ctx.markdownSegmentRegistry) {
pageElement = markReactNode(pageElement, {
segmentByComponent: ctx.markdownSegmentByComponent,
segmentRegistry: ctx.markdownSegmentRegistry,
})
}
......@@ -875,6 +893,8 @@ async function createComponentTreeInternal(
? createElement(
SegmentViewNode,
{
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
key: cacheNodeKey + '-' + segmentType,
type: segmentType,
pagePath: pageFilePath,
......@@ -1052,9 +1072,9 @@ async function createComponentTreeInternal(
)
}
if (ctx.markdownSegmentByComponent) {
if (ctx.markdownSegmentRegistry) {
serverSegment = markReactNode(serverSegment, {
segmentByComponent: ctx.markdownSegmentByComponent,
segmentRegistry: ctx.markdownSegmentRegistry,
})
}
......@@ -1105,6 +1125,8 @@ async function createComponentTreeInternal(
? createElement(
SegmentViewNode,
{
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
key: 'layout',
type: 'layout',
pagePath: layoutFilePath,
......@@ -1238,7 +1260,7 @@ async function createBoundaryConventionElement({
componentMod: { createElement, Fragment },
} = ctx
const isSegmentViewEnabled =
!!process.env.__NEXT_DEV_SERVER && !ctx.markdownSegmentByComponent
!!process.env.__NEXT_DEV_SERVER && !ctx.markdownSegmentRegistry
const dir =
(process.env.NEXT_RUNTIME === 'edge'
? process.env.__NEXT_EDGE_PROJECT_DIR
......@@ -1255,6 +1277,8 @@ async function createBoundaryConventionElement({
? createElement(
SegmentViewNode,
{
[MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PROP]:
MARKDOWN_INTERNAL_COMPONENT_BEHAVIOR_PASSTHROUGH,
key: cacheNodeKey + '-' + conventionName,
type: conventionName,
// TODO: Discovered when moving to `createElement`.
......
......@@ -89,6 +89,7 @@ export type ServerOnInstrumentationRequestError = (
export interface RenderOptsPartial {
dir?: string
tsconfigPath?: string
previewProps: __ApiPreviewProps | undefined
err?: Error | null
basePath: string
......
This diff is collapsed.
......@@ -6,16 +6,6 @@ export type MarkdownRouteConfig<TRender = (...args: any[]) => unknown> = {
render?: TRender
}
export function loadMarkdownRootComponents(): MarkdownComponents {
if (process.env.NEXT_RUNTIME === 'edge') {
return {}
}
return (
require('../../lib/require-markdown-components') as typeof import('../../lib/require-markdown-components')
).requireMarkdownComponents()
}
export function getMarkdownRouteConfig<
TRender = (...args: any[]) => unknown,
>(routeModule: {
......
import { MARKDOWN_CONTENT_TYPE_HEADER } from '../../lib/constants'
import type { NegotiatedDocumentRepresentation } from '../document-representation'
import { acceptsMarkdown, appendAcceptVaryHeader } from './accepts-markdown'
export const markdownDocumentRepresentation: NegotiatedDocumentRepresentation =
{
id: 'markdown',
contentType: MARKDOWN_CONTENT_TYPE_HEADER,
outputSuffix: '.markdown',
accepts: acceptsMarkdown,
appendVary: appendAcceptVaryHeader,
}
import type { MarkdownComponents } from './runtime'
export async function loadMarkdownRootComponents(
dir: string,
tsconfigPath?: string
): Promise<MarkdownComponents> {
return await (
require('../../lib/require-markdown-components') as typeof import('../../lib/require-markdown-components')
).requireMarkdownComponents({
dir,
tsconfigPath,
dev: Boolean(process.env.__NEXT_DEV_SERVER),
})
}
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment