3.6.0 • Published 2 months ago

offensive v3.6.0

Weekly downloads
207
License
MIT
Repository
github
Last release
2 months ago

offensive :facepunch: js

NPM version

A human-readable, fast and boilerplate-free contract programming library for JavaScript.

Why would I want it?

  1. It reduces the boilerplate of writing assertion messsages to zero,
  2. Provides very intuitive and extensible DSL for writing assertions,
  3. Low core bundle size (22.5kB minified) and a way of bundling only needed assertions,
  4. Has zero runtime dependencies which greatly increases package security,
  5. It's TypeScript-friendly (contains its own .d.ts files).

Installation

npm install --save offensive

Loading The Library

// node-style require
const { contract } = require('offensive');
// or (with all assertions pre-loaded)
const { contract } = require('offensive/all');

// es6-style default import
import contract from 'offensive';
// or (with all assertions pre-loaded)
import contract from 'offensive/all';

Loading Assertions

In order to minimize the bundle payload, each assertion can be imported separately, either during application bootup or in each file where the specific assertions are used. The same assertion can be safely imported multiple times (importing an assertion second time is a no op).

// node-style require
require('offensive/assertions/aString/register');

// es6-style import
import 'offensive/assertions/aString/register';

When using the library on server-side, the bundle size is typically of no concern. For those situations, the library supports loading all assertions at once.

import 'offensive/assertions/register';
import { contract } from 'offensive';

// or even shorter
import { contract } from 'offensive/all';

Usage Examples

Precondition Checks A.K.A. Offensive Programming

Programming offensively is about throwing exceptions a lot. As soon as corrupted state or illegal parameter is detected, program is crashed with a descriptive error message. This technique greatly helps in finding bugs at their cause.

import 'offensive/assertions/fieldThat/register';
import 'offensive/assertions/aNumber/register';

import contract from 'offensive';

class Point2D {
  /**
   * @param init initializer object containing `x` and `y` properties.
   */
  constructor(init) {
    // Contract is satisfied if init contains
    // `x` and `y` property of type number.
    contract('init', init)
      .has.fieldThat('x', x => x.is.aNumber)
      .and.fieldThat('y', y => y.is.aNumber)
      .check();
    this.x = init.x;
    this.y = init.y;
  }
}

Now, following erroneus call...

const point = new Point2D({ x: 'a', y: null });

...will result in throwing following exception.

ContractError: init.x must be a number (got 'a') and init.y be a number (got null)
  at operatorContext (offensives/ContextFactory.js:34:33)
  at new Point2D (example.js:16:7)
  at Object.<anonymous> (example.js:22:15)

Alternatively, above contract could be implemented using multiple checks, but the error would only contain information about first failed check.

contract('init', init).is.anObject.check();
contract('init.x', init.x).is.aNumber.check();
contract('init.y', init.y).is.aNumber.check();

Above examples use only .anObject, .aNumber and .fieldThat assertions.

See full list of offensive.js built-in assertions.

Defensive Programming

Offensive programming is not applicable when collaborating with external components. A program should not crash in response to a bug in another program. Logging an error and trying to correct it by using default value or simply ignoring erroneus input would be a better way of handling such cases.

Ping Server

Following example is a fully functional HTTP-based ping server implemented using express.js with defensive checks on HTTP request implemented using offensive.js.

import * as express from 'express';
import * as bodyParser from 'body-parser';

import 'offensive/assertions/aString/register';
import 'offensive/assertions/fieldThat/register';
import contract from 'offensive';

const app = express();
app.use(bodyParser.json());

// A simple ping service which reflects messages sent to it.
app.post('/ping', function (req, res, next) {
  // Contract is satisfied if body has a message which is a string
  // (.propertyThat is an alias of .fieldThat assertion)
  const error = contract('req.body', req.body)
    .contains.propertyThat('message', message => message.is.aString)
    .getError();
  if (error) {
    res.status(400).json({ error });
    return;
  }

  const { message } = body;
  res.json({ message });
});

Above code presents defensive programming on the server side, but the same technique is applicable in the client. Client-server contract should be tested both, after receiving request from the client, and after receiving response from the server.

API Reference

Table of Contents

  1. Contract Function
  2. .check()
  3. .getError()
  4. Assertions
  5. Boolean Operators
  6. Legacy Call Operator

Contract Function

function contract<T>(varName : string, testedValue : T) : AssertionBuilder<T>;

Creates an instance of AssertionBuilder. Methods of returned instance add assertions to the builder. Requested assertions will be checked against given testedValue after executing assertion expression. In case some assertions fail, given name will be used as part of error message.

import contract from 'offensive';
...

contract('arg', arg)...

.check() aliases: throwIfUnmet()

interface AssertionBuilder<T> {
  check(errorName?: string = 'ContractError') : T;
}

Executes built assert expression. Returns testedValue if assertion succeeds. Throws ContractError in case it fails. intended for offensive programming.

import 'offensive/assertions/length';
import contract from 'offensive';

contract('arg', arg)
  .has.length(10)
  .check(); // <- executes built assert expression

NOTE: Assertion will not be run unless this method or .getError() is invoked.

.getError()

interface AssertionBuilder<T> {
  getError(errorName?: string = 'ContractError') : string | null;
}

Executes built assert expression. Returns error message if assertion fails. Returns null in case it succeeds. Intended for defensive programming.

import 'offensive/assertions/length';
import contract from 'offensive';

const error = contract('arg', arg)
  .has.length(10)
  .getError(); // <- executes built assert expression

NOTE: Assertion will not be run unless this method or .check() is invoked.

Assertions

offensive.js contains following built-in assertions.

Table of Contents

  1. .Null
  2. .Undefined
  3. .Empty
  4. .ofType(requiredType)
  5. .aBoolean
  6. .aNumber
  7. .anInteger
  8. .aString
  9. .anObject
  10. .aFunction
  11. .anArray
  12. .anInstanceOf(RequiredClass)
  13. .aDate
  14. .aRegExp
  15. .True
  16. .False
  17. .truthy
  18. .falsy
  19. .matches(regexp)
  20. .anEmail
  21. .anEmptyString
  22. .aNonEmptyString
  23. .anIntegerString
  24. .startsWith(substring)
  25. .endsWith(substring)
  26. .substring(substring)
  27. .equalTo
  28. .exactly
  29. .lessThan(rightBounds)
  30. .lessThanOrEqualTo(rightBounds)
  31. .greaterThan(leftBounds)
  32. .greaterThanOrEqualTo(leftBounds)
  33. .inRange(leftBounds, rightBounds)
  34. .before(rightBounds, boundsVarName?)
  35. .after(leftBounds, boundsVarName?)
  36. .field(fieldName)
  37. .fieldThat(fieldName, condition)
  38. .allFieldsThat(condition)
  39. .method(methodName)
  40. .length(requiredLength)
  41. .oneOf(set, name)
  42. .elementThat(index, assertName, condition)
  43. .allElementsThat(assertName, condition)
  44. .includes(element)
  45. .includesAllOf(element)
  46. .includesElementThat(condition)

.Null aliases: .null, .Nil, .nil

Asserts that checked value is null using ===. Typically used in combination with .not operator.

contract('arg', arg).is.not.Null.check();

.Undefined aliases: .undefined

Asserts that checked value is undefined. Typically used in combination with .not operator.

contract('arg', arg).is.not.Undefined.check();

.Empty aliases: .empty

Asserts that checked value is null or undefined. Typically used in combination with .not operator.

contract('arg', arg).is.not.Empty.check();

.ofType(requiredType : string) aliases: .type

Asserts that checked value is of requiredType by ivoking typeof operator.

contract('arg', arg).is.ofType('boolean').check();

.aBoolean aliases: .Boolean, .boolean

Asserts that checked value is a boolean by ivoking typeof operator.

contract('arg', arg).is.aBoolean.check();

.aNumber aliases: .Number, .number

Asserts that checked value is a number by ivoking typeof operator.

contract('arg', arg).is.aNumber.check();

.anInteger aliases: .Integer, .anInt, .int

Asserts that checked value is an integer by ivoking Number.isInteger.

contract('arg', arg).is.anInteger.check();

.aString aliases: .String, .string

Asserts that checked value is a string by ivoking typeof operator.

contract('arg', arg).is.aString.check();

.anObject aliases: .Object, .object

Asserts that checked value is an object by ivoking typeof operator. Be wary that this will be true also for array instances and null. Use .anArray and .Null in order to test for these specific cases.

contract('arg', arg).is.anObject.check();

.aFunction aliases: .Function, .function

Asserts that checked value is a function by ivoking typeof operator.

contract('arg', arg).is.aFunction.check();

.anArray aliases: .Array, .array

Asserts that checked value is an array by invoking Array.isArray.

contract('arg', arg).is.anArray.check();

.anInstanceOf(RequiredClass : Function) aliases: .instanceOf

Asserts that checked value is a instance of RequiredClass, by using instanceof operator.

contract('arg', arg).is.anInstanceOf(RegExp).check();

.aDate aliases: .Date, .date

Asserts that checked value is a instance of Date, by using instanceof operator.

contract('arg', arg).is.aDate.check();

.aRegExp aliases: .RegExp, .regexp

Asserts that checked value is a instance of RegExp, by using instanceof operator.

contract('arg', arg).is.aRegExp.check();

.True aliases: .true

Asserts that checked value is a boolean of value true.

contract('arg', arg).is.True.check();

.False aliases: .false

Asserts that checked value is a boolean of value false.

contract('arg', arg).is.False.check();

.truthy aliases: .Truthy, .truethy, .Truethy

Asserts that checked value is truthy (converts to true).

contract('arg', arg).is.truthy.check();

.falsy aliases: .Falsy, .falsey, .Falsey

Asserts that checked value is falsy (converts to false).

contract('arg', arg).is.falsy.check();

.matches(regexp : RegExp) aliases: .matchesRegexp, .matchesRegExp

Asserts that checked value fully matches given regexp.

contract('arg', arg).matches(/[a-z]+/).check();

.anEmail aliases: .Email, .email

Asserts that checked value is a valid email.

contract('arg', arg).is.anEmail();

.anEmptyString aliases: .emptyString

Asserts that checked value is an empty string (string of length 0).

contract('arg', arg).is.anEmptyString.check();

.aNonEmptyString aliases: .nonEmptyString

Asserts that checked value is an non-empty string (string of length > 0).

contract('arg', arg).is.aNonEmptyString.check();

.anIntegerString aliases: .IntegerString, .intString

Asserts that checked value is a valid string form of an integer.

contract('arg', arg).is.anIntegerString.check();

.startsWith(substring : string) aliases: .startWith, .startingWith

Asserts that checked value is a string that starts with given substring.

contract('arg', arg).is.startsWith('abc').check();

.endsWith(substring : string) aliases: .endWith, .endingWith

Asserts that checked value is a string that ends with given substring.

contract('arg', arg).is.endsWith('xyz').check();

.substring(substring : string) aliases: .substr

Asserts that checked value is a string that is contains given substring.

contract('arg', arg).has.substring('xyz').check();

.equalTo(another : any) aliases: .equal, .equals

Asserts that checked value is equal to another. Comparison is made with == (double equals) operator.

contract('arg', arg).is.equalTo(100).check();

.exactly(another : any)

Asserts that checked value is exactly the same as another. Comparison is made with === (triple equals) operator.

contract('arg', arg).is.exactly(instance).check();

.lessThan(rightBounds : number) aliases: .lt, .less

Asserts that checked value is less than rightBounds.

contract('arg', arg).is.lessThan(100).check();

.lessThanOrEqualTo(rightBounds : number) aliases: .lte, .lessThanEqual

Asserts that checked value is less than or equal to rightBounds.

contract('arg', arg).is.lessThanOrEqualTo(100).check();

.greaterThan(leftBounds : number) aliases: .gt, .greater

Asserts that checked value is greater than leftBounds.

contract('arg', arg).is.greaterThan(0).check();

.greaterThanOrEqualTo(leftBounds : number) aliases: .gte, .greaterThanEqual

Asserts that checked value is greater than or equal to leftBounds.

contract('arg', arg).is.greaterThanOrEqualTo(0).check();

.inRange(leftBounds : number, rightBounds : number) aliases: .between

Asserts that checked value is grater than or equal to leftBounds and less than rightBounds.

contract('arg', arg).is.inRange(0, 100).check();

.before(rightBounds : Date, boundsVarName ?: string)

Asserts that checked value a Date chronologically before rightBounds.

contract('arg', arg).is.before(new Date(0), 'Epoch').check();

.after(leftBounds : Date, boundsVarName ?: string)

Asserts that checked value a Date chronologically after leftBounds.

contract('arg', arg).is.after(new Date(0), 'Epoch').check();

.field(fieldName : string) aliases: .property

Asserts that checked value has field of name propertyName.

contract('arg', arg).has.property('length').check();

.fieldThat(fieldName : string, builder : FieldAssertionBuilder)

Asserts that checked value has field of name propertyName, which satisfied assertion created in gived builder.

contract('arg', arg)
  .has.propertyThat('x', x => x.is.aNumber)
  .check();

.allFieldsThat(builder : FieldAssertionBuilder)

Asserts that: 1. Checked value is not null or undefined, 2. Value of each field of this object satisfies assertuin created by given builder.

contract('arg', arg)
  .has.allFieldsThat(field => field.is.aNumber)
  .check();

.method(methodName : string)

Asserts that checked value has field of name methodName which is a function.

contract('arg', arg).has.method('toString').check();

.length(requiredLength : number) aliases: .len

Asserts that checked value has property of name "length" and value of requiredLength.

contract('arg', arg).has.length(0).check();

.oneOf(set : any[], name ?: string) aliases: .elementOf, .containedIn

Asserts that checked value is contained in given set. Given name (if present) is used as a name of set in produced error message.

contract('arg', arg)
  .is.oneOf([ 'started', 'running', 'finished' ])
  .check();

// or (with set name used in the error message)
contract('arg', arg)
  .is.oneOf([ 'started', 'running', 'finished' ], 'valid status')
  .check();

.elementThat(index : number, builder : ElemAssertionBuilder) aliases: .elementWhichIs

Asserts that: 1. Checked value is an array of length at least index+ 1, 2. Element under index satisfies assertion created by given builder.

contract('arg', arg)
  .has.elementThat(0, elem => elem.is.anInteger)
  .check();

.allElementsThat(builder : ElemAssertionBuilder) aliases: .allElementsWhich

Asserts that: 1. Checked value is an array, 2. Each element of this array satisfies assertion created by given builder.

contract('arg', arg)
  .has.allElementsThat(elem => elem.is.anInteger)
  .check();

.includes(element : any) aliases: .contains

Asserts that: 1. Checked value is an array, 2. The array contains given element.

contract('arg', arg)
  .has.includes(elem)
  .check();

.includesAllOf(elements : any[]) aliases: .includesAll

Asserts that: 1. Checked value is an array, 2. The array contains all elements of elements.

contract('categories', categories)
  .has.includesAlOf(['functional', 'performance'])
  .check();

.includesElementThat(builder: ElemAssertionBuilder) aliases: .includesElement

Asserts that: 1. Checked value is an array, 2. The array contains at least one element that satisfies assertion created by given builder.

contract('arg', arg)
  .includesElementThat(elem => elem.is.anInteger)
  .check();

Boolean Operators

offensive.js implements following operators.

Table of Contents

  1. .and
  2. .or
  3. .not

.and aliases: .of, .with

Logical conjunction of two boolean values which are separated by call to .and operator.

contract('arg', arg)
  .has.length(2)
  .and.allElementsThat(elem => elem.is.aNumber)
  .check();

.or()

Logical alternative of two (or more) values which are separated by call to .or operator.

contract('arg', arg)
  .is.anObject.or.aFunction
  .check();

.not aliases: .no, .dont, .doesnt

Logical negation of an assertion after .not operator.

contract('arg', arg).is.not.Undefined.check();

Legacy Call Operator

interface AssertionBuilder<T> {
  () : T;
}

Alias for .check().

import 'offensive/assertions/aString';
import contract from 'offensive';

contract('arg', arg).is.aString.check(); // <- executes the expression
contract('arg', arg).is.aString(); // <- the same but with a call operator

The call operator was the only way to execute an offensive expression until version 2. Initially, it was seen as an elegant API with the least amount of boilerplate possible. While this is true for all assertions without arguments, assertions with arguments have their own call operator. This led to situations where two consecutive call operators were needed in order to execute the expression.

import 'offensive/assertions/length';
import contract from 'offensive';

contract('arg', arg).has.length(3)(); // <- double call operators weirdness
contract('arg', arg).has.length(3).check(); // <- this looks much better

.check() (introduced in version 3) solves the problem of readability and adds a bit of explicitness at the cost of a little bit more code. The call operator is still supported for backwards compatilibity.

Extension API

offensive.js is extensible, but extension API is not documented yet. If you wish to write an extension, take a look at the implementation of built-in assertions, operators and also at the interface of Registry class.

License

Released under MIT license.

3.6.0

2 months ago

3.5.0

2 months ago

3.4.0

2 months ago

3.3.0

4 months ago

3.2.0

6 months ago

3.1.1

8 months ago

3.0.4

9 months ago

3.0.3

10 months ago

3.0.2

1 year ago

3.0.1

1 year ago

3.0.0

1 year ago

2.8.1

1 year ago

2.8.0

1 year ago

2.7.41

2 years ago

2.7.40

3 years ago

2.7.39

3 years ago

2.7.38

3 years ago

2.7.37

3 years ago

2.7.36

3 years ago

2.7.35

3 years ago

2.7.34

3 years ago

2.7.33

3 years ago

2.7.32

3 years ago

2.7.31

3 years ago

2.7.30

3 years ago

2.7.29

3 years ago

2.7.28

3 years ago

2.7.27

3 years ago

2.7.26

3 years ago

2.7.25

3 years ago

2.7.24

3 years ago

2.7.23

3 years ago

2.7.22

3 years ago

2.7.21

4 years ago

2.7.20

4 years ago

2.7.19

4 years ago

2.7.18

4 years ago

2.7.17

4 years ago

2.7.16

4 years ago

2.7.15

4 years ago

2.7.14

4 years ago

2.7.13

4 years ago

2.7.12

4 years ago

2.7.11

4 years ago

2.7.10

4 years ago

2.7.9

4 years ago

2.7.8

4 years ago

2.7.7

4 years ago

2.7.6

4 years ago

2.7.5

4 years ago

2.7.4

4 years ago

2.7.3

4 years ago

2.7.2

4 years ago

2.7.1

4 years ago

2.7.0

4 years ago

2.6.25

4 years ago

2.6.24

4 years ago

2.6.23

4 years ago

2.6.22

4 years ago

2.6.21

4 years ago

2.6.20

4 years ago

2.6.19

4 years ago

2.6.18

4 years ago

2.6.17

4 years ago

2.6.16

4 years ago

2.6.15

4 years ago

2.6.14

4 years ago

2.6.13

4 years ago

2.6.12

4 years ago

2.6.11

4 years ago

2.6.10

4 years ago

2.6.9

4 years ago

2.6.8

4 years ago

2.6.7

4 years ago

2.6.6

4 years ago

2.6.5

4 years ago

2.6.4

4 years ago

2.6.3

4 years ago

2.6.2

4 years ago

2.6.1

4 years ago

2.6.0

4 years ago

2.5.0

4 years ago

2.4.7

4 years ago

2.4.6

4 years ago

2.4.5

4 years ago

2.4.4

4 years ago

2.4.3

4 years ago

2.4.2

4 years ago

2.4.1

4 years ago

2.4.0

4 years ago

2.3.1

4 years ago

2.3.0

4 years ago

2.2.1

4 years ago

2.2.0

4 years ago

2.1.87

4 years ago

2.1.86

4 years ago

2.1.85

4 years ago

2.1.84

4 years ago

2.1.83

4 years ago

2.1.82

4 years ago

2.1.81

4 years ago

2.1.80

4 years ago

2.1.79

4 years ago

2.1.78

4 years ago

2.1.77

4 years ago

2.1.76

4 years ago

2.1.75

4 years ago

2.1.74

4 years ago

2.1.73

4 years ago

2.1.72

4 years ago

2.1.71

4 years ago

2.1.70

4 years ago

2.1.69

4 years ago

2.1.68

4 years ago

2.1.67

4 years ago

2.1.66

4 years ago

2.1.65

4 years ago

2.1.64

4 years ago

2.1.63

4 years ago

2.1.62

4 years ago

2.1.61

4 years ago

2.1.60

4 years ago

2.1.58

4 years ago

2.1.59

4 years ago

2.1.57

4 years ago

2.1.56

4 years ago

2.1.55

4 years ago

2.1.54

4 years ago

2.1.53

4 years ago

2.1.52

4 years ago

2.1.51

4 years ago

2.1.50

4 years ago

2.1.49

4 years ago

2.1.48

4 years ago

2.1.47

4 years ago

2.1.46

4 years ago

2.1.45

4 years ago

2.1.44

4 years ago

2.1.43

4 years ago

2.1.42

4 years ago

2.1.41

4 years ago

2.1.40

4 years ago

2.1.39

4 years ago

2.1.38

4 years ago

2.1.37

4 years ago

2.1.36

4 years ago

2.1.35

4 years ago

2.1.34

4 years ago

2.1.33

4 years ago

2.1.32

4 years ago

2.1.31

4 years ago

2.1.30

4 years ago

2.1.29

5 years ago

2.1.28

5 years ago

2.1.27

5 years ago

2.1.26

5 years ago

2.1.25

5 years ago

2.1.24

5 years ago

2.1.23

5 years ago

2.1.22

5 years ago

2.1.21

5 years ago

2.1.20

5 years ago

2.1.19

5 years ago

2.1.18

5 years ago

2.1.17

5 years ago

2.1.16

5 years ago

2.1.15

5 years ago

2.1.14

5 years ago

2.1.13

5 years ago

2.1.12

5 years ago

2.1.11

5 years ago

2.1.10

5 years ago

2.1.9

5 years ago

2.1.8

5 years ago

2.1.7

5 years ago

2.1.6

5 years ago

2.1.5

5 years ago

2.1.4

5 years ago

2.1.3

5 years ago

2.1.2

5 years ago

2.1.1

5 years ago

2.1.0

5 years ago

2.0.10

5 years ago

2.0.9

5 years ago

2.0.8

5 years ago

2.0.7

5 years ago

2.0.6

5 years ago

2.0.5

5 years ago

2.0.4

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.2.1

6 years ago

1.2.0

6 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.9.3

6 years ago

0.9.2

6 years ago

0.9.1

6 years ago

0.9.0

6 years ago

0.8.2

6 years ago

0.8.0

7 years ago

0.7.3

7 years ago

0.7.2

7 years ago

0.7.1

8 years ago

0.7.0

8 years ago

0.6.0

8 years ago

0.5.1

8 years ago

0.5.0

8 years ago

0.4.0

8 years ago

0.3.0

8 years ago

0.2.0

8 years ago

0.1.0

8 years ago