Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions packages/rari/src/router/build/evaluate-static-params.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { spawn } from 'node:child_process'
import process from 'node:process'
import { pathToFileURL } from 'node:url'

const GENERATE_STATIC_PARAMS_TIMEOUT_MS = 60_000
const FORCE_KILL_GRACE_MS = 1_000

export async function evaluateGenerateStaticParams(compiledPath: string): Promise<unknown> {
const href = pathToFileURL(compiledPath).href
const script = `
import { registerHooks } from "node:module";
registerHooks({
resolve(specifier, context, nextResolve) {
if (specifier === "react-server-dom-rari/server") {
return nextResolve("rari/runtime/rsc-references", context);
}
return nextResolve(specifier, context);
},
});
const mod = await import(${JSON.stringify(href)});
const result =
typeof mod.generateStaticParams !== "function"
? null
: ((await mod.generateStaticParams()) ?? null);
process.send(result, () => {
process.disconnect();
});
`

return new Promise((resolve, reject) => {
Comment thread
sentry[bot] marked this conversation as resolved.
const child = spawn(
process.execPath,
['--conditions=react-server', '--input-type=module', '--eval', script],
{
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
env: process.env,
},
)

let stdout = ''
let stderr = ''
let settled = false
let ipcReceived = false
let ipcValue: unknown
let timeoutId: ReturnType<typeof setTimeout> | undefined
let forceKillId: ReturnType<typeof setTimeout> | undefined

const clearTimers = () => {
if (timeoutId !== undefined) clearTimeout(timeoutId)
if (forceKillId !== undefined) clearTimeout(forceKillId)
timeoutId = undefined
forceKillId = undefined
}

timeoutId = setTimeout(() => {
if (settled) return
settled = true
if (timeoutId !== undefined) clearTimeout(timeoutId)
timeoutId = undefined
child.kill('SIGTERM')
forceKillId = setTimeout(() => {
child.kill('SIGKILL')
}, FORCE_KILL_GRACE_MS)
reject(
new Error(
`generateStaticParams timed out after ${GENERATE_STATIC_PARAMS_TIMEOUT_MS}ms for ${compiledPath}`,
),
)
}, GENERATE_STATIC_PARAMS_TIMEOUT_MS)

child.stdout?.setEncoding('utf8')
child.stderr?.setEncoding('utf8')
child.stdout?.on('data', (chunk: string) => {
stdout += chunk
})
child.stderr?.on('data', (chunk: string) => {
stderr += chunk
})
child.on('message', (value: unknown) => {
ipcReceived = true
ipcValue = value
})
child.on('error', error => {
if (settled) return
settled = true
clearTimers()
reject(error)
})
child.on('close', code => {
clearTimers()
if (settled) return
settled = true

const diagnostics = [stderr.trim(), stdout.trim()].filter(Boolean).join('\n')

if (code !== 0) {
reject(new Error(diagnostics || `generateStaticParams worker exited with code ${code}`))
return
}
if (!ipcReceived) {
reject(
new Error(
diagnostics ||
`generateStaticParams worker exited without an IPC result for ${compiledPath}`,
),
)
return
}
resolve(ipcValue)
})
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
13 changes: 5 additions & 8 deletions packages/rari/src/router/build/props-extractor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isRecord, isStaticParamsArray, warnInvalidStaticParams } from '@/shared/utils/type-guards'
import { evaluateGenerateStaticParams } from './evaluate-static-params'

export interface ServerSidePropsResult {
props: Record<string, any>
Expand Down Expand Up @@ -320,14 +321,10 @@ export function mergeMetadata(
/* v8 ignore start - requires dynamic imports, better tested in integration/e2e */
export async function extractStaticParams(componentPath: string): Promise<StaticParamsResult> {
try {
const module = await loadComponentModule(componentPath)

if (typeof module.generateStaticParams === 'function') {
const params = await module.generateStaticParams()
if (isStaticParamsArray(params)) return params
warnInvalidStaticParams(componentPath)
}

const params = await evaluateGenerateStaticParams(componentPath)
if (params == null) return []
if (isStaticParamsArray(params)) return params
warnInvalidStaticParams(componentPath)
return []
} catch (error) {
console.error(`[rari] Router: Failed to extract static params from ${componentPath}:`, error)
Expand Down
74 changes: 46 additions & 28 deletions packages/rari/src/router/build/vite-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
warnInvalidStaticParams,
} from '@/shared/utils/type-guards'
import { toRariPlugin } from '@/vite/plugin/types'
import { evaluateGenerateStaticParams } from './evaluate-static-params'
import { generateAppRouteManifest } from './routes'

const METADATA_EXPORT_REGEX = /export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/
Expand Down Expand Up @@ -478,40 +479,57 @@ export function rariRouter(options: RariRouterPluginOptions = {}): RariPlugin {
if (!manifestRecord || !isAppRouteManifest(manifestRecord)) return

const manifest = manifestRecord
let updated = false

for (const route of manifest.routes) {
if (!route.isDynamic) continue

const dynamicRoutes = manifest.routes.flatMap(route => {
if (!route.isDynamic) return []
const componentId = route.componentId
if (componentId == null || componentId === '') continue

const compiledPath = path.join(serverDir, `${componentId}.js`)

try {
const module: unknown = await import(/* @vite-ignore */ compiledPath)
if (isRecord(module) && typeof module.generateStaticParams === 'function') {
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- dynamically imported route module
const generateStaticParams = module.generateStaticParams as () => unknown
const params = await generateStaticParams()
if (isStaticParamsArray(params)) {
if (params.length > 0) {
route.staticParams = params
updated = true
if (componentId == null || componentId === '') return []
return [{ route, componentId }]
})

const concurrency = Math.min(8, Math.max(1, dynamicRoutes.length))
const results = dynamicRoutes.map(() => false)
let index = 0
let active = 0

await new Promise<void>(resolveAll => {
const next = () => {
while (active < concurrency && index < dynamicRoutes.length) {
const taskIndex = index++
const { route, componentId } = dynamicRoutes[taskIndex]
const compiledPath = path.join(serverDir, `${componentId}.js`)

active++
void (async () => {
try {
const params = await evaluateGenerateStaticParams(compiledPath)
if (params == null) return
if (isStaticParamsArray(params)) {
route.staticParams = params
results[taskIndex] = true
} else {
warnInvalidStaticParams(componentId)
}
} catch (error) {
console.warn(
`[rari] Failed to evaluate generateStaticParams for ${componentId}:`,
error,
)
} finally {
active--
if (index >= dynamicRoutes.length && active === 0) resolveAll()
else next()
}
} else {
warnInvalidStaticParams(componentId)
}
})()
}
} catch (error) {
console.warn(
`[rari] Failed to evaluate generateStaticParams for ${componentId}:`,
error,
)

if (dynamicRoutes.length === 0) resolveAll()
}
}

if (updated) await fs.writeFile(routesPath, JSON.stringify(manifest), 'utf-8')
next()
})

if (results.some(Boolean)) await fs.writeFile(routesPath, JSON.stringify(manifest), 'utf-8')
} catch (error) {
console.warn('[rari] Failed to enrich routes manifest with static params:', error)
}
Expand Down
Loading