Initial commit with Advoware proxy

This commit is contained in:
root
2025-10-19 14:57:07 +00:00
commit 273aa8b549
45771 changed files with 5534555 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
### Versions
## 1.0.7
###### *Jan 7, 2021*
- package: add jsdelivr source path
## 1.0.6
###### *Jan 3, 2021*
- use default export in the entry file
- fix library import in `spec.js`
## 1.0.5
###### *Jan 3, 2021*
- replace `webpack` with `rollup`
- add cjs/es bundles
## 1.0.4
###### *Nov 15, 2020*
- revert "corrected moudles"
## 1.0.3
###### *Nov 15, 2020*
- remove `src` from `.npmignore` and refer it to `package.module`
## 1.0.2
###### *Nov 14, 2020*
- fix `module` path in package.json
## 1.0.1
###### *Aug 6, 2020*
- add default export into the index point
## 1.0.0
###### *Aug 6, 2020*
🎉 First stable version of the library

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Suren Atoyan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,312 @@
# State · [![monthly downloads](https://img.shields.io/npm/dm/state-local)](https://www.npmjs.com/package/state-local) [![gitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/suren-atoyan/state-local/blob/master/LICENSE) [![Rate on Openbase](https://badges.openbase.io/js/rating/state-local.svg)](https://openbase.io/js/state-local?utm_source=embedded&utm_medium=badge&utm_campaign=rate-badge) [![build size](https://img.shields.io/bundlephobia/minzip/state-local)](https://bundlephobia.com/result?p=state-local) [![npm version](https://img.shields.io/npm/v/state-local.svg?style=flat)](https://www.npmjs.com/package/state-local) [![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/suren-atoyan/state-local/pulls)
:zap: Tiny, simple, and robust technique for defining and acting with local states (for all js environments - node, browser, etc.)
## Synopsis
A local state for modules, functions, and other ECs
## Motivation
We all love functional programming and the concepts of it. It gives us many clean patterns, which we use in our code regardless of exactly which paradigm is in the base of our codebase. But sometimes, for some reason, we can't keep our code "clean" and have to interact with items that are outside of the current lexical environment
For example:
:x:
```javascript
let x = 0;
let y = 1;
// ...
function someFn() {
// ...
x++;
}
// ...
function anotherFn() {
// ...
y = 6;
console.log(x);
}
// ...
function yetAnotherFn() {
// ...
y = x + 4;
x = null; // 🚶
}
```
The example above lacks control over the mutations and consumption, which can lead to unpredictable and unwanted results. It is just an example of real-life usage and there are many similar cases that belong to the same class of the problem
**The purpose of this library is to give an opportunity to work with local states in a clear, predictable, trackable, and strict way**
:white_check_mark:
```javascript
import state from 'state-local';
const [getState, setState] = state.create({ x: 0, y: 1 });
// ...
function someFn() {
// ...
setState(state => ({ x: state.x + 1 }));
}
// ...
function anotherFn() {
// ...
setState({ y: 6 });
const state = getState();
console.log(state);
}
// ...
function yetAnotherFn() {
// ...
setState(state => ({ y: state.x + 4, x: null }));
}
```
[codesandbox](https://codesandbox.io/s/motivation-1-xv5el?file=/src/index.js)
We also can track the changes in items:
```javascript
import state from 'state-local';
const [getState, setState] = state.create({ x: 0, y: 1 }, {
x: latestX => console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; "x" has been changed. "x" now is:', latestX),
y: latestY => console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; "y" has been changed. "y" now is:', latestY),
});
// ...
```
[codesandbox](https://codesandbox.io/s/motivation-2-ivf7d)
We can use the subset of the state in some execution contexts:
```javascript
import state from 'state-local';
const [getState, setState] = state.create({ x: 5, y: 7 });
// ...
function someFn() {
const state = getState(({ x }) => ({ x }));
console.log(state.x); // 5
console.log(state.y); // ❌ undefined - there is no y
}
```
[codesandbox](https://codesandbox.io/s/motivation-3-femne)
And much more...
## Documentation
#### Contents
* [Installation](#installation)
* Usage
* [create](#create)
* [initial state](#initial-state)
* [handler](#handler)
* [getState](#getstate)
* [selector](#selector)
* [setState](#setstate)
#### Installation
You can install this library as an npm package or download it from the CDN and use it in node or browser:
```bash
npm install state-local
```
or
```bash
yarn add state-local
```
or
```html
<script src="https://unpkg.com/state-local/dist/state-local.js"></script>
<script>
// now it is available in `window` (window.state)
const [getState, setState] = state.create({ x: 11, y: 13 });
// ...
</script>
```
#### create
The default export has a method called `create`, which is supposed to be a function to create a state:
```javascript
import state from 'state-local';
// state.create
// ...
```
[codesandbox](https://codesandbox.io/s/docs-create-t1cxe)
`create` is a function with two parameters:
1) [`initial state`](#initial-state) (**required**)
2) [`handler`](#handler) (**optional**)
#### initial state
`initial state` is a base structure and a value for the state. It should be a non-empty object
```javascript
import state from 'state-local';
/*
const [getState, setState] = state.create(); // ❌ error - initial state is required
const [getState, setState] = state.create(5); // ❌ error - initial state should be an object
const [getState, setState] = state.create({}); // ❌ error - initial state shouldn\'t be an empty object
*/
const [getState, setState] = state.create({ isLoading: false, payload: null }); // ✅
// ...
```
[codesandbox](https://codesandbox.io/s/docs-initial-state-22i3s)
#### handler
`handler` is a second parameter for `create` function and it is optional. It is going to be a handler for state updates. Hence it can be either a function or an object.
- If the handler is a function than it should be called immediately after every state update (with the latest state)
- If the handler is an object than the keys of that object should be a subset of the state and the values should be called immediately after every update of the corresponding field in the state (with the latest value of the field)
see example below:
if `handler` is a function
```javascript
import state from 'state-local';
const [getState, setState] = state.create({ x: 2, y: 3, z: 5 }, handleStateUpdate /* will be called immediately after every state update */);
function handleStateUpdate(latestState) {
console.log('hey state has been updated; the new state is:', latestState); // { x: 7, y: 11, z: 13 }
}
setState({ x: 7, y: 11, z: 13 });
// ...
```
[codesandbox](https://codesandbox.io/s/handler-function-uevxj)
if `handler` is an object
```javascript
import state from 'state-local';
const [getState, setState] = state.create({ x: 2, y: 3, z: 5 }, {
x: handleXUpdate, // will be called immediately after every "x" update
y: handleYUpdate, // will be called immediately after every "y" update
// and we don't want to listen "z" updates 😔
});
function handleXUpdate(latestX) {
console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; "x" has been changed. "x" now is:', latestX); // ... "x" now is 7
}
function handleYUpdate(latestY) {
console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; "y" has been changed. "y" now is:', latestY); // ... "y" now is 11
}
setState({ x: 7, y: 11, z: 13 });
// ...
```
[codesandbox](https://codesandbox.io/s/handler-object-8k0pt)
#### getState
`getState` is the first element of the pair returned by `create` function. It will return the current state or the subset of the current state depending on how it was called. It has an optional parameter `selector`
```javascript
import state from "state-local";
const [getState, setState] = state.create({ p1: 509, p2: 521 });
const state = getState();
console.log(state.p1); // 509
console.log(state.p2); // 521
// or
const { p1, p2 } = getState();
console.log(p1); // 509
console.log(p2); // 521
```
[codesandbox](https://codesandbox.io/s/getstate-zn3hj)
#### selector
`selector` is a function that is supposed to be passed (optional) as an argument to `getState`. It receives the current state and returns a subset of the state
```javascript
import state from 'state-local';
const [getState, setState] = state.create({ p1: 389, p2: 397, p3: 401 });
function someFn() {
const state = getState(({ p1, p2 }) => ({ p1, p2 }));
console.log(state.p1); // 389
console.log(state.p2); // 397
console.log(state.p3); // ❌ undefined - there is no p3
}
```
[codesandbox](https://codesandbox.io/s/selector-vjmdu)
#### setState
`setState` is the second element of the pair returned by `create` function. It is going to receive an object as a change for the state. The change object will be shallow merged with the current state and the result will be the next state
**NOTE: the change object can't contain a field that is not specified in the "initial" state**
```javascript
import state from 'state-local';
const [getState, setState] = state.create({ x:0, y: 0 });
setState({ z: 'some value' }); // ❌ error - it seams you want to change a field in the state which is not specified in the "initial" state
setState({ x: 11 }); // ✅ ok
setState({ y: 1 }); // ✅ ok
setState({ x: -11, y: 11 }); // ✅ ok
```
[codesandbox](https://codesandbox.io/s/setstate-1-u4fq0)
`setState` also can receive a function which will be called with the current state and it is supposed to return the change object
```javascript
import state from 'state-local';
const [getState, setState] = state.create({ x:0, y: 0 });
setState(state => ({ x: state.x + 2 })); // ✅ ok
setState(state => ({ x: state.x - 11, y: state.y + 11 })); // ✅ ok
setState(state => ({ z: 'some value' })); // ❌ error - it seams you want to change a field in the state which is not specified in the "initial" state
```
[codesandbox](https://codesandbox.io/s/smoosh-wildflower-nv9dg)
## License
[MIT](./LICENSE)

View File

@@ -0,0 +1,195 @@
'use strict';
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function compose() {
for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
fns[_key] = arguments[_key];
}
return function (x) {
return fns.reduceRight(function (y, f) {
return f(y);
}, x);
};
}
function curry(fn) {
return function curried() {
var _this = this;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return args.length >= fn.length ? fn.apply(this, args) : function () {
for (var _len3 = arguments.length, nextArgs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
nextArgs[_key3] = arguments[_key3];
}
return curried.apply(_this, [].concat(args, nextArgs));
};
};
}
function isObject(value) {
return {}.toString.call(value).includes('Object');
}
function isEmpty(obj) {
return !Object.keys(obj).length;
}
function isFunction(value) {
return typeof value === 'function';
}
function hasOwnProperty(object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
}
function validateChanges(initial, changes) {
if (!isObject(changes)) errorHandler('changeType');
if (Object.keys(changes).some(function (field) {
return !hasOwnProperty(initial, field);
})) errorHandler('changeField');
return changes;
}
function validateSelector(selector) {
if (!isFunction(selector)) errorHandler('selectorType');
}
function validateHandler(handler) {
if (!(isFunction(handler) || isObject(handler))) errorHandler('handlerType');
if (isObject(handler) && Object.values(handler).some(function (_handler) {
return !isFunction(_handler);
})) errorHandler('handlersType');
}
function validateInitial(initial) {
if (!initial) errorHandler('initialIsRequired');
if (!isObject(initial)) errorHandler('initialType');
if (isEmpty(initial)) errorHandler('initialContent');
}
function throwError(errorMessages, type) {
throw new Error(errorMessages[type] || errorMessages["default"]);
}
var errorMessages = {
initialIsRequired: 'initial state is required',
initialType: 'initial state should be an object',
initialContent: 'initial state shouldn\'t be an empty object',
handlerType: 'handler should be an object or a function',
handlersType: 'all handlers should be a functions',
selectorType: 'selector should be a function',
changeType: 'provided value of changes should be an object',
changeField: 'it seams you want to change a field in the state which is not specified in the "initial" state',
"default": 'an unknown error accured in `state-local` package'
};
var errorHandler = curry(throwError)(errorMessages);
var validators = {
changes: validateChanges,
selector: validateSelector,
handler: validateHandler,
initial: validateInitial
};
function create(initial) {
var handler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
validators.initial(initial);
validators.handler(handler);
var state = {
current: initial
};
var didUpdate = curry(didStateUpdate)(state, handler);
var update = curry(updateState)(state);
var validate = curry(validators.changes)(initial);
var getChanges = curry(extractChanges)(state);
function getState() {
var selector = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function (state) {
return state;
};
validators.selector(selector);
return selector(state.current);
}
function setState(causedChanges) {
compose(didUpdate, update, validate, getChanges)(causedChanges);
}
return [getState, setState];
}
function extractChanges(state, causedChanges) {
return isFunction(causedChanges) ? causedChanges(state.current) : causedChanges;
}
function updateState(state, changes) {
state.current = _objectSpread2(_objectSpread2({}, state.current), changes);
return changes;
}
function didStateUpdate(state, handler, changes) {
isFunction(handler) ? handler(state.current) : Object.keys(changes).forEach(function (field) {
var _handler$field;
return (_handler$field = handler[field]) === null || _handler$field === void 0 ? void 0 : _handler$field.call(handler, state.current[field]);
});
return changes;
}
var index = {
create: create
};
module.exports = index;

View File

@@ -0,0 +1,193 @@
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function compose() {
for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
fns[_key] = arguments[_key];
}
return function (x) {
return fns.reduceRight(function (y, f) {
return f(y);
}, x);
};
}
function curry(fn) {
return function curried() {
var _this = this;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return args.length >= fn.length ? fn.apply(this, args) : function () {
for (var _len3 = arguments.length, nextArgs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
nextArgs[_key3] = arguments[_key3];
}
return curried.apply(_this, [].concat(args, nextArgs));
};
};
}
function isObject(value) {
return {}.toString.call(value).includes('Object');
}
function isEmpty(obj) {
return !Object.keys(obj).length;
}
function isFunction(value) {
return typeof value === 'function';
}
function hasOwnProperty(object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
}
function validateChanges(initial, changes) {
if (!isObject(changes)) errorHandler('changeType');
if (Object.keys(changes).some(function (field) {
return !hasOwnProperty(initial, field);
})) errorHandler('changeField');
return changes;
}
function validateSelector(selector) {
if (!isFunction(selector)) errorHandler('selectorType');
}
function validateHandler(handler) {
if (!(isFunction(handler) || isObject(handler))) errorHandler('handlerType');
if (isObject(handler) && Object.values(handler).some(function (_handler) {
return !isFunction(_handler);
})) errorHandler('handlersType');
}
function validateInitial(initial) {
if (!initial) errorHandler('initialIsRequired');
if (!isObject(initial)) errorHandler('initialType');
if (isEmpty(initial)) errorHandler('initialContent');
}
function throwError(errorMessages, type) {
throw new Error(errorMessages[type] || errorMessages["default"]);
}
var errorMessages = {
initialIsRequired: 'initial state is required',
initialType: 'initial state should be an object',
initialContent: 'initial state shouldn\'t be an empty object',
handlerType: 'handler should be an object or a function',
handlersType: 'all handlers should be a functions',
selectorType: 'selector should be a function',
changeType: 'provided value of changes should be an object',
changeField: 'it seams you want to change a field in the state which is not specified in the "initial" state',
"default": 'an unknown error accured in `state-local` package'
};
var errorHandler = curry(throwError)(errorMessages);
var validators = {
changes: validateChanges,
selector: validateSelector,
handler: validateHandler,
initial: validateInitial
};
function create(initial) {
var handler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
validators.initial(initial);
validators.handler(handler);
var state = {
current: initial
};
var didUpdate = curry(didStateUpdate)(state, handler);
var update = curry(updateState)(state);
var validate = curry(validators.changes)(initial);
var getChanges = curry(extractChanges)(state);
function getState() {
var selector = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function (state) {
return state;
};
validators.selector(selector);
return selector(state.current);
}
function setState(causedChanges) {
compose(didUpdate, update, validate, getChanges)(causedChanges);
}
return [getState, setState];
}
function extractChanges(state, causedChanges) {
return isFunction(causedChanges) ? causedChanges(state.current) : causedChanges;
}
function updateState(state, changes) {
state.current = _objectSpread2(_objectSpread2({}, state.current), changes);
return changes;
}
function didStateUpdate(state, handler, changes) {
isFunction(handler) ? handler(state.current) : Object.keys(changes).forEach(function (field) {
var _handler$field;
return (_handler$field = handler[field]) === null || _handler$field === void 0 ? void 0 : _handler$field.call(handler, state.current[field]);
});
return changes;
}
var index = {
create: create
};
export default index;

View File

@@ -0,0 +1,25 @@
// Type definitions for state-local v0.0.1
// Project: state-local
// Definitions by: Suren Atoyan contact@surenatoyan.com
export as namespace state;
export type State = Record<string, unknown>;
export type Selector = (state: State) => State;
export type ChangeGetter = (state: State) => State;
export type GetState = (selector?: Selector) => State;
export type SetState = (change: State | ChangeGetter) => void;
export type StateUpdateHandler = (update: State) => unknown;
export type FieldUpdateHandler = (update: any) => unknown;
export type Handlers = Record<string, FieldUpdateHandler>;
/**
* `state.create` is a function with two parameters:
* the first one (required) is the initial state and it should be a non-empty object
* the second one (optional) is the handler, which can be function or object
* if the handler is a function than it should be called immediately after every state update
* if the handler is an object than the keys of that object should be a subset of the state
* and the all values of that object should be functions, plus they should be called immediately
* after every update of the corresponding field in the state
*/
export function create(initial: State, handler?: StateUpdateHandler | Handlers): [GetState, SetState];

View File

@@ -0,0 +1,201 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.state = factory());
}(this, (function () { 'use strict';
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function compose() {
for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
fns[_key] = arguments[_key];
}
return function (x) {
return fns.reduceRight(function (y, f) {
return f(y);
}, x);
};
}
function curry(fn) {
return function curried() {
var _this = this;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return args.length >= fn.length ? fn.apply(this, args) : function () {
for (var _len3 = arguments.length, nextArgs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
nextArgs[_key3] = arguments[_key3];
}
return curried.apply(_this, [].concat(args, nextArgs));
};
};
}
function isObject(value) {
return {}.toString.call(value).includes('Object');
}
function isEmpty(obj) {
return !Object.keys(obj).length;
}
function isFunction(value) {
return typeof value === 'function';
}
function hasOwnProperty(object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
}
function validateChanges(initial, changes) {
if (!isObject(changes)) errorHandler('changeType');
if (Object.keys(changes).some(function (field) {
return !hasOwnProperty(initial, field);
})) errorHandler('changeField');
return changes;
}
function validateSelector(selector) {
if (!isFunction(selector)) errorHandler('selectorType');
}
function validateHandler(handler) {
if (!(isFunction(handler) || isObject(handler))) errorHandler('handlerType');
if (isObject(handler) && Object.values(handler).some(function (_handler) {
return !isFunction(_handler);
})) errorHandler('handlersType');
}
function validateInitial(initial) {
if (!initial) errorHandler('initialIsRequired');
if (!isObject(initial)) errorHandler('initialType');
if (isEmpty(initial)) errorHandler('initialContent');
}
function throwError(errorMessages, type) {
throw new Error(errorMessages[type] || errorMessages["default"]);
}
var errorMessages = {
initialIsRequired: 'initial state is required',
initialType: 'initial state should be an object',
initialContent: 'initial state shouldn\'t be an empty object',
handlerType: 'handler should be an object or a function',
handlersType: 'all handlers should be a functions',
selectorType: 'selector should be a function',
changeType: 'provided value of changes should be an object',
changeField: 'it seams you want to change a field in the state which is not specified in the "initial" state',
"default": 'an unknown error accured in `state-local` package'
};
var errorHandler = curry(throwError)(errorMessages);
var validators = {
changes: validateChanges,
selector: validateSelector,
handler: validateHandler,
initial: validateInitial
};
function create(initial) {
var handler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
validators.initial(initial);
validators.handler(handler);
var state = {
current: initial
};
var didUpdate = curry(didStateUpdate)(state, handler);
var update = curry(updateState)(state);
var validate = curry(validators.changes)(initial);
var getChanges = curry(extractChanges)(state);
function getState() {
var selector = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function (state) {
return state;
};
validators.selector(selector);
return selector(state.current);
}
function setState(causedChanges) {
compose(didUpdate, update, validate, getChanges)(causedChanges);
}
return [getState, setState];
}
function extractChanges(state, causedChanges) {
return isFunction(causedChanges) ? causedChanges(state.current) : causedChanges;
}
function updateState(state, changes) {
state.current = _objectSpread2(_objectSpread2({}, state.current), changes);
return changes;
}
function didStateUpdate(state, handler, changes) {
isFunction(handler) ? handler(state.current) : Object.keys(changes).forEach(function (field) {
var _handler$field;
return (_handler$field = handler[field]) === null || _handler$field === void 0 ? void 0 : _handler$field.call(handler, state.current[field]);
});
return changes;
}
var index = {
create: create
};
return index;
})));

View File

@@ -0,0 +1 @@
!function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):(global="undefined"!=typeof globalThis?globalThis:global||self).state=factory()}(this,(function(){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function _objectSpread2(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys(Object(source),!0).forEach((function(key){_defineProperty(target,key,source[key])})):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach((function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))}))}return target}function compose(){for(var _len=arguments.length,fns=new Array(_len),_key=0;_key<_len;_key++)fns[_key]=arguments[_key];return function(x){return fns.reduceRight((function(y,f){return f(y)}),x)}}function curry(fn){return function curried(){for(var _this=this,_len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++)args[_key2]=arguments[_key2];return args.length>=fn.length?fn.apply(this,args):function(){for(var _len3=arguments.length,nextArgs=new Array(_len3),_key3=0;_key3<_len3;_key3++)nextArgs[_key3]=arguments[_key3];return curried.apply(_this,[].concat(args,nextArgs))}}}function isObject(value){return{}.toString.call(value).includes("Object")}function isFunction(value){return"function"==typeof value}var errorHandler=curry((function(errorMessages,type){throw new Error(errorMessages[type]||errorMessages.default)}))({initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"}),validators={changes:function(initial,changes){return isObject(changes)||errorHandler("changeType"),Object.keys(changes).some((function(field){return object=initial,property=field,!Object.prototype.hasOwnProperty.call(object,property);var object,property}))&&errorHandler("changeField"),changes},selector:function(selector){isFunction(selector)||errorHandler("selectorType")},handler:function(handler){isFunction(handler)||isObject(handler)||errorHandler("handlerType"),isObject(handler)&&Object.values(handler).some((function(_handler){return!isFunction(_handler)}))&&errorHandler("handlersType")},initial:function(initial){var obj;initial||errorHandler("initialIsRequired"),isObject(initial)||errorHandler("initialType"),obj=initial,Object.keys(obj).length||errorHandler("initialContent")}};function extractChanges(state,causedChanges){return isFunction(causedChanges)?causedChanges(state.current):causedChanges}function updateState(state,changes){return state.current=_objectSpread2(_objectSpread2({},state.current),changes),changes}function didStateUpdate(state,handler,changes){return isFunction(handler)?handler(state.current):Object.keys(changes).forEach((function(field){var _handler$field;return null===(_handler$field=handler[field])||void 0===_handler$field?void 0:_handler$field.call(handler,state.current[field])})),changes}return{create:function(initial){var handler=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};validators.initial(initial),validators.handler(handler);var state={current:initial},didUpdate=curry(didStateUpdate)(state,handler),update=curry(updateState)(state),validate=curry(validators.changes)(initial),getChanges=curry(extractChanges)(state);function getState(){var selector=arguments.length>0&&void 0!==arguments[0]?arguments[0]:function(state){return state};return validators.selector(selector),selector(state.current)}function setState(causedChanges){compose(didUpdate,update,validate,getChanges)(causedChanges)}return[getState,setState]}}}));

View File

@@ -0,0 +1,59 @@
{
"name": "state-local",
"version": "1.0.7",
"description": "Tiny, simple, and robust technique for defining and acting with local states",
"main": "lib/cjs/state-local.js",
"module": "lib/es/state-local.js",
"unpkg": "lib/umd/state-local.min.js",
"jsdelivr": "lib/umd/state-local.min.js",
"types": "lib/types.d.ts",
"author": "Suren Atoyan <contact@surenatoyan.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/suren-atoyan/state-local"
},
"bugs": {
"url": "https://github.com/suren-atoyan/state-local/issues"
},
"homepage": "https://github.com/suren-atoyan/state-local#readme",
"keywords": [
"state",
"state management",
"local state"
],
"scripts": {
"test": "jest",
"test-watch": "npm run build && jest --watch",
"coverage": "jest --collect-coverage",
"lint": "npx eslint src",
"prepublish": "npm test && npm run lint && npm run build",
"build": "rollup -c && cp ./src/types.d.ts ./lib/"
},
"babel": {
"presets": [
"@babel/preset-env"
]
},
"husky": {
"hooks": {
"pre-commit": "npm test && npm run lint"
}
},
"devDependencies": {
"@babel/core": "^7.11.0",
"@babel/preset-env": "^7.11.0",
"@rollup/plugin-babel": "^5.2.2",
"@rollup/plugin-commonjs": "^17.0.0",
"@rollup/plugin-node-resolve": "^11.0.1",
"@rollup/plugin-replace": "^2.3.4",
"babel-jest": "^26.2.2",
"babel-loader": "^8.1.0",
"eslint": "^7.6.0",
"husky": "^4.2.5",
"jest": "^26.2.2",
"rollup": "^2.35.1",
"rollup-plugin-terser": "^7.0.2"
},
"dependencies": {}
}

View File

@@ -0,0 +1,70 @@
import nodeResolve from '@rollup/plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';
import replace from '@rollup/plugin-replace';
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel';
const defaultNodeResolveConfig = {};
const nodeResolvePlugin = nodeResolve(defaultNodeResolveConfig);
const commonPlugins = [
nodeResolvePlugin,
babel.default({
presets: ['@babel/preset-env'],
babelHelpers: 'bundled',
}),
commonjs(),
];
const developmentPlugins = [
...commonPlugins,
replace({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
];
const productionPlugins = [
...commonPlugins,
replace({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
terser({ mangle: false }),
];
export default [
{
input: 'src/index.js',
output: {
file: 'lib/cjs/state-local.js',
format: 'cjs',
exports: 'default',
},
plugins: commonPlugins,
},
{
input: 'src/index.js',
output: {
file: 'lib/es/state-local.js',
format: 'es',
},
plugins: commonPlugins,
},
{
input: 'src/index.js',
output: {
file: 'lib/umd/state-local.js',
format: 'umd',
name: 'state',
},
plugins: developmentPlugins,
},
{
input: 'src/index.js',
output: {
file: 'lib/umd/state-local.min.js',
format: 'umd',
name: 'state',
},
plugins: productionPlugins,
},
];