Turbopack JS entrypoint and native build entrypoint using napi

In order to integrate Turbopack more cleanly into our benchmarking
suite, we need to have a standalone Turbopack binary that can
isolate the bundler behavior without including Next crates.

This commit is basically boilerplate necessary to bridge JS and
Rust, without actually hooking into build functionality. It looks
for and parses a config file (necessary for benchmark suites later)
but does nothing with it. The next PR in the stack will actually
run a basic build from the selected entrypoint.
parent 10f370c1
......@@ -10780,6 +10780,26 @@ dependencies = [
"turbopack-ecmascript",
]
[[package]]
name = "turbopack-napi"
version = "0.1.0"
dependencies = [
"anyhow",
"napi",
"napi-build",
"napi-derive",
"serde",
"serde_json",
"tokio",
"tracing",
"turbo-rcstr",
"turbo-tasks",
"turbo-tasks-backend",
"turbo-tasks-malloc",
"turbopack-core",
"vergen-gitcl",
]
[[package]]
name = "turbopack-nft"
version = "0.1.0"
......
# `turbopack`
The standalone Turbopack bundler CLI, intended for benchmarking the bundler
against generic JavaScript codebases.
The package has two halves that build independently:
- the native addon, built from the `turbopack-napi` crate in
`turbopack/crates/turbopack-napi` into `native/`
- the TypeScript CLI in `src/`, compiled into `dist/`
### Building
Build both halves:
```sh
pnpm --filter turbopack build
```
Build just one half. While iterating on `src/`, there is no need to rebuild the
native addon:
```sh
pnpm --filter turbopack build-native
pnpm --filter turbopack build-ts
```
Run the result:
```sh
node packages/turbopack/dist/cli.js help
```
### Scripts
| Script | Description |
| ---------------------- | ----------------------------------------------------------------- |
| `build` | Builds the native addon and then the TypeScript CLI. |
| `build-native` | Builds the `turbopack-napi` crate into `native/` (debug profile). |
| `build-native-release` | Same as above, but with the release profile. |
| `build-ts` | Compiles `src/` into `dist/` with `tsc`. |
| `typescript` | Type-checks `src/` without emitting. |
| `clean` | Removes `native/` and `dist/`. |
{
"name": "turbopack",
"version": "0.0.0",
"description": "Standalone Turbopack bundler CLI -- for benchmarking",
"license": "MIT",
"private": true,
"bin": {
"turbopack": "./dist/cli.js"
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist/",
"native/"
],
"scripts": {
"build": "pnpm build-native && pnpm build-ts",
"build-ts": "tsc -p tsconfig.json",
"build-native": "napi build --platform -p turbopack-napi --manifest-path ../../Cargo.toml --no-js -o native",
"build-native-release": "napi build --platform -p turbopack-napi --manifest-path ../../Cargo.toml --release --no-js -o native",
"typescript": "tsc --noEmit -p tsconfig.json",
"clean": "node ../../scripts/rm.mjs native dist"
},
"napi": {
"binaryName": "turbopack",
"targets": [
"x86_64-apple-darwin",
"aarch64-apple-darwin",
"x86_64-unknown-linux-gnu",
"aarch64-unknown-linux-gnu",
"x86_64-unknown-linux-musl",
"aarch64-unknown-linux-musl",
"x86_64-pc-windows-msvc",
"aarch64-pc-windows-msvc"
]
},
"dependencies": {
"zod": "^4.6.0"
},
"devDependencies": {
"@napi-rs/cli": "3.7.2",
"typescript": "6.0.2"
}
}
import { existsSync, readdirSync } from 'fs'
import { arch, platform } from 'os'
import path from 'path'
/**
* Opaque native handles. Mirrors the `{ __napiType }`-tagged externals the addon returns.
*/
export type NativeProject = { __napiType: 'Project' }
export type NativeRootTask = { __napiType: 'RootTask' }
export interface NapiProjectOptions {
rootPath: string
entries: string[]
distDir?: string
}
/** Build provenance baked into the native addon (from `build.rs`). */
export interface NapiBuildInfo {
version: string
gitSha: string
gitDirty: boolean
}
/** The raw functions exported by the `.node` addon (camelCase — napi converts from snake_case). */
export interface RawBinding {
buildInfo(): NapiBuildInfo
projectNew(options: NapiProjectOptions): Promise<NativeProject>
projectBuild(project: NativeProject): Promise<void>
}
/**
* On Linux, is the C library musl (Alpine etc.) rather than glibc? Uses Node's own libc detection
* via `process.report` — no dependency. glibc runtime present -> gnu; absent -> musl.
*/
export function isMusl(): boolean {
if (platform() !== 'linux') return false
try {
const report = (
process.report as { getReport?: () => unknown } | undefined
)?.getReport?.() as
| { header?: { glibcVersionRuntime?: string }; sharedObjects?: string[] }
| undefined
if (report?.header?.glibcVersionRuntime) return false
if (Array.isArray(report?.sharedObjects)) {
return report.sharedObjects.some((o) => /libc\.musl-|ld-musl-/.test(o))
}
// No glibc runtime reported and no shared-object hint → assume musl.
return true
} catch {
return false
}
}
/**
* The napi platform-arch-abi triple (matches the per-platform npm package suffix and the
* `turbopack.<triple>.node` filename): `darwin-arm64`, `linux-x64-musl`, `win32-x64-msvc`, …
*/
export function tripleName(
p: NodeJS.Platform = platform(),
a: string = arch(),
musl: boolean = isMusl()
): string {
switch (p) {
case 'darwin':
return `darwin-${a}`
case 'win32':
return `win32-${a}-msvc`
case 'linux':
return `linux-${a}-${musl ? 'musl' : 'gnu'}`
default:
return `${p}-${a}`
}
}
/** The published per-platform package name for a triple, e.g. `turbopack-darwin-arm64`. */
export function platformPackageName(triple: string = tripleName()): string {
return `turbopack-${triple}`
}
let cached: RawBinding | undefined
export function loadBinding(): RawBinding {
if (cached) return cached
const nativeDir = path.join(__dirname, '..', 'native')
const triple = tripleName()
const attempts: string[] = []
// Resolution order:
// 1. the published per-platform package (`turbopack-<triple>`) — what `npm i` installs;
// 2. a locally-built binary in `native/turbopack.<triple>.node`;
// 3. any single `.node` in `native/` (covers a hand-built/renamed binary).
const candidates: string[] = [
platformPackageName(triple),
path.join(nativeDir, `turbopack.${triple}.node`),
...(existsSync(nativeDir)
? readdirSync(nativeDir)
.filter((f) => f.endsWith('.node'))
.map((f) => path.join(nativeDir, f))
: []),
]
for (const candidate of candidates) {
try {
cached = require(candidate) as RawBinding
return cached
} catch (err) {
attempts.push(` ${candidate}: ${(err as Error).message}`)
}
}
throw new Error(
`Failed to load the turbopack native addon for ${triple}. Tried:\n${attempts.join('\n')}\n` +
`Build it with: pnpm --filter turbopack build-native`
)
}
#!/usr/bin/env node
import fs from 'fs'
import path from 'path'
import type { NapiProjectOptions } from './binding'
import { loadTurbopackConfig, resolveProjectOptions } from './config'
function flag(
args: string[],
name: string,
fallback?: string
): string | undefined {
const i = args.indexOf(`--${name}`)
return i >= 0 && i + 1 < args.length ? args[i + 1] : fallback
}
function splitCommaSeparatedOption(value: string): string[] {
return value
.split(',')
.map((e) => e.trim())
.filter(Boolean)
}
/** CLI-flag overrides applied on top of `turbopack.config.ts` (flags win). */
function flagOverrides(args: string[]): Partial<NapiProjectOptions> {
const overrides: Partial<NapiProjectOptions> = {}
const entry = flag(args, 'entry')
if (entry) overrides.entries = splitCommaSeparatedOption(entry)
return overrides
}
/** Bundle JavaScript and other static assets into a deployment-ready output */
async function build(args: string[]): Promise<void> {
const root = path.resolve(flag(args, 'root', process.cwd())!)
const distFlag = flag(args, 'dist')
const overrides = flagOverrides(args)
const { config, configPath } = await loadTurbopackConfig(root)
const options = resolveProjectOptions({ config, root, dev: false, overrides })
if (!options.entries || options.entries.length === 0)
options.entries = ['index.html']
if (distFlag) options.distDir = distFlag
// Time ONLY the turbopack build (compile + emit) — not project setup, the public/ copy, or the
// cache flush. This is the "built in N ms" number other bundlers report.
const started = Date.now()
// This is where the project build goes!
const buildMs = Date.now() - started
// Copy public/ into the out dir (static passthrough) — outside the reported build time.
const outDir = path.resolve(root, options.distDir ?? 'dist')
const publicDir = path.join(root, 'public')
if (fs.existsSync(publicDir)) {
fs.cpSync(publicDir, outDir, { recursive: true })
}
// The server bundle (dist/server/*) is emitted as CommonJS — module.exports plus require() for
// chunk loading. Node picks a .js file's module type from the nearest package.json, so a project
// whose root package.json is "type":"module" would parse these .js files (the entry AND its
// chunks/*.js) as ESM and throw "require is not defined". Pin the whole server subtree to
// CommonJS with its own package.json — the mechanism Node designed for this, and what bundlers
// like Next.js use for their server output. Written before prerenderStatic require()s the bundle;
// covers both static (required at build) and server (served at runtime) modes.
const serverDir = path.join(outDir, 'server')
if (fs.existsSync(serverDir)) {
fs.writeFileSync(
path.join(serverDir, 'package.json'),
'{ "type": "commonjs" }\n'
)
}
console.log(
`\n turbopack build → ${outDir} (${buildMs}ms)` +
`${configPath ? ` (config: ${path.basename(configPath)})` : ''}\n`
)
// Clean up the project here
process.exit(0)
}
/**
* help — detailed, self-contained reference
*/
const HELP = `turbopack — a fast web bundler designed around incremental compilation
The standalone turbopack CLI is intended for benchmarking the bundler against
generic JavaScript codebases.
USAGE
turbopack <command> [options]
COMMANDS
build Produce an optimized static build in the output directory
(default: dist/). Minifies, content-hashes chunk filenames, and —
unless the config sets build.optimize - enables scope hoisting +
identifier mangling. Copies public/ into the output.
help Print this reference.
OPTIONS (per command)
build
--root <dir> Project root. Default: current working directory.
--dist <dir> Output directory. Default: dist (or build.distDir from the config).
CLI flags always override values from turbopack.config.ts.
`
function help(): void {
console.log(HELP)
}
async function main(): Promise<void> {
const [cmd, ...rest] = process.argv.slice(2)
// Top-level help flags work before command dispatch. `--verbose` adds the full reference.
if (cmd === 'help' || cmd === '--help' || cmd === '-h') {
help()
return
}
switch (cmd) {
case 'build':
await build(rest)
break
default:
console.error(
`Unknown command "${cmd}". Run "turbopack help" for usage ` +
`(commands: build | help).`
)
process.exit(1)
}
}
main().catch((err) => {
console.error(err)
process.exit(1)
})
import fs from 'fs'
import path from 'path'
import { pathToFileURL } from 'url'
import { z } from 'zod'
import type { NapiProjectOptions } from './binding'
/**
* User-facing `turbopack.config.ts` shape, providing access to all of the
* configurable settings that control how Turbopack bundles.
*/
export interface TurbopackConfig {
/** Project root (default: cwd). */
root?: string
/** Entry points — HTML templates and/or bare JS/TS modules (relative to root). */
entries?: string[]
/** Resolve aliases, e.g. `{ '@': './src' }` — adds `@` and `@/*`. */
alias?: Record<string, string>
/** Build options. */
build?: {
distDir?: string
sourceMaps?: boolean
}
}
/** Identity helper so users get typed config with `export default defineConfig({...})`. */
export function defineConfig(config: TurbopackConfig): TurbopackConfig {
return config
}
/**
* Runtime schema for `turbopack.config.ts` (mirrors `TurbopackConfig`).
* Validation is advisory: on failure we warn (listing the offending options)
* and continue with the user's config unchanged, so a new config value never
* outright fails on an older CLI.
*/
export const configSchema: z.ZodType<TurbopackConfig> = z.strictObject({
root: z.string().optional(),
entries: z.array(z.string()).optional(),
alias: z.record(z.string(), z.string()).optional(),
build: z
.strictObject({
distDir: z.string().optional(),
sourceMaps: z.boolean().optional(),
})
.optional(),
})
/** Format zod issues into readable lines and warn (advisory, must never throw). */
function warnConfigIssues(configFile: string, error: z.ZodError): void {
const lines = [`Invalid ${configFile} options detected:`]
for (const issue of error.issues) {
if (issue.code === 'unrecognized_keys') {
lines.push(` unknown option(s): ${issue.keys.join(', ')}`)
} else {
const at = issue.path.length ? issue.path.join('.') : '<root>'
lines.push(` ${at}: ${issue.message}`)
}
}
console.warn(`\n${lines.join('\n')}\n`)
}
/**
* A genuine dynamic `import()`. tsc's CommonJS output rewrites a literal `import()` into
* `require()`, which cannot load an ESM/TS file by URL. This indirection keeps a real native
* `import` so Node's TS stripping + ESM loading apply.
*/
// eslint-disable-next-line no-new-func
const nativeImport = new Function('specifier', 'return import(specifier)') as (
specifier: string
) => Promise<any>
/** All supported config filenames */
const CONFIG_FILES = [
'turbopack.config.ts',
'turbopack.config.mjs',
'turbopack.config.js',
]
/** Find the config file at `root`, if any. */
export function findConfigFile(root: string): string | undefined {
for (const name of CONFIG_FILES) {
const full = path.join(root, name)
if (fs.existsSync(full)) return full
}
return undefined
}
/**
* Load `turbopack.config.ts` via Node's native TypeScript import (`import(fileURL)`, taking
* the default export). No transpile step or extra deps, so long as Node is newer
* than 22.6. The older `.js`/`.mjs` configs can load on any Node. Returns `{}`
* when there is no config file.
*/
export async function loadTurbopackConfig(
root: string
): Promise<{ config: TurbopackConfig; configPath?: string }> {
const configPath = findConfigFile(root)
if (!configPath) return { config: {} }
// `process.features.typescript` is present on Node ≥ 22.6 but not yet in @types/node.
const nativeTs = (process.features as { typescript?: unknown }).typescript
if (configPath.endsWith('.ts') && !nativeTs) {
throw new Error(
`Loading ${path.basename(configPath)} needs Node's native TypeScript support ` +
`(Node ≥ 22.6). Upgrade Node, or use turbopack.config.mjs. (Detected: ${process.version})`
)
}
// Cache-bust so an edited config re-imports (the CLI restarts the project on change).
const url = `${pathToFileURL(configPath).href}?t=${fs.statSync(configPath).mtimeMs}`
const mod = await nativeImport(url)
const config = (mod.default ?? mod) as TurbopackConfig
// Validation pass to warn about invalid or unknown options. Unknown values
// aren't an error, use the config as-is.
const parsed = configSchema.safeParse(config)
if (!parsed.success) warnConfigIssues(path.basename(configPath), parsed.error)
return { config, configPath }
}
/**
* Fold a loaded config into `NapiProjectOptions`. `overrides` (from CLI flags) win over
* the config file.
*/
export function resolveProjectOptions(args: {
config: TurbopackConfig
root: string
dev: boolean
overrides?: Partial<NapiProjectOptions>
}): NapiProjectOptions {
const { config, root, overrides = {} } = args
const options: NapiProjectOptions = {
rootPath: root,
entries: config.entries ?? [],
distDir: config.build?.distDir,
...overrides,
}
return options
}
{
"compilerOptions": {
"target": "es2021",
"lib": ["es2021", "dom"],
"module": "commonjs",
"moduleResolution": "node",
"ignoreDeprecations": "6.0",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"declaration": false,
"sourceMap": true,
"types": ["node"]
},
"include": ["src/**/*.ts"]
}
......@@ -312,7 +312,7 @@ importers:
version: 5.2.1(eslint@9.37.0(jiti@2.6.1))
eslint-plugin-import:
specifier: 2.31.0
version: 2.31.0(eslint@9.37.0(jiti@2.6.1))
version: 2.31.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.6.1))(typescript@6.0.2))(eslint@9.37.0(jiti@2.6.1))
eslint-plugin-jest:
specifier: 27.6.3
version: 27.6.3(eslint@9.37.0(jiti@2.6.1))(jest@29.7.0(@types/node@20.17.7(patch_hash=fe6957869a9b616ec526ededb72bbe846b863bd2349204218772df5c1e62d6ab))(babel-plugin-macros@3.1.0))(typescript@6.0.2)
......@@ -1944,7 +1944,7 @@ importers:
devDependencies:
'@napi-rs/cli':
specifier: 3.7.2
version: 3.7.2(@emnapi/runtime@1.9.2)(@types/node@20.17.7(patch_hash=fe6957869a9b616ec526ededb72bbe846b863bd2349204218772df5c1e62d6ab))(node-addon-api@6.1.0)
version: 3.7.2(@emnapi/runtime@1.11.3)(@types/node@20.17.7(patch_hash=fe6957869a9b616ec526ededb72bbe846b863bd2349204218772df5c1e62d6ab))(node-addon-api@6.1.0)
cross-env:
specifier: 6.0.3
version: 6.0.3
......@@ -1983,6 +1983,19 @@ importers:
specifier: 6.0.2
version: 6.0.2
packages/turbopack:
dependencies:
zod:
specifier: ^4.6.0
version: 4.6.2
devDependencies:
'@napi-rs/cli':
specifier: 3.7.2
version: 3.7.2(@emnapi/runtime@1.9.2)(@types/node@20.17.7(patch_hash=fe6957869a9b616ec526ededb72bbe846b863bd2349204218772df5c1e62d6ab))(node-addon-api@6.1.0)
typescript:
specifier: 6.0.2
version: 6.0.2
turbopack/crates/turbopack-cli/js:
dependencies:
'@vercel/turbopack-ecmascript-runtime':
......@@ -18968,6 +18981,9 @@ packages:
zod@3.25.76:
resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
zod@4.6.2:
resolution: {integrity: sha512-lh5RCAGFa1Cm2hjtNwLQhSs/AsqdWnTQaBER9fEwN/88pSh7KOtJavtBx/0VlkN/uFd61SwYmljLMDAsHlvzBQ==}
zwitch@1.0.5:
resolution: {integrity: sha512-V50KMwwzqJV0NpZIZFwfOD5/lyny3WlSzRiXgA0G7VUnRlqttta1L6UQIHzd6EuBY/cHGfwTIck7w1yH6Q5zUw==}
......@@ -21842,6 +21858,37 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@napi-rs/cli@3.7.2(@emnapi/runtime@1.11.3)(@types/node@20.17.7(patch_hash=fe6957869a9b616ec526ededb72bbe846b863bd2349204218772df5c1e62d6ab))(node-addon-api@6.1.0)':
dependencies:
'@inquirer/prompts': 8.5.2(@types/node@20.17.7(patch_hash=fe6957869a9b616ec526ededb72bbe846b863bd2349204218772df5c1e62d6ab))
'@napi-rs/cross-toolchain': 1.0.3
'@napi-rs/wasm-tools': 1.1.0
'@octokit/rest': 22.0.1
clipanion: 4.0.0-rc.4(typanion@3.14.0)
colorette: 2.0.20
emnapi: 1.11.3(node-addon-api@6.1.0)
es-toolkit: 1.50.0
js-yaml: 4.2.0
obug: 2.1.4
semver: 7.8.5
typanion: 3.14.0
optionalDependencies:
'@emnapi/runtime': 1.11.3
transitivePeerDependencies:
- '@napi-rs/cross-toolchain-arm64-target-aarch64'
- '@napi-rs/cross-toolchain-arm64-target-armv7'
- '@napi-rs/cross-toolchain-arm64-target-ppc64le'
- '@napi-rs/cross-toolchain-arm64-target-s390x'
- '@napi-rs/cross-toolchain-arm64-target-x86_64'
- '@napi-rs/cross-toolchain-x64-target-aarch64'
- '@napi-rs/cross-toolchain-x64-target-armv7'
- '@napi-rs/cross-toolchain-x64-target-ppc64le'
- '@napi-rs/cross-toolchain-x64-target-s390x'
- '@napi-rs/cross-toolchain-x64-target-x86_64'
- '@types/node'
- node-addon-api
- supports-color
'@napi-rs/cli@3.7.2(@emnapi/runtime@1.9.2)(@types/node@20.17.7(patch_hash=fe6957869a9b616ec526ededb72bbe846b863bd2349204218772df5c1e62d6ab))(node-addon-api@6.1.0)':
dependencies:
'@inquirer/prompts': 8.5.2(@types/node@20.17.7(patch_hash=fe6957869a9b616ec526ededb72bbe846b863bd2349204218772df5c1e62d6ab))
......@@ -28402,10 +28449,11 @@ snapshots:
- bluebird
- supports-color
eslint-module-utils@2.12.0(eslint-import-resolver-node@0.3.9)(eslint@9.37.0(jiti@2.6.1)):
eslint-module-utils@2.12.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.6.1))(typescript@6.0.2))(eslint-import-resolver-node@0.3.9)(eslint@9.37.0(jiti@2.6.1)):
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 8.46.0(eslint@9.37.0(jiti@2.6.1))(typescript@6.0.2)
eslint: 9.37.0(jiti@2.6.1)
eslint-import-resolver-node: 0.3.9
transitivePeerDependencies:
......@@ -28446,7 +28494,7 @@ snapshots:
- typescript
optional: true
eslint-plugin-import@2.31.0(eslint@9.37.0(jiti@2.6.1)):
eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.6.1))(typescript@6.0.2))(eslint@9.37.0(jiti@2.6.1)):
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.8
......@@ -28457,7 +28505,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.37.0(jiti@2.6.1)
eslint-import-resolver-node: 0.3.9
eslint-module-utils: 2.12.0(eslint-import-resolver-node@0.3.9)(eslint@9.37.0(jiti@2.6.1))
eslint-module-utils: 2.12.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.6.1))(typescript@6.0.2))(eslint-import-resolver-node@0.3.9)(eslint@9.37.0(jiti@2.6.1))
hasown: 2.0.2
is-core-module: 2.16.1
is-glob: 4.0.3
......@@ -28468,6 +28516,8 @@ snapshots:
semver: 6.3.1
string.prototype.trimend: 1.0.9
tsconfig-paths: 3.15.0
optionalDependencies:
'@typescript-eslint/parser': 8.46.0(eslint@9.37.0(jiti@2.6.1))(typescript@6.0.2)
transitivePeerDependencies:
- eslint-import-resolver-typescript
- eslint-import-resolver-webpack
......@@ -28574,8 +28624,8 @@ snapshots:
'@babel/parser': 7.27.0
eslint: 9.37.0(jiti@2.6.1)
hermes-parser: 0.25.1
zod: 3.25.76
zod-validation-error: 4.0.2(zod@3.25.76)
zod: 4.6.2
zod-validation-error: 4.0.2(zod@4.6.2)
transitivePeerDependencies:
- supports-color
......@@ -39056,14 +39106,16 @@ snapshots:
dependencies:
zod: 3.25.76
zod-validation-error@4.0.2(zod@3.25.76):
zod-validation-error@4.0.2(zod@4.6.2):
dependencies:
zod: 3.25.76
zod: 4.6.2
zod@3.24.4: {}
zod@3.25.76: {}
zod@4.6.2: {}
zwitch@1.0.5: {}
zwitch@2.0.4: {}
[package]
name = "turbopack-napi"
version = "0.1.0"
description = "The single #[napi] addon for the standalone Turbopack CLI"
license = "MIT"
edition = "2024"
autobenches = false
publish = false
[lib]
crate-type = ["cdylib"]
bench = false
[lints]
workspace = true
[features]
default = ["custom_allocator"]
custom_allocator = ["turbo-tasks-malloc/custom_allocator"]
[dependencies]
anyhow = { workspace = true }
napi = { workspace = true }
napi-derive = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["full"] }
tracing = { workspace = true }
turbo-rcstr = { workspace = true }
turbo-tasks = { workspace = true }
turbo-tasks-backend = { workspace = true }
turbo-tasks-malloc = { workspace = true, default-features = false }
turbopack-core = { workspace = true }
[build-dependencies]
anyhow = { workspace = true }
napi-build = { workspace = true }
serde_json = { workspace = true }
vergen-gitcl = { workspace = true }
use std::{fs, path::Path};
use serde_json::Value;
fn main() -> anyhow::Result<()> {
println!("cargo:rerun-if-env-changed=CI");
println!("cargo:rerun-if-env-changed=CARGO_CFG_TARGET_OS");
// Version key for the persistent cache: `v<pkg version>-<git sha>` + git-dirty state.
// The tool version + commit fully determines the transform/codegen behavior, so it is the
// correct cache-invalidation key; mirrors `crates/next-napi-bindings/build.rs`.
let pkg_version = {
let package_json_path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../..")
.join("packages/turbopack/package.json");
println!("cargo:rerun-if-changed={}", package_json_path.display());
let content = fs::read_to_string(&package_json_path)?;
let json: Value = serde_json::from_str(&content)?;
json["version"]
.as_str()
.expect("Expected a `version` string in packages/turbopack/package.json")
.to_string()
};
println!("cargo:rustc-env=TURBOPACK_PKG_VERSION={pkg_version}");
// `git describe`-style sha + dirty flag. `dirty(false)` = untracked files do NOT count toward
// dirtiness (only tracked modifications), so scratch/untracked files never flip the cache to
// the throwaway `temp` version or trigger spurious rebuilds.
let cargo = vergen_gitcl::CargoBuilder::default()
.target_triple(true)
.build()?;
let git = vergen_gitcl::GitclBuilder::default()
.dirty(/* include_untracked */ false)
.sha(/* short */ true)
.build()?;
vergen_gitcl::Emitter::default()
.fail_on_error()
.add_instructions(&cargo)?
.add_instructions(&git)?
.emit()?;
let is_macos_target = std::env::var("CARGO_CFG_TARGET_OS").is_ok_and(|value| value == "macos");
if !is_macos_target {
napi_build::setup();
}
// napi always adds a GCC-specific flag on macOS; use dynamic lookup instead so the
// Node symbols resolve at load time (mirrors crates/next-napi-bindings/build.rs).
if is_macos_target {
println!("cargo:rerun-if-env-changed=DEBUG_GENERATED_CODE");
println!("cargo:rerun-if-env-changed=TYPE_DEF_TMP_PATH");
println!("cargo:rerun-if-env-changed=CARGO_CFG_NAPI_RS_CLI_VERSION");
println!("cargo:rustc-cdylib-link-arg=-undefined");
println!("cargo:rustc-cdylib-link-arg=dynamic_lookup");
}
#[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
println!("cargo:rustc-link-arg=-Wl,--warn-unresolved-symbols");
Ok(())
}
//! turbopack-napi — the single `#[napi]` addon for the standalone React-on-Turbopack web
//! toolchain. Thin FFI: it marshals opaque `External<T>` handles (never data structures) and
//! keeps all NAPI-only types (`ProjectInstance`, `RootTask`) out of turbo-tasks functions.
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
pub mod project;
#[global_allocator]
static ALLOC: turbo_tasks_malloc::TurboMalloc = turbo_tasks_malloc::TurboMalloc;
/// Install a multi-thread tokio runtime (with TurboMalloc thread hooks) as the runtime that
/// napi async functions execute on. Mirrors `crates/next-napi-bindings/src/lib.rs`.
#[napi_derive::module_init]
fn init() {
use napi::bindgen_prelude::create_custom_tokio_runtime;
use tokio::runtime::Builder;
use turbo_tasks::{panic_hooks::handle_panic, parallel::available_parallelism};
use turbo_tasks_malloc::TurboMalloc;
let prev_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
handle_panic(info);
prev_hook(info);
}));
let worker_threads = available_parallelism().map(|n| n.get()).unwrap_or(1);
let rt = Builder::new_multi_thread()
.enable_all()
.on_thread_stop(|| {
TurboMalloc::thread_stop();
})
.on_thread_park(|| {
TurboMalloc::thread_park();
})
.worker_threads(worker_threads)
.max_blocking_threads(usize::MAX - worker_threads)
.disable_lifo_slot()
.build()
.unwrap();
create_custom_tokio_runtime(rt);
}
//! The napi project surface. Opaque `External` handles only.
use napi::bindgen_prelude::External;
use napi_derive::napi;
use turbo_rcstr::RcStr;
fn napi_err(err: impl std::fmt::Display) -> napi::Error {
napi::Error::from_reason(err.to_string())
}
// ---------------------------------------------------------------------------
// napi option DTOs (camelCase on the JS side).
// ---------------------------------------------------------------------------
#[napi(object)]
pub struct NapiProjectOptions {
pub root_path: String,
pub entries: Vec<String>,
pub dist_dir: Option<String>,
}
// ---------------------------------------------------------------------------
// Opaque handles.
// ---------------------------------------------------------------------------
/// The long-lived per-project handle passed to JS as `External<ProjectInstance>`.
/// NAPI-only, never enters a turbo-tasks function.
pub struct ProjectInstance {
project_dir: RcStr,
}
#[napi(object)]
pub struct NapiBuildInfo {
/// Package version baked into the native binary at build time.
pub version: String,
/// Short git SHA the binary was built from.
pub git_sha: String,
/// Whether the git tree had uncommitted tracked changes at build time.
pub git_dirty: bool,
}
/// Build provenance of the native addon (baked by `build.rs`; see `cache_describe`). The
/// `turbopack version` command surfaces this alongside the npm package version.
#[napi]
pub fn build_info() -> NapiBuildInfo {
NapiBuildInfo {
version: env!("TURBOPACK_PKG_VERSION").to_string(),
git_sha: env!("VERGEN_GIT_SHA").to_string(),
git_dirty: env!("VERGEN_GIT_DIRTY") == "true",
}
}
// ---------------------------------------------------------------------------
// napi surface.
// ---------------------------------------------------------------------------
#[napi(ts_return_type = "Promise<{ __napiType: \"Project\" }>")]
pub async fn project_new(options: NapiProjectOptions) -> napi::Result<External<ProjectInstance>> {
let project_dir = options.root_path.clone();
Ok(External::new(ProjectInstance {
project_dir: RcStr::from(project_dir),
}))
}
#[napi]
pub async fn project_build(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
) -> napi::Result<()> {
println!("no-op");
Ok(())
}
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