11import { atom } from "jotai" ;
2+ import { bundle } from "@/lib/bundle" ;
23import type {
34 RspackChunkGroupInfo ,
45 RspackChunkInfo ,
56 RspackModuleDeps ,
67} from "@/lib/bundle/dependency" ;
78import { deserializeShareData } from "@/lib/share" ;
9+ import { activeOutputFileAtom } from "./editor" ;
810import { getPresetFiles , PresetBasicLibrary } from "./presets" ;
9- import { getSafeInitRspackVersion } from "./version" ;
11+ import { getSafeInitRspackVersion , rspackVersionAtom } from "./version" ;
1012
1113export interface SourceFile {
1214 filename : string ;
@@ -26,6 +28,21 @@ export interface BundleResult {
2628 chunkGroups : RspackChunkGroupInfo [ ] ; // chunk group graph data
2729}
2830
31+ function createBundleFailure ( message : string ) : BundleResult {
32+ return {
33+ duration : 0 ,
34+ output : [ ] ,
35+ formattedOutput : [ ] ,
36+ success : false ,
37+ errors : [ message ] ,
38+ warnings : [ ] ,
39+ sourcemaps : new Map ( ) ,
40+ modules : [ ] ,
41+ chunks : [ ] ,
42+ chunkGroups : [ ] ,
43+ } ;
44+ }
45+
2946function getInitFiles ( ) {
3047 const hash = window . location . hash . slice ( 1 ) ;
3148 if ( hash ) {
@@ -45,3 +62,54 @@ export const latestBundleRequestIdAtom = atom(0);
4562export const inputFilesAtom = atom < SourceFile [ ] > ( getInitFiles ( ) ) ;
4663export const bundleResultAtom = atom < BundleResult | null > ( null ) ;
4764export const enableFormatCode = atom ( true ) ;
65+
66+ export const bundleActionAtom = atom (
67+ null ,
68+ async (
69+ get ,
70+ set ,
71+ { files, versionOverride } : { files : SourceFile [ ] ; versionOverride ?: string } ,
72+ ) => {
73+ const requestId = get ( latestBundleRequestIdAtom ) + 1 ;
74+ set ( latestBundleRequestIdAtom , requestId ) ;
75+
76+ const targetVersion = versionOverride ?? ( await get ( rspackVersionAtom ) ) ;
77+ const shouldLoadBinding = get ( bindingLoadedAtom ) !== targetVersion ;
78+ const isLatestRequest = ( ) => requestId === get ( latestBundleRequestIdAtom ) ;
79+
80+ set ( isBundlingAtom , true ) ;
81+ if ( shouldLoadBinding ) {
82+ set ( bindingLoadingAtom , true ) ;
83+ }
84+
85+ try {
86+ const result = await bundle ( files , targetVersion ) ;
87+ if ( ! isLatestRequest ( ) ) {
88+ return ;
89+ }
90+
91+ set ( bundleResultAtom , result ) ;
92+
93+ if ( shouldLoadBinding ) {
94+ set ( bindingLoadedAtom , targetVersion ) ;
95+ }
96+
97+ const activeOutputFile = get ( activeOutputFileAtom ) ;
98+ if ( result . output . length > 0 && activeOutputFile >= result . output . length ) {
99+ set ( activeOutputFileAtom , 0 ) ;
100+ }
101+ } catch ( error ) {
102+ if ( ! isLatestRequest ( ) ) {
103+ return ;
104+ }
105+
106+ const message = error instanceof Error ? error . message : "Failed to load rspack binding" ;
107+ set ( bundleResultAtom , createBundleFailure ( message ) ) ;
108+ } finally {
109+ if ( isLatestRequest ( ) ) {
110+ set ( bindingLoadingAtom , false ) ;
111+ set ( isBundlingAtom , false ) ;
112+ }
113+ }
114+ } ,
115+ ) ;
0 commit comments