npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

argsert

v1.0.9

Published

Type assertion utility for method arguments.

Downloads

14

Readme

Argsert

Simple argument type assertion.

Install

$ npm install argsert

Usage

Argsert works by mapping defined types for each argument in a method's signature to a given type. Arguments can be marked as required or optional using the <> and [] tokens. If an argument can be of multiple types simply separate each type by |.

import * as Argsert from 'argsert';
const argsert = Argsert.configure(/* your options here */);

// This method allows "email" to be the second argument.
function addUser(name, age, email) {
  argsert.assert('<string> <string|number> [string]', [name, age, email]);
}

Tokens

Angle brackets <> denote a required argument square brackets [] denote an optional argument. Each definition is separated by a space. To define multiple types for an argument we use a | to denote the argument accepts multiple types.

For example the following creates definitions for a method with two arguments. The first being a string and the second an array or args.

const map = '<string> [array]'

Multiple assertion types.

const map = '<string> [string|array]'

Custom named argument by prefixing with "some_name:". This would replace the "first" since its the first arg with "username" instead. For complex methods with multiple overrides using the positional placeholders e.g. first, second... is likely a better option.

const map = '<username:string> [array]'

Options

The defaults will likely work for most use cases. You may wish to have errors not thrown which you can disable by setting "onError" to false. Or you may want to use your own validators other than the defaults that are shipped.

Validators

Validators are simple configuation objects with two properties. A handler function and a key representing whether it's enabled or disabled. By default there are only three validators as listed below.

Add

Adding a validator is pretty easy just provide a name and a config with a handler method. The handler should return either null if it passes or a string which will be converted to an error, an Error instance or an IArgsertValidationResult object containing the error and optionally the offending argument.

argsert.add('myValidator', {

  enabled: true,
  handler: (result) => {

    // Argsert creates two arrays of keys one for
    // required and one for optional arguments.
    // For this example validator we'll combine
    // them for this example.

    // Filter out any arg which contains
    // a type of "email".
    const keys =
      result
        .required
        .concat(result.optional);

    keys.forEach(i => {

      // Get the config for this argument.
      // A parsed argument looks like the below.

      // arg = {
      //    index: 0
      //    type: 'string'
      //    types: ['string']
      //    value: any;
      //    required: boolean;
      // }

      // Get the arg's parsed config by key.
      // The keys are basically the argument's index.
      const arg = result[i];

      // Run some check if valid return null.
      if (valid)
        return null;

      // Otherwise return the string or error along
      // with the optional offending argument
      return {
        error: new Error(`whoops ${arg.value} doesn't look right...`),
        argument: arg;
      };

      // NOTE: you can also just return the
      // error string or Error instance

    });

  }
});

Enable & Disable

You can call .enable() or .disable() to define which validators are active or inactive and then toggle them back.

argsert
  .disable()              // disable all.
  .enable('mismatch');    // enable only mismatch.

Validate Once

The validate once method enables only the validators you provide and uses them once then discards reverting to previous settings.

argsert
  .once('unmet') // only unmet is enabled for next validate call.
  .assert('<string> <string|number>', arguments);

Types & Parser

By default the following types are supported.

  • string
  • boolean
  • number
  • array
  • function
  • object
  • regexp
  • null
  • undefined

If you wish to implement even more granular detail as to types this can be done quite easily by providing your own parser. Below is the logic for the default parser as you can see it's rather simple.

It would be trivial to implement logic for say floats or say email addresses and so on.

 function parseType(val: any) {

    if (val === null)
      return 'null';

    if ((val instanceof RegExp))
      return 'regexp';

    if (Array.isArray(val))
      return 'array';

    return typeof val;

  }

Using a Custom Parser

You could also provide this in your configuration object.

argsert.option('parser', myCustomParser);

Templates

These are primarily exposed for use with localization. It's important that the same number of format args are maintained. If you wish greater control you'll need to create your own validators rather than using the defaults.

Docs

See https://blujedis.github.io/argsert/

Change

See CHANGE.md

License

See LICENSE