New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

envsafe

Package Overview
Dependencies
Maintainers
1
Versions
19
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

envsafe - npm Package Compare versions

Comparing version 1.0.0-0 to 1.0.0-1

dist/freezeObject.d.ts

41

dist/envsafe.cjs.development.js

@@ -151,2 +151,34 @@ 'use strict';

var inspectables = ['length', 'inspect', 'hasOwnProperty', 'toJSON', // jest stuff:
'asymmetricMatch', 'nodeType', '$$typeof', 'constructor', '@@__IMMUTABLE_ITERABLE__@@', '@@__IMMUTABLE_RECORD__@@', '_isMockFunction', // For libs that use `then` checks to see if objects are Promises
// https://github.com/af/envalid/issues/74
'then', // For usage with TypeScript esModuleInterop flag
'__esModule'];
function freezeObject(envObj, env) {
var frozen = Object.freeze ? Object.freeze(envObj) : envObj;
return global.Proxy ? new Proxy(frozen, {
get: function get(_target, name) {
// These checks are needed because calling console.log on a
// proxy that throws crashes the entire process. This whitelists
// the necessary properties for `console.log(frozen)`, `frozen.length`,
// `frozen.hasOwnProperty('string')` to work.
if (typeof name !== 'string' || inspectables.includes(name)) {
return frozen[name];
}
var varExists = frozen.hasOwnProperty(name);
if (!varExists) {
if (env.hasOwnProperty(name)) {
throw new ReferenceError("[envsafe] Env var " + String(name) + " was accessed but not validated. This var is set in the environment; please add an envsafe validator for it.");
}
throw new ReferenceError("[envsafe] Env var \"" + String(name) + "\" not found");
}
return frozen[name];
}
}) : frozen;
}
function defaultReporterText(_ref) {

@@ -194,3 +226,3 @@ var errors = _ref.errors;

throw new Error(text);
throw new TypeError(text);
}

@@ -233,3 +265,5 @@

_ref2$env = _ref2.env,
env = _ref2$env === void 0 ? process.env : _ref2$env;
env = _ref2$env === void 0 ? process.env : _ref2$env,
_ref2$strict = _ref2.strict,
strict = _ref2$strict === void 0 ? false : _ref2$strict;

@@ -262,3 +296,3 @@ var errors = {};

return Object.freeze ? Object.freeze(output) : output;
return strict ? freezeObject(output, env) : output;
}

@@ -357,2 +391,3 @@

exports.envsafe = envsafe;
exports.freezeObject = freezeObject;
exports.invalidEnvError = invalidEnvError;

@@ -359,0 +394,0 @@ exports.json = json;

2

dist/envsafe.cjs.production.min.js

@@ -1,2 +0,2 @@

"use strict";function t(){return(t=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function e(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}function r(t){return(r=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function n(t,e){return(n=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function o(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}function i(t,e,r){return(i=o()?Reflect.construct:function(t,e,r){var o=[null];o.push.apply(o,e);var i=new(Function.bind.apply(t,o));return r&&n(i,r.prototype),i}).apply(null,arguments)}function u(t){var e="function"==typeof Map?new Map:void 0;return(u=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,o)}function o(){return i(t,arguments,r(this).constructor)}return o.prototype=Object.create(t.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),n(o,t)})(t)}function c(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}Object.defineProperty(exports,"__esModule",{value:!0});var s=function(t){function r(e){var n;return n=t.call(this,e)||this,Object.setPrototypeOf(c(n),r.prototype),n}return e(r,t),r}(u(TypeError)),a=function(t,e){return new s("Invalid "+t+' input: "'+e+'"')},f=function(t){function r(e){var n;return n=t.call(this,e)||this,Object.setPrototypeOf(c(n),r.prototype),n}return e(r,t),r}(u(ReferenceError));function p(t){for(var e=t.errors,r=[],n=[],o=0,i=Object.keys(e);o<i.length;o++){var u=i[o],c=e[u];c instanceof f?n.push(" "+u+": "+(c.message||"required")):r.push(" "+u+": "+(c.message||"invalid"))}return r.length&&r.unshift("❌ Invalid environment variables:"),n.length&&n.unshift("💨 Missing environment variables:"),["========================================"].concat(r,n,["========================================"]).join("\n")}function l(t){var e,r,n=p(t);throw console.error(n),"undefined"!=typeof process&&(null===(e=process)||void 0===e?void 0:e.exit)&&process.exit(1),"undefined"!=typeof window&&(null===(r=window)||void 0===r?void 0:r.alert)&&window.alert(n),new Error(n)}function v(t){var e,r=t.env,n=t.validator,o=null!==(e=n.input)&&void 0!==e?e:r[t.key];if(void 0===o&&"production"!==r.NODE_ENV&&void 0!==n.devDefault&&(o=n.devDefault),void 0===o&&void 0!==n.default&&(o=n.default),void 0===o)throw new f("Missing value");var i=n._parse(o);if(n.choices&&!n.choices.includes(i))throw new s('Value "'+i+'" not in choices ['+n.choices+"]");return i}var d=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function h(e){return function(r){return void 0===r&&(r={}),t({},r,{_parse:e})}}var y=h((function(t){switch(t){case!0:case"true":case"t":case"1":return!0;case!1:case"false":case"f":case"0":return!1;default:throw a("str",t)}})),w=h((function(t){if("string"!=typeof t)throw a("str",t);return t})),b=h((function(t){if(!d.test(t))throw a("email",t);return t})),O=h((function(t){var e=+t;if(Number.isNaN(e))throw a("num",t);return e})),x=h((function(t){var e=+t;if(Number.isNaN(e)||""+e!=""+t||e%1!=0||e<1||e>65535)throw a("port",t);return e})),g=h((function(t){try{return new URL(t),t}catch(e){throw a("url",t)}})),j=h((function(t){try{return"string"!=typeof t?t:JSON.parse(t)}catch(e){throw a("json",t)}}));exports.InvalidEnvError=s,exports.MissingEnvError=f,exports.bool=y,exports.defaultReporter=l,exports.defaultReporterText=p,exports.email=b,exports.envsafe=function(t,e){var r=void 0===e?{}:e,n=r.reporter,o=void 0===n?l:n,i=r.env,u=void 0===i?process.env:i,c={},s={};for(var a in t){var f=t[a];try{var p=v({env:u,validator:f,key:a});s[a]=p}catch(t){c[a]=t}}return Object.keys(c).length&&o({errors:c,output:s,env:u}),Object.freeze?Object.freeze(s):s},exports.invalidEnvError=a,exports.json=j,exports.makeValidator=h,exports.num=O,exports.port=x,exports.str=w,exports.url=g;
"use strict";function e(){return(e=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function t(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function r(e){return(r=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function n(e,t){return(n=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function o(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function i(e,t,r){return(i=o()?Reflect.construct:function(e,t,r){var o=[null];o.push.apply(o,t);var i=new(Function.bind.apply(e,o));return r&&n(i,r.prototype),i}).apply(null,arguments)}function u(e){var t="function"==typeof Map?new Map:void 0;return(u=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,o)}function o(){return i(e,arguments,r(this).constructor)}return o.prototype=Object.create(e.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),n(o,e)})(e)}function c(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}Object.defineProperty(exports,"__esModule",{value:!0});var s=function(e){function r(t){var n;return n=e.call(this,t)||this,Object.setPrototypeOf(c(n),r.prototype),n}return t(r,e),r}(u(TypeError)),a=function(e,t){return new s("Invalid "+e+' input: "'+t+'"')},f=function(e){function r(t){var n;return n=e.call(this,t)||this,Object.setPrototypeOf(c(n),r.prototype),n}return t(r,e),r}(u(ReferenceError)),p=["length","inspect","hasOwnProperty","toJSON","asymmetricMatch","nodeType","$$typeof","constructor","@@__IMMUTABLE_ITERABLE__@@","@@__IMMUTABLE_RECORD__@@","_isMockFunction","then","__esModule"];function l(e,t){var r=Object.freeze?Object.freeze(e):e;return global.Proxy?new Proxy(r,{get:function(e,n){if("string"!=typeof n||p.includes(n))return r[n];if(!r.hasOwnProperty(n)){if(t.hasOwnProperty(n))throw new ReferenceError("[envsafe] Env var "+String(n)+" was accessed but not validated. This var is set in the environment; please add an envsafe validator for it.");throw new ReferenceError('[envsafe] Env var "'+String(n)+'" not found')}return r[n]}}):r}function v(e){for(var t=e.errors,r=[],n=[],o=0,i=Object.keys(t);o<i.length;o++){var u=i[o],c=t[u];c instanceof f?n.push(" "+u+": "+(c.message||"required")):r.push(" "+u+": "+(c.message||"invalid"))}return r.length&&r.unshift("❌ Invalid environment variables:"),n.length&&n.unshift("💨 Missing environment variables:"),["========================================"].concat(r,n,["========================================"]).join("\n")}function d(e){var t,r,n=v(e);throw console.error(n),"undefined"!=typeof process&&(null===(t=process)||void 0===t?void 0:t.exit)&&process.exit(1),"undefined"!=typeof window&&(null===(r=window)||void 0===r?void 0:r.alert)&&window.alert(n),new TypeError(n)}function h(e){var t,r=e.env,n=e.validator,o=null!==(t=n.input)&&void 0!==t?t:r[e.key];if(void 0===o&&"production"!==r.NODE_ENV&&void 0!==n.devDefault&&(o=n.devDefault),void 0===o&&void 0!==n.default&&(o=n.default),void 0===o)throw new f("Missing value");var i=n._parse(o);if(n.choices&&!n.choices.includes(i))throw new s('Value "'+i+'" not in choices ['+n.choices+"]");return i}var y=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function w(t){return function(r){return void 0===r&&(r={}),e({},r,{_parse:t})}}var O=w((function(e){switch(e){case!0:case"true":case"t":case"1":return!0;case!1:case"false":case"f":case"0":return!1;default:throw a("str",e)}})),b=w((function(e){if("string"!=typeof e)throw a("str",e);return e})),_=w((function(e){if(!y.test(e))throw a("email",e);return e})),g=w((function(e){var t=+e;if(Number.isNaN(t))throw a("num",e);return t})),x=w((function(e){var t=+e;if(Number.isNaN(t)||""+t!=""+e||t%1!=0||t<1||t>65535)throw a("port",e);return t})),E=w((function(e){try{return new URL(e),e}catch(t){throw a("url",e)}})),j=w((function(e){try{return"string"!=typeof e?e:JSON.parse(e)}catch(t){throw a("json",e)}}));exports.InvalidEnvError=s,exports.MissingEnvError=f,exports.bool=O,exports.defaultReporter=d,exports.defaultReporterText=v,exports.email=_,exports.envsafe=function(e,t){var r=void 0===t?{}:t,n=r.reporter,o=void 0===n?d:n,i=r.env,u=void 0===i?process.env:i,c=r.strict,s=void 0!==c&&c,a={},f={};for(var p in e){var v=e[p];try{var y=h({env:u,validator:v,key:p});f[p]=y}catch(e){a[p]=e}}return Object.keys(a).length&&o({errors:a,output:f,env:u}),s?l(f,u):f},exports.freezeObject=l,exports.invalidEnvError=a,exports.json=j,exports.makeValidator=w,exports.num=g,exports.port=x,exports.str=b,exports.url=E;
//# sourceMappingURL=envsafe.cjs.production.min.js.map

@@ -1,2 +0,2 @@

import { envsafeOpts, Validators } from './types';
export declare function envsafe<TCleanEnv>(validators: Validators<TCleanEnv>, { reporter, env, }?: envsafeOpts<TCleanEnv>): Readonly<TCleanEnv>;
import { EnvsafeOpts, Validators } from './types';
export declare function envsafe<TCleanEnv>(validators: Validators<TCleanEnv>, { reporter, env, strict, }?: EnvsafeOpts<TCleanEnv>): Readonly<TCleanEnv>;

@@ -147,2 +147,34 @@ function _extends() {

var inspectables = ['length', 'inspect', 'hasOwnProperty', 'toJSON', // jest stuff:
'asymmetricMatch', 'nodeType', '$$typeof', 'constructor', '@@__IMMUTABLE_ITERABLE__@@', '@@__IMMUTABLE_RECORD__@@', '_isMockFunction', // For libs that use `then` checks to see if objects are Promises
// https://github.com/af/envalid/issues/74
'then', // For usage with TypeScript esModuleInterop flag
'__esModule'];
function freezeObject(envObj, env) {
var frozen = Object.freeze ? Object.freeze(envObj) : envObj;
return global.Proxy ? new Proxy(frozen, {
get: function get(_target, name) {
// These checks are needed because calling console.log on a
// proxy that throws crashes the entire process. This whitelists
// the necessary properties for `console.log(frozen)`, `frozen.length`,
// `frozen.hasOwnProperty('string')` to work.
if (typeof name !== 'string' || inspectables.includes(name)) {
return frozen[name];
}
var varExists = frozen.hasOwnProperty(name);
if (!varExists) {
if (env.hasOwnProperty(name)) {
throw new ReferenceError("[envsafe] Env var " + String(name) + " was accessed but not validated. This var is set in the environment; please add an envsafe validator for it.");
}
throw new ReferenceError("[envsafe] Env var \"" + String(name) + "\" not found");
}
return frozen[name];
}
}) : frozen;
}
function defaultReporterText(_ref) {

@@ -190,3 +222,3 @@ var errors = _ref.errors;

throw new Error(text);
throw new TypeError(text);
}

@@ -229,3 +261,5 @@

_ref2$env = _ref2.env,
env = _ref2$env === void 0 ? process.env : _ref2$env;
env = _ref2$env === void 0 ? process.env : _ref2$env,
_ref2$strict = _ref2.strict,
strict = _ref2$strict === void 0 ? false : _ref2$strict;

@@ -258,3 +292,3 @@ var errors = {};

return Object.freeze ? Object.freeze(output) : output;
return strict ? freezeObject(output, env) : output;
}

@@ -346,3 +380,3 @@

export { InvalidEnvError, MissingEnvError, bool, defaultReporter, defaultReporterText, email, envsafe, invalidEnvError, json, makeValidator, num, port, str, url };
export { InvalidEnvError, MissingEnvError, bool, defaultReporter, defaultReporterText, email, envsafe, freezeObject, invalidEnvError, json, makeValidator, num, port, str, url };
//# sourceMappingURL=envsafe.esm.js.map

@@ -6,1 +6,2 @@ export * from './envsafe';

export * from './validators';
export * from './freezeObject';

@@ -43,6 +43,19 @@ export interface Spec<TValue> {

};
export declare type Reporter<TCleanEnv> = (opts: ReporterOpts<TCleanEnv>) => void;
export declare type envsafeOpts<TCleanEnv> = {
reporter?: Reporter<TCleanEnv>;
export declare type ReporterFn<TCleanEnv> = (opts: ReporterOpts<TCleanEnv>) => void;
export declare type EnvsafeOpts<TCleanEnv> = {
/**
* Override the built-in reporter
* @default `defaultReporter`
*/
reporter?: ReporterFn<TCleanEnv>;
/**
* @default process.env
*/
env?: Environment;
/**
* Wrap the returned object in a `Proxy` which throws an error whenever an attempt is made to access an undefined property
* Useful if you're not using TypeScript
* @default false
*/
strict?: boolean;
};

@@ -49,0 +62,0 @@ export declare type Validators<TCleanEnv> = {

{
"version": "1.0.0-0",
"version": "1.0.0-1",
"license": "MIT",

@@ -4,0 +4,0 @@ "main": "dist/index.js",

@@ -5,4 +5,14 @@ [![Maintainability](https://api.codeclimate.com/v1/badges/c17614f0d80b810e47a6/maintainability)](https://codeclimate.com/github/KATT/envsafe/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/c17614f0d80b810e47a6/test_coverage)](https://codeclimate.com/github/KATT/envsafe/test_coverage)

Mostly based on the great project [envalid](https://github.com/af/envalid), but with some minor differences
```
========================================
❌ Invalid environment variables:
API_URL: Invalid url input: "http//example.com/graphql"
💨 Missing environment variables:
MY_VAR: Missing value
PORT: Missing value
========================================
```
Mostly based on the great project [envalid](https://github.com/af/envalid), but with some key differences:
- Written in 100% TypeScript

@@ -12,2 +22,12 @@ - Always strict - only get the props you have defined

---
- [How to use](#how-to-use)
- [Install](#install)
- [Basic usage](#basic-usage)
- [Built-in validators](#built-in-validators)
- [Possible options](#possible-options)
- [Custom validators/parsers](#custom-validatorsparsers)
- [Error reporting](#error-reporting)
## How to use

@@ -17,2 +37,14 @@

### Install
```sh
yarn add envsafe
```
```sh
npm i envsafe --save
```
### Basic usage
```ts

@@ -129,71 +161,19 @@ import { str, envsafe, url } from 'envsafe';

# Contributing
## Strict mode (recommended for JS-users)
## Running the project locally
By default envsafe returns a `Readonly<T>` which in TypeScript ensures the env can't be modified and undefined properties from being accessed, but if you're using JavaScript you are still able to access env vars that don't exist. Therefore there's a strict mode option, which is recommended if your project is using vanilla JS, but not recommended if you use TypeScript.
To run TSDX, use:
It wraps the function in `Object.freeze` and a `Proxy` that disallows access to any props that aren't defined.
```bash
npm start # or yarn start
```
This builds to `/dist` and runs the project in watch mode so any edits you save inside `src` causes a rebuild to `/dist`.
To do a one-off build, use `npm run build` or `yarn build`.
To run tests, use `npm test` or `yarn test`.
## Configuration
Code quality is set up for you with `prettier`, `husky`, and `lint-staged`.
### Jest
Jest tests are set up to run with `npm test` or `yarn test`.
### Rollup
TSDX uses [Rollup](https://rollupjs.org) as a bundler and generates multiple rollup configs for various module formats and build settings. See [Optimizations](#optimizations) for details.
### TypeScript
`tsconfig.json` is set up to interpret `dom` and `esnext` types.
## Continuous Integration
### GitHub Actions
A simple action is included that runs these steps on all pushes:
- Installs deps w/ cache
- Lints, tests, and builds
## Optimizations
Please see the main `tsdx` [optimizations docs](https://github.com/palmerhq/tsdx#optimizations). In particular, know that you can take advantage of development-only optimizations:
```js
// ./types/index.d.ts
declare var __DEV__: boolean;
import { envsafe, str } from 'envsafe';
// inside your code...
if (__DEV__) {
console.log('foo');
}
export const browserEnv = envsafe(
{
MY_ENV: str(),
},
{
strict: true,
},
);
```
You can also choose to install and use [invariant](https://github.com/palmerhq/tsdx#invariant) and [warning](https://github.com/palmerhq/tsdx#warning) functions.
## Module Formats
CJS, ESModules, and UMD module formats are supported.
The appropriate paths are configured in `package.json` and `dist/index.js` accordingly. Please report if any issues are found.
## Named Exports
Per Palmer Group guidelines, [always use named exports.](https://github.com/palmerhq/typescript#exports) Code split inside your React app instead of your React library.
```
```
import { InvalidEnvError, MissingEnvError } from './errors';
import { freezeObject } from './freezeObject';
import { defaultReporter } from './reporter';
import {
envsafeOpts,
EnvsafeOpts,
Environment,

@@ -54,3 +55,4 @@ Errors,

env = process.env,
}: envsafeOpts<TCleanEnv> = {},
strict = false,
}: EnvsafeOpts<TCleanEnv> = {},
): Readonly<TCleanEnv> {

@@ -74,3 +76,3 @@ const errors: Errors = {};

return Object.freeze ? Object.freeze(output) : output;
return strict ? freezeObject(output, env) : output;
}

@@ -6,1 +6,2 @@ export * from './envsafe';

export * from './validators';
export * from './freezeObject';

@@ -48,3 +48,3 @@ import { MissingEnvError } from './errors';

throw new Error(text);
throw new TypeError(text);
}

@@ -48,7 +48,20 @@ export interface Spec<TValue> {

export type Reporter<TCleanEnv> = (opts: ReporterOpts<TCleanEnv>) => void;
export type ReporterFn<TCleanEnv> = (opts: ReporterOpts<TCleanEnv>) => void;
export type envsafeOpts<TCleanEnv> = {
reporter?: Reporter<TCleanEnv>;
export type EnvsafeOpts<TCleanEnv> = {
/**
* Override the built-in reporter
* @default `defaultReporter`
*/
reporter?: ReporterFn<TCleanEnv>;
/**
* @default process.env
*/
env?: Environment;
/**
* Wrap the returned object in a `Proxy` which throws an error whenever an attempt is made to access an undefined property
* Useful if you're not using TypeScript
* @default false
*/
strict?: boolean;
};

@@ -55,0 +68,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc