File size: 1,959 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import path from 'path'

import { Worker } from '../../lib/worker'
import { NextBuildContext } from '../build-context'

async function turbopackBuildWithWorker() {
  try {
    const worker = new Worker(path.join(__dirname, 'impl.js'), {
      exposedMethods: ['workerMain', 'waitForShutdown'],
      debuggerPortOffset: -1,
      isolatedMemory: false,
      numWorkers: 1,
      maxRetries: 0,
      forkOptions: {
        env: {
          NEXT_PRIVATE_BUILD_WORKER: '1',
        },
      },
    }) as Worker & typeof import('./impl')
    const { nextBuildSpan, ...prunedBuildContext } = NextBuildContext
    const result = await worker.workerMain({
      buildContext: prunedBuildContext,
    })

    // destroy worker when Turbopack has shutdown so it's not sticking around using memory
    // We need to wait for shutdown to make sure persistent cache is flushed
    result.shutdownPromise = worker.waitForShutdown().then(() => {
      worker.end()
    })

    return result
  } catch (err: any) {
    // When the error is a serialized `Error` object we need to recreate the `Error` instance
    // in order to keep the consistent error reporting behavior.
    if (err.type === 'Error') {
      const error = new Error(err.message)
      if (err.name) {
        error.name = err.name
      }
      if (err.cause) {
        error.cause = err.cause
      }
      error.message = err.message
      error.stack = err.stack
      throw error
    }
    throw err
  }
}

export function turbopackBuild(
  withWorker: boolean
): ReturnType<typeof import('./impl').turbopackBuild> {
  const nextBuildSpan = NextBuildContext.nextBuildSpan!
  return nextBuildSpan
    .traceChild('run-turbopack-compiler')
    .traceAsyncFn(async () => {
      if (withWorker) {
        return await turbopackBuildWithWorker()
      } else {
        const build = (require('./impl') as typeof import('./impl'))
          .turbopackBuild
        return await build()
      }
    })
}