or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

argument-parsing.mdcli-usage.mddata-cleaning.mdindex.mdlibrary-api.mdtype-system.md

library-api.mddocs/

0

# Library API

1

2

Non-singleton API providing full control over parsing behavior, error handling, and advanced features. Offers complete configuration flexibility without global state.

3

4

## Capabilities

5

6

### Library Access

7

8

Access the non-singleton library API for advanced usage patterns.

9

10

```javascript { .api }

11

/**

12

* Non-singleton library API with full configuration control

13

*/

14

const lib = require("nopt").lib;

15

// or

16

const lib = require("nopt/lib/nopt-lib");

17

18

interface LibraryAPI {

19

nopt: (args: string[], options?: NoptOptions) => ParsedOptions;

20

clean: (data: object, options?: CleanOptions) => void;

21

parse: (args: string[], data: object, remain: string[], options?: ParseOptions) => void;

22

validate: (data: object, key: string, value: any, type: any, options?: ValidateOptions) => boolean;

23

resolveShort: (arg: string, ...rest: any[]) => string[] | null;

24

typeDefs: TypeDefinitions;

25

}

26

```

27

28

**Usage Examples:**

29

30

```javascript

31

const { lib } = require("nopt");

32

33

// Configure parsing options

34

const options = {

35

types: { verbose: Boolean, count: Number },

36

shorthands: { v: ["--verbose"], c: ["--count"] },

37

invalidHandler: (key, val) => console.error(`Invalid: ${key}=${val}`),

38

unknownHandler: (key) => console.error(`Unknown: ${key}`),

39

abbrevHandler: (short, long) => console.log(`${short} -> ${long}`)

40

};

41

42

// Parse with full control

43

const result = lib.nopt(["--verbose", "-c", "5"], options);

44

```

45

46

### Library Parsing Function

47

48

Parse arguments with complete configuration control.

49

50

```javascript { .api }

51

/**

52

* Parse arguments with complete configuration control

53

* @param args - Array of arguments to parse

54

* @param options - Complete configuration object

55

* @returns Parsed data with argv metadata

56

*/

57

function nopt(args: string[], options?: NoptOptions): ParsedOptions;

58

59

interface NoptOptions {

60

types?: object; // Type definitions for options

61

shorthands?: object; // Shorthand mappings

62

typeDefs?: object; // Type validator definitions

63

invalidHandler?: Function | false; // Handler for invalid values

64

unknownHandler?: Function | false; // Handler for unknown options

65

abbrevHandler?: Function | false; // Handler for abbreviations

66

typeDefault?: any[]; // Default type array for untyped options

67

dynamicTypes?: Function; // Function to dynamically determine types

68

}

69

```

70

71

**Advanced Usage Examples:**

72

73

```javascript

74

const { lib } = require("nopt");

75

76

// Dynamic type resolution

77

const dynamicOptions = {

78

types: { verbose: Boolean },

79

dynamicTypes: function(key) {

80

if (key.startsWith('num-')) {

81

return Number;

82

}

83

if (key.endsWith('-path')) {

84

return lib.typeDefs.path.type;

85

}

86

return undefined;

87

}

88

};

89

90

const result = lib.nopt([

91

"--verbose",

92

"--num-workers", "4", // Dynamically typed as Number

93

"--output-path", "~/out" // Dynamically typed as path

94

], dynamicOptions);

95

```

96

97

### Library Clean Function

98

99

Clean data with full configuration control.

100

101

```javascript { .api }

102

/**

103

* Clean and validate data with full configuration control

104

* @param data - Object to clean (modified in place)

105

* @param options - Configuration object for cleaning

106

*/

107

function clean(data: object, options?: CleanOptions): void;

108

109

interface CleanOptions {

110

types?: object; // Type definitions

111

typeDefs?: object; // Type validators

112

dynamicTypes?: Function; // Dynamic type resolution

113

invalidHandler?: Function | false; // Invalid value handler

114

typeDefault?: any[]; // Default types for untyped values

115

}

116

```

117

118

```javascript

119

// Advanced cleaning with custom configuration

120

const data = {

121

count: "42",

122

unknown: "value",

123

"num-threads": "8"

124

};

125

126

const cleanOptions = {

127

types: { count: Number },

128

dynamicTypes: (key) => key.startsWith('num-') ? Number : undefined,

129

invalidHandler: (key, val, type) => {

130

console.warn(`Removing invalid ${key}: ${val} (expected ${type})`);

131

return false; // Remove the property

132

}

133

};

134

135

lib.clean(data, cleanOptions);

136

// Result: { count: 42, "num-threads": 8 }

137

// 'unknown' property removed due to no type definition

138

```

139

140

### Core Parsing Function

141

142

Low-level parsing function for complete control over the parsing process.

143

144

```javascript { .api }

145

/**

146

* Core argument parsing function with complete control

147

* @param args - Arguments array to parse

148

* @param data - Object to populate with parsed data

149

* @param remain - Array to populate with remaining non-option arguments

150

* @param options - Parsing configuration

151

*/

152

function parse(

153

args: string[],

154

data: object,

155

remain: string[],

156

options?: ParseOptions

157

): void;

158

159

interface ParseOptions {

160

types?: object;

161

shorthands?: object;

162

typeDefs?: object;

163

dynamicTypes?: Function;

164

unknownHandler?: Function | false;

165

abbrevHandler?: Function | false;

166

}

167

```

168

169

```javascript

170

// Manual parsing with complete control

171

const args = ["--verbose", "file1.txt", "--count", "5", "file2.txt"];

172

const data = {};

173

const remain = [];

174

175

const parseOptions = {

176

types: { verbose: Boolean, count: Number },

177

unknownHandler: (key) => console.log(`Found unknown option: ${key}`)

178

};

179

180

lib.parse(args, data, remain, parseOptions);

181

182

console.log(data); // { verbose: true, count: 5 }

183

console.log(remain); // ["file1.txt", "file2.txt"]

184

```

185

186

### Single Value Validation

187

188

Validate individual option values against type definitions.

189

190

```javascript { .api }

191

/**

192

* Validate a single option value against its type

193

* @param data - Data object to modify if valid

194

* @param key - Option key name

195

* @param value - Value to validate

196

* @param type - Type definition to validate against

197

* @param options - Validation configuration

198

* @returns true if valid, false if invalid

199

*/

200

function validate(

201

data: object,

202

key: string,

203

value: any,

204

type: any,

205

options?: ValidateOptions

206

): boolean;

207

208

interface ValidateOptions {

209

typeDefs?: object;

210

invalidHandler?: Function | false;

211

typeDefault?: any[];

212

}

213

```

214

215

```javascript

216

// Validate individual values

217

const data = {};

218

const options = { typeDefs: lib.typeDefs };

219

220

// Valid number

221

const isValid1 = lib.validate(data, "count", "42", Number, options);

222

console.log(isValid1, data.count); // true, 42

223

224

// Invalid number

225

const isValid2 = lib.validate(data, "port", "invalid", Number, options);

226

console.log(isValid2); // false

227

```

228

229

### Shorthand Resolution

230

231

Resolve shorthand argument expansions.

232

233

```javascript { .api }

234

/**

235

* Resolve shorthand option expansions

236

* @param arg - Argument to resolve

237

* @param shorthands - Shorthand mapping object

238

* @param abbreviations - Abbreviation mapping object

239

* @param unknown - Unknown option handler

240

* @param abbrev - Abbreviation handler

241

* @returns Array of expanded arguments or null

242

*/

243

function resolveShort(

244

arg: string,

245

shorthands?: object,

246

abbreviations?: object,

247

unknown?: Function | false,

248

abbrev?: Function | false

249

): string[] | null;

250

```

251

252

```javascript

253

// Resolve shorthand expansions

254

const shorthands = {

255

v: ["--verbose"],

256

h: ["--help"],

257

o: ["--output"]

258

};

259

260

// Single shorthand

261

const result1 = lib.resolveShort("-v", shorthands);

262

console.log(result1); // ["--verbose"]

263

264

// Combined shorthands

265

const result2 = lib.resolveShort("-vh", shorthands);

266

console.log(result2); // ["--verbose", "--help"]

267

268

// With value

269

const result3 = lib.resolveShort("-o=file.txt", shorthands);

270

console.log(result3); // ["--output", "file.txt"]

271

```

272

273

## Types

274

275

```javascript { .api }

276

// Complete library options interface

277

interface NoptOptions {

278

types?: { [key: string]: any };

279

shorthands?: { [key: string]: string[] };

280

typeDefs?: { [key: string]: TypeValidator };

281

invalidHandler?: InvalidHandler | false;

282

unknownHandler?: UnknownHandler | false;

283

abbrevHandler?: AbbrevHandler | false;

284

typeDefault?: any[];

285

dynamicTypes?: (key: string) => any;

286

}

287

288

// Specialized option interfaces

289

interface CleanOptions {

290

types?: { [key: string]: any };

291

typeDefs?: { [key: string]: TypeValidator };

292

dynamicTypes?: (key: string) => any;

293

invalidHandler?: InvalidHandler | false;

294

typeDefault?: any[];

295

}

296

297

interface ParseOptions {

298

types?: { [key: string]: any };

299

shorthands?: { [key: string]: string[] };

300

typeDefs?: { [key: string]: TypeValidator };

301

dynamicTypes?: (key: string) => any;

302

unknownHandler?: UnknownHandler | false;

303

abbrevHandler?: AbbrevHandler | false;

304

}

305

306

interface ValidateOptions {

307

typeDefs?: { [key: string]: TypeValidator };

308

invalidHandler?: InvalidHandler | false;

309

typeDefault?: any[];

310

}

311

312

// Handler function types

313

type InvalidHandler = (key: string, value: any, type: any, data: object) => boolean | void;

314

type UnknownHandler = (key: string, nextValue?: string) => void;

315

type AbbrevHandler = (short: string, long: string) => void;

316

type DynamicTypesFunction = (key: string) => any;

317

```