import { readFileSync } from "fs" ; import { CtrlbBufferType } from "./buffers/type" ; export interface ActionInfo { id ? : string ; method : string ; params ? : ActionArgs ; } export class ArgParser { public parse ( arg ) { let method = "" ; let actionArgs = { } ; for ( const value of arg . split ( " " ) ) { if ( ! value . startsWith ( "-" ) ) { method = value ; continue ; } if ( ! value . includes ( "=" ) ) { const key = this . parseArgKey ( value ) ; actionArgs [ key ] = true ; continue ; } const equalIndex = value . indexOf ( "=" ) ; const argKey = this . parseArgKey ( value . slice ( 0 , equalIndex ) ) ; const argValue = this . convertValue ( value . slice ( equalIndex + 1 ) ) ; actionArgs [ argKey ] = argValue ; } return { method : method , params : actionArgs , } ; } protected parseArgKey ( value ) { const key = value . slice ( 1 ) ; if ( key . length === 0 ) { throw new Error ( "Arg key must not be empty." ) ; } return key ; } protected convertValue ( value ) { const v = value . toString ( ) ; if ( this . isNumber ( v ) || this . isFloat ( v ) ) { return Number ( v ) ; } return v ; } protected isNumber ( value ) { return ( ( n ) => ! isNaN ( n ) ) ( Number ( value ) ) ; } protected isFloat ( value ) { return this . isNumber ( value . replace ( "." , "1" ) ) ; } public isBufferType ( value ) { return value in CtrlbBufferType ; } public parseJsonFile ( jsonFilePath ) { const content = readFileSync ( jsonFilePath ) ; const json = JSON . parse ( content . toString ( ) ) ; return json ; } } type ActionArgs = { [ index ] : string | number | boolean | null ; } ;