or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

choice-prompts.mdconfirmation-prompts.mdcore-prompting.mdindex.mdnumber-date-prompts.mdtesting.mdtext-prompts.md

core-prompting.mddocs/

0

# Core Prompting

1

2

Main prompting functionality providing the core API for creating interactive CLI prompts with single or multiple questions, validation, callbacks, and dynamic question flow.

3

4

```javascript

5

const prompts = require('prompts');

6

// Or for specific imports:

7

const { prompt, inject, override } = require('prompts');

8

```

9

10

## Capabilities

11

12

### Main Prompt Function

13

14

The primary function for creating interactive prompts. Accepts single question objects or arrays of questions and returns a promise with user responses.

15

16

```javascript { .api }

17

/**

18

* Prompt for a series of questions

19

* @param questions - Single question object or Array of question objects

20

* @param options - Optional configuration for submit and cancel callbacks

21

* @returns Promise resolving to object with values from user input

22

*/

23

function prompts(

24

questions: Question | Question[],

25

options?: PromptOptions

26

): Promise<Answers>;

27

28

// The main export can be used directly or via the prompt property

29

const prompts = require('prompts');

30

// Both of these are equivalent:

31

prompts({ type: 'text', name: 'username', message: 'Username?' });

32

prompts.prompt({ type: 'text', name: 'username', message: 'Username?' });

33

34

interface Question {

35

/** Prompt type or function returning type. If falsy, question is skipped */

36

type: string | ((prev: any, values: Answers, prompt: Question) => string | null);

37

/** Property name for response object or function returning name */

38

name: string | ((prev: any, values: Answers, prompt: Question) => string);

39

/** Display message for user or function returning message */

40

message: string | ((prev: any, values: Answers, prompt: Question) => string);

41

/** Default/initial value or function returning initial value */

42

initial?: any | ((prev: any, values: Answers, prompt: Question) => Promise<any> | any);

43

/** Custom formatter for user input. Receives value and all answers */

44

format?: (val: any, values: Answers) => any | Promise<any>;

45

/** Validation function. Returns true if valid, error message string if invalid */

46

validate?: (val: any, values: Answers) => boolean | string | Promise<boolean | string>;

47

/** Render callback receiving kleur styling library. 'this' refers to current prompt */

48

onRender?: (kleur: any) => void;

49

/** State change callback receiving state object with value and aborted properties */

50

onState?: (state: { value: any; aborted: boolean }) => void;

51

/** Input stream. Defaults to process.stdin */

52

stdin?: NodeJS.ReadableStream;

53

/** Output stream. Defaults to process.stdout */

54

stdout?: NodeJS.WritableStream;

55

}

56

57

interface PromptOptions {

58

/** Callback invoked after each prompt submission. Return true to quit early */

59

onSubmit?: (prompt: Question, answer: any, answers: Answers) => boolean | Promise<boolean>;

60

/** Callback invoked when user cancels. Return true to continue prompting */

61

onCancel?: (prompt: Question, answers: Answers) => boolean | Promise<boolean>;

62

}

63

64

type Answers = Record<string, any>;

65

```

66

67

**Usage Examples:**

68

69

```javascript

70

const prompts = require('prompts');

71

72

// Single prompt

73

const response = await prompts({

74

type: 'text',

75

name: 'username',

76

message: 'What is your GitHub username?',

77

validate: value => value.length < 3 ? 'Username too short' : true

78

});

79

80

// Multiple prompts

81

const questions = [

82

{

83

type: 'text',

84

name: 'username',

85

message: 'What is your GitHub username?'

86

},

87

{

88

type: 'number',

89

name: 'age',

90

message: 'How old are you?',

91

validate: value => value < 18 ? 'Must be 18 or older' : true

92

},

93

{

94

type: 'confirm',

95

name: 'subscribe',

96

message: 'Subscribe to newsletter?',

97

initial: true

98

}

99

];

100

101

const response = await prompts(questions);

102

// { username: 'alice', age: 25, subscribe: true }

103

```

104

105

### Dynamic Question Flow

106

107

Questions can have dynamic properties using functions that receive previous answers, enabling conditional prompts and dynamic question generation.

108

109

```javascript { .api }

110

/**

111

* Dynamic question properties receive context about previous answers

112

* @param prev - Value from the immediately previous prompt

113

* @param values - Object containing all answers collected so far

114

* @param prompt - The previous prompt object

115

* @returns The computed value for the property

116

*/

117

type DynamicProperty<T> = (prev: any, values: Answers, prompt: Question) => T;

118

```

119

120

**Usage Examples:**

121

122

```javascript

123

const questions = [

124

{

125

type: 'text',

126

name: 'dish',

127

message: 'What is your favorite dish?'

128

},

129

{

130

type: prev => prev === 'pizza' ? 'text' : null, // Skip if not pizza

131

name: 'topping',

132

message: 'What is your favorite topping?'

133

},

134

{

135

type: 'confirm',

136

name: 'hungry',

137

message: (prev, values) => `Are you hungry for ${values.dish}?`

138

}

139

];

140

141

const response = await prompts(questions);

142

```

143

144

### Callback Handling

145

146

Configure callbacks for handling prompt submission and cancellation events with support for early termination and error recovery.

147

148

```javascript { .api }

149

/**

150

* Submit callback invoked after each prompt completion

151

* @param prompt - The completed prompt object

152

* @param answer - The user's answer to the prompt

153

* @param answers - All answers collected so far

154

* @returns Boolean indicating whether to quit early (true) or continue (false)

155

*/

156

type OnSubmitCallback = (

157

prompt: Question,

158

answer: any,

159

answers: Answers

160

) => boolean | Promise<boolean>;

161

162

/**

163

* Cancel callback invoked when user cancels a prompt

164

* @param prompt - The prompt that was canceled

165

* @param answers - All answers collected so far

166

* @returns Boolean indicating whether to continue (true) or abort (false)

167

*/

168

type OnCancelCallback = (

169

prompt: Question,

170

answers: Answers

171

) => boolean | Promise<boolean>;

172

```

173

174

**Usage Examples:**

175

176

```javascript

177

const questions = [

178

{ type: 'text', name: 'name', message: 'Your name?' },

179

{ type: 'number', name: 'age', message: 'Your age?' },

180

{ type: 'text', name: 'email', message: 'Your email?' }

181

];

182

183

const response = await prompts(questions, {

184

onSubmit: (prompt, answer, answers) => {

185

console.log(`Got ${answer} for ${prompt.name}`);

186

// Quit early if name is 'admin'

187

return answers.name === 'admin';

188

},

189

onCancel: (prompt, answers) => {

190

console.log('User canceled. Continuing...');

191

return true; // Continue prompting

192

}

193

});

194

```

195

196

### Question Validation

197

198

Input validation with custom validator functions supporting both synchronous and asynchronous validation logic.

199

200

```javascript { .api }

201

/**

202

* Validation function for user input

203

* @param value - The user's input value

204

* @param values - All answers collected so far

205

* @returns true if valid, error message string if invalid, or Promise resolving to same

206

*/

207

type ValidateFunction = (

208

value: any,

209

values: Answers

210

) => boolean | string | Promise<boolean | string>;

211

```

212

213

**Usage Examples:**

214

215

```javascript

216

const questions = [

217

{

218

type: 'text',

219

name: 'email',

220

message: 'Enter your email:',

221

validate: value => {

222

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

223

return emailRegex.test(value) || 'Please enter a valid email address';

224

}

225

},

226

{

227

type: 'number',

228

name: 'port',

229

message: 'Enter port number:',

230

validate: async (value) => {

231

if (value < 1024) return 'Port must be 1024 or higher';

232

if (value > 65535) return 'Port must be 65535 or lower';

233

234

// Async validation - check if port is available

235

const isAvailable = await checkPortAvailability(value);

236

return isAvailable || `Port ${value} is already in use`;

237

}

238

}

239

];

240

```

241

242

### Input Formatting

243

244

Transform user input before storing in the response object using custom format functions.

245

246

```javascript { .api }

247

/**

248

* Format function for transforming user input

249

* @param value - The user's raw input value

250

* @param values - All answers collected so far

251

* @returns Transformed value to store in response object

252

*/

253

type FormatFunction = (value: any, values: Answers) => any | Promise<any>;

254

```

255

256

**Usage Examples:**

257

258

```javascript

259

const questions = [

260

{

261

type: 'text',

262

name: 'name',

263

message: 'Enter your name:',

264

format: value => value.trim().toLowerCase()

265

},

266

{

267

type: 'number',

268

name: 'price',

269

message: 'Enter price:',

270

format: value => {

271

// Format as currency

272

return new Intl.NumberFormat('en-US', {

273

style: 'currency',

274

currency: 'USD'

275

}).format(value);

276

}

277

}

278

];

279

```