or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdconfiguration.mdcore-api.mdfetchers.mdindex.mdutility-functions.md

utility-functions.mddocs/

0

# Utility Functions

1

2

Standalone utility functions for specialized package operations and processing. These functions are used internally by pacote but are also exposed as part of the public API for advanced usage scenarios.

3

4

## Capabilities

5

6

### Git SHA Management

7

8

Add SHA hashes to git URL specifications for precise version control.

9

10

```javascript { .api }

11

/**

12

* Add SHA hash to git URL specification

13

* @param {string} spec - Git URL specification

14

* @param {string} sha - SHA hash to append

15

* @returns {string} Modified git URL with SHA

16

*/

17

function addGitSha(spec, sha);

18

```

19

20

**Usage Examples:**

21

22

```javascript

23

const { addGitSha } = require('pacote/lib/util/add-git-sha');

24

25

// Add commit SHA to GitHub URL

26

const gitUrl = addGitSha('git+https://github.com/user/repo.git', 'abc123def456');

27

console.log(gitUrl); // 'git+https://github.com/user/repo.git#abc123def456'

28

29

// Add SHA to shorthand GitHub spec

30

const shortUrl = addGitSha('github:user/repo', '789def012abc');

31

console.log(shortUrl); // 'github:user/repo#789def012abc'

32

```

33

34

### Cache Directory Management

35

36

Get platform-specific cache directory paths for pacote operations.

37

38

```javascript { .api }

39

/**

40

* Get cache directory paths for different platforms

41

* @param {string} fakePlatform - Platform identifier for testing

42

* @returns {Object} Cache directory configuration

43

*/

44

function cacheDir(fakePlatform);

45

46

interface CacheDirResult {

47

/** Main cache directory for packages and metadata */

48

cacache: string;

49

/** TUF cache directory for attestation keys */

50

tufcache: string;

51

}

52

```

53

54

**Usage Examples:**

55

56

```javascript

57

const { cacheDir } = require('pacote/lib/util/cache-dir');

58

59

// Get default cache directories

60

const dirs = cacheDir();

61

console.log('Main cache:', dirs.cacache);

62

console.log('TUF cache:', dirs.tufcache);

63

64

// Get cache directories for specific platform (testing)

65

const winDirs = cacheDir('win32');

66

const linuxDirs = cacheDir('linux');

67

const macDirs = cacheDir('darwin');

68

```

69

70

Platform-specific cache locations:

71

- **Windows**: `%LOCALAPPDATA%/npm-cache` and `%LOCALAPPDATA%/npm-cache/_tuf`

72

- **macOS**: `~/Library/Caches/npm` and `~/Library/Caches/npm/_tuf`

73

- **Linux**: `~/.npm` and `~/.npm/_tuf`

74

75

### Package Binary Detection

76

77

Check if a file path corresponds to a package binary script.

78

79

```javascript { .api }

80

/**

81

* Check if path is a package binary script

82

* @param {Object} pkg - Package manifest object

83

* @param {string} path - File path to check

84

* @returns {boolean} True if path is a package binary

85

*/

86

function isPackageBin(pkg, path);

87

```

88

89

**Usage Examples:**

90

91

```javascript

92

const { isPackageBin } = require('pacote/lib/util/is-package-bin');

93

94

const manifest = {

95

name: 'example-package',

96

bin: {

97

'example': './bin/example.js',

98

'helper': './scripts/helper.js'

99

}

100

};

101

102

// Check various paths

103

console.log(isPackageBin(manifest, 'bin/example.js')); // true

104

console.log(isPackageBin(manifest, 'scripts/helper.js')); // true

105

console.log(isPackageBin(manifest, 'lib/index.js')); // false

106

107

// Works with string bin field too

108

const simpleBin = { name: 'simple', bin: './cli.js' };

109

console.log(isPackageBin(simpleBin, 'cli.js')); // true

110

```

111

112

### Tar Archive Configuration

113

114

Generate tar creation options for reproducible package archives.

115

116

```javascript { .api }

117

/**

118

* Generate tar creation options for package archiving

119

* @param {Object} manifest - Package manifest object

120

* @returns {Object} Tar creation options

121

*/

122

function tarCreateOptions(manifest);

123

124

interface TarCreateOptions {

125

cwd: string;

126

prefix: string;

127

gzip: boolean;

128

file?: string;

129

portable: boolean;

130

noMtime: boolean;

131

filter: (path: string, stat: Object) => boolean;

132

}

133

```

134

135

**Usage Examples:**

136

137

```javascript

138

const { tarCreateOptions } = require('pacote/lib/util/tar-create-options');

139

const tar = require('tar');

140

141

const manifest = {

142

name: 'my-package',

143

version: '1.0.0'

144

};

145

146

// Get tar options for reproducible archives

147

const opts = tarCreateOptions(manifest);

148

console.log('Archive prefix:', opts.prefix); // 'package/'

149

console.log('Gzip enabled:', opts.gzip); // true

150

console.log('Portable format:', opts.portable); // true

151

152

// Create tar archive with consistent options

153

await tar.create(opts, ['src/', 'package.json', 'README.md']);

154

155

// Custom tar file destination

156

const fileOpts = { ...opts, file: './my-package-1.0.0.tgz' };

157

await tar.create(fileOpts, ['.']);

158

```

159

160

### String Path Utilities

161

162

Remove trailing slashes from file paths and URLs.

163

164

```javascript { .api }

165

/**

166

* Remove trailing slashes from input string

167

* @param {string} input - Input path or URL

168

* @returns {string} Path without trailing slashes

169

*/

170

function removeTrailingSlashes(input);

171

```

172

173

**Usage Examples:**

174

175

```javascript

176

const { removeTrailingSlashes } = require('pacote/lib/util/trailing-slashes');

177

178

// Clean file paths

179

console.log(removeTrailingSlashes('/path/to/dir/')); // '/path/to/dir'

180

console.log(removeTrailingSlashes('/path/to/dir///')); // '/path/to/dir'

181

182

// Clean URLs

183

console.log(removeTrailingSlashes('https://registry.npmjs.org/'));

184

// 'https://registry.npmjs.org'

185

186

// Preserve single paths

187

console.log(removeTrailingSlashes('/')); // '/'

188

console.log(removeTrailingSlashes('file.txt')); // 'file.txt'

189

```

190

191

### NPM Command Execution

192

193

Execute npm commands with proper environment and error handling.

194

195

```javascript { .api }

196

/**

197

* Execute npm command with spawn

198

* @param {string} npmBin - npm binary path

199

* @param {string[]} npmCommand - npm command arguments array

200

* @param {string} cwd - Working directory

201

* @param {Object} env - Environment variables

202

* @param {Object} extra - Additional spawn options

203

* @returns {Promise<Object>} Spawn result with stdout/stderr

204

*/

205

function npm(npmBin, npmCommand, cwd, env, extra);

206

207

interface NpmResult {

208

stdout: string;

209

stderr: string;

210

code: number;

211

signal: string | null;

212

}

213

```

214

215

**Usage Examples:**

216

217

```javascript

218

const { npm } = require('pacote/lib/util/npm');

219

220

// Run npm install

221

const result = await npm('npm', ['install'], './my-project', process.env, {

222

stdio: 'pipe'

223

});

224

225

console.log('Exit code:', result.code);

226

console.log('Output:', result.stdout);

227

228

// Run with custom npm binary

229

await npm('yarn', ['install', '--frozen-lockfile'], './workspace', {

230

...process.env,

231

NODE_ENV: 'production'

232

}, { stdio: 'inherit' });

233

234

// Run npm scripts

235

const scriptResult = await npm('npm', ['run', 'build'], './package', {

236

...process.env,

237

CI: 'true'

238

});

239

240

if (scriptResult.code !== 0) {

241

throw new Error(`Build failed: ${scriptResult.stderr}`);

242

}

243

```

244

245

## Import Patterns

246

247

These utilities can be imported individually for specific use cases:

248

249

```javascript

250

// Import specific utilities

251

const { addGitSha } = require('pacote/lib/util/add-git-sha');

252

const { cacheDir } = require('pacote/lib/util/cache-dir');

253

const { isPackageBin } = require('pacote/lib/util/is-package-bin');

254

const { tarCreateOptions } = require('pacote/lib/util/tar-create-options');

255

const { removeTrailingSlashes } = require('pacote/lib/util/trailing-slashes');

256

const { npm } = require('pacote/lib/util/npm');

257

258

// Or use through main pacote module (less common)

259

const pacote = require('pacote');

260

// Utilities are not re-exported, must import directly

261

```

262

263

## Advanced Usage Patterns

264

265

### Custom Package Processing Pipeline

266

267

```javascript

268

const { tarCreateOptions, isPackageBin } = require('pacote/lib/util/tar-create-options');

269

const { isPackageBin } = require('pacote/lib/util/is-package-bin');

270

const tar = require('tar');

271

const fs = require('fs');

272

273

async function processPackage(manifest, sourceDir) {

274

// Get tar options

275

const tarOpts = tarCreateOptions(manifest);

276

277

// Custom filter to exclude non-binary files from executable check

278

tarOpts.filter = (path, stat) => {

279

if (stat.isFile() && isPackageBin(manifest, path)) {

280

// Ensure binary files are executable

281

stat.mode |= 0o111;

282

}

283

return true;

284

};

285

286

// Create reproducible archive

287

await tar.create({

288

...tarOpts,

289

file: `${manifest.name}-${manifest.version}.tgz`,

290

cwd: sourceDir

291

}, ['.']);

292

}

293

```

294

295

### Cache Directory Management

296

297

```javascript

298

const { cacheDir } = require('pacote/lib/util/cache-dir');

299

const fs = require('fs').promises;

300

301

async function setupCustomCache() {

302

const dirs = cacheDir();

303

304

// Ensure cache directories exist

305

await fs.mkdir(dirs.cacache, { recursive: true });

306

await fs.mkdir(dirs.tufcache, { recursive: true });

307

308

// Set custom cache in pacote options

309

return {

310

cache: dirs.cacache,

311

tufCache: dirs.tufcache

312

};

313

}

314

315

// Use in pacote operations

316

const cacheOpts = await setupCustomCache();

317

const manifest = await pacote.manifest('express@latest', cacheOpts);

318

```