@@ -131,6 +131,7 @@ export const init = new Command()
131131 let componentsJsonBackupPath : string | undefined
132132 let reinstallComponents : string [ ] = [ ]
133133
134+ // Restore components.json backup on unexpected exit (e.g. process.exit in preflight).
134135 const restoreBackupOnExit = ( ) => {
135136 if ( componentsJsonBackupPath ) {
136137 restoreFileBackup (
@@ -498,6 +499,9 @@ export const init = new Command()
498499 // We need to check if we're initializing with a new style.
499500 // This will allow us to determine if we need to install the base style.
500501 if ( components . length > 0 ) {
502+ // Back up existing components.json if it exists.
503+ // Since components.json might not be valid at this point,
504+ // temporarily rename it to allow preflight to run.
501505 const componentsJsonPath = path . resolve ( cwd , "components.json" )
502506
503507 if ( hasExistingConfig ) {
@@ -510,6 +514,7 @@ export const init = new Command()
510514 }
511515 }
512516
517+ // Resolve registry:base config from the first component.
513518 const {
514519 registryBaseConfig,
515520 installStyleIndex,
@@ -520,6 +525,7 @@ export const init = new Command()
520525 | undefined ,
521526 } )
522527
528+ // Use the clean URL (track param stripped) for subsequent fetches.
523529 components [ 0 ] = cleanUrl
524530
525531 if ( ! installStyleIndex ) {
@@ -537,10 +543,13 @@ export const init = new Command()
537543 logger . log (
538544 `Project initialization completed.\nYou may now add components.`
539545 )
546+
547+ // Success — remove the backup and exit listener.
540548 process . removeListener ( "exit" , restoreBackupOnExit )
541549 deleteFileBackup ( path . resolve ( cwd , "components.json" ) )
542550 logger . break ( )
543551 } catch ( error ) {
552+ // Restore handled by exit listener, but also do it here for non-exit errors.
544553 process . removeListener ( "exit" , restoreBackupOnExit )
545554 restoreBackupOnExit ( )
546555 logger . break ( )
0 commit comments