import {Context} from '@chix/common' import {Flow, xNode} from '@chix/flow' import * as forOf from 'object-forof' import * as prompt from 'prompt' /** * * Prompt Context Provider * * @constructor * @public */ export class PromptContextProvider { public questions: any[] = [] public questioning = false public addContext(node: xNode | Flow, defaultContext: Context, schema: any) { node.inputTimeout = 120000 if (typeof defaultContext !== 'undefined') { const question = this.askForContext(node, defaultContext, schema) if (!this.questioning) { question() } else { this.questions.push(question) } } } public askForContext( node: xNode | Flow, defaultContext: Context, schema: any ) { return () => { this.questioning = true forOf((name: string, val: any) => { schema[name].default = val }, defaultContext) ;(prompt as any).start() ;(prompt as any).message = `${node.ns}:${node.name}` ;(prompt as any).get( {properties: schema}, (error: Error, result: any) => { if (error) { throw error } for (const key in result) { if (result.hasOwnProperty(key)) { if (typeof defaultContext[key] === 'object') { result[key] = JSON.parse(result[key]) } node.setContextProperty(key, result[key], true) } } if (this.questions.length) { ;(this.questions as any).pop().question() } else { this.questioning = false } } ) } } }