File size: 2,007 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const { readFileSync, writeFileSync, readdirSync } = require( 'fs' );
const { resolve } = require( 'path' );
const chalk = require( 'chalk' );
const prettier = require( 'prettier' );

convertFlow();

/**
 * Processes a Stepper flow to make it load its steps asynchronously.
 *
 * Usage: `node bin/make-stepper-flow-async.js <flow-name>`
 */
function convertFlow() {
	const passedFlowName = process.argv[ 2 ];
	const flowsDir = resolve( __dirname, '../client/landing/stepper/declarative-flow' );
	const availableFlows = readdirSync( flowsDir ).filter( ( filename ) => {
		return (
			filename.endsWith( '.ts' ) &&
			readFileSync( resolve( flowsDir, filename ) ).toString().includes( 'useStepNavigation' )
		);
	} );

	if ( ! availableFlows.find( ( flow ) => flow === passedFlowName + '.ts' ) ) {
		console.error( chalk.red( 'Flow does not exist.' ) );
		console.error( chalk.cyan( `Available options are:\n${ availableFlows.join( '\n' ) }` ) );
		process.exit( 1 );
	}

	const filename = resolve( flowsDir, passedFlowName + '.ts' );

	const prettierOptions = prettier.resolveConfig.sync( resolve( __dirname, '../.prettierrc' ) );

	const contents = readFileSync( filename );

	const stepsImported = contents
		.toString()
		.matchAll( /import ([A-Z].*?) from ('.\/internals\/steps-repository\/.*?');\n?/g );

	const stepsMap = {};
	const stepsImports = [];

	Array.from( stepsImported ).forEach( ( match ) => {
		stepsMap[ match[ 1 ] ] = match[ 2 ];
		stepsImports.push( match[ 0 ] );
	}, {} );

	const results = stepsImports.reduce( ( result, stepImport ) => {
		return result.replace( stepImport, '' );
	}, contents.toString() );

	const finalResult = results.replace(
		/slug: '(.*?)',.*?component: (.*?) \}/gm,
		( match, slug, component ) => {
			return `slug: '${ slug }', asyncComponent: () => import( ${ stepsMap[ component ] } ) }`;
		}
	);

	writeFileSync(
		filename,
		prettier.format( finalResult, { ...prettierOptions, parser: 'typescript' } )
	);
	console.log( `Processed ${ filename }` );
}