Unverified Commit 1dc3c010 authored by OJ Kwon's avatar OJ Kwon Committed by GitHub

docs(turbopack): build more docs (#61977)

### What

This PR changes setup for the turbopack documentation.

Long story in short, we want to 2 types of documentation: one for high
level description (archtecture, etcs) and another for the api doc.
rustdoc / cargo doc unfortunately doesn't support to integrate both
easily.

PR adds mdbook setup to workaround those - instead of using rustdoc's
index as entrypoint, mdbook becomes an entrypoint to rustdoc. This
allows to host plain text document, and also able to access full rustdoc
pages.


preview: https://turbopack-rust-docs-b6qta4xdq.vercel.sh/
rustdoc:
https://turbopack-rust-docs-b6qta4xdq.vercel.sh/rustdoc/index.html


Closes PACK-2475
Closes PACK-2468
parent 292ebad8
...@@ -477,6 +477,7 @@ jobs: ...@@ -477,6 +477,7 @@ jobs:
name: Deploy Turbopack docs name: Deploy Turbopack docs
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: [build] needs: [build]
continue-on-error: true
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
...@@ -485,6 +486,11 @@ jobs: ...@@ -485,6 +486,11 @@ jobs:
run: npm i -g vercel@latest run: npm i -g vercel@latest
- name: Install Rust - name: Install Rust
uses: ./.github/actions/setup-rust uses: ./.github/actions/setup-rust
- name: Setup mdBook
uses: peaceiris/actions-mdbook@v1
with:
mdbook-version: 'latest'
- uses: Swatinem/rust-cache@v2
- name: Deploy preview docs - name: Deploy preview docs
if: ${{ needs.build.outputs.isRelease != 'true' }} if: ${{ needs.build.outputs.isRelease != 'true' }}
run: ./scripts/deploy-turbopack-docs.sh run: ./scripts/deploy-turbopack-docs.sh
......
...@@ -108,6 +108,12 @@ jobs: ...@@ -108,6 +108,12 @@ jobs:
with: with:
components: rustfmt, clippy components: rustfmt, clippy
- name: Setup mdBook
uses: peaceiris/actions-mdbook@v1
if: ${{ inputs.skipNativeBuild != 'yes' || inputs.needsNextest == 'yes' || inputs.needsRust == 'yes' }}
with:
mdbook-version: 'latest'
- name: 'Install mold linker' - name: 'Install mold linker'
if: ${{ inputs.mold == 'yes' }} if: ${{ inputs.mold == 'yes' }}
run: | run: |
......
...@@ -101,9 +101,9 @@ impl Task for MinifyTask { ...@@ -101,9 +101,9 @@ impl Task for MinifyTask {
} }
} }
/// `inline: 3` breaks some codes. /// **NOTE** `inline: 3` breaks some codes.
/// ///
/// https://github.com/vercel/next.js/pull/57904 /// <https://github.com/vercel/next.js/pull/57904>
fn patch_opts(opts: &mut JsMinifyOptions) { fn patch_opts(opts: &mut JsMinifyOptions) {
opts.compress = BoolOrDataConfig::from_obj(TerserCompressorOptions { opts.compress = BoolOrDataConfig::from_obj(TerserCompressorOptions {
inline: Some(TerserInlineOption::Num(2)), inline: Some(TerserInlineOption::Num(2)),
......
...@@ -82,8 +82,10 @@ pub async fn get_issues<T: Send>(source: Vc<T>) -> Result<Arc<Vec<ReadRef<PlainI ...@@ -82,8 +82,10 @@ pub async fn get_issues<T: Send>(source: Vc<T>) -> Result<Arc<Vec<ReadRef<PlainI
Ok(Arc::new(issues.get_plain_issues().await?)) Ok(Arc::new(issues.get_plain_issues().await?))
} }
/// Collect [turbopack::core::diagnostics::Diagnostic] from given source, /// Reads the [turbopack_binding::turbopack::core::diagnostics::Diagnostic] held
/// returns [turbopack::core::diagnostics::PlainDiagnostic] /// by the given source and returns it as a
/// [turbopack_binding::turbopack::core::diagnostics::PlainDiagnostic]. It does
/// not consume any Diagnostics held by the source.
pub async fn get_diagnostics<T: Send>(source: Vc<T>) -> Result<Arc<Vec<ReadRef<PlainDiagnostic>>>> { pub async fn get_diagnostics<T: Send>(source: Vc<T>) -> Result<Arc<Vec<ReadRef<PlainDiagnostic>>>> {
let captured_diags = source.peek_diagnostics().await?; let captured_diags = source.peek_diagnostics().await?;
......
...@@ -87,7 +87,7 @@ pub fn init_heap_profiler() -> napi::Result<External<RefCell<Option<u32>>>> { ...@@ -87,7 +87,7 @@ pub fn init_heap_profiler() -> napi::Result<External<RefCell<Option<u32>>>> {
pub fn teardown_heap_profiler(_guard_external: External<RefCell<Option<u32>>>) {} pub fn teardown_heap_profiler(_guard_external: External<RefCell<Option<u32>>>) {}
/// Initialize tracing subscriber to emit traces. This configures subscribers /// Initialize tracing subscriber to emit traces. This configures subscribers
/// for Trace Event Format (https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview). /// for Trace Event Format <https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview>.
#[napi] #[napi]
pub fn init_custom_trace_subscriber( pub fn init_custom_trace_subscriber(
trace_out_file_path: Option<String>, trace_out_file_path: Option<String>,
......
...@@ -105,27 +105,28 @@ pub(crate) async fn collect_evaluated_chunk_group( ...@@ -105,27 +105,28 @@ pub(crate) async fn collect_evaluated_chunk_group(
} }
/// Returns a mapping of the dynamic imports for each module, if the import is /// Returns a mapping of the dynamic imports for each module, if the import is
/// wrapped in `next/dynamic`'s `dynamic()`. Refer https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports for the usecases. /// wrapped in `next/dynamic`'s `dynamic()`. Refer [documentation](https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports) for the usecases.
/// ///
/// If an import is specified as dynamic, next.js does few things: /// If an import is specified as dynamic, next.js does few things:
/// - Runs a next_dynamic transform to the source file (https://github.com/vercel/next.js/blob/ae1b89984d26b2af3658001fa19a19e1e77c312d/packages/next-swc/crates/next-transform-dynamic/src/lib.rs#L22) /// - Runs a next_dynamic [transform to the source file](https://github.com/vercel/next.js/blob/ae1b89984d26b2af3658001fa19a19e1e77c312d/packages/next-swc/crates/next-transform-dynamic/src/lib.rs#L22)
/// - This transform will inject `loadableGenerated` property, which contains the list of the import ids in the form of `${origin} -> ${imported}`. /// - This transform will [inject `loadableGenerated` property](https://github.com/vercel/next.js/blob/ae1b89984d26b2af3658001fa19a19e1e77c312d/packages/next-swc/crates/next-transform-dynamic/tests/fixture/wrapped-import/output-webpack-dev.js#L5),
/// (https://github.com/vercel/next.js/blob/ae1b89984d26b2af3658001fa19a19e1e77c312d/packages/next-swc/crates/next-transform-dynamic/tests/fixture/wrapped-import/output-webpack-dev.js#L5) /// which contains the list of the import ids in the form of `${origin} ->
/// ${imported}`.
/// - Emits `react-loadable-manifest.json` which contains the mapping of the /// - Emits `react-loadable-manifest.json` which contains the mapping of the
/// import ids to the chunk ids. /// import ids to the chunk ids.
/// - Webpack: (https://github.com/vercel/next.js/blob/ae1b89984d26b2af3658001fa19a19e1e77c312d/packages/next/src/build/webpack/plugins/react-loadable-plugin.ts) /// - Webpack: [implementation](https://github.com/vercel/next.js/blob/ae1b89984d26b2af3658001fa19a19e1e77c312d/packages/next/src/build/webpack/plugins/react-loadable-plugin.ts)
/// - Turbopack: ( https://github.com/vercel/next.js/pull/56389/files#diff-3cac9d9bfe73e0619e6407f21f6fe652da0719d0ec9074ff813ad3e416d0eb1a /// - Turbopack: [implementation 1](https://github.com/vercel/next.js/pull/56389/files#diff-3cac9d9bfe73e0619e6407f21f6fe652da0719d0ec9074ff813ad3e416d0eb1a),
/// / https://github.com/vercel/next.js/pull/56389/files#diff-791951bbe1fa09bcbad9be9173412d0848168f7d658758f11b6e8888a021552c /// [implementation 2](https://github.com/vercel/next.js/pull/56389/files#diff-791951bbe1fa09bcbad9be9173412d0848168f7d658758f11b6e8888a021552c),
/// / https://github.com/vercel/next.js/pull/56389/files#diff-c33f6895801329243dd3f627c69da259bcab95c2c9d12993152842591931ff01R557 /// [implementation 3](https://github.com/vercel/next.js/pull/56389/files#diff-c33f6895801329243dd3f627c69da259bcab95c2c9d12993152842591931ff01R557)
/// )
/// - When running an application, /// - When running an application,
/// - Server reads generated `react-loadable-manifest.json`, sets dynamicImportIds with the mapping of the import ids, and dynamicImports to the actual corresponding chunks. /// - Server reads generated `react-loadable-manifest.json`, sets dynamicImportIds with the mapping of the import ids, and dynamicImports to the actual corresponding chunks.
/// (https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/server/load-components.ts#L119 / /// [implementation 1](https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/server/load-components.ts#L119),
/// https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/server/render.tsx#L1417C7-L1420) /// [implementation 2](https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/server/render.tsx#L1417C7-L1420)
/// - Server embeds those into __NEXT_DATA__ and sent to the client. (https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/server/render.tsx#L1453) /// - Server embeds those into __NEXT_DATA__ and [send to the client.](https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/server/render.tsx#L1453)
/// - When client boots up, pass it to the client preload (https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/client/index.tsx#L943) /// - When client boots up, pass it to the [client preload](https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/client/index.tsx#L943)
/// - Loadable runtime injects preload fn to wait until all the dynamic components are being loaded, this ensures hydration mismatch won't occur /// - Loadable runtime [injects preload fn](https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/shared/lib/loadable.shared-runtime.tsx#L281)
/// (https://github.com/vercel/next.js/blob/ad42b610c25b72561ad367b82b1c7383fd2a5dd2/packages/next/src/shared/lib/loadable.shared-runtime.tsx#L281) /// to wait until all the dynamic components are being loaded, this ensures
/// hydration mismatch won't occur
pub(crate) async fn collect_next_dynamic_imports( pub(crate) async fn collect_next_dynamic_imports(
entry: Vc<Box<dyn EcmascriptChunkPlaceable>>, entry: Vc<Box<dyn EcmascriptChunkPlaceable>>,
) -> Result<IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>> { ) -> Result<IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>> {
......
...@@ -330,8 +330,7 @@ impl PagesProject { ...@@ -330,8 +330,7 @@ impl PagesProject {
} }
/// Returns a context specific to pages/api. /// Returns a context specific to pages/api.
/// This mimics the current configuration in next-dev. /// This mimics the current configuration in [next-dev](https://github.com/vercel/next.js/blob/9b4b0847ed4a1025e73bec16a9ee11766e632e14/packages/next/src/build/webpack-config.ts#L1381-L1385)
/// (https://github.com/vercel/next.js/blob/9b4b0847ed4a1025e73bec16a9ee11766e632e14/packages/next/src/build/webpack-config.ts#L1381-L1385)
#[turbo_tasks::function] #[turbo_tasks::function]
pub(super) fn api_module_context(self: Vc<Self>) -> Vc<ModuleAssetContext> { pub(super) fn api_module_context(self: Vc<Self>) -> Vc<ModuleAssetContext> {
ModuleAssetContext::new( ModuleAssetContext::new(
......
...@@ -525,8 +525,7 @@ impl Project { ...@@ -525,8 +525,7 @@ impl Project {
) )
} }
/// Emit a telemetry event corresponding to webpack configuration telemetry /// Emit a telemetry event corresponding to [webpack configuration telemetry](https://github.com/vercel/next.js/blob/9da305fe320b89ee2f8c3cfb7ecbf48856368913/packages/next/src/build/webpack-config.ts#L2516)
/// (https://github.com/vercel/next.js/blob/9da305fe320b89ee2f8c3cfb7ecbf48856368913/packages/next/src/build/webpack-config.ts#L2516)
/// to detect which feature is enabled. /// to detect which feature is enabled.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn collect_project_feature_telemetry(self: Vc<Self>) -> Result<Vc<()>> { async fn collect_project_feature_telemetry(self: Vc<Self>) -> Result<Vc<()>> {
......
...@@ -169,7 +169,7 @@ fn action_modifier() -> Vc<String> { ...@@ -169,7 +169,7 @@ fn action_modifier() -> Vc<String> {
Vc::cell("action".to_string()) Vc::cell("action".to_string())
} }
/// Traverses the entire module graph starting from [module], looking for magic /// Traverses the entire module graph starting from [Module], looking for magic
/// comment which identifies server actions. Every found server action will be /// comment which identifies server actions. Every found server action will be
/// returned along with the module which exports that action. /// returned along with the module which exports that action.
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -258,7 +258,7 @@ async fn to_rsc_context( ...@@ -258,7 +258,7 @@ async fn to_rsc_context(
} }
/// Our graph traversal visitor, which finds the primary modules directly /// Our graph traversal visitor, which finds the primary modules directly
/// referenced by [parent]. /// referenced by parent.
async fn get_referenced_modules( async fn get_referenced_modules(
(layer, module): (ActionLayer, Vc<Box<dyn Module>>), (layer, module): (ActionLayer, Vc<Box<dyn Module>>),
) -> Result<impl Iterator<Item = (ActionLayer, Vc<Box<dyn Module>>)> + Send> { ) -> Result<impl Iterator<Item = (ActionLayer, Vc<Box<dyn Module>>)> + Send> {
...@@ -291,7 +291,7 @@ pub fn parse_server_actions<C: Comments>( ...@@ -291,7 +291,7 @@ pub fn parse_server_actions<C: Comments>(
}) })
} }
/// Inspects the comments inside [module] looking for the magic actions comment. /// Inspects the comments inside [Module] looking for the magic actions comment.
/// If found, we return the mapping of every action's hashed id to the name of /// If found, we return the mapping of every action's hashed id to the name of
/// the exported action function. If not, we return a None. /// the exported action function. If not, we return a None.
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -318,7 +318,7 @@ async fn parse_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<OptionActionMap ...@@ -318,7 +318,7 @@ async fn parse_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<OptionActionMap
Ok(Vc::cell(Some(Vc::cell(actions)))) Ok(Vc::cell(Some(Vc::cell(actions))))
} }
/// Converts our cached [parsed_actions] call into a data type suitable for /// Converts our cached [parse_actions] call into a data type suitable for
/// collecting into a flat-mapped [IndexMap]. /// collecting into a flat-mapped [IndexMap].
async fn parse_actions_filter_map( async fn parse_actions_filter_map(
(layer, module): (ActionLayer, Vc<Box<dyn Module>>), (layer, module): (ActionLayer, Vc<Box<dyn Module>>),
......
...@@ -1110,8 +1110,7 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1110,8 +1110,7 @@ async fn directory_tree_to_entrypoints_internal_untraced(
Ok(Vc::cell(result)) Ok(Vc::cell(result))
} }
/// ref: https://github.com/vercel/next.js/blob/c390c1662bc79e12cf7c037dcb382ef5ead6e492/packages/next/src/build/entries.ts#L119 /// If path contains %5F, replace it with _. [reference](https://github.com/vercel/next.js/blob/c390c1662bc79e12cf7c037dcb382ef5ead6e492/packages/next/src/build/entries.ts#L119)
/// if path contains %5F, replace it with _.
fn get_underscore_normalized_path(path: &str) -> String { fn get_underscore_normalized_path(path: &str) -> String {
path.replace("%5F", "_") path.replace("%5F", "_")
} }
......
...@@ -251,7 +251,7 @@ pub fn is_metadata_route(mut route: &str) -> bool { ...@@ -251,7 +251,7 @@ pub fn is_metadata_route(mut route: &str) -> bool {
!page.ends_with("/page") && is_metadata_route_file(&page, &[], false) !page.ends_with("/page") && is_metadata_route_file(&page, &[], false)
} }
/// http://www.cse.yorku.ca/~oz/hash.html /// djb_2 hash implementation referenced from [here](http://www.cse.yorku.ca/~oz/hash.html)
fn djb2_hash(str: &str) -> u32 { fn djb2_hash(str: &str) -> u32 {
str.chars().fold(5381, |hash, c| { str.chars().fold(5381, |hash, c| {
((hash << 5).wrapping_add(hash)).wrapping_add(c as u32) // hash * 33 + c ((hash << 5).wrapping_add(hash)).wrapping_add(c as u32) // hash * 33 + c
......
#![allow(rustdoc::private_intra_doc_links)]
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use turbo_tasks::Vc; use turbo_tasks::Vc;
use turbopack_binding::turbopack::{ use turbopack_binding::turbopack::{
...@@ -9,8 +10,8 @@ use turbopack_binding::turbopack::{ ...@@ -9,8 +10,8 @@ use turbopack_binding::turbopack::{
ecmascript::chunk::EcmascriptChunkPlaceable, ecmascript::chunk::EcmascriptChunkPlaceable,
}; };
/// An [`EcmascriptClientReferenceModule`] is a marker module, used by the /// An [EcmascriptClientReferenceModule] is a marker module, used by the
/// [`EcmascriptClientReferenceProxyModule`] to indicate which client reference /// [super::ecmascript_client_reference_proxy_module::EcmascriptClientReferenceProxyModule] to indicate which client reference
/// should appear in the client reference manifest. /// should appear in the client reference manifest.
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct EcmascriptClientReferenceModule { pub struct EcmascriptClientReferenceModule {
...@@ -21,7 +22,7 @@ pub struct EcmascriptClientReferenceModule { ...@@ -21,7 +22,7 @@ pub struct EcmascriptClientReferenceModule {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl EcmascriptClientReferenceModule { impl EcmascriptClientReferenceModule {
/// Create a new [`EcmascriptClientReferenceModule`]. /// Create a new [EcmascriptClientReferenceModule].
/// ///
/// # Arguments /// # Arguments
/// ///
......
...@@ -443,10 +443,10 @@ pub struct ExperimentalConfig { ...@@ -443,10 +443,10 @@ pub struct ExperimentalConfig {
pub fetch_cache_key_prefix: Option<String>, pub fetch_cache_key_prefix: Option<String>,
pub isr_flush_to_disk: Option<bool>, pub isr_flush_to_disk: Option<bool>,
/// For use with `@next/mdx`. Compile MDX files using the new Rust compiler. /// For use with `@next/mdx`. Compile MDX files using the new Rust compiler.
/// @see https://nextjs.org/docs/app/api-reference/next-config-js/mdxRs /// @see [api reference](https://nextjs.org/docs/app/api-reference/next-config-js/mdxRs)
mdx_rs: Option<bool>, mdx_rs: Option<bool>,
/// A list of packages that should be treated as external in the RSC server /// A list of packages that should be treated as external in the RSC server
/// build. @see https://nextjs.org/docs/app/api-reference/next-config-js/server_components_external_packages /// build. @see [api reference](https://nextjs.org/docs/app/api-reference/next-config-js/server_components_external_packages)
pub server_components_external_packages: Option<Vec<String>>, pub server_components_external_packages: Option<Vec<String>>,
pub strict_next_head: Option<bool>, pub strict_next_head: Option<bool>,
pub swc_plugins: Option<Vec<(String, serde_json::Value)>>, pub swc_plugins: Option<Vec<(String, serde_json::Value)>>,
...@@ -461,8 +461,7 @@ pub struct ExperimentalConfig { ...@@ -461,8 +461,7 @@ pub struct ExperimentalConfig {
pub optimistic_client_cache: Option<bool>, pub optimistic_client_cache: Option<bool>,
pub middleware_prefetch: Option<MiddlewarePrefetchType>, pub middleware_prefetch: Option<MiddlewarePrefetchType>,
/// optimizeCss can be boolean or critters' option object /// optimizeCss can be boolean or critters' option object
/// Use Record<string, unknown> as critters doesn't export its Option type /// Use Record<string, unknown> as critters doesn't export its Option type ([link](https://github.com/GoogleChromeLabs/critters/blob/a590c05f9197b656d2aeaae9369df2483c26b072/packages/critters/src/index.d.ts))
/// https://github.com/GoogleChromeLabs/critters/blob/a590c05f9197b656d2aeaae9369df2483c26b072/packages/critters/src/index.d.ts
pub optimize_css: Option<serde_json::Value>, pub optimize_css: Option<serde_json::Value>,
pub next_script_workers: Option<bool>, pub next_script_workers: Option<bool>,
pub web_vitals_attribution: Option<Vec<String>>, pub web_vitals_attribution: Option<Vec<String>>,
...@@ -519,7 +518,7 @@ pub struct ExperimentalConfig { ...@@ -519,7 +518,7 @@ pub struct ExperimentalConfig {
trust_host_header: Option<bool>, trust_host_header: Option<bool>,
/// Generate Route types and enable type checking for Link and Router.push, /// Generate Route types and enable type checking for Link and Router.push,
/// etc. This option requires `appDir` to be enabled first. /// etc. This option requires `appDir` to be enabled first.
/// @see https://nextjs.org/docs/app/api-reference/next-config-js/typedRoutes /// @see [api reference](https://nextjs.org/docs/app/api-reference/next-config-js/typedRoutes)
typed_routes: Option<bool>, typed_routes: Option<bool>,
url_imports: Option<serde_json::Value>, url_imports: Option<serde_json::Value>,
/// This option is to enable running the Webpack build in a worker thread /// This option is to enable running the Webpack build in a worker thread
......
...@@ -137,7 +137,7 @@ fn calc_average_width(font: &mut Font<DynamicFontTableProvider>) -> Option<f32> ...@@ -137,7 +137,7 @@ fn calc_average_width(font: &mut Font<DynamicFontTableProvider>) -> Option<f32>
) )
} }
/// From https://github.com/vercel/next.js/blob/dbdf47cf617b8d7213ffe1ff28318ea8eb88c623/packages/font/src/local/pick-font-file-for-fallback-generation.ts#L59 /// From [implementation](https://github.com/vercel/next.js/blob/dbdf47cf617b8d7213ffe1ff28318ea8eb88c623/packages/font/src/local/pick-font-file-for-fallback-generation.ts#L59)
/// ///
/// If multiple font files are provided for a font family, we need to pick /// If multiple font files are provided for a font family, we need to pick
/// one to use for the automatic fallback generation. This function returns /// one to use for the automatic fallback generation. This function returns
...@@ -196,7 +196,7 @@ fn pick_font_for_fallback_generation( ...@@ -196,7 +196,7 @@ fn pick_font_for_fallback_generation(
} }
} }
/// From https://github.com/vercel/next.js/blob/dbdf47cf617b8d7213ffe1ff28318ea8eb88c623/packages/font/src/local/pick-font-file-for-fallback-generation.ts#L18 /// From[implementation](https://github.com/vercel/next.js/blob/dbdf47cf617b8d7213ffe1ff28318ea8eb88c623/packages/font/src/local/pick-font-file-for-fallback-generation.ts#L18)
/// ///
/// Get the distance from normal (400) weight for the provided weight. /// Get the distance from normal (400) weight for the provided weight.
/// If it's not a variable font we can just return the distance. /// If it's not a variable font we can just return the distance.
...@@ -227,10 +227,10 @@ fn get_distance_from_normal_weight(weight: &Option<FontWeight>) -> Result<f64> { ...@@ -227,10 +227,10 @@ fn get_distance_from_normal_weight(weight: &Option<FontWeight>) -> Result<f64> {
}) })
} }
/// From https://github.com/vercel/next.js/blob/dbdf47cf617b8d7213ffe1ff28318ea8eb88c623/packages/font/src/local/pick-font-file-for-fallback-generation.ts#L6 /// From [implementation](https://github.com/vercel/next.js/blob/dbdf47cf617b8d7213ffe1ff28318ea8eb88c623/packages/font/src/local/pick-font-file-for-fallback-generation.ts#L6)
/// ///
/// Convert the weight string to a number so it can be used for comparison. /// Convert the weight string to a number so it can be used for comparison.
/// Weights can be defined as a number, 'normal' or 'bold'. https://developer.mozilla.org/docs/Web/CSS/@font-face/font-weight /// Weights can be defined as a number, 'normal' or 'bold'. [reference](https://developer.mozilla.org/docs/Web/CSS/@font-face/font-weight)
fn parse_weight_string(weight_str: &str) -> Result<f64> { fn parse_weight_string(weight_str: &str) -> Result<f64> {
if weight_str == "normal" { if weight_str == "normal" {
Ok(NORMAL_WEIGHT) Ok(NORMAL_WEIGHT)
......
...@@ -64,7 +64,7 @@ pub(crate) async fn get_scoped_font_family( ...@@ -64,7 +64,7 @@ pub(crate) async fn get_scoped_font_family(
Ok(Vc::cell(format!("__{}_{}", font_family_name, hash))) Ok(Vc::cell(format!("__{}_{}", font_family_name, hash)))
} }
/// Returns a [[Vc<String>]] uniquely identifying the request for the font. /// Returns a [Vc] for [String] uniquely identifying the request for the font.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn get_request_id(font_family: Vc<String>, request_hash: Vc<u32>) -> Result<Vc<String>> { pub async fn get_request_id(font_family: Vc<String>, request_hash: Vc<u32>) -> Result<Vc<String>> {
Ok(Vc::cell(format!( Ok(Vc::cell(format!(
......
...@@ -5,10 +5,8 @@ use turbopack_binding::{ ...@@ -5,10 +5,8 @@ use turbopack_binding::{
turbopack::core::diagnostics::{Diagnostic, DiagnosticPayload}, turbopack::core::diagnostics::{Diagnostic, DiagnosticPayload},
}; };
/// A struct represent telemetry event if certain feature of next.js /// A structure that keeps track of whether a particular Next.js feature is
/// is enabled, such as next.config.swcMinify. /// enabled for the telemetry. The original implementation code can be found at the following [link](https://github.com/vercel/next.js/blob/9da305fe320b89ee2f8c3cfb7ecbf48856368913/packages/next/src/build/webpack-config.ts#L2516).
/// This is an equivalent representation of the following code:
/// https://github.com/vercel/next.js/blob/9da305fe320b89ee2f8c3cfb7ecbf48856368913/packages/next/src/build/webpack-config.ts#L2516
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct NextFeatureTelemetry { pub struct NextFeatureTelemetry {
pub event_name: String, pub event_name: String,
......
...@@ -333,8 +333,7 @@ async fn get_pages_structure_for_root_directory( ...@@ -333,8 +333,7 @@ async fn get_pages_structure_for_root_directory(
} }
/// Handles a directory in the pages directory (or the pages directory itself). /// Handles a directory in the pages directory (or the pages directory itself).
/// Calls itself recursively for sub directories or the /// Calls itself recursively for sub directories.
/// [create_page_source_for_file] method for files.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn get_pages_structure_for_directory( async fn get_pages_structure_for_directory(
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
......
...@@ -65,7 +65,7 @@ pub async fn get_typescript_transform_options( ...@@ -65,7 +65,7 @@ pub async fn get_typescript_transform_options(
} }
/// Build the transform options for the decorators. /// Build the transform options for the decorators.
/// [TODO]: Currnently only typescript's legacy decorators are supported /// **TODO** Currnently only typescript's legacy decorators are supported
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn get_decorators_transform_options( pub async fn get_decorators_transform_options(
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
......
...@@ -19,7 +19,7 @@ use turbopack_binding::swc::core::{ ...@@ -19,7 +19,7 @@ use turbopack_binding::swc::core::{
/// Creates a SWC visitor to transform `next/dynamic` calls to have the /// Creates a SWC visitor to transform `next/dynamic` calls to have the
/// corresponding `loadableGenerated` property. /// corresponding `loadableGenerated` property.
/// ///
/// [NOTE] We do not use `NextDynamicMode::Turbopack` yet. It isn't compatible /// **NOTE** We do not use `NextDynamicMode::Turbopack` yet. It isn't compatible
/// with current loadable manifest, which causes hydration errors. /// with current loadable manifest, which causes hydration errors.
pub fn next_dynamic( pub fn next_dynamic(
is_development: bool, is_development: bool,
......
...@@ -44,7 +44,8 @@ pub struct Options { ...@@ -44,7 +44,8 @@ pub struct Options {
} }
/// A visitor that transforms given module to use module proxy if it's a React /// A visitor that transforms given module to use module proxy if it's a React
/// server component. [NOTE] Turbopack uses ClientDirectiveTransformer for the /// server component.
/// **NOTE** Turbopack uses ClientDirectiveTransformer for the
/// same purpose, so does not run this transform. /// same purpose, so does not run this transform.
struct ReactServerComponents<C: Comments> { struct ReactServerComponents<C: Comments> {
is_react_server_layer: bool, is_react_server_layer: bool,
......
//! The original transform is available on the Next.js repository: //! The original transform is available on the [Next.js repository](https://github.com/vercel/next.js/blob/f7fecf00cb40c2f784387ff8ccc5e213b8bdd9ca/packages/next-swc/crates/core/src/next_ssg.rs):
//! https://github.com/vercel/next.js/blob/f7fecf00cb40c2f784387ff8ccc5e213b8bdd9ca/packages/next-swc/crates/core/src/next_ssg.rs
//! //!
//! This version adds support for eliminating client-side exports only. //! This version adds support for eliminating client-side exports only.
//! [TODO] may consolidate into next_ssg //! **TODO** may consolidate into next_ssg
use std::{cell::RefCell, mem::take, rc::Rc}; use std::{cell::RefCell, mem::take, rc::Rc};
......
[book]
authors = []
language = "en"
multilingual = false
src = "src"
title = "Turbopack"
# Turbopack
Welcome to an overview of the Turbopack documentation.
Currently it's work in progress, the only package available is [Turbo tasks-fs](turbo_tasks_fs/index.html)
[comment]: # 'Temporary index page document'
# Turbopack
Turbopack is an incremental bundler optimized for JavaScript and TypeScript, written in Rust.
This document aims to cover documentation for developing/debugging Turbopack. For information on using Turbopack for Next.js applications, see the Next.js [documentation](https://nextjs.org/docs).
### What to read
If this is your first time setting up a development environment, recommend that you read [Setup dev environment](setup.md) and [How to run tests](how_to_run_tests.md) first.
The implementation of Next.js features in Turbopack is covered in the `Next.js integration` section, and `How Turbopack works` covers high level documentation for how turbopack's internal works.
Lastly, [API references](api.md) contains all of Turbopack-related package's api documentation based on rustdoc.
# Summary
[Introduction](README.md)
# Getting started
- [Setup dev environment](setup.md)
- [How to run tests](how_to_run_tests.md)
# How Turbopack works
- [Architecture](architecture.md)
# Next.js integration
- [Turbopack binding](turbopack_binding.md)
## Custom transforms
- [Next/dynamic](next_dynamic.md)
- [React server components](rsc.md)
# Appendix
- [API references](api.md)
- [Writing documentation](documentation.md)
# API references
Turbopack uses code comments and rustdoc to document the API. The full package documentation can be found [here](rustdoc/index.html).
The list below are packages and brief descriptions that you may want to refer to when first approaching the code.
- [napi](rustdoc/next_swc_napi/index.html): NAPI bindings to make Turbopack and SWC's features available in JS code in Next.js
- [next-custom-transforms](rustdoc/next_custom_transforms/index.html): Collection of SWC transform visitor implementations for features provided by Next.js
- [next_api](rustdoc/next_api/index.html): Linking the interfaces and data structures of the NAPI bindings with the actual Turbopack's next.js feature implementation interfaces
- [next_core](rustdoc/next_core/index.html): Support and implementation of Next.js features in Turbopack
# Writing documentation for Turbopack
Turbopack has two main types of documentation. One is a description of the code and APIs, and the other is a high-level description of the overall behavior. Since there is no [way](https://github.com/rust-lang/rust/issues/66249) to integrate with rustdoc yet, we deploy mdbook and rustdoc together with a script.
## Write a general overview document
Files written in markdown format in `packages/next-swc/docs/src` can be read by [mdbook](https://rust-lang.github.io/mdBook/).(Like the page you're looking at now)
## Write a rustdoc comment
If you write a [documentation comment](https://doc.rust-lang.org/reference/comments.html) in your code, it will be included in the documentation generated by rustdoc. The full index can be found [here](https://turbopack-rust-docs.vercel.sh/rustdoc/index.html), and individual packages can be read via `https://turbopack-rust-docs.vercel.sh/rustdoc/${pkg_name}/index.html`.
## Build the documentation
The `scripts/deploy-turbopack-docs.sh` script bundles the mdbook and rustdoc and deploys them. You can use it locally as a build script because it won't run the deployment if it doesn't have a token. The script runs a rustdoc build followed by an mdbook build, and then copies the output of the rustdoc build under `mdbook/rustdoc`.
# React server components
...@@ -12,7 +12,12 @@ else ...@@ -12,7 +12,12 @@ else
fi fi
fi fi
RUSTDOCFLAGS="-Z unstable-options --index-page $(pwd)/packages/next-swc/docs/index.md" cargo doc -p turbo-tasks-fs --no-deps mdbook build --dest-dir $(pwd)/target/mdbook ./packages/next-swc/docs
PACKAGES="-p next-swc-napi -p next-api -p next-build -p next-core -p next-custom-transforms"
RUSTDOCFLAGS="-Z unstable-options --enable-index-page" cargo doc $PACKAGES --no-deps --document-private-items
cp -r $(pwd)/target/doc $(pwd)/target/mdbook/rustdoc
if [ -z ${VERCEL_API_TOKEN+x} ]; then if [ -z ${VERCEL_API_TOKEN+x} ]; then
echo "VERCEL_API_TOKEN was not providing, skipping..." echo "VERCEL_API_TOKEN was not providing, skipping..."
...@@ -20,7 +25,7 @@ if [ -z ${VERCEL_API_TOKEN+x} ]; then ...@@ -20,7 +25,7 @@ if [ -z ${VERCEL_API_TOKEN+x} ]; then
fi fi
DOCS_OUTDIR="$(pwd)/target/doc" DOCS_OUTDIR="$(pwd)/target/mdbook"
PROJECT="turbopack-rust-docs" PROJECT="turbopack-rust-docs"
echo "Deploying directory $DOCS_OUTDIR as $PROJECT to Vercel..." echo "Deploying directory $DOCS_OUTDIR as $PROJECT to Vercel..."
......
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