or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Sort Package JSON

1

2

Sort Package JSON is a JavaScript utility that sorts package.json files according to well-established conventions. It provides both programmatic API and CLI interfaces for organizing package.json keys in a standardized order, helping maintain consistent project structure across teams and development environments.

3

4

## Package Information

5

6

- **Package Name**: sort-package-json

7

- **Package Type**: npm

8

- **Language**: JavaScript (ES Modules)

9

- **Installation**: `npm install sort-package-json`

10

11

## Core Imports

12

13

```javascript

14

import sortPackageJson from "sort-package-json";

15

import { sortPackageJson, sortOrder } from "sort-package-json";

16

```

17

18

For CommonJS environments:

19

20

```javascript

21

const sortPackageJson = require("sort-package-json");

22

const { sortPackageJson, sortOrder } = require("sort-package-json");

23

```

24

25

## Basic Usage

26

27

```javascript

28

import sortPackageJson from "sort-package-json";

29

30

// Sort a package.json string

31

const packageJsonString = `{

32

"dependencies": {

33

"sort-package-json": "1.0.0",

34

"sort-object-keys": "1.0.0"

35

},

36

"version": "1.0.0",

37

"name": "my-awesome-project"

38

}`;

39

40

console.log(sortPackageJson(packageJsonString));

41

// Output: Formatted JSON string with keys in proper order

42

43

// Sort a package.json object

44

const packageJsonObject = JSON.parse(packageJsonString);

45

const sorted = sortPackageJson(packageJsonObject);

46

console.log(sorted);

47

// Output: Object with keys sorted according to conventions

48

```

49

50

## Capabilities

51

52

### Package JSON Sorting

53

54

Main function that sorts package.json content according to well-known field conventions.

55

56

```typescript { .api }

57

/**

58

* Sort packageJson object or string according to well-known conventions

59

* @param packageJson - Package.json content as string or object

60

* @param options - Optional sorting configuration

61

* @returns Sorted package.json with same type as input

62

*/

63

function sortPackageJson<T extends Record<any, any>>(packageJson: T, options?: Options): T;

64

function sortPackageJson(packageJson: string, options?: Options): string;

65

66

interface Options {

67

readonly sortOrder?: readonly string[] | ComparatorFunction;

68

}

69

70

type ComparatorFunction = (left: string, right: string) => number;

71

```

72

73

**Key Features:**

74

75

- **Dual Input Support**: Accepts both JSON strings and JavaScript objects

76

- **Format Preservation**: Maintains original indentation and line endings for string inputs

77

- **Smart Field Recognition**: Recognizes 100+ package.json fields including dependencies, scripts, and tool configurations

78

- **Custom Sort Orders**: Supports custom field ordering via options parameter

79

- **Type Safety**: Full TypeScript support with proper type inference

80

81

**Usage Examples:**

82

83

```javascript

84

import sortPackageJson from "sort-package-json";

85

86

// Basic sorting with string input

87

const sorted = sortPackageJson('{"version":"1.0.0","name":"test"}');

88

// Returns: '{"name":"test","version":"1.0.0"}'

89

90

// Sorting with object input

91

const obj = { version: "1.0.0", name: "test", dependencies: {} };

92

const sortedObj = sortPackageJson(obj);

93

// Returns object with fields in conventional order

94

95

// Custom sort order

96

const customSorted = sortPackageJson(obj, {

97

sortOrder: ['version', 'name'] // version will come before name

98

});

99

100

// Function-based sorting

101

const funcSorted = sortPackageJson(obj, {

102

sortOrder: (left, right) => right.localeCompare(left) // reverse alphabetical

103

});

104

```

105

106

### Default Sort Order

107

108

Array containing the default field ordering used by the sorting function.

109

110

```typescript { .api }

111

/**

112

* Default sort order for package.json fields

113

* Contains 100+ field names in conventional order

114

*/

115

const sortOrder: readonly string[];

116

```

117

118

The default sort order includes standard fields like:

119

120

1. **Metadata**: `$schema`, `name`, `displayName`, `version`, `private`, `description`

121

2. **Repository Info**: `keywords`, `homepage`, `bugs`, `repository`, `funding`, `license`

122

3. **People**: `author`, `maintainers`, `contributors`, `publisher`

123

4. **Module System**: `type`, `exports`, `main`, `module`, `browser`, `types`

124

5. **Executables**: `bin`, `man`, `directories`, `files`

125

6. **Scripts**: `scripts`, `betterScripts`

126

7. **Dependencies**: `dependencies`, `devDependencies`, `peerDependencies`, `optionalDependencies`

127

8. **Configuration**: `engines`, `volta`, `config`, tool-specific configs (eslint, prettier, etc.)

128

129

**Usage Example:**

130

131

```javascript

132

import { sortOrder } from "sort-package-json";

133

134

console.log(sortOrder.slice(0, 5));

135

// Output: ['$schema', 'name', 'displayName', 'version', 'stableVersion']

136

137

// Use in custom sorting

138

const customOrder = [...sortOrder, 'myCustomField'];

139

```

140

141

## CLI Interface

142

143

The package provides a command-line interface for sorting package.json files directly.

144

145

### Installation and Basic Usage

146

147

```bash

148

# Global installation

149

npm install -g sort-package-json

150

151

# Or use via npx

152

npx sort-package-json

153

154

# Sort specific files

155

sort-package-json package.json

156

sort-package-json "packages/*/package.json"

157

```

158

159

### CLI Commands and Options

160

161

```bash

162

sort-package-json [options] [file/glob ...]

163

164

Options:

165

-c, --check Check if files are sorted (validation mode)

166

-q, --quiet Don't output success messages

167

-h, --help Display help information

168

-i, --ignore An array of glob patterns to ignore (default: ['node_modules/**'])

169

-v, --version Display package version

170

--stdin Read from stdin, output to stdout

171

```

172

173

**Usage Examples:**

174

175

```bash

176

# Sort current package.json

177

sort-package-json

178

179

# Check if files are sorted

180

sort-package-json --check

181

sort-package-json "**/*.json" --check

182

183

# Sort multiple files with ignore patterns

184

sort-package-json "packages/*/package.json" --ignore "packages/legacy/*"

185

186

# Use with stdin/stdout

187

cat package.json | sort-package-json --stdin > sorted-package.json

188

189

# Quiet mode (suppress success messages)

190

sort-package-json --quiet

191

```

192

193

### CLI Exit Codes

194

195

The CLI returns different exit codes to indicate various outcomes:

196

197

- **0**: Success - all files processed successfully

198

- **1**: Check mode failed - some files are not sorted (only in `--check` mode)

199

- **2**: Error - no matching files found, invalid arguments, or file processing errors

200

201

**Examples:**

202

203

```bash

204

# Check if files are sorted (exits with 1 if any are unsorted)

205

sort-package-json --check

206

echo $? # Will be 1 if files need sorting

207

208

# Successful sorting (exits with 0)

209

sort-package-json package.json

210

echo $? # Will be 0 on success

211

212

# Error case - no files found (exits with 2)

213

sort-package-json "nonexistent/*.json"

214

echo $? # Will be 2

215

```

216

217

## Advanced Configuration

218

219

### Custom Sort Orders

220

221

You can customize the field ordering using the `sortOrder` option:

222

223

```javascript

224

import sortPackageJson from "sort-package-json";

225

226

// Array-based custom order (fields not listed fall back to default order)

227

const result = sortPackageJson(packageJson, {

228

sortOrder: ['version', 'name'] // version will appear before name

229

});

230

231

// Function-based custom sorting

232

const result2 = sortPackageJson(packageJson, {

233

sortOrder: (left, right) => {

234

// Custom comparison logic

235

return left.localeCompare(right);

236

}

237

});

238

```

239

240

### Private Field Handling

241

242

Fields starting with underscore (`_`) are treated as private and sorted separately at the end:

243

244

```javascript

245

const packageJson = {

246

name: "test",

247

version: "1.0.0",

248

_private: "value",

249

_internal: "data"

250

};

251

252

const sorted = sortPackageJson(packageJson);

253

// Result: name, version, _internal, _private

254

```

255

256

### Format Preservation

257

258

For string inputs, the function preserves original formatting:

259

260

```javascript

261

// Preserves 4-space indentation

262

const indented = sortPackageJson('{\n "version": "1.0.0",\n "name": "test"\n}');

263

264

// Preserves tab indentation

265

const tabbed = sortPackageJson('{\n\t"version": "1.0.0",\n\t"name": "test"\n}');

266

267

// Preserves Windows line endings

268

const windows = sortPackageJson('{"version":"1.0.0",\r\n"name":"test"}');

269

```

270

271

## Error Handling

272

273

The library handles various edge cases gracefully:

274

275

- **Invalid JSON**: Returns original input unchanged for string inputs

276

- **Non-object inputs**: Arrays and primitive values are returned unchanged

277

- **Missing fields**: Only sorts fields that are present

278

- **Nested objects**: Automatically sorts nested objects in specific fields (dependencies, etc.)

279

280

## Types

281

282

```typescript { .api }

283

interface Options {

284

/** Custom sort order as array of field names or comparison function */

285

readonly sortOrder?: readonly string[] | ComparatorFunction;

286

}

287

288

type ComparatorFunction = (left: string, right: string) => number;

289

290

interface SortPackageJson {

291

/** Sort packageJson object */

292

<T extends Record<any, any>>(packageJson: T, options?: Options): T;

293

/** Sort packageJson string */

294

(packageJson: string, options?: Options): string;

295

}

296

```