Unverified Commit d5276f04 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Make TurbopackResult payloads disjoint (#98575)

### What?

Refactors the JavaScript-facing `TurbopackResult<T>` into a stable
wrapper whose payload lives under `value` and whose issues remain
top-level. Native API consumers, entrypoint conversion,
development-server paths, HMR handling, and direct API tests now follow
the disjoint shape.

Two event subscriptions that had inaccurate wrapper declarations now
expose their existing plain runtime payloads explicitly: update-info
events remain `UpdateMessage`, and compilation events remain
`CompilationEvent`. Nullable native entrypoint payloads are also
declared accurately and normalized at the JavaScript API boundary.

### Why?

The previous intersection-based representation merged payload fields
with result metadata. That allowed fields such as `issues` to overwrite
one another and caused non-object payloads to be discarded, making the
result shape depend on `T`. A dedicated payload property avoids those
collisions and preserves every payload type, including `null`.

Keeping plain event streams distinct from result wrappers also ensures
`TurbopackResult<T>` consistently means the native API actually provides
wrapper metadata.

### How?

The N-API serializer now always creates a fresh wrapper rather than
mutating an object payload. The shared TypeScript type models that
wrapper directly and requires an explicit payload type. Conversion
layers replace only the nested payload while explicitly preserving
wrapper issues. Call sites continue to process wrapper issues while
reading domain data through `value`.

The update-info and compilation-event declarations were aligned with
their native callback types instead of introducing new runtime wrappers
for streams that do not collect issues. Rust `Option<NapiEntrypoints>`
payloads are declared as nullable, then normalized to the existing
empty-entrypoints representation after a null-safe route check.

### Verification

- `pnpm build-all`
- `pnpm --filter=next types`
- `pnpm swc-build-native`
- `cargo check -p next-napi-bindings`
- `cargo fmt --all -- --check`
- ESLint and Prettier on changed files
- `pnpm test-dev-experimental-turbo
test/development/app-aspath/app-aspath.test.ts`
- `pnpm test-dev-turbo test/development/basic/next-rs-api.test.ts` — 26
passed, 1 skipped, 15 snapshots; Jest reported lingering open handles
after the green summary
- `pnpm test-dev-turbo
test/development/app-dir/concurrent-install/concurrent-install.test.ts`
- `pnpm test-dev-experimental-turbo
test/development/app-dir/concurrent-install/concurrent-install.test.ts`

<!-- NEXT_JS_LLM -->

<!-- fleet 74688340-f99a-462e-8f75-88d12c88000a -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent d4c9abe0
......@@ -191,10 +191,8 @@ pub fn endpoint_server_changed_subscribe(
env: Env,
#[napi(ts_arg_type = "{ __napiType: \"Endpoint\" }")] endpoint: &External<ExternalEndpoint>,
issues: bool,
#[napi(ts_arg_type = "(err: Error, value: TurbopackResult) => void")] func: FunctionRef<
TurbopackResult<()>,
(),
>,
#[napi(ts_arg_type = "(err: Error, value: TurbopackResult<undefined>) => void")]
func: FunctionRef<TurbopackResult<()>, ()>,
) -> napi::Result<External<SubscriptionTask>> {
let turbopack_ctx = endpoint.turbopack_ctx().clone();
let endpoint = ****endpoint;
......@@ -278,10 +276,8 @@ async fn subscribe_issues_and_diags_operation(
pub fn endpoint_client_changed_subscribe(
env: Env,
#[napi(ts_arg_type = "{ __napiType: \"Endpoint\" }")] endpoint: &External<ExternalEndpoint>,
#[napi(ts_arg_type = "(err: Error, value: TurbopackResult) => void")] func: FunctionRef<
TurbopackResult<()>,
(),
>,
#[napi(ts_arg_type = "(err: Error, value: TurbopackResult<undefined>) => void")]
func: FunctionRef<TurbopackResult<()>, ()>,
) -> napi::Result<External<SubscriptionTask>> {
let turbopack_ctx = endpoint.turbopack_ctx().clone();
let endpoint_op = ****endpoint;
......
......@@ -1342,7 +1342,7 @@ async fn app_route_filter_for_write_phase(
}
#[tracing::instrument(level = "info", name = "write all entrypoints to disk", skip_all)]
#[napi(ts_return_type = "Promise<TurbopackResult<Partial<NapiEntrypoints>>>")]
#[napi(ts_return_type = "Promise<TurbopackResult<Partial<NapiEntrypoints> | null>>")]
pub async fn project_write_all_entrypoints_to_disk(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
app_dir_only: bool,
......@@ -1729,7 +1729,7 @@ async fn output_assets_operation(
}
#[tracing::instrument(level = "info", name = "get entrypoints", skip_all)]
#[napi(ts_return_type = "Promise<TurbopackResult<Partial<NapiEntrypoints>>>")]
#[napi(ts_return_type = "Promise<TurbopackResult<Partial<NapiEntrypoints> | null>>")]
pub async fn project_entrypoints(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
) -> napi::Result<TurbopackResult<Option<NapiEntrypoints>>> {
......@@ -1770,7 +1770,10 @@ pub async fn project_entrypoints(
pub fn project_entrypoints_subscribe(
env: Env,
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
#[napi(ts_arg_type = "(err: Error, value: TurbopackResult<Partial<NapiEntrypoints>>) => void")]
#[napi(
ts_arg_type = "(err: Error, value: TurbopackResult<Partial<NapiEntrypoints> | null>) => \
void"
)]
func: FunctionRef<TurbopackResult<Option<NapiEntrypoints>>, ()>,
) -> napi::Result<External<SubscriptionTask>> {
let turbopack_ctx = project.turbopack_ctx.clone();
......@@ -2245,8 +2248,10 @@ pub fn project_update_info_subscribe(
env: Env,
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
aggregation_ms: u32,
#[napi(ts_arg_type = "(err: Error, value: TurbopackResult<UpdateMessage>) => void")]
func: FunctionRef<NapiUpdateMessage, ()>,
#[napi(ts_arg_type = "(err: Error, value: UpdateMessage) => void")] func: FunctionRef<
NapiUpdateMessage,
(),
>,
) -> napi::Result<()> {
let func: ThreadsafeFunction<UpdateMessage, (), NapiUpdateMessage, Status, true> = func
.borrow_back(&env)?
......@@ -2322,8 +2327,10 @@ impl From<Arc<dyn CompilationEvent>> for NapiCompilationEvent {
pub fn project_compilation_events_subscribe(
env: Env,
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
#[napi(ts_arg_type = "(err: Error, value: TurbopackResult<CompilationEvent>) => void")]
func: FunctionRef<NapiCompilationEvent, ()>,
#[napi(ts_arg_type = "(err: Error, value: CompilationEvent) => void")] func: FunctionRef<
NapiCompilationEvent,
(),
>,
event_types: Option<Vec<String>>,
) -> napi::Result<()> {
let tsfn: ThreadsafeFunction<
......
......@@ -419,15 +419,9 @@ impl<T: ToNapiValue> ToNapiValue for TurbopackResult<T> {
) -> napi::Result<napi::sys::napi_value> {
let result_raw = unsafe { T::to_napi_value(env, val.result)? };
let result = unsafe { Unknown::from_raw_unchecked(env, result_raw) };
let mut obj = Object::new(&Env::from_raw(env))?;
// When the result is an object, extend it in place with the `issues`
// property. Otherwise, produce a fresh object holding only `issues`.
let mut obj = if matches!(result.get_type()?, napi::ValueType::Object) {
Object::from_raw(env, result_raw)
} else {
Object::new(&Env::from_raw(env))?
};
obj.set_named_property("value", result)?;
obj.set_named_property("issues", val.issues)?;
Ok(obj.raw())
......
......@@ -16,8 +16,8 @@ export function formatWarningsHeader(count: number): string {
* @throws {Error} If a fatal issue is encountered, this function throws an error. In development mode, we only throw on
* 'fatal' and 'bug' issues. In production mode, we also throw on 'error' issues.
*/
export function printBuildErrors(
entrypoints: TurbopackResult,
export function printBuildErrors<T>(
entrypoints: TurbopackResult<T>,
isDev: boolean,
opts?: { deferWarnings?: boolean }
): { warnings: string[] } {
......
......@@ -79,13 +79,13 @@ export declare function codeFrameColumns(
export declare function endpointClientChangedSubscribe(
endpoint: { __napiType: 'Endpoint' },
func: (err: Error, value: TurbopackResult) => void
func: (err: Error, value: TurbopackResult<undefined>) => void
): { __napiType: 'RootTask' }
export declare function endpointServerChangedSubscribe(
endpoint: { __napiType: 'Endpoint' },
issues: boolean,
func: (err: Error, value: TurbopackResult) => void
func: (err: Error, value: TurbopackResult<undefined>) => void
): { __napiType: 'RootTask' }
export declare function endpointWriteToDisk(endpoint: {
......@@ -586,17 +586,20 @@ export declare function projectClientHmrEvents(
/** Subscribes to all compilation events that are not cached like timing and progress information. */
export declare function projectCompilationEventsSubscribe(
project: { __napiType: 'Project' },
func: (err: Error, value: TurbopackResult<CompilationEvent>) => void,
func: (err: Error, value: CompilationEvent) => void,
eventTypes?: Array<string> | undefined | null
): void
export declare function projectEntrypoints(project: {
__napiType: 'Project'
}): Promise<TurbopackResult<Partial<NapiEntrypoints>>>
}): Promise<TurbopackResult<Partial<NapiEntrypoints> | null>>
export declare function projectEntrypointsSubscribe(
project: { __napiType: 'Project' },
func: (err: Error, value: TurbopackResult<Partial<NapiEntrypoints>>) => void
func: (
err: Error,
value: TurbopackResult<Partial<NapiEntrypoints> | null>
) => void
): { __napiType: 'RootTask' }
/**
......@@ -698,13 +701,13 @@ export declare function projectUpdate(
export declare function projectUpdateInfoSubscribe(
project: { __napiType: 'Project' },
aggregationMs: number,
func: (err: Error, value: TurbopackResult<UpdateMessage>) => void
func: (err: Error, value: UpdateMessage) => void
): void
export declare function projectWriteAllEntrypointsToDisk(
project: { __napiType: 'Project' },
appDirOnly: boolean
): Promise<TurbopackResult<Partial<NapiEntrypoints>>>
): Promise<TurbopackResult<Partial<NapiEntrypoints> | null>>
export declare function projectWriteAnalyzeData(
project: { __napiType: 'Project' },
......
......@@ -723,14 +723,15 @@ function bindingToApi(
const napiEndpoints = (await binding.projectWriteAllEntrypointsToDisk(
this._nativeProject,
appDirOnly
)) as TurbopackResult<Partial<NapiEntrypoints>>
)) as TurbopackResult<Partial<NapiEntrypoints> | null>
if ('routes' in napiEndpoints) {
if (napiEndpoints.value && 'routes' in napiEndpoints.value) {
return napiEntrypointsToRawEntrypoints(
napiEndpoints as TurbopackResult<NapiEntrypoints>
)
} else {
return {
value: {},
issues: napiEndpoints.issues,
}
}
......@@ -743,19 +744,20 @@ function bindingToApi(
}
entrypointsSubscribe() {
const subscription = subscribe<TurbopackResult<NapiEntrypoints | {}>>(
false,
async (callback) =>
binding.projectEntrypointsSubscribe(this._nativeProject, callback)
const subscription = subscribe<
TurbopackResult<NapiEntrypoints | {} | null>
>(false, async (callback) =>
binding.projectEntrypointsSubscribe(this._nativeProject, callback)
)
return (async function* () {
for await (const entrypoints of subscription) {
if ('routes' in (entrypoints as TurbopackResult<NapiEntrypoints>)) {
if (entrypoints.value && 'routes' in entrypoints.value) {
yield napiEntrypointsToRawEntrypoints(
entrypoints as TurbopackResult<NapiEntrypoints>
)
} else {
yield {
value: {},
issues: entrypoints.issues,
} as TurbopackResult<{}>
}
......@@ -819,7 +821,7 @@ function bindingToApi(
}
updateInfoSubscribe(aggregationMs: number) {
return subscribe<TurbopackResult<UpdateMessage>>(true, async (callback) =>
return subscribe<UpdateMessage>(true, async (callback) =>
binding.projectUpdateInfoSubscribe(
this._nativeProject,
aggregationMs,
......@@ -829,16 +831,13 @@ function bindingToApi(
}
compilationEventsSubscribe(eventTypes?: string[]) {
return subscribe<TurbopackResult<CompilationEvent>>(
true,
async (callback) => {
binding.projectCompilationEventsSubscribe(
this._nativeProject,
callback,
eventTypes
)
}
)
return subscribe<CompilationEvent>(true, async (callback) => {
binding.projectCompilationEventsSubscribe(
this._nativeProject,
callback,
eventTypes
)
})
}
invalidateFileSystemCache(): Promise<void> {
......@@ -867,8 +866,10 @@ function bindingToApi(
)) as TurbopackResult<WrittenEndpoint>
}
async clientChanged(): Promise<AsyncIterableIterator<TurbopackResult>> {
const clientSubscription = subscribe<TurbopackResult>(
async clientChanged(): Promise<
AsyncIterableIterator<TurbopackResult<void>>
> {
const clientSubscription = subscribe<TurbopackResult<void>>(
false,
async (callback) =>
binding.endpointClientChangedSubscribe(this._nativeEndpoint, callback)
......@@ -879,8 +880,8 @@ function bindingToApi(
async serverChanged(
includeIssues: boolean
): Promise<AsyncIterableIterator<TurbopackResult>> {
const serverSubscription = subscribe<TurbopackResult>(
): Promise<AsyncIterableIterator<TurbopackResult<void>>> {
const serverSubscription = subscribe<TurbopackResult<void>>(
false,
async (callback) =>
binding.endpointServerChangedSubscribe(
......@@ -1186,7 +1187,7 @@ function bindingToApi(
entrypoints: TurbopackResult<NapiEntrypoints>
): TurbopackResult<RawEntrypoints> {
const routes = new Map()
for (const { pathname, ...nativeRoute } of entrypoints.routes) {
for (const { pathname, ...nativeRoute } of entrypoints.value.routes) {
let route: Route
const routeType = nativeRoute.type
switch (routeType) {
......@@ -1240,8 +1241,8 @@ function bindingToApi(
endpoint: new EndpointImpl(middleware.endpoint),
isProxy: middleware.isProxy,
})
const middleware = entrypoints.middleware
? napiMiddlewareToMiddleware(entrypoints.middleware)
const middleware = entrypoints.value.middleware
? napiMiddlewareToMiddleware(entrypoints.value.middleware)
: undefined
const napiInstrumentationToInstrumentation = (
instrumentation: NapiInstrumentation
......@@ -1249,19 +1250,23 @@ function bindingToApi(
nodeJs: new EndpointImpl(instrumentation.nodeJs),
edge: new EndpointImpl(instrumentation.edge),
})
const instrumentation = entrypoints.instrumentation
? napiInstrumentationToInstrumentation(entrypoints.instrumentation)
const instrumentation = entrypoints.value.instrumentation
? napiInstrumentationToInstrumentation(entrypoints.value.instrumentation)
: undefined
return {
routes,
middleware,
instrumentation,
pagesDocumentEndpoint: new EndpointImpl(
entrypoints.pagesDocumentEndpoint
),
pagesAppEndpoint: new EndpointImpl(entrypoints.pagesAppEndpoint),
pagesErrorEndpoint: new EndpointImpl(entrypoints.pagesErrorEndpoint),
value: {
routes,
middleware,
instrumentation,
pagesDocumentEndpoint: new EndpointImpl(
entrypoints.value.pagesDocumentEndpoint
),
pagesAppEndpoint: new EndpointImpl(entrypoints.value.pagesAppEndpoint),
pagesErrorEndpoint: new EndpointImpl(
entrypoints.value.pagesErrorEndpoint
),
},
issues: entrypoints.issues,
}
}
......
......@@ -177,7 +177,8 @@ export interface BuildFeatureUsage {
invocationCount: number
}
export type TurbopackResult<T = {}> = T & {
export type TurbopackResult<T> = {
value: T
issues: Issue[]
}
......@@ -367,11 +368,11 @@ export interface Project {
updateInfoSubscribe(
aggregationMs: number
): AsyncIterableIterator<TurbopackResult<UpdateMessage>>
): AsyncIterableIterator<UpdateMessage>
compilationEventsSubscribe(
eventTypes?: string[]
): AsyncIterableIterator<TurbopackResult<CompilationEvent>>
): AsyncIterableIterator<CompilationEvent>
invalidateFileSystemCache(): Promise<void>
......@@ -417,7 +418,7 @@ export interface Endpoint {
* After clientChanged() has been awaited it will listen to changes.
* The async iterator will yield for each change.
*/
clientChanged(): Promise<AsyncIterableIterator<TurbopackResult>>
clientChanged(): Promise<AsyncIterableIterator<TurbopackResult<void>>>
/**
* Listen to server-side changes to the endpoint.
......@@ -426,7 +427,7 @@ export interface Endpoint {
*/
serverChanged(
includeIssues: boolean
): Promise<AsyncIterableIterator<TurbopackResult>>
): Promise<AsyncIterableIterator<TurbopackResult<void>>>
}
interface EndpointConfig {
......
......@@ -18,11 +18,7 @@ import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compi
import { getSupportedBrowsers } from '../get-supported-browsers'
import { printBuildErrors } from '../print-build-errors'
import { normalizePath } from '../../lib/normalize-path'
import type {
ProjectOptions,
RawEntrypoints,
TurbopackResult,
} from '../swc/types'
import type { ProjectOptions, RawEntrypoints } from '../swc/types'
import { Bundler } from '../../lib/bundler'
export async function turbopackBuild(telemetry: Telemetry): Promise<{
......@@ -200,7 +196,7 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{
}
}
const routes = entrypoints.routes
const routes = entrypoints.value.routes
if (!routes) {
// This should never ever happen, there should be an error issue, or the bindings call should
// have thrown.
......@@ -227,7 +223,7 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{
})
const currentEntrypoints = await rawEntrypointsToEntrypoints(
entrypoints as TurbopackResult<RawEntrypoints>
entrypoints.value as RawEntrypoints
)
const promises: Promise<void>[] = []
......@@ -270,12 +266,12 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{
manifestLoader.loadFontManifest('_error'),
]
: []),
entrypoints.instrumentation &&
entrypoints.value.instrumentation &&
manifestLoader.loadMiddlewareManifest(
'instrumentation',
'instrumentation'
),
entrypoints.middleware &&
entrypoints.value.middleware &&
(await manifestLoader.loadMiddlewareManifest(
'middleware',
'middleware'
......
......@@ -264,7 +264,7 @@ function setupServerHmr(
// `issues` is intentionally dropped: this pull scans project-wide chunk
// lists, so its issues may belong to an unrelated or removed route, and
// endpoint writes already report route-scoped issues.
const update = await project.getServerHmrUpdate(
const { value: update } = await project.getServerHmrUpdate(
versions.get(versionKey),
entryPaths
)
......@@ -1000,7 +1000,7 @@ export async function createHotReloaderTurbopack(
includeIssues: boolean,
endpoint: Endpoint,
createMessage: (
change: TurbopackResult,
change: TurbopackResult<void>,
hash: string
) => Promise<HmrMessageSentToBrowser> | HmrMessageSentToBrowser | void,
onError?: (
......@@ -1068,15 +1068,15 @@ export async function createHotReloaderTurbopack(
// emission can be a real update. Ignore only the usual issues-only result.
try {
const initial = await subscription.next()
if (!initial.done && initial.value.type !== 'issues') {
if (!initial.done && initial.value.value.type !== 'issues') {
processIssues(state.clientIssues, key, initial.value, false, true)
sendTurbopackMessage(initial.value as TurbopackUpdate)
sendTurbopackMessage(initial.value.value)
}
for await (const data of subscription) {
processIssues(state.clientIssues, key, data, false, true)
if (data.type !== 'issues') {
sendTurbopackMessage(data as TurbopackUpdate)
if (data.value.type !== 'issues') {
sendTurbopackMessage(data.value)
}
}
} catch (e) {
......@@ -1120,7 +1120,7 @@ export async function createHotReloaderTurbopack(
processTopLevelIssues(currentTopLevelIssues, entrypoints)
// Certain crtical issues prevent any entrypoints from being constructed so return early
if (!('routes' in entrypoints)) {
if (!('routes' in entrypoints.value)) {
printBuildErrors(entrypoints, true)
currentEntriesHandlingResolve!()
......@@ -1128,7 +1128,7 @@ export async function createHotReloaderTurbopack(
continue
}
const routes = entrypoints.routes
const routes = entrypoints.value.routes
const prevRouteKeys = previousRouteKeys
const addedRoutes = prevRouteKeys
? [...routes.keys()].filter((route) => !prevRouteKeys.has(route))
......@@ -1161,8 +1161,10 @@ export async function createHotReloaderTurbopack(
hooks: {
handleWrittenEndpoint: (id, result, forceDeleteCache) => {
currentWrittenEntrypoints.set(id, result)
return clearRequireCache(id, result, { force: forceDeleteCache })
currentWrittenEntrypoints.set(id, result.value)
return clearRequireCache(id, result.value, {
force: forceDeleteCache,
})
},
propagateServerField: propagateServerField.bind(null, opts),
sendHmr,
......@@ -1991,9 +1993,9 @@ export async function createHotReloaderTurbopack(
hooks: {
subscribeToChanges: subscribeToClientChanges,
handleWrittenEndpoint: (id, result, forceDeleteCache) => {
currentWrittenEntrypoints.set(id, result)
assetMapper.setPathsForKey(id, result.clientPaths)
return clearRequireCache(id, result, {
currentWrittenEntrypoints.set(id, result.value)
assetMapper.setPathsForKey(id, result.value.clientPaths)
return clearRequireCache(id, result.value, {
force: forceDeleteCache,
})
},
......@@ -2069,13 +2071,16 @@ export async function createHotReloaderTurbopack(
: ((async () => {}) as StartChangeSubscription),
handleServerComponentChanges,
handleWrittenEndpoint: (id, result, forceDeleteCache) => {
currentWrittenEntrypoints.set(id, result)
assetMapper.setPathsForKey(id, result.clientPaths)
shouldPullServerHmr ||= participatesInServerHmr(id, result)
if (result.serverHmrEntryPaths.length > 0) {
serverHmrEntryPaths = result.serverHmrEntryPaths
currentWrittenEntrypoints.set(id, result.value)
assetMapper.setPathsForKey(id, result.value.clientPaths)
shouldPullServerHmr ||= participatesInServerHmr(
id,
result.value
)
if (result.value.serverHmrEntryPaths.length > 0) {
serverHmrEntryPaths = result.value.serverHmrEntryPaths
}
return clearRequireCache(id, result, {
return clearRequireCache(id, result.value, {
force: forceDeleteCache,
})
},
......
......@@ -75,9 +75,9 @@ export function printNonFatalIssue(issue: Issue) {
}
}
export function processTopLevelIssues(
export function processTopLevelIssues<T>(
currentTopLevelIssues: TopLevelIssuesMap,
result: TurbopackResult
result: TurbopackResult<T>
) {
currentTopLevelIssues.clear()
......@@ -91,7 +91,7 @@ export { msToNs } from '../../shared/lib/turbopack/compilation-events'
export type ChangeSubscriptions = Map<
EntryKey,
Promise<AsyncIterableIterator<TurbopackResult>>
Promise<AsyncIterableIterator<TurbopackResult<void>>>
>
export type HandleWrittenEndpoint = (
......@@ -105,7 +105,7 @@ export type StartChangeSubscription = (
includeIssues: boolean,
endpoint: Endpoint,
createMessage: (
change: TurbopackResult,
change: TurbopackResult<void>,
hash: string
) => Promise<HmrMessageSentToBrowser> | HmrMessageSentToBrowser | void,
onError?: (
......@@ -228,7 +228,7 @@ export async function handleRouteType({
documentOrAppChanged
)
const type = writtenEndpoint?.type
const type = writtenEndpoint.value.type
await manifestLoader.loadClientBuildManifest(page)
await manifestLoader.loadBuildManifest(page)
......@@ -324,7 +324,7 @@ export async function handleRouteType({
const writtenEndpoint = await route.endpoint.writeToDisk()
hooks?.handleWrittenEndpoint(key, writtenEndpoint, false)
const type = writtenEndpoint.type
const type = writtenEndpoint.value.type
await manifestLoader.loadPagesManifest(page)
if (type === 'edge') {
......@@ -376,7 +376,7 @@ export async function handleRouteType({
)
}
const type = writtenEndpoint.type
const type = writtenEndpoint.value.type
if (type === 'edge') {
warnAboutEdgeRuntime()
......@@ -434,7 +434,7 @@ export async function handleRouteType({
)
}
const type = writtenEndpoint.type
const type = writtenEndpoint.value.type
manifestLoader.loadAppPathsManifest(page)
if (route.hasActionManifest) {
......@@ -620,16 +620,17 @@ export async function handleEntrypoints({
dev: HandleEntrypointsDevOpts
}) {
currentEntrypoints.global.app = entrypoints.pagesAppEndpoint
currentEntrypoints.global.document = entrypoints.pagesDocumentEndpoint
currentEntrypoints.global.error = entrypoints.pagesErrorEndpoint
const value = entrypoints.value
currentEntrypoints.global.app = value.pagesAppEndpoint
currentEntrypoints.global.document = value.pagesDocumentEndpoint
currentEntrypoints.global.error = value.pagesErrorEndpoint
currentEntrypoints.global.instrumentation = entrypoints.instrumentation
currentEntrypoints.global.instrumentation = value.instrumentation
currentEntrypoints.page.clear()
currentEntrypoints.app.clear()
for (const [pathname, route] of entrypoints.routes) {
for (const [pathname, route] of value.routes) {
switch (route.type) {
case 'page':
case 'page-api':
......@@ -666,7 +667,7 @@ export async function handleEntrypoints({
})
}
const { middleware, instrumentation } = entrypoints
const { middleware, instrumentation } = value
// We check for explicit true/false, since it's initialized to
// undefined during the first loop (middlewareChanges event is
......
......@@ -50,10 +50,10 @@ export function getIssueKey(issue: Issue): IssueKey {
)}-${JSON.stringify(issue.description)}`
}
export function processIssues(
export function processIssues<T>(
currentEntryIssues: EntryIssuesMap,
key: EntryKey,
result: TurbopackResult,
result: TurbopackResult<T>,
throwIssue: boolean,
logErrors: boolean
) {
......
......@@ -206,7 +206,7 @@ async function main() {
});
const entrypointsSubscription = project.entrypointsSubscribe();
const entrypoints = (await entrypointsSubscription.next()).value;
const entrypoints = (await entrypointsSubscription.next()).value.value;
const RUNS = 1000;
async function compileRoute(route) {
......@@ -371,11 +371,11 @@ describe('next.rs api', () => {
const entrypointsSubscription = project.entrypointsSubscribe()
const entrypoints = await entrypointsSubscription.next()
expect(entrypoints.done).toBe(false)
if (!('routes' in entrypoints.value)) {
if (!('routes' in entrypoints.value.value)) {
throw new Error('Entrypoints not available due to compilation errors')
}
expect(Array.from(entrypoints.value.routes.keys()).sort()).toEqual([
expect(Array.from(entrypoints.value.value.routes.keys()).sort()).toEqual([
'/',
'/_not-found',
'/api/edge',
......@@ -464,11 +464,11 @@ describe('next.rs api', () => {
const entrypoints: TurbopackResult<RawEntrypoints | {}> = (
await entrypointsSubscribtion.next()
).value
if (!('routes' in entrypoints)) {
if (!('routes' in entrypoints.value)) {
throw new Error('Entrypoints not available due to compilation errors')
}
const route = entrypoints.routes.get(path)
const route = entrypoints.value.routes.get(path)
entrypointsSubscribtion.return()
expect(route.type).toBe(type)
......@@ -477,32 +477,32 @@ describe('next.rs api', () => {
case 'page-api':
case 'app-route': {
const result = await route.endpoint.writeToDisk()
expect(result.type).toBe(runtime)
expect(result.config).toEqual(config)
expect(result.value.type).toBe(runtime)
expect(result.value.config).toEqual(config)
expect(normalizeIssues(result.issues)).toMatchSnapshot('issues')
break
}
case 'page': {
const result = await route.htmlEndpoint.writeToDisk()
expect(result.type).toBe(runtime)
expect(result.config).toEqual(config)
expect(result.value.type).toBe(runtime)
expect(result.value.config).toEqual(config)
expect(normalizeIssues(result.issues)).toMatchSnapshot('issues')
const result2 = await route.dataEndpoint.writeToDisk()
expect(result2.type).toBe(runtime)
expect(result2.config).toEqual(config)
expect(result2.value.type).toBe(runtime)
expect(result2.value.config).toEqual(config)
expect(normalizeIssues(result2.issues)).toMatchSnapshot('data issues')
break
}
case 'app-page': {
const result = await route.pages[0].htmlEndpoint.writeToDisk()
expect(result.type).toBe(runtime)
expect(result.config).toEqual(config)
expect(result.value.type).toBe(runtime)
expect(result.value.config).toEqual(config)
expect(normalizeIssues(result.issues)).toMatchSnapshot('issues')
const result2 = await route.pages[0].rscHmrEndpoint.writeToDisk()
expect(result2.type).toBe(runtime)
expect(result2.config).toEqual(config)
expect(result2.value.type).toBe(runtime)
expect(result2.value.config).toEqual(config)
expect(normalizeIssues(result2.issues)).toMatchSnapshot('rsc issues')
break
......@@ -588,17 +588,17 @@ describe('next.rs api', () => {
const entrypoints: TurbopackResult<RawEntrypoints | {}> = (
await entrypointsSubscribtion.next()
).value
if (!('routes' in entrypoints)) {
if (!('routes' in entrypoints.value)) {
throw new Error('Entrypoints not available due to compilation errors')
}
const route = entrypoints.routes.get(path)
const route = entrypoints.value.routes.get(path)
entrypointsSubscribtion.return()
expect(route.type).toBe(type)
let serverSideSubscription:
| AsyncIterableIterator<TurbopackResult>
| AsyncIterableIterator<TurbopackResult<void>>
| undefined
switch (route.type) {
case 'page': {
......@@ -620,7 +620,7 @@ describe('next.rs api', () => {
const result = await project.clientHmrChunkNamesSubscribe().next()
expect(result.done).toBe(false)
const chunkNames = result.value.chunkNames
const chunkNames = result.value.value.chunkNames
expect(chunkNames).toHaveProperty('length', expect.toBePositive())
const subscriptions = chunkNames.map((chunkName) =>
......@@ -630,8 +630,11 @@ describe('next.rs api', () => {
subscriptions.map(async (subscription) => {
const result = await subscription.next()
expect(result.done).toBe(false)
expect(result.value).toHaveProperty('resource', expect.toBeObject())
expect(result.value).toHaveProperty('type', 'issues')
expect(result.value.value).toHaveProperty(
'resource',
expect.toBeObject()
)
expect(result.value.value).toHaveProperty('type', 'issues')
expect(normalizeIssues(result.value.issues)).toEqual([])
})
)
......@@ -652,8 +655,8 @@ describe('next.rs api', () => {
const merged = raceIterators(subscriptions)
for await (const item of merged) {
if (done) return
if (item.type === 'partial') {
expect(item.instruction).toEqual({
if (item.value.type === 'partial') {
expect(item.value.instruction).toEqual({
type: 'ChunkListUpdate',
merged: [
expect.objectContaining({
......@@ -663,13 +666,13 @@ describe('next.rs api', () => {
],
})
const updates = Object.keys(
item.instruction.merged[0].entries
item.value.instruction.merged[0].entries
)
expect(updates).not.toBeEmpty()
foundUpdates = foundUpdates || []
foundUpdates.push(
...Object.keys(item.instruction.merged[0].entries)
...Object.keys(item.value.instruction.merged[0].entries)
)
}
}
......@@ -728,11 +731,11 @@ describe('next.rs api', () => {
const entrypoints: TurbopackResult<RawEntrypoints | {}> = (
await entrypointsSubscribtion.next()
).value
if (!('routes' in entrypoints)) {
if (!('routes' in entrypoints.value)) {
throw new Error('Entrypoints not available due to compilation errors')
}
const route = entrypoints.routes.get('/')
const route = entrypoints.value.routes.get('/')
entrypointsSubscribtion.return()
if (route.type !== 'page') throw new Error('unknown route type')
......@@ -740,7 +743,7 @@ describe('next.rs api', () => {
const result = await project.clientHmrChunkNamesSubscribe().next()
expect(result.done).toBe(false)
const chunkNames = result.value.chunkNames
const chunkNames = result.value.value.chunkNames
const subscriptions = chunkNames.map((chunkName) =>
project.clientHmrEvents(chunkName)
......@@ -749,8 +752,11 @@ describe('next.rs api', () => {
subscriptions.map(async (subscription) => {
const result = await subscription.next()
expect(result.done).toBe(false)
expect(result.value).toHaveProperty('resource', expect.toBeObject())
expect(result.value).toHaveProperty('type', 'issues')
expect(result.value.value).toHaveProperty(
'resource',
expect.toBeObject()
)
expect(result.value.value).toHaveProperty('type', 'issues')
})
)
const merged = raceIterators(subscriptions)
......@@ -769,7 +775,7 @@ describe('next.rs api', () => {
while (true) {
const { value, done } = await merged.next()
expect(done).toBe(false)
if (value.type === 'partial') {
if (value.value.type === 'partial') {
break
}
}
......
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