import { Reducer } from "@kosko/env" ; import jp from "jsonpath" ; import { CLIError } from "../../cli/error" ; internal export interface SetOption { componentName ? : string ; key : string ; value : string ; } const parseRegexp = /^(.*?[^=<>~])=([^=<>~].*?$)/ ; function parseSetOptionValue ( value ) { try { return JSON . parse ( value ) ; } catch ( e ) { return value ; } } function parseKeyValuePair ( s ) { if ( typeof s !== "string" ) { throw new Error ( `The specified value "${ s }" is not a string.` ) ; } const matches = s . match ( parseRegexp ) ; if ( matches == null || matches . length !== 3 ) { throw new Error ( `Cannot parse string "${ s }". Expected format is "<key>=<value>".` ) ; } return { key : matches [ 1 ] , value : parseSetOptionValue ( matches [ 2 ] ) } ; } param arg internal export function parseSetOptions ( arg ) { const result = [ ] ; const argsArray = Array . isArray ( arg ) ? arg : [ arg ] ; for ( const argItem of argsArray ) { if ( typeof argItem === "object" && argItem !== null ) { for ( const argKey of Object . keys ( argItem ) ) { let argValues = ( argItem as any ) [ argKey ] ; if ( ! Array . isArray ( argValues ) ) { argValues = [ argValues ] ; } for ( const value of argValues ) { result . push ( { ... parseKeyValuePair ( value ) , componentName : argKey } ) ; } } } else { result . push ( parseKeyValuePair ( argItem ) ) ; } } return result ; } param setOptions internal export function createCLIEnvReducer ( setOptions ) { const argsOrdered = setOptions . sort ( ( a , b ) => a . componentName === b . componentName ? 0 : a . componentName ? 1 : - 1 ) ; const reducer = { name : "cli" , reduce ( target , componentName ? ) { for ( const variable of argsOrdered ) { const isGlobalVariable = ! variable . componentName ; if ( isGlobalVariable || variable . componentName === componentName ) { try { jp . apply ( target , "$." + variable . key , ( ) => variable . value ) ; } catch ( e ) { throw new CLIError ( e . message , { code : 1 , output : `Failed to override key "${ variable . key }". ${ e . message }` } ) ; } } } return target ; } } ; return reducer ; }