or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md
tile.json

index.mddocs/

0

# Invariant

1

2

Invariant is a utility function for asserting invariant conditions in JavaScript applications. It enables developers to create descriptive error messages during development while providing generic error messages in production environments for security and performance optimization.

3

4

## Package Information

5

6

- **Package Name**: invariant

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install invariant`

10

11

## Core Imports

12

13

```javascript

14

const invariant = require('invariant');

15

```

16

17

For ES6 modules (via bundler with CommonJS interop):

18

19

```javascript

20

import invariant from 'invariant';

21

// or

22

import * as invariant from 'invariant';

23

```

24

25

## Basic Usage

26

27

```javascript

28

const invariant = require('invariant');

29

30

// Assert a condition with a descriptive message

31

invariant(user.isAuthenticated, 'User must be authenticated to access this resource');

32

33

// With %s formatting (only %s placeholders supported)

34

invariant(user.age >= 18, 'User %s must be at least %s years old', user.name, 18);

35

36

// Multiple substitutions (supports up to 6 arguments)

37

invariant(

38

score >= 0 && score <= 100,

39

'Score %s for user %s must be between %s and %s',

40

score,

41

user.name,

42

0,

43

100

44

);

45

```

46

47

## Capabilities

48

49

### Condition Assertion

50

51

Asserts that a condition is truthy, throwing an error with environment-aware messaging if the condition fails.

52

53

```javascript { .api }

54

/**

55

* Asserts that a condition is truthy, throwing an error if false

56

* @param {any} condition - The condition to test

57

* @param {string} [format] - Format string with %s placeholders (only %s supported, not full sprintf)

58

* @param {any} a - First substitution argument

59

* @param {any} b - Second substitution argument

60

* @param {any} c - Third substitution argument

61

* @param {any} d - Fourth substitution argument

62

* @param {any} e - Fifth substitution argument

63

* @param {any} f - Sixth substitution argument

64

* @throws {Error} Throws Error when condition is falsy

65

* @returns {void}

66

*/

67

function invariant(condition, format, a, b, c, d, e, f);

68

```

69

70

**Environment Behavior:**

71

72

- **Development Mode** (`NODE_ENV !== 'production'`):

73

- Requires `format` parameter - throws Error if format is undefined

74

- Provides detailed error messages with %s substitution

75

- Error name is "Invariant Violation"

76

- Error message contains the formatted string with substitutions

77

78

- **Production Mode** (`NODE_ENV === 'production'`):

79

- Does not require `format` parameter

80

- Strips detailed error messages for security/performance

81

- Provides generic "Minified exception occurred" message when format is undefined

82

- Still throws errors to maintain logic consistency

83

84

**Error Properties:**

85

86

```javascript { .api }

87

interface InvariantError extends Error {

88

name: string; // "Invariant Violation" (with format) or "Error" (without format)

89

message: string; // Formatted message or generic production message

90

framesToPop: number; // Always 1 (for stack trace optimization)

91

}

92

```

93

94

**Platform Variants:**

95

96

- **Node.js Version**: Caches `process.env.NODE_ENV` at module load time for performance

97

- **Browser Version**: Checks `process.env.NODE_ENV` on each call, designed for browserify + envify transforms

98

99

**Usage Examples:**

100

101

```javascript

102

// Basic assertion

103

invariant(condition, 'Something went wrong');

104

105

// With single substitution

106

invariant(user !== null, 'User %s not found', userId);

107

108

// With multiple substitutions

109

invariant(

110

price >= minPrice && price <= maxPrice,

111

'Product %s price %s must be between %s and %s',

112

productName,

113

price,

114

minPrice,

115

maxPrice

116

);

117

118

// Production vs Development behavior

119

if (process.env.NODE_ENV !== 'production') {

120

// Development: requires format parameter

121

invariant(condition, 'Detailed error message');

122

} else {

123

// Production: format parameter optional

124

invariant(condition); // Throws generic error message

125

}

126

```

127

128

## Error Handling

129

130

The invariant function throws standard JavaScript `Error` objects:

131

132

- **In Development**: Detailed error messages with "Invariant Violation" name

133

- **In Production**: Generic error messages to avoid exposing sensitive information

134

- **All Environments**: `framesToPop` property set to 1 for cleaner stack traces

135

136

```javascript

137

try {

138

invariant(false, 'User %s is not authorized', username);

139

} catch (error) {

140

// Development: error.message = "User alice is not authorized"

141

// Production: error.message = "User alice is not authorized" (same, but only if format provided)

142

console.error('Invariant violation:', error.message);

143

}

144

```

145

146

## Build Tool Integration

147

148

- **Browserify**: Configured with `loose-envify` transform for `process.env.NODE_ENV` replacement

149

- **Environment Variables**: Supports NODE_ENV-based dead code elimination in production builds

150

- **Bundle Optimization**: Production builds can strip development-only code paths through static analysis