property-accessor 1.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,29 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](http://keepachangelog.com/)
6
+ and this project adheres to [Semantic Versioning](http://semver.org/).
7
+
8
+ ## [2.0.1] - 2025-05-01
9
+
10
+ ### Fixed
11
+
12
+ - Fixed changelog
13
+ - Refactored code
14
+
15
+ ## [2.0.0] - 2025-05-01
16
+
17
+ ### Added
18
+
19
+ - Re-implemented with TypeScript
20
+ - Added path validation
21
+ - Added tests
22
+
23
+ ### Fixed
24
+
25
+ - Refactored code
26
+
27
+ ## [1.0.0] - 2019-06-27
28
+
29
+ Basic package implementation with ES2015
package/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ (The MIT License)
2
+ Copyright (c) 2024 Pavlo Lazunko <pavlo@databikers.com>
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software
5
+ and associated documentation files (the "Software"), to deal in the Software without restriction,
6
+ including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
7
+ and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
8
+ subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice
11
+ shall be included in all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
14
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
16
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
17
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,44 +1,81 @@
1
- #Property Accessor
1
+ # Property Accessor
2
+ #### [Changelog](./CHANGELOG.md)
3
+
4
+ This utility provides methods to **evaluate and manipulate deeply nested properties** of objects using string-based paths like:
2
5
 
3
- Install package:
4
6
  ```
5
- yarn add property-accessor
7
+ "prop1[0].prop2[9]['name']"
6
8
  ```
7
9
 
8
- Usage example:
10
+ You can use it to **get** or **set** values dynamically within complex object structures.
11
+
12
+ ---
13
+
14
+ ## Installation
9
15
 
16
+ ```bash
17
+ npm i property-accessor
10
18
  ```
11
- const PropertyAccessor = require('property-accessor');
12
19
 
13
- let target = {
20
+ ---
21
+
22
+ ## Methods
23
+
24
+ ### `PropertyAccessor.get(key: string, target: any): any`
25
+
26
+ Retrieves a value from the object using a dot/bracket notation path.
27
+
28
+ - **Parameters:**
29
+ - `key` (`string`): Property path (e.g. `"prop1.prop2[0]['name']"`)
30
+ - `target` (`object`): The target object to evaluate
31
+
32
+ ---
33
+
34
+ ### `PropertyAccessor.set(key: string, value: any, target: any): boolean`
35
+
36
+ Sets a value at the given path. Returns `true` on success, `false` otherwise.
37
+ **Automatically creates nested objects and arrays as needed**.
38
+
39
+ - **Parameters:**
40
+ - `key` (`string`): Property path (e.g. `"prop1.prop2[0]['name']"`)
41
+ - `value` (`any`): Value to set
42
+ - `target` (`object`): The target object to modify
43
+
44
+ ---
45
+
46
+ ## Usage Example
47
+
48
+ ```js
49
+ const { PropertyAccessor } = require('property-accessor');
50
+
51
+ const target = {
14
52
  users: [
15
- {
16
- firstName: 'John',
17
- surName: 'Doe',
18
- age: 25
19
- },
20
- {
21
- firstName: 'Ann',
22
- surName: 'Doe',
23
- age: 23
24
- }
25
- ]
53
+ { firstName: 'John', surName: 'Doe', age: 25 },
54
+ { firstName: 'Ann', surName: 'Doe', age: 23 },
55
+ ],
26
56
  };
27
57
 
28
- let proxy = new PropertyAccessor(target);
58
+ console.log(PropertyAccessor.get('users[0].firstName', target));
59
+ // Output: John
60
+
61
+ PropertyAccessor.set('users[1].age', 24, target); // true
62
+ console.log(PropertyAccessor.get('users[1].age', target));
63
+ // Output: 24
29
64
 
30
- console.log(proxy.get('users[0].firstName'));
31
- // John
65
+ PropertyAccessor.set('users[0].children[0]', { name: 'Nick', age: 1 }, target);
66
+ console.log(target.users[0].children);
67
+ // Output: [ { name: 'Nick', age: 1 } ]
68
+ ```
32
69
 
33
- proxy.set('users[1].age', 24);
34
- console.log(proxy.get('users[1].age'));
35
- // 24
70
+ ---
36
71
 
37
- target.users[0].age = 26;
38
- console.log(proxy.get('users[0].age'));
39
- // 26
72
+ ## Optional: Instance-Based Usage
40
73
 
41
- proxy.set('users[0].children[0]', { name: 'Nick', age: 1 });
42
- console.log(target.users[0].children);
43
- // [ { name: 'Nick', age: 1 } ]
74
+ For backward compatibility, you can also create an instance and bind a specific target via the constructor:
75
+
76
+ ```js
77
+ const propertyAccessor = new PropertyAccessor({ a: [{ b: 3 }] });
78
+ propertyAccessor.set('a[1].b', 4);
44
79
  ```
80
+
81
+ ---
package/ROADMAP.md ADDED
File without changes
@@ -0,0 +1 @@
1
+ export * from './valid-path-regex';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./valid-path-regex"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/constants/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,qDAAmC"}
@@ -0,0 +1 @@
1
+ export declare const VALID_PATH_REGEX: RegExp;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VALID_PATH_REGEX = void 0;
4
+ exports.VALID_PATH_REGEX = /^(\w+)(\.?(\w+)|\[(\d+|(['"])\w+\5)\])+/;
5
+ //# sourceMappingURL=valid-path-regex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"valid-path-regex.js","sourceRoot":"","sources":["../../src/constants/valid-path-regex.ts"],"names":[],"mappings":";;;AAAa,QAAA,gBAAgB,GAAG,yCAAyC,CAAC"}
@@ -0,0 +1 @@
1
+ export * from './validate-path';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./validate-path"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/helpers/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,kDAAgC"}
@@ -0,0 +1 @@
1
+ export declare function validatePath(key: string): boolean;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validatePath = void 0;
4
+ const _const_1 = require("../constants");
5
+ function validatePath(key) {
6
+ const normalizedKey = key.replace(/\['([^']+)'\]/g, '[$1]').replace(/\["([^"]+)"\]/g, '[$1]');
7
+ return _const_1.VALID_PATH_REGEX.test(normalizedKey);
8
+ }
9
+ exports.validatePath = validatePath;
10
+ //# sourceMappingURL=validate-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-path.js","sourceRoot":"","sources":["../../src/helpers/validate-path.ts"],"names":[],"mappings":";;;AAAA,mCAA0C;AAE1C,SAAgB,YAAY,CAAC,GAAW;IACtC,MAAM,aAAa,GAAG,GAAG,CAAC,OAAO,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC;IAC9F,OAAO,yBAAgB,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;AAC9C,CAAC;AAHD,oCAGC"}
@@ -0,0 +1 @@
1
+ export * from './library';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./library"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B"}
@@ -0,0 +1 @@
1
+ export * from './property-accessor';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./property-accessor"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/library/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sDAAoC"}
@@ -0,0 +1,8 @@
1
+ export declare class PropertyAccessor {
2
+ protected target: any;
3
+ constructor(target: any);
4
+ get(key: string): any;
5
+ set(key: string, value: any): boolean;
6
+ static get(path: string, src: any): any;
7
+ static set(path: string, value: any, src: any): boolean;
8
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PropertyAccessor = void 0;
4
+ const _helpers_1 = require("../helpers");
5
+ class PropertyAccessor {
6
+ target;
7
+ constructor(target) {
8
+ this.target = target;
9
+ }
10
+ get(key) {
11
+ return PropertyAccessor.get(key, this.target);
12
+ }
13
+ set(key, value) {
14
+ return PropertyAccessor.set(key, value, this.target);
15
+ }
16
+ static get(path, src) {
17
+ if (!src) {
18
+ return;
19
+ }
20
+ if (!path) {
21
+ return src;
22
+ }
23
+ if (!(0, _helpers_1.validatePath)(path)) {
24
+ return;
25
+ }
26
+ return path.split('.').reduce((acc, part) => {
27
+ if (acc === undefined || acc === null) {
28
+ return;
29
+ }
30
+ const parts = part.split(/[\[\]]/).filter(Boolean);
31
+ for (const part of parts) {
32
+ acc = acc?.[part];
33
+ if (acc === undefined) {
34
+ return;
35
+ }
36
+ }
37
+ return acc;
38
+ }, src);
39
+ }
40
+ static set(path, value, src) {
41
+ if (!src) {
42
+ return;
43
+ }
44
+ if (!path) {
45
+ return false;
46
+ }
47
+ if (!(0, _helpers_1.validatePath)(path)) {
48
+ return false;
49
+ }
50
+ const keys = path.split('.');
51
+ let target = src;
52
+ for (let i = 0; i < keys.length; i++) {
53
+ const parts = keys[i].split(/[\[\]]/).filter(Boolean);
54
+ for (let j = 0; j < parts.length; j++) {
55
+ const key = parts[j];
56
+ const isLastKey = i === keys.length - 1 && j === parts.length - 1;
57
+ if (isLastKey) {
58
+ target[key] = value;
59
+ }
60
+ else {
61
+ if (!target[key] || typeof target[key] !== 'object') {
62
+ target[key] = /^\d+$/.test(parts[j + 1] || '') ? [] : {};
63
+ }
64
+ target = target[key];
65
+ }
66
+ }
67
+ }
68
+ return true;
69
+ }
70
+ }
71
+ exports.PropertyAccessor = PropertyAccessor;
72
+ //# sourceMappingURL=property-accessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"property-accessor.js","sourceRoot":"","sources":["../../src/library/property-accessor.ts"],"names":[],"mappings":";;;AAAA,uCAAwC;AAExC,MAAa,gBAAgB;IACjB,MAAM,CAAM;IAEtB,YAAY,MAAW;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB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,4CAoEC"}
package/package.json CHANGED
@@ -1,25 +1,46 @@
1
1
  {
2
2
  "name": "property-accessor",
3
- "version": "1.0.0",
4
- "description": "Proxy object which get access to target property with string key which contains full path to it (f.e. 'users[0].firstName')",
5
- "main": "index.js",
3
+ "version": "2.0.1",
4
+ "description": "This package evaluates path to nested object properties like 'prop1[0].prop2[9]['name']' and returns value ",
5
+ "keywords": [
6
+ "proxy",
7
+ "property accessor",
8
+ "evaluate path"
9
+ ],
10
+ "main": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "author": "Pavlo Lazunko",
13
+ "license": "MIT",
6
14
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
15
+ "build": "rm -rf dist && tsc && tsc-alias && eslint src/**/*.ts{,x}",
16
+ "eslint": "eslint src --ext .ts",
17
+ "prettier-check": "prettier . --check",
18
+ "prettier-write": "prettier . --write",
19
+ "test": "node test/test.js",
20
+ "runtime": "node dist/index.js"
8
21
  },
9
- "repository": {
10
- "type": "git",
11
- "url": "git+https://github.com/Paul-Lazunko/property-accessor.git"
22
+ "dependencies": {},
23
+ "devDependencies": {
24
+ "@types/node": "20.10.6",
25
+ "@types/prettier": "2.6.0",
26
+ "@types/uuid": "10.0.0",
27
+ "@typescript-eslint/eslint-plugin": "6.17.0",
28
+ "@typescript-eslint/parser": "6.17.0",
29
+ "eslint": "8.47.0",
30
+ "husky": "3.0.0",
31
+ "prettier": "3.3.3",
32
+ "prettier-plugin-multiline-arrays": "3.0.6",
33
+ "ts-node": "10.9.2",
34
+ "tsc-alias": "1.8.10",
35
+ "typescript": "5.3.3"
12
36
  },
13
- "keywords": [
14
- "Javascript",
15
- "property",
16
- "accessor",
17
- "proxy"
18
- ],
19
- "author": "Paul Lazunko",
20
- "license": "ISC",
21
- "bugs": {
22
- "url": "https://github.com/Paul-Lazunko/property-accessor/issues"
37
+ "husky": {
38
+ "hooks": {
39
+ "pre-commit": "npm run eslint"
40
+ }
23
41
  },
24
- "homepage": "https://github.com/Paul-Lazunko/property-accessor#readme"
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git@github.com:Paul-Lazunko/property-accessor.git"
45
+ }
25
46
  }
package/test/test.js ADDED
@@ -0,0 +1,34 @@
1
+ const assert = require('assert');
2
+ const { PropertyAccessor } = require('../dist');
3
+
4
+ const target = {
5
+ a: [
6
+ {
7
+ b: [
8
+ {
9
+ c: 'd',
10
+ e: 1,
11
+ },
12
+ {
13
+ f: 'g',
14
+ h: 2,
15
+ },
16
+ ],
17
+ },
18
+ ],
19
+ };
20
+
21
+ assert.equal(PropertyAccessor.get('a[0]b[0].c', target), 'd');
22
+ assert.equal(PropertyAccessor.get('a[0]b[0].e', target), 1);
23
+ assert.equal(PropertyAccessor.get('a[0]b[1].f', target), 'g');
24
+ assert.equal(PropertyAccessor.get('a[0]b[2].f', target), undefined);
25
+ assert.equal(PropertyAccessor.set('a[0]b[5].f', 3, target), true);
26
+ assert.equal(PropertyAccessor.set('a[1]b.c.d.f', 3, target), true);
27
+ assert.equal(PropertyAccessor.get('a[0]b.length', target), 6);
28
+
29
+ const propertyAccessor = new PropertyAccessor({ a: [{ b: 2 }] });
30
+
31
+ assert.equal(propertyAccessor.get('a[0].b'), 2);
32
+ assert.equal(propertyAccessor.set('a[0].c', 3), true);
33
+
34
+ console.log('tests passed');
package/index.js DELETED
@@ -1,73 +0,0 @@
1
- const PropertyAccessor = function ( target ) {
2
- let instance = Object.create( PropertyAccessor.prototype );
3
- instance.target = target;
4
- return instance;
5
- };
6
-
7
- PropertyAccessor.prototype = {
8
- target: {},
9
- set: function( key, value ) {
10
- let target = this.target;
11
- let keys = key.split('.');
12
- let isArray = false;
13
- for ( let i = 0; i < keys.length; i++ ) {
14
- let check = keys[ i ].match(/\[(.*)\]/);
15
- if ( check ) {
16
- keys[ i ] = keys[ i ].replace( check[0], '' );
17
- check = check[ 1 ].split( '][' ).length > 1 ? check[ 1 ].split( '][' ) : check;
18
- if ( ! target[keys[i]] ) {
19
- target[keys[i]] = check[1] && check[1].match(/^\d+$/) ? []: {};
20
- isArray = !! check[1] && check[1].match(/^\d+$/);
21
- }
22
- target = target[ keys[i] ];
23
- check = check[ 1 ].split( '][' );
24
- for ( let j = 0; j < check.length; j++ ) {
25
- if ( ! isArray ) {
26
- target = target [ check[ j ] ];
27
- }
28
- }
29
- if ( i === keys.length - 1 ) {
30
- if ( isArray ) {
31
- target.push(value)
32
- } else {
33
- target = value;
34
- }
35
- }
36
- } else {
37
- if ( i < keys.length - 1 ) {
38
- target[ keys[ i ] ] = target[ keys[ i ] ] || {};
39
- target = target[ keys[ i ] ];
40
- } else {
41
- target ? target[ keys[ i ] ] = value : target = value;
42
- }
43
- }
44
- }
45
- },
46
-
47
- get: function( key ) {
48
- let target = this.target;
49
- let keys = key.split( '.' );
50
- for( let i = 0; i < keys.length; i++ ) {
51
- let check = keys[ i ].match( /\[(.*)\]/ );
52
- if ( check ) {
53
- keys[ i ] = keys[ i ].replace( check[ 0 ], '');
54
- check = check[ 1 ].split( '][' );
55
- target = target[ keys[ i ] ];
56
- for ( let j = 0; j < check.length; j++ ) {
57
- target = target [ check[ j ] ];
58
- }
59
- if ( i === keys.length - 1 ) {
60
- return target;
61
- }
62
- } else {
63
- if ( i < keys.length - 1 ) {
64
- target = target[ keys[ i ] ] ? target[ keys[ i ] ] : undefined;
65
- } else {
66
- return target ? target[ keys[ i ] ] : undefined;
67
- }
68
- }
69
- }
70
- }
71
- };
72
-
73
- module.exports = PropertyAccessor;
package/license.txt DELETED
@@ -1,13 +0,0 @@
1
- Copyright (c) 2019, Paul Lazunko <plavel@gmail.com>
2
-
3
- Permission to use, copy, modify, and/or distribute this software for any
4
- purpose with or without fee is hereby granted, provided that the above
5
- copyright notice and this permission notice appear in all copies.
6
-
7
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10
- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.