or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

build-compilation.mdconfiguration.mddevelopment-integration.mdindex.mdmodule-packaging.mdpackagers.mdutilities.mdwebpack-integration.md

utilities.mddocs/

0

# Utilities

1

2

Core utility functions for webpack integration, process management, and serverless framework operations.

3

4

## Capabilities

5

6

### Runtime Detection Utilities

7

8

Utilities for detecting runtime environments and function configurations.

9

10

```javascript { .api }

11

/**

12

* Check if a runtime string indicates a Node.js runtime

13

* @param runtime - Runtime identifier (e.g., 'nodejs18.x', 'python3.9')

14

* @returns True if runtime is Node.js-based

15

*/

16

function isNodeRuntime(runtime: string): boolean;

17

18

/**

19

* Get all Node.js functions from the serverless configuration

20

* @returns Array of function names that use Node.js runtime

21

*/

22

function getAllNodeFunctions(): string[];

23

24

/**

25

* Check if the serverless provider is Google Cloud Platform

26

* @param serverless - Serverless framework instance

27

* @returns True if provider is Google Cloud

28

*/

29

function isProviderGoogle(serverless: ServerlessInstance): boolean;

30

```

31

32

**Usage Examples:**

33

34

```javascript

35

const { isNodeRuntime, getAllNodeFunctions, isProviderGoogle } = require('serverless-webpack/lib/utils');

36

37

// Check if runtime is Node.js

38

if (isNodeRuntime('nodejs18.x')) {

39

console.log('Using Node.js runtime');

40

}

41

42

// Get all Node.js functions (context: 'this' bound to plugin instance)

43

const nodeFunctions = getAllNodeFunctions.call(this);

44

console.log('Node.js functions:', nodeFunctions);

45

46

// Check provider

47

if (isProviderGoogle(serverless)) {

48

console.log('Using Google Cloud provider');

49

}

50

```

51

52

### Process Management Utilities

53

54

Utilities for spawning child processes and generating unique identifiers.

55

56

```javascript { .api }

57

/**

58

* Execute a child process with unlimited stdout/stderr buffer

59

* @param command - Command to execute

60

* @param args - Array of command arguments

61

* @param options - Child process spawn options

62

* @returns Promise resolving to stdout and stderr strings

63

* @throws SpawnError if process exits with non-zero code

64

*/

65

function spawnProcess(command: string, args?: string[], options?: object): Promise<{stdout: string, stderr: string}>;

66

67

/**

68

* Generate a unique GUID string

69

* @returns UUID-like string for unique identification

70

*/

71

function guid(): string;

72

```

73

74

**Usage Examples:**

75

76

```javascript

77

const { spawnProcess, guid, SpawnError } = require('serverless-webpack/lib/utils');

78

79

// Execute npm install

80

try {

81

const { stdout, stderr } = await spawnProcess('npm', ['install'], { cwd: '/path/to/project' });

82

console.log('Install output:', stdout);

83

} catch (error) {

84

if (error instanceof SpawnError) {

85

console.error('Install failed:', error.stderr);

86

}

87

}

88

89

// Generate unique identifier

90

const uniqueId = guid();

91

console.log('Generated ID:', uniqueId); // e.g., "a1b2-c3d4-e5f6-g7h8-i9j0k1l2m3n4"

92

```

93

94

### Module Cache Management

95

96

Utilities for managing Node.js require cache and module resolution.

97

98

```javascript { .api }

99

/**

100

* Remove a module and its dependencies from the require cache

101

* @param moduleName - Name of module to purge from cache

102

* @returns Promise that resolves when cache is cleared

103

*/

104

function purgeCache(moduleName: string): Promise<void>;

105

106

/**

107

* Search require cache for a module and process it with callback

108

* @param moduleName - Module name to search for

109

* @param processor - Function to call for each cache entry found

110

* @returns Promise that resolves when processing is complete

111

*/

112

function searchAndProcessCache(moduleName: string, processor: (mod: any) => void): Promise<void>;

113

```

114

115

**Usage Examples:**

116

117

```javascript

118

const { purgeCache, searchAndProcessCache } = require('serverless-webpack/lib/utils');

119

120

// Clear webpack config from cache for hot reloading

121

await purgeCache('./webpack.config.js');

122

123

// Process all lodash modules in cache

124

await searchAndProcessCache('lodash', (mod) => {

125

console.log('Found lodash module:', mod.id);

126

});

127

```

128

129

### Data Parsing Utilities

130

131

Utilities for safe data parsing and string manipulation.

132

133

```javascript { .api }

134

/**

135

* Safely parse JSON string without throwing errors

136

* @param str - JSON string to parse

137

* @returns Parsed object or null if parsing fails

138

*/

139

function safeJsonParse(str: string): any | null;

140

141

/**

142

* Split string by line breaks (handles both \n and \r\n)

143

* @param str - String to split into lines

144

* @returns Array of lines

145

*/

146

function splitLines(str: string): string[];

147

```

148

149

**Usage Examples:**

150

151

```javascript

152

const { safeJsonParse, splitLines } = require('serverless-webpack/lib/utils');

153

154

// Parse JSON safely

155

const packageJson = safeJsonParse(packageFileContent);

156

if (packageJson) {

157

console.log('Package name:', packageJson.name);

158

} else {

159

console.log('Invalid JSON format');

160

}

161

162

// Split multiline output

163

const lines = splitLines(commandOutput);

164

lines.forEach((line, index) => {

165

console.log(`Line ${index + 1}: ${line}`);

166

});

167

```

168

169

## Error Handling

170

171

### SpawnError Class

172

173

Enhanced error class for process execution failures.

174

175

```javascript { .api }

176

/**

177

* Error thrown by spawnProcess when child process fails

178

*/

179

class SpawnError extends Error {

180

stdout: string; // Process stdout output

181

stderr: string; // Process stderr output

182

183

constructor(message: string, stdout: string, stderr: string);

184

185

/**

186

* Convert error to string with stderr included

187

* @returns Formatted error message with stderr

188

*/

189

toString(): string;

190

}

191

```

192

193

**Usage Examples:**

194

195

```javascript

196

const { spawnProcess, SpawnError } = require('serverless-webpack/lib/utils');

197

198

try {

199

await spawnProcess('npm', ['test']);

200

} catch (error) {

201

if (error instanceof SpawnError) {

202

console.error('Command failed:', error.message);

203

console.error('Error output:', error.stderr);

204

console.log('Partial output:', error.stdout);

205

}

206

}

207

```

208

209

## Import Patterns

210

211

```javascript

212

// Import specific utilities

213

const { isNodeRuntime, spawnProcess } = require('serverless-webpack/lib/utils');

214

215

// Import all utilities

216

const utils = require('serverless-webpack/lib/utils');

217

218

// Access utilities

219

const isNode = utils.isNodeRuntime('nodejs18.x');

220

const result = await utils.spawnProcess('npm', ['--version']);

221

```

222

223

## Integration with Plugin

224

225

These utilities are used internally by the serverless-webpack plugin and can also be accessed directly for custom webpack configurations or external tooling:

226

227

```javascript

228

// In webpack.config.js - access through serverless-webpack lib

229

const slsw = require('serverless-webpack');

230

231

// Check if running in local development

232

if (slsw.lib.webpack.isLocal) {

233

// Use utilities for local-specific configuration

234

const utils = require('serverless-webpack/lib/utils');

235

const uniqueId = utils.guid();

236

}

237

```