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

next analyze: annotate polyfill modules in UI (#86062)

For small routes, it can appear like the polyfill chunk takes up a sizable amount of data, but `polyfill-nomodule.js` is only sent to legacy browsers. This makes it clearer.

This PR enhances the bundle analyzer by adding visual indicators for polyfill chunks, and noting they're conditionally sent to modern or legacy browsers. The changes include:

- Adds a source map to polyfill chunks (for the large pre-bundled input only)
- Visually distinguished polyfill chunks in the treemap by lightening their color
- Added a "Polyfill" badge (other badges coming soon!) with text when viewing polyfill chunk details

<img width="388" height="227" alt="image" src="https://github.com/user-attachments/assets/bcebfba6-1e10-459a-9364-b6b8197cd3df" />

Fixes PACK-5826
parent b53beca2
...@@ -32,6 +32,8 @@ ...@@ -32,6 +32,8 @@
--sidebar-accent-foreground: oklch(0.205 0 0); --sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0); --sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0); --sidebar-ring: oklch(0.708 0 0);
--polyfill: #5f707f;
--polyfill-foreground: #ffffff;
} }
.dark { .dark {
...@@ -62,6 +64,8 @@ ...@@ -62,6 +64,8 @@
--sidebar-accent-foreground: oklch(0.985 0 0); --sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(0.269 0 0); --sidebar-border: oklch(0.269 0 0);
--sidebar-ring: oklch(0.439 0 0); --sidebar-ring: oklch(0.439 0 0);
--polyfill: #5f707f;
--polyfill-foreground: #ffffff;
} }
@theme inline { @theme inline {
...@@ -98,6 +102,8 @@ ...@@ -98,6 +102,8 @@
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground); --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border); --color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring); --color-sidebar-ring: var(--sidebar-ring);
--color-polyfill: var(--polyfill);
--color-polyfill-foreground: var(--polyfill-foreground);
} }
@layer base { @layer base {
......
...@@ -14,6 +14,8 @@ import { Input } from '@/components/ui/input' ...@@ -14,6 +14,8 @@ import { Input } from '@/components/ui/input'
import { Skeleton, TreemapSkeleton } from '@/components/ui/skeleton' import { Skeleton, TreemapSkeleton } from '@/components/ui/skeleton'
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
import { AnalyzeData, ModulesData } from '@/lib/analyze-data' import { AnalyzeData, ModulesData } from '@/lib/analyze-data'
import { SpecialModule } from '@/lib/types'
import { getSpecialModuleType } from '@/lib/utils'
function formatBytes(bytes: number): string { function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B' if (bytes === 0) return '0 B'
...@@ -137,6 +139,11 @@ export default function Home() { ...@@ -137,6 +139,11 @@ export default function Home() {
const isAnyLoading = isAnalyzeLoading || isModulesLoading const isAnyLoading = isAnalyzeLoading || isModulesLoading
const rootSourceIndex = getRootSourceIndex(analyzeData) const rootSourceIndex = getRootSourceIndex(analyzeData)
const specialModuleType = getSpecialModuleType(
analyzeData,
selectedSourceIndex
)
return ( return (
<main <main
className="h-screen flex flex-col bg-background" className="h-screen flex flex-col bg-background"
...@@ -289,12 +296,39 @@ export default function Home() { ...@@ -289,12 +296,39 @@ export default function Home() {
{selectedSourceIndex != null && {selectedSourceIndex != null &&
analyzeData.source(selectedSourceIndex) && ( analyzeData.source(selectedSourceIndex) && (
<> <>
<p className="text-xs text-muted-foreground mt-2"> <dl className="space-y-2">
<div>
<dt className="text-xs text-muted-foreground inline">
Output Size:{' '} Output Size:{' '}
</dt>
<dd className="text-xs text-muted-foreground inline">
{formatBytes( {formatBytes(
analyzeData.getSourceOutputSize(selectedSourceIndex) analyzeData.getSourceOutputSize(
selectedSourceIndex
)
)} )}
</p> </dd>
</div>
{(specialModuleType === SpecialModule.POLYFILL_MODULE ||
specialModuleType ===
SpecialModule.POLYFILL_NOMODULE) && (
<div className="flex items-center gap-2">
<dt className="inline-flex items-center rounded-md bg-polyfill/10 dark:bg-polyfill/30 px-2 py-1 text-xs font-medium text-polyfill dark:text-polyfill-foreground ring-1 ring-inset ring-polyfill/20 shrink-0">
Polyfill
</dt>
<dd className="text-xs text-muted-foreground">
Next.js built-in polyfills
{specialModuleType ===
SpecialModule.POLYFILL_NOMODULE ? (
<>
. <code>polyfill-nomodule.js</code> is only
sent to legacy browsers.
</>
) : null}
</dd>
</div>
)}
</dl>
{modulesData && ( {modulesData && (
<ImportChain <ImportChain
key={selectedSourceIndex} key={selectedSourceIndex}
......
'use client' 'use client'
import { darken, lighten } from 'polished' import { darken, lighten, readableColor } from 'polished'
import type React from 'react' import type React from 'react'
import { useEffect, useMemo, useRef, useState } from 'react' import { useEffect, useMemo, useRef, useState } from 'react'
import type { AnalyzeData } from '@/lib/analyze-data' import type { AnalyzeData } from '@/lib/analyze-data'
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
type LayoutNode, type LayoutNode,
type LayoutNodeInfo, type LayoutNodeInfo,
} from '@/lib/treemap-layout' } from '@/lib/treemap-layout'
import { SpecialModule } from '@/lib/types'
interface TreemapVisualizerProps { interface TreemapVisualizerProps {
analyzeData: AnalyzeData analyzeData: AnalyzeData
...@@ -23,6 +24,8 @@ interface TreemapVisualizerProps { ...@@ -23,6 +24,8 @@ interface TreemapVisualizerProps {
onHoveredNodeChangeDelayed?: (nodeInfo: LayoutNodeInfo | null) => void onHoveredNodeChangeDelayed?: (nodeInfo: LayoutNodeInfo | null) => void
searchQuery?: string searchQuery?: string
filterSource?: (sourceIndex: number) => boolean filterSource?: (sourceIndex: number) => boolean
isModulePolyfillChunk?: (sourceIndex: number) => boolean
isNoModulePolyfillChunk?: (sourceIndex: number) => boolean
} }
function getFileColor(node: { function getFileColor(node: {
...@@ -33,12 +36,17 @@ function getFileColor(node: { ...@@ -33,12 +36,17 @@ function getFileColor(node: {
server?: boolean server?: boolean
client?: boolean client?: boolean
traced?: boolean traced?: boolean
specialModuleType: SpecialModule | null
}): string { }): string {
const { js, css, json, asset, client, traced } = node const { js, css, json, asset, client, traced, specialModuleType } = node
if (isPolyfill(specialModuleType)) {
return '#5f707f'
}
let color = '#9ca3af' // gray-400 default let color = '#9ca3af' // gray-400 default
if (js) color = '#0068d6' if (js) color = '#4682b4'
if (css) color = '#663399' if (css) color = '#8b7d9e'
if (json) color = '#297a3a' if (json) color = '#297a3a'
if (asset) color = '#da2f35' if (asset) color = '#da2f35'
...@@ -54,6 +62,13 @@ function getFileColor(node: { ...@@ -54,6 +62,13 @@ function getFileColor(node: {
return color return color
} }
function isPolyfill(specialModuleType: SpecialModule | null): boolean {
return (
specialModuleType === SpecialModule.POLYFILL_MODULE ||
specialModuleType === SpecialModule.POLYFILL_NOMODULE
)
}
function findNodeAtPosition( function findNodeAtPosition(
node: LayoutNode, node: LayoutNode,
x: number, x: number,
...@@ -320,7 +335,8 @@ function drawTreemap( ...@@ -320,7 +335,8 @@ function drawTreemap(
ctx.strokeRect(rect.x, rect.y, rect.width, rect.height) ctx.strokeRect(rect.x, rect.y, rect.width, rect.height)
if (rect.width > 60 && rect.height > 30) { if (rect.width > 60 && rect.height > 30) {
ctx.fillStyle = colors.text const textColor = readableColor(color)
ctx.fillStyle = textColor
ctx.font = '12px sans-serif' ctx.font = '12px sans-serif'
ctx.textAlign = 'center' ctx.textAlign = 'center'
ctx.textBaseline = 'middle' ctx.textBaseline = 'middle'
...@@ -516,6 +532,7 @@ function wrapLayoutWithAncestorsUsingIndices( ...@@ -516,6 +532,7 @@ function wrapLayoutWithAncestorsUsingIndices(
titleBarHeight: titleBarHeight, titleBarHeight: titleBarHeight,
children: [currentNode], children: [currentNode],
sourceIndex: ancestorIndex, sourceIndex: ancestorIndex,
specialModuleType: null,
} }
currentNode = ancestorNode currentNode = ancestorNode
...@@ -539,6 +556,7 @@ function wrapLayoutWithAncestorsUsingIndices( ...@@ -539,6 +556,7 @@ function wrapLayoutWithAncestorsUsingIndices(
titleBarHeight: minTitleBarHeight, titleBarHeight: minTitleBarHeight,
children: [currentNode], children: [currentNode],
sourceIndex: rootIndex, sourceIndex: rootIndex,
specialModuleType: null,
} }
return rootNode return rootNode
......
...@@ -388,6 +388,20 @@ export class AnalyzeData { ...@@ -388,6 +388,20 @@ export class AnalyzeData {
return { client, server, traced, js, css, json, asset } return { client, server, traced, js, css, json, asset }
} }
isPolyfillModule(index: number): boolean {
const fullSourcePath = this.getFullSourcePath(index)
return fullSourcePath.endsWith(
'node_modules/next/dist/build/polyfills/polyfill-module.js'
)
}
isPolyfillNoModule(index: number): boolean {
const fullSourcePath = this.getFullSourcePath(index)
return fullSourcePath.endsWith(
'node_modules/next/dist/build/polyfills/polyfill-nomodule.js'
)
}
// Get the raw header for debugging // Get the raw header for debugging
getRawAnalyzeHeader(): AnalyzeDataHeader { getRawAnalyzeHeader(): AnalyzeDataHeader {
return this.analyzeHeader return this.analyzeHeader
......
import type { AnalyzeData } from './analyze-data' import type { AnalyzeData } from './analyze-data'
import { layoutTreemap } from './layout-treemap' import { layoutTreemap } from './layout-treemap'
import { SpecialModule } from './types'
import { getSpecialModuleType } from './utils'
export interface LayoutRect { export interface LayoutRect {
x: number x: number
...@@ -18,6 +20,7 @@ export interface LayoutNode extends LayoutNodeInfo { ...@@ -18,6 +20,7 @@ export interface LayoutNode extends LayoutNodeInfo {
size: number size: number
rect: LayoutRect rect: LayoutRect
type: 'file' | 'directory' | 'collapsed-directory' type: 'file' | 'directory' | 'collapsed-directory'
specialModuleType: SpecialModule | null
titleBarHeight?: number titleBarHeight?: number
children?: LayoutNode[] children?: LayoutNode[]
itemCount?: number itemCount?: number
...@@ -141,6 +144,7 @@ function computeTreemapLayoutFromAnalyzeInternal( ...@@ -141,6 +144,7 @@ function computeTreemapLayoutFromAnalyzeInternal(
type: 'file', type: 'file',
rect, rect,
sourceIndex, sourceIndex,
specialModuleType: getSpecialModuleType(analyzeData, sourceIndex),
...analyzeData.getSourceFlags(sourceIndex), ...analyzeData.getSourceFlags(sourceIndex),
} }
} }
...@@ -178,6 +182,7 @@ function computeTreemapLayoutFromAnalyzeInternal( ...@@ -178,6 +182,7 @@ function computeTreemapLayoutFromAnalyzeInternal(
itemCount: countDescendants(sourceIndex), itemCount: countDescendants(sourceIndex),
children: [], children: [],
sourceIndex, sourceIndex,
specialModuleType: null,
} }
} }
...@@ -211,6 +216,7 @@ function computeTreemapLayoutFromAnalyzeInternal( ...@@ -211,6 +216,7 @@ function computeTreemapLayoutFromAnalyzeInternal(
titleBarHeight, titleBarHeight,
children: [], children: [],
sourceIndex, sourceIndex,
specialModuleType: null,
} }
} }
...@@ -240,6 +246,7 @@ function computeTreemapLayoutFromAnalyzeInternal( ...@@ -240,6 +246,7 @@ function computeTreemapLayoutFromAnalyzeInternal(
titleBarHeight, titleBarHeight,
children: layoutChildren, children: layoutChildren,
sourceIndex, sourceIndex,
specialModuleType: null,
} }
} }
......
...@@ -33,3 +33,8 @@ export interface RouteManifest { ...@@ -33,3 +33,8 @@ export interface RouteManifest {
staticRoutes: Array<Route> staticRoutes: Array<Route>
dynamicRoutes: Array<Route> dynamicRoutes: Array<Route>
} }
export enum SpecialModule {
POLYFILL_MODULE,
POLYFILL_NOMODULE,
}
import { type ClassValue, clsx } from 'clsx' import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge' import { twMerge } from 'tailwind-merge'
import { SpecialModule } from './types'
import { AnalyzeData } from './analyze-data'
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)) return twMerge(clsx(inputs))
...@@ -8,3 +10,19 @@ export function cn(...inputs: ClassValue[]) { ...@@ -8,3 +10,19 @@ export function cn(...inputs: ClassValue[]) {
export function jsonFetcher<T>(url: string): Promise<T> { export function jsonFetcher<T>(url: string): Promise<T> {
return fetch(url).then((res) => res.json()) return fetch(url).then((res) => res.json())
} }
export function getSpecialModuleType(
analyzeData: AnalyzeData | undefined,
sourceIndex: number | null
): SpecialModule | null {
if (!analyzeData || sourceIndex == null) return null
const path = analyzeData.source(sourceIndex)?.path || ''
if (path.endsWith('polyfill-module.js')) {
return SpecialModule.POLYFILL_MODULE
} else if (path.endsWith('polyfill-nomodule.js')) {
return SpecialModule.POLYFILL_NOMODULE
}
return null
}
...@@ -21,6 +21,8 @@ ...@@ -21,6 +21,8 @@
--border: oklch(0.922 0 0); --border: oklch(0.922 0 0);
--input: oklch(0.922 0 0); --input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0); --ring: oklch(0.708 0 0);
--polyfill: oklch(0.478 0.0185 252.37);
--polyfill-foreground: oklch(0.99 0 0);
--radius: 0.625rem; --radius: 0.625rem;
} }
...@@ -42,6 +44,8 @@ ...@@ -42,6 +44,8 @@
--border: oklch(0.269 0 0); --border: oklch(0.269 0 0);
--input: oklch(0.269 0 0); --input: oklch(0.269 0 0);
--ring: oklch(0.439 0 0); --ring: oklch(0.439 0 0);
--polyfill: oklch(0.478 0.0185 252.37);
--polyfill-foreground: oklch(0.99 0 0);
} }
@theme inline { @theme inline {
...@@ -64,6 +68,8 @@ ...@@ -64,6 +68,8 @@
--color-border: var(--border); --color-border: var(--border);
--color-input: var(--input); --color-input: var(--input);
--color-ring: var(--ring); --color-ring: var(--ring);
--color-polyfill: var(--polyfill);
--color-polyfill-foreground: var(--polyfill-foreground);
--radius-sm: calc(var(--radius) - 4px); --radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px); --radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius); --radius-lg: var(--radius);
......
...@@ -367,6 +367,7 @@ pub async fn analyze_output_assets(output_assets: Vc<OutputAssets>) -> Result<Vc ...@@ -367,6 +367,7 @@ pub async fn analyze_output_assets(output_assets: Vc<OutputAssets>) -> Result<Vc
// Skip source maps. // Skip source maps.
continue; continue;
} }
let output_file_index = builder.add_output_file(AnalyzeOutputFile { filename }); let output_file_index = builder.add_output_file(AnalyzeOutputFile { filename });
let chunk_parts = split_output_asset_into_parts(*asset).await?; let chunk_parts = split_output_asset_into_parts(*asset).await?;
for chunk_part in chunk_parts { for chunk_part in chunk_parts {
......
...@@ -62,14 +62,16 @@ use turbopack_core::{ ...@@ -62,14 +62,16 @@ use turbopack_core::{
chunk_group_info::{ChunkGroup, ChunkGroupEntry}, chunk_group_info::{ChunkGroup, ChunkGroupEntry},
}, },
output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced}, output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced},
raw_output::RawOutput,
reference::all_assets_from_entries, reference::all_assets_from_entries,
reference_type::{CommonJsReferenceSubType, CssReferenceSubType, ReferenceType}, reference_type::{CommonJsReferenceSubType, CssReferenceSubType, ReferenceType},
resolve::{origin::PlainResolveOrigin, parse::Request, pattern::Pattern}, resolve::{origin::PlainResolveOrigin, parse::Request, pattern::Pattern},
source::Source, source::Source,
source_map::SourceMapAsset,
virtual_output::VirtualOutputAsset, virtual_output::VirtualOutputAsset,
}; };
use turbopack_ecmascript::resolve::cjs_resolve; use turbopack_ecmascript::{
resolve::cjs_resolve, single_file_ecmascript_output::SingleFileEcmascriptOutput,
};
use crate::{ use crate::{
dynamic_imports::{NextDynamicChunkAvailability, collect_next_dynamic_chunks}, dynamic_imports::{NextDynamicChunkAvailability, collect_next_dynamic_chunks},
...@@ -1300,11 +1302,11 @@ impl AppEndpoint { ...@@ -1300,11 +1302,11 @@ impl AppEndpoint {
let manifest_path_prefix = &app_entry.original_name; let manifest_path_prefix = &app_entry.original_name;
// polyfill-nomodule.js is a pre-compiled asset distributed as part of next, // polyfill-nomodule.js is a pre-compiled asset distributed as part of next
// load it as a RawModule.
let next_package = get_next_package(project.project_path().owned().await?).await?; let next_package = get_next_package(project.project_path().owned().await?).await?;
let polyfill_source = let polyfill_source_path =
FileSource::new(next_package.join("dist/build/polyfills/polyfill-nomodule.js")?); next_package.join("dist/build/polyfills/polyfill-nomodule.js")?;
let polyfill_source = FileSource::new(polyfill_source_path.clone());
let polyfill_output_path = client_chunking_context let polyfill_output_path = client_chunking_context
.chunk_path( .chunk_path(
Some(Vc::upcast(polyfill_source)), Some(Vc::upcast(polyfill_source)),
...@@ -1314,13 +1316,26 @@ impl AppEndpoint { ...@@ -1314,13 +1316,26 @@ impl AppEndpoint {
) )
.owned() .owned()
.await?; .await?;
let polyfill_output_asset = ResolvedVc::upcast(
RawOutput::new(polyfill_output_path, Vc::upcast(polyfill_source)) let polyfill_output = SingleFileEcmascriptOutput::new(
polyfill_output_path.clone(),
polyfill_source_path,
Vc::upcast(polyfill_source),
)
.to_resolved() .to_resolved()
.await?, .await?;
);
let polyfill_output_asset = ResolvedVc::upcast(polyfill_output);
client_assets.insert(polyfill_output_asset); client_assets.insert(polyfill_output_asset);
let polyfill_source_map_asset = SourceMapAsset::new_fixed(
polyfill_output_path.clone(),
*ResolvedVc::upcast(polyfill_output),
)
.to_resolved()
.await?;
client_assets.insert(ResolvedVc::upcast(polyfill_source_map_asset));
let client_assets: ResolvedVc<OutputAssets> = let client_assets: ResolvedVc<OutputAssets> =
ResolvedVc::cell(client_assets.into_iter().collect::<Vec<_>>()); ResolvedVc::cell(client_assets.into_iter().collect::<Vec<_>>());
......
...@@ -9,7 +9,7 @@ use turbo_tasks::{ ...@@ -9,7 +9,7 @@ use turbo_tasks::{
}; };
use turbopack_core::{ use turbopack_core::{
module_graph::{GraphEntries, ModuleGraph}, module_graph::{GraphEntries, ModuleGraph},
output::OutputAssets, output::{OptionOutputAsset, OutputAssets},
}; };
use crate::{operation::OptionEndpoint, paths::ServerPath, project::Project}; use crate::{operation::OptionEndpoint, paths::ServerPath, project::Project};
...@@ -72,6 +72,10 @@ pub trait Endpoint { ...@@ -72,6 +72,10 @@ pub trait Endpoint {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn module_graphs(self: Vc<Self>) -> Vc<ModuleGraphs>; fn module_graphs(self: Vc<Self>) -> Vc<ModuleGraphs>;
#[turbo_tasks::function]
fn polyfill_asset(self: Vc<Self>) -> Vc<OptionOutputAsset> {
Vc::cell(None)
}
} }
#[derive( #[derive(
......
...@@ -24,6 +24,7 @@ mod path_visitor; ...@@ -24,6 +24,7 @@ mod path_visitor;
pub mod references; pub mod references;
pub mod runtime_functions; pub mod runtime_functions;
pub mod side_effect_optimization; pub mod side_effect_optimization;
pub mod single_file_ecmascript_output;
pub mod source_map; pub mod source_map;
pub(crate) mod static_code; pub(crate) mod static_code;
mod swc_comments; mod swc_comments;
......
use std::sync::Arc;
use anyhow::Result;
use swc_core::common::{BytePos, FileName, LineCol, SourceMap};
use tokio::io::AsyncReadExt;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{FileContent, FileSystemPath, rope::Rope};
use turbopack_core::{
asset::{Asset, AssetContent},
output::{OutputAsset, OutputAssetsReference},
source::Source,
source_map::{GenerateSourceMap, OptionStringifiedSourceMap},
};
use crate::parse::generate_js_source_map;
/// An EcmaScript OutputAsset composed of one file, no parsing and no references. Includes a source
/// map to the original file.
#[turbo_tasks::value]
pub struct SingleFileEcmascriptOutput {
output_path: FileSystemPath,
source_path: FileSystemPath,
source: ResolvedVc<Box<dyn Source>>,
}
#[turbo_tasks::value_impl]
impl OutputAsset for SingleFileEcmascriptOutput {
#[turbo_tasks::function]
fn path(&self) -> Vc<FileSystemPath> {
self.output_path.clone().cell()
}
}
#[turbo_tasks::value_impl]
impl OutputAssetsReference for SingleFileEcmascriptOutput {}
#[turbo_tasks::value_impl]
impl Asset for SingleFileEcmascriptOutput {
#[turbo_tasks::function]
fn content(&self) -> Vc<AssetContent> {
self.source.content()
}
}
#[turbo_tasks::value_impl]
impl SingleFileEcmascriptOutput {
#[turbo_tasks::function]
pub fn new(
output_path: FileSystemPath,
source_path: FileSystemPath,
source: ResolvedVc<Box<dyn Source>>,
) -> Vc<SingleFileEcmascriptOutput> {
SingleFileEcmascriptOutput {
output_path,
source_path,
source,
}
.cell()
}
}
#[turbo_tasks::value_impl]
impl GenerateSourceMap for SingleFileEcmascriptOutput {
#[turbo_tasks::function]
pub async fn generate_source_map(&self) -> Result<Vc<OptionStringifiedSourceMap>> {
let FileContent::Content(file) = &*self.source.content().file_content().await? else {
return Ok(Vc::cell(None));
};
let file_source = {
let mut s = String::new();
file.read().read_to_string(&mut s).await?;
s
};
let mut mappings = vec![];
// Start from 1 because 0 is reserved for dummy spans in SWC.
let mut pos: u32 = 1;
for (index, line) in file_source.split_inclusive('\n').enumerate() {
mappings.push((
BytePos(pos),
LineCol {
line: index as u32,
col: 0,
},
));
pos += line.len() as u32;
}
let sm: Arc<SourceMap> = Default::default();
sm.new_source_file(
FileName::Custom(self.source_path.to_string()).into(),
file_source,
);
let map = generate_js_source_map(&*sm, mappings, None::<&Rope>, true, true)?;
Ok(Vc::cell(Some(map)))
}
}
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