jfather 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020-2024 Sébastien Règne
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # JFather
2
+
3
+ <!-- Utiliser du HTML (avec l'attribut "align" obsolète) pour faire flotter
4
+ l'image à droite. -->
5
+ <!-- markdownlint-disable-next-line no-inline-html-->
6
+ <img src="asset/logo.svg" align="right" alt="">
7
+
8
+ [![npm][img-npm]][link-npm]
9
+ [![build][img-build]][link-build]
10
+ [![coverage][img-coverage]][link-coverage]
11
+ [![semver][img-semver]][link-semver]
12
+
13
+ > Boys use JSON; Men use JFather.
14
+
15
+ ## Overview
16
+
17
+ **JFather** is
18
+ [JSON](https://www.json.org/json-fr.html "JavaScript Object Notation") with
19
+ features to merge, extend and override JSON objects.
20
+
21
+ ```JavaScript
22
+ import JFather from "jfather";
23
+
24
+ const merged = JFather.merge(
25
+ { foo: "a", bar: "alpha" },
26
+ { foo: "b", baz: "beta" },
27
+ );
28
+
29
+ console.log(merged);
30
+ // { foo: "b", bar: "alpha", baz: "beta" }
31
+ ```
32
+
33
+ ## Install
34
+
35
+ ### Node.js
36
+
37
+ JFather is published on [npm][link-npm].
38
+
39
+ ```JavaScript
40
+ import JFather from "jfather";
41
+ ```
42
+
43
+ ### Deno
44
+
45
+ The library is available in [Deno](https://deno.land/x/jfather).
46
+
47
+ ```JavaScript
48
+ import JFather from "https://deno.land/x/jfather/mod.js";
49
+ ```
50
+
51
+ ### Browsers
52
+
53
+ It can also be accessed directly from the CDN
54
+ [esm.sh](https://esm.sh/jfather) (ou
55
+ [jsDelivr](https://www.jsdelivr.com/package/npm/jfather),
56
+ [UNPKG](https://unpkg.com/browse/jfather/)) :
57
+
58
+ ```JavaScript
59
+ import JFather from "https://esm.sh/jfather@0";
60
+ // import JFather from "https://cdn.jsdelivr.net/npm/jfather@0";
61
+ // import JFather from "https://unpkg.com/jfather@0";
62
+ ```
63
+
64
+ ## API
65
+
66
+ - [`merge()`](#merge)
67
+ - [`load()`](#load)
68
+ - [`parse()`](#parse)
69
+
70
+ ### merge()
71
+
72
+ Merge two variables.
73
+
74
+ <!-- markdownlint-disable no-inline-html -->
75
+ <table>
76
+ <tr>
77
+ <th><code>a</code></th>
78
+ <th><code>b</code></th>
79
+ <th><code>JFather.merge(a, b)</code></th>
80
+ </tr>
81
+ <tr>
82
+ <td><code>1</code></td>
83
+ <td><code>2</code></td>
84
+ <td><code>2</code></td>
85
+ </tr>
86
+ <tr>
87
+ <td><code>{ foo: "alpha", bar: "ALPHA" }</code></td>
88
+ <td><code>{ foo: "beta", baz: "BETA" }</code></td>
89
+ <td><code>{ foo: "beta", bar: "ALPHA", baz: "BETA" }</code></td>
90
+ </tr>
91
+ </tr>
92
+ <tr>
93
+ <td><code>{ foo: [1, 10, 11] }</code></td>
94
+ <td><code>{ foo: [2, 20, 22] }</code></td>
95
+ <td><code>{ foo: [2, 20, 22] }</code></td>
96
+ </tr>
97
+ </table>
98
+ <!-- markdownlint-enable no-inline-html -->
99
+
100
+ ### load()
101
+
102
+ Load an object from an URL.
103
+
104
+ ### parse()
105
+
106
+ Parse a string.
107
+
108
+ [img-npm]: https://img.shields.io/npm/dm/jfather?label=npm&logo=npm&logoColor=whitesmoke
109
+ [img-build]: https://img.shields.io/github/actions/workflow/status/regseb/jfather/ci.yml?branch=main&logo=github&logoColor=whitesmoke
110
+ [img-coverage]: https://img.shields.io/endpoint?label=coverage&url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fregseb%2Fjfather%2Fmain&logo=stryker&logoColor=whitesmoke
111
+ [img-semver]: https://img.shields.io/badge/semver-2.0.0-blue?logo=semver&logoColor=whitesmoke
112
+ [link-npm]: https://www.npmjs.com/package/jfather
113
+ [link-build]: https://github.com/regseb/jfather/actions/workflows/ci.yml?query=branch%3Amain
114
+ [link-coverage]: https://dashboard.stryker-mutator.io/reports/github.com/regseb/jfather/main
115
+ [link-semver]: https://semver.org/spec/v2.0.0.html "Semantic Versioning 2.0.0"
package/package.json ADDED
@@ -0,0 +1,80 @@
1
+ {
2
+ "name": "jfather",
3
+ "version": "0.1.0",
4
+ "description": "JSON with merge, extend and override.",
5
+ "keywords": [
6
+ "jfather",
7
+ "json",
8
+ "merge",
9
+ "extend",
10
+ "override",
11
+ "front-end",
12
+ "backend"
13
+ ],
14
+ "homepage": "https://github.com/regseb/jfather#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/regseb/jfather/issues",
17
+ "email": "regseb@gmail.com"
18
+ },
19
+ "license": "MIT",
20
+ "author": "Sébastien Règne <regseb@gmail.com> (https://github.com/regseb)",
21
+ "funding": "https://www.paypal.me/sebastienregne",
22
+ "files": [
23
+ "./src/",
24
+ "./types/"
25
+ ],
26
+ "exports": {
27
+ ".": {
28
+ "types": "./types/index.d.ts",
29
+ "default": "./src/index.js"
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "main": "./src/index.js",
34
+ "types": "./types/index.d.ts",
35
+ "repository": "regseb/jfather",
36
+ "type": "module",
37
+ "scripts": {
38
+ "lint": "metalint",
39
+ "lint:fix": "metalint --fix",
40
+ "lint:types": "tsc --project .tsconfig_lint.json",
41
+ "test": "npm run test:coverage",
42
+ "test:unit": "mocha --config test/mocharc.json",
43
+ "test:coverage": "stryker run",
44
+ "jsdocs": "typedoc --tsconfig .tsconfig_jsdocs.json",
45
+ "prepare": "tsc --project .tsconfig_types.json",
46
+ "clean": "node .script/clean.js"
47
+ },
48
+ "devDependencies": {
49
+ "@prantlf/jsonlint": "14.0.3",
50
+ "@prettier/plugin-xml": "3.3.0",
51
+ "@stryker-mutator/core": "8.2.3",
52
+ "@stryker-mutator/mocha-runner": "8.2.3",
53
+ "@types/mocha": "10.0.6",
54
+ "@types/node": "20.11.17",
55
+ "@types/sinon": "17.0.3",
56
+ "eslint": "8.56.0",
57
+ "eslint-plugin-array-func": "4.0.0",
58
+ "eslint-plugin-eslint-comments": "3.2.0",
59
+ "eslint-plugin-import": "2.29.1",
60
+ "eslint-plugin-jsdoc": "48.0.6",
61
+ "eslint-plugin-mocha": "10.2.0",
62
+ "eslint-plugin-n": "16.6.2",
63
+ "eslint-plugin-no-unsanitized": "4.0.2",
64
+ "eslint-plugin-promise": "6.1.1",
65
+ "eslint-plugin-regexp": "2.2.0",
66
+ "eslint-plugin-unicorn": "51.0.1",
67
+ "markdownlint": "0.33.0",
68
+ "metalint": "0.15.0",
69
+ "mocha": "10.3.0",
70
+ "npm-package-json-lint": "7.1.0",
71
+ "prettier": "3.2.5",
72
+ "sinon": "17.0.1",
73
+ "typedoc": "0.25.8",
74
+ "typescript": "5.3.3",
75
+ "yaml-lint": "1.7.0"
76
+ },
77
+ "engines": {
78
+ "node": ">=20.6.0"
79
+ }
80
+ }
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @module jfather
3
+ * @license MIT
4
+ * @author Sébastien Règne
5
+ */
6
+
7
+ import { load, merge, parse } from "./jfather.js";
8
+
9
+ export default { load, merge, parse };
package/src/jfather.js ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * @module
3
+ * @license MIT
4
+ * @author Sébastien Règne
5
+ */
6
+
7
+ /**
8
+ * Exécute une fonction sur un objet et tous ses sous-objets (en partant des
9
+ * objets les plus profonds).
10
+ *
11
+ * @param {any} obj Une variable quelconque.
12
+ * @param {Function} fn La fonction appliquée sur tous les objets.
13
+ * @returns {any} Le retour de la fonction.
14
+ */
15
+ export const walk = function (obj, fn) {
16
+ if (Object === obj?.constructor) {
17
+ return fn(
18
+ Object.fromEntries(
19
+ Object.entries(obj).map(([k, v]) => [k, walk(v, fn)]),
20
+ ),
21
+ );
22
+ }
23
+
24
+ if (Array.isArray(obj)) {
25
+ return obj.map((v) => walk(v, fn));
26
+ }
27
+
28
+ return obj;
29
+ };
30
+
31
+ /**
32
+ * Exécute une fonction asynchrone sur un objet et tous ses sous-objets (en
33
+ * partant des objets les plus profonds).
34
+ *
35
+ * @param {any} obj Une variable quelconque.
36
+ * @param {Function} fn La fonction asynchrone appliquée sur tous les objets.
37
+ * @returns {Promise<any>} Une promesse contenant le retour de la fonction.
38
+ */
39
+ export const walkAsync = async function (obj, fn) {
40
+ if (Object === obj?.constructor) {
41
+ return fn(
42
+ Object.fromEntries(
43
+ await Promise.all(
44
+ Object.entries(obj).map(async ([key, value]) => [
45
+ key,
46
+ await walkAsync(value, fn),
47
+ ]),
48
+ ),
49
+ ),
50
+ );
51
+ }
52
+
53
+ if (Array.isArray(obj)) {
54
+ return Promise.all(obj.map((v) => walkAsync(v, fn)));
55
+ }
56
+
57
+ return obj;
58
+ };
59
+
60
+ /**
61
+ * Clone récursivement un objet.
62
+ *
63
+ * @param {any} obj Une variable quelconque.
64
+ * @returns {any} Le clone de la variable d'entrée.
65
+ */
66
+ export const clone = function (obj) {
67
+ return walk(obj, (/** @type {any} */ v) => v);
68
+ };
69
+
70
+ /**
71
+ * Extrait un élément d'un objet.
72
+ *
73
+ * @param {Record<string, any>} obj L'objet où sera extrait l'élément.
74
+ * @param {string} chain Le chemin de l'élément.
75
+ * @returns {any} L'élément extrait.
76
+ * @throws {TypeError} Si le chemin est invalide.
77
+ */
78
+ export const query = function (obj, chain) {
79
+ const re = /^\.(?<prop>\w+)|^\[(?<index>\d+)\]/u;
80
+ const sub = { obj, chain };
81
+ while (0 !== sub.chain.length) {
82
+ const result = re.exec(sub.chain);
83
+ if (undefined !== result?.groups?.prop) {
84
+ sub.obj = sub.obj[result.groups.prop];
85
+ // eslint-disable-next-line no-negated-condition
86
+ } else if (undefined !== result?.groups?.index) {
87
+ sub.obj = sub.obj[Number(result.groups.index)];
88
+ } else {
89
+ throw new TypeError(`Invalid chain: ${chain}`);
90
+ }
91
+ sub.chain = sub.chain.slice(result[0].length);
92
+ }
93
+ return sub.obj;
94
+ };
95
+
96
+ /**
97
+ * Fusionne deux objets récursivement.
98
+ *
99
+ * @param {any} parent L'objet parent.
100
+ * @param {any} child L'objet enfant.
101
+ * @returns {any} La fusion des deux objets.
102
+ */
103
+ export const merge = function (parent, child) {
104
+ if (Object !== parent?.constructor || Object !== child?.constructor) {
105
+ return clone(child);
106
+ }
107
+
108
+ const overrode = /** @type {Record<string, any>} */ ({});
109
+ for (const key of new Set([
110
+ ...Object.keys(parent),
111
+ ...Object.keys(child),
112
+ ])) {
113
+ // Ne pas copier les surcharges d'éléments.
114
+ if (key.startsWith("$")) {
115
+ continue;
116
+ }
117
+
118
+ // Si la propriété est dans les deux objets : fusionner les deux
119
+ // valeurs.
120
+ if (key in parent && key in child) {
121
+ overrode[key] = merge(parent[key], child[key]);
122
+ // Si la propriété est seulement dans l'objet parent.
123
+ } else if (key in parent) {
124
+ overrode[key] = clone(parent[key]);
125
+ // Si la propriété est seulement dans l'objet enfant.
126
+ } else {
127
+ overrode[key] = clone(child[key]);
128
+ }
129
+
130
+ // Si la valeur est un tableau : chercher si l'objet enfant a des
131
+ // surcharges d'éléments.
132
+ if (Array.isArray(overrode[key])) {
133
+ const overelemRegex = new RegExp(
134
+ `^\\$${key}\\[(?<index>\\d*)\\]$`,
135
+ "u",
136
+ );
137
+ const overelems = Object.entries(child)
138
+ .map(([k, v]) => [overelemRegex.exec(k)?.groups?.index, v])
139
+ .filter(([i]) => undefined !== i);
140
+ for (const [index, value] of overelems) {
141
+ if ("" === index) {
142
+ overrode[key].push(clone(value));
143
+ } else {
144
+ overrode[key][Number(index)] = merge(
145
+ overrode[key][Number(index)],
146
+ value,
147
+ );
148
+ }
149
+ }
150
+ }
151
+ }
152
+ return overrode;
153
+ };
154
+
155
+ /**
156
+ * Étendre un objet JSON en utilisant les propriétes <code>"$extends"</code>.
157
+ *
158
+ * @param {Record<string, any>} obj L'objet qui sera étendu.
159
+ * @returns {Promise<Record<string, any>>} Une promesse contenant l'objet
160
+ * étendu.
161
+ */
162
+ export const inherit = async function (obj) {
163
+ if (undefined === obj?.$extends) {
164
+ return obj;
165
+ }
166
+
167
+ // eslint-disable-next-line no-use-before-define
168
+ return merge(await load(obj.$extends), obj);
169
+ };
170
+
171
+ /**
172
+ * Étendre un objet récursivement.
173
+ *
174
+ * @param {any} obj L'objet qui sera étendu.
175
+ * @returns {Promise<any>} Une promesse contenant l'objet étendu.
176
+ */
177
+ export const transform = function (obj) {
178
+ return walkAsync(obj, inherit);
179
+ };
180
+
181
+ /**
182
+ * Charge un objet JSON depuis une URL.
183
+ *
184
+ * @param {string} url L'URL du fichier JSON.
185
+ * @returns {Promise<any>} Une promesse contenant l'objet.
186
+ */
187
+ export const load = async function (url) {
188
+ const response = await fetch(url);
189
+ const json = await response.json();
190
+ return transform(query(json, new URL(url).hash.replace(/^#/u, ".")));
191
+ };
192
+
193
+ /**
194
+ * Parse une chaine de caractères.
195
+ *
196
+ * @param {string} text La chaine de caractères qui sera parsée.
197
+ * @returns {any} L'objet.
198
+ */
199
+ export const parse = function (text) {
200
+ return transform(JSON.parse(text));
201
+ };
@@ -0,0 +1,9 @@
1
+ declare namespace _default {
2
+ export { load };
3
+ export { merge };
4
+ export { parse };
5
+ }
6
+ export default _default;
7
+ import { load } from "./jfather.js";
8
+ import { merge } from "./jfather.js";
9
+ import { parse } from "./jfather.js";
@@ -0,0 +1,9 @@
1
+ export function walk(obj: any, fn: Function): any;
2
+ export function walkAsync(obj: any, fn: Function): Promise<any>;
3
+ export function clone(obj: any): any;
4
+ export function query(obj: Record<string, any>, chain: string): any;
5
+ export function merge(parent: any, child: any): any;
6
+ export function inherit(obj: Record<string, any>): Promise<Record<string, any>>;
7
+ export function transform(obj: any): Promise<any>;
8
+ export function load(url: string): Promise<any>;
9
+ export function parse(text: string): any;