@a-ludi/rjsf-formulas 0.1.0 → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arne Ludwig
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,71 @@
1
+ # rjsf-formulas
2
+
3
+ RJSF extension for computed fields driven by formulas embedded in a JSON schema.
4
+
5
+ **[Documentation](https://a-ludi.github.io/rjsf-formulas/) · [Live Demo](https://a-ludi.github.io/rjsf-formulas/demo/) · [GitHub](https://github.com/a-ludi/rjsf-formulas)**
6
+
7
+ ## Overview
8
+
9
+ `rjsf-formulas` is a React library that extends [RJSF](https://github.com/rjsf-team/react-jsonschema-form) with computed fields. Fields marked with a formula key in the JSON schema are evaluated automatically on every data change — the user cannot edit them directly.
10
+
11
+ ```json
12
+ {
13
+ "type": "object",
14
+ "properties": {
15
+ "price": { "type": "number" },
16
+ "quantity": { "type": "number" },
17
+ "total": { "type": "number", "x-formula": "price * quantity" }
18
+ }
19
+ }
20
+ ```
21
+
22
+ ## Installation
23
+
24
+ ```sh
25
+ npm install @a-ludi/rjsf-formulas
26
+ ```
27
+
28
+ Peer dependencies: `@rjsf/core ≥ 5`, `@rjsf/utils ≥ 5`, `react ≥ 17`.
29
+
30
+ ## Usage
31
+
32
+ ```tsx
33
+ import { FormulaForm } from '@a-ludi/rjsf-formulas'
34
+ import validator from '@rjsf/validator-ajv8'
35
+ import { Parser } from 'expr-eval'
36
+
37
+ const parser = new Parser()
38
+
39
+ function MyForm() {
40
+ return (
41
+ <FormulaForm
42
+ schema={schema}
43
+ validator={validator}
44
+ evaluator={(formula, ctx) => parser.evaluate(formula, ctx)}
45
+ />
46
+ )
47
+ }
48
+ ```
49
+
50
+ `FormulaForm` is a drop-in replacement for RJSF's `<Form>` — it accepts all the same props.
51
+
52
+ ## Security
53
+
54
+ **Do not use `eval` as the evaluator with user-supplied formulas.**
55
+
56
+ `eval` gives untrusted code unrestricted access to the JavaScript environment, which can lead to arbitrary code execution and XSS attacks. If the formulas in your schema come from user input, use a sandboxed evaluator instead:
57
+
58
+ - [`expr-eval`](https://github.com/silentmatt/expr-eval) — safe parser with no `eval`, supports arithmetic and common math functions
59
+ - [`mathjs`](https://mathjs.org/) — full math library with a safe expression parser
60
+ - A [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) running a restricted evaluator — strongest isolation
61
+
62
+ Using `eval` is only appropriate when formulas are authored by trusted developers and shipped as part of the application code.
63
+
64
+ ## Documentation
65
+
66
+ Full documentation including the Customization guide and API reference is at:
67
+ **<https://a-ludi.github.io/rjsf-formulas/>**
68
+
69
+ ## License
70
+
71
+ MIT © 2026 Arne Ludwig
package/dist/index.d.cts CHANGED
@@ -1,41 +1,174 @@
1
1
  import { default as default_2 } from 'react';
2
2
  import { FormContextType } from '@rjsf/utils';
3
- import { FormProps } from '@rjsf/utils';
3
+ import { FormProps } from '@rjsf/core';
4
4
  import { RJSFSchema } from '@rjsf/utils';
5
5
  import { StrictRJSFSchema } from '@rjsf/utils';
6
6
 
7
+ /**
8
+ * Scans a JSON Schema and returns descriptors for every field that carries a formula key.
9
+ *
10
+ * @remarks
11
+ * Traversal is depth-first. Schema composition operators (`$ref`, `oneOf`, `anyOf`, `allOf`)
12
+ * are not supported and emit a `console.warn` when encountered.
13
+ *
14
+ * @param schema - The root RJSF schema to scan.
15
+ * @param options - Optional key overrides for locating formulas in the schema.
16
+ * @returns An array of {@link FormulaField} descriptors, one per computed field found.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import { analyzeSchema } from '@a-ludi/rjsf-formulas'
21
+ *
22
+ * const fields = analyzeSchema({
23
+ * type: 'object',
24
+ * properties: {
25
+ * price: { type: 'number' },
26
+ * total: { type: 'number', 'x-formula': 'price * 2' },
27
+ * },
28
+ * })
29
+ * // fields[0].path => ['total']
30
+ * // fields[0].formula => 'price * 2'
31
+ * ```
32
+ */
7
33
  export declare function analyzeSchema(schema: RJSFSchema, options?: AnalyzeSchemaOptions): FormulaField[];
8
34
 
35
+ /**
36
+ * Options for {@link analyzeSchema}.
37
+ */
9
38
  export declare type AnalyzeSchemaOptions = {
39
+ /** Schema key that marks a field as computed. Defaults to `'x-formula'`. */
10
40
  formulaKey?: string;
41
+ /** Schema key that selects the context mode for a computed field. Defaults to `'x-formula-context'`. */
11
42
  formulaContextKey?: string;
12
43
  };
13
44
 
14
- /** Package-internal — not re-exported from the public entry point. Used by enrich.ts and mergeReadOnly.ts. */
15
- declare const ARRAY_INDEX: unique symbol;
45
+ /* Excluded from this release type: ARRAY_INDEX */
16
46
 
17
- declare type ArrayIndex = typeof ARRAY_INDEX;
47
+ /* Excluded from this release type: ArrayIndex */
18
48
 
49
+ /**
50
+ * Controls which values are injected into the formula evaluation context.
51
+ *
52
+ * - `'siblings'` (default): only the sibling fields of the computed field are available by name.
53
+ * - `'extended'`: full form data and the field's resolved path are injected alongside sibling
54
+ * values, under the keys configured by `formulaDataKey` and `formulaPathKey`.
55
+ *
56
+ * Set via the `x-formula-context` schema key (or the `formulaContextKey` prop).
57
+ */
19
58
  export declare type ContextMode = 'siblings' | 'extended';
20
59
 
60
+ /**
61
+ * Describes a single computed field discovered by {@link analyzeSchema}.
62
+ */
21
63
  export declare type FormulaField = {
64
+ /** JSON path to the field within the form data. Uniform array item positions are represented by {@link ARRAY_INDEX}. */
22
65
  path: (string | number | ArrayIndex)[];
66
+ /** The raw formula string from the schema. */
23
67
  formula: string;
68
+ /** Which values are available when evaluating this field's formula. */
24
69
  contextMode: ContextMode;
25
70
  };
26
71
 
72
+ /**
73
+ * Drop-in replacement for RJSF's `<Form>` with support for computed fields.
74
+ *
75
+ * @remarks
76
+ * Fields marked with a formula key in the JSON schema are evaluated automatically
77
+ * on every data change and rendered as read-only. The `evaluator` prop receives
78
+ * the formula string and a context object, and returns the computed value.
79
+ *
80
+ * @example
81
+ * ```tsx
82
+ * import { FormulaForm } from '@a-ludi/rjsf-formulas'
83
+ * import validator from '@rjsf/validator-ajv8'
84
+ * import { Parser } from 'expr-eval'
85
+ *
86
+ * const parser = new Parser()
87
+ *
88
+ * const schema = {
89
+ * type: 'object' as const,
90
+ * properties: {
91
+ * price: { type: 'number' as const },
92
+ * quantity: { type: 'number' as const },
93
+ * total: { type: 'number' as const, 'x-formula': 'price * quantity' },
94
+ * },
95
+ * }
96
+ *
97
+ * function MyForm() {
98
+ * return (
99
+ * <FormulaForm
100
+ * schema={schema}
101
+ * validator={validator}
102
+ * evaluator={(formula, ctx) => parser.evaluate(formula, ctx)}
103
+ * />
104
+ * )
105
+ * }
106
+ * ```
107
+ */
27
108
  export declare function FormulaForm<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(props: FormulaFormProps<T, S, F>): JSX.Element;
28
109
 
110
+ /**
111
+ * Props accepted by {@link FormulaForm}.
112
+ *
113
+ * Extends all standard RJSF `FormProps` with formula-specific configuration.
114
+ * All formula-specific props are optional except `evaluator`.
115
+ */
29
116
  export declare type FormulaFormProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = FormProps<T, S, F> & {
117
+ /**
118
+ * Evaluates a formula string against a context object and returns the computed value.
119
+ *
120
+ * @remarks
121
+ * May return a plain value or a `Promise`. For user-supplied formulas, **do not use `eval`**
122
+ * — it allows arbitrary code execution. Prefer a sandboxed evaluator such as
123
+ * [`expr-eval`](https://github.com/silentmatt/expr-eval) or
124
+ * [`mathjs`](https://mathjs.org/). For additional isolation, run the evaluator in a Web Worker.
125
+ *
126
+ * @param formula - The formula string from the schema.
127
+ * @param context - Sibling field values, or full form data in extended mode.
128
+ * @returns The computed value, or a Promise resolving to it.
129
+ */
30
130
  evaluator: (formula: string, context: object) => unknown | Promise<unknown>;
131
+ /**
132
+ * Inner RJSF `Form` component to render.
133
+ * Defaults to `Form` from `@rjsf/core`. Swap to use a themed form
134
+ * (e.g. `Form` from `@rjsf/bootstrap-4`).
135
+ */
31
136
  Form?: default_2.ComponentType<FormProps<T, S, F>>;
137
+ /** Schema key that marks a field as computed. Defaults to `'x-formula'`. */
32
138
  formulaKey?: string;
139
+ /** Schema key that selects the context mode for a field. Defaults to `'x-formula-context'`. */
33
140
  formulaContextKey?: string;
141
+ /**
142
+ * Key injected into the extended context carrying the full form data.
143
+ * Defaults to `'__formData__'`. Override if a sibling field uses the same name.
144
+ */
34
145
  formulaDataKey?: string;
146
+ /**
147
+ * Key injected into the extended context carrying the field's resolved path.
148
+ * Defaults to `'__path__'`. Override if a sibling field uses the same name.
149
+ */
35
150
  formulaPathKey?: string;
151
+ /**
152
+ * Maximum number of re-evaluation passes triggered by a single input event.
153
+ * Guards against infinite loops from circular formula dependencies. Defaults to `10`.
154
+ */
36
155
  maxConvergencePasses?: number;
156
+ /**
157
+ * Milliseconds to debounce formula evaluation after a user input event. Defaults to `300`.
158
+ * Set to `0` to disable the debounce delay and evaluate on the next event loop tick.
159
+ */
37
160
  debounceMs?: number;
161
+ /**
162
+ * Called when a formula throws during evaluation.
163
+ * @param path - JSON path of the field whose formula failed.
164
+ * @param error - The error thrown by the evaluator.
165
+ */
38
166
  onFormulaError?: (path: (string | number)[], error: Error) => void;
167
+ /**
168
+ * Called whenever the set of currently-evaluating fields changes.
169
+ * Useful for showing per-field loading indicators.
170
+ * @param loadingPaths - Paths of all fields whose evaluations are in progress.
171
+ */
39
172
  onLoadingChange?: (loadingPaths: (string | number)[][]) => void;
40
173
  };
41
174
 
package/dist/index.d.mts CHANGED
@@ -1,41 +1,174 @@
1
1
  import { default as default_2 } from 'react';
2
2
  import { FormContextType } from '@rjsf/utils';
3
- import { FormProps } from '@rjsf/utils';
3
+ import { FormProps } from '@rjsf/core';
4
4
  import { RJSFSchema } from '@rjsf/utils';
5
5
  import { StrictRJSFSchema } from '@rjsf/utils';
6
6
 
7
+ /**
8
+ * Scans a JSON Schema and returns descriptors for every field that carries a formula key.
9
+ *
10
+ * @remarks
11
+ * Traversal is depth-first. Schema composition operators (`$ref`, `oneOf`, `anyOf`, `allOf`)
12
+ * are not supported and emit a `console.warn` when encountered.
13
+ *
14
+ * @param schema - The root RJSF schema to scan.
15
+ * @param options - Optional key overrides for locating formulas in the schema.
16
+ * @returns An array of {@link FormulaField} descriptors, one per computed field found.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import { analyzeSchema } from '@a-ludi/rjsf-formulas'
21
+ *
22
+ * const fields = analyzeSchema({
23
+ * type: 'object',
24
+ * properties: {
25
+ * price: { type: 'number' },
26
+ * total: { type: 'number', 'x-formula': 'price * 2' },
27
+ * },
28
+ * })
29
+ * // fields[0].path => ['total']
30
+ * // fields[0].formula => 'price * 2'
31
+ * ```
32
+ */
7
33
  export declare function analyzeSchema(schema: RJSFSchema, options?: AnalyzeSchemaOptions): FormulaField[];
8
34
 
35
+ /**
36
+ * Options for {@link analyzeSchema}.
37
+ */
9
38
  export declare type AnalyzeSchemaOptions = {
39
+ /** Schema key that marks a field as computed. Defaults to `'x-formula'`. */
10
40
  formulaKey?: string;
41
+ /** Schema key that selects the context mode for a computed field. Defaults to `'x-formula-context'`. */
11
42
  formulaContextKey?: string;
12
43
  };
13
44
 
14
- /** Package-internal — not re-exported from the public entry point. Used by enrich.ts and mergeReadOnly.ts. */
15
- declare const ARRAY_INDEX: unique symbol;
45
+ /* Excluded from this release type: ARRAY_INDEX */
16
46
 
17
- declare type ArrayIndex = typeof ARRAY_INDEX;
47
+ /* Excluded from this release type: ArrayIndex */
18
48
 
49
+ /**
50
+ * Controls which values are injected into the formula evaluation context.
51
+ *
52
+ * - `'siblings'` (default): only the sibling fields of the computed field are available by name.
53
+ * - `'extended'`: full form data and the field's resolved path are injected alongside sibling
54
+ * values, under the keys configured by `formulaDataKey` and `formulaPathKey`.
55
+ *
56
+ * Set via the `x-formula-context` schema key (or the `formulaContextKey` prop).
57
+ */
19
58
  export declare type ContextMode = 'siblings' | 'extended';
20
59
 
60
+ /**
61
+ * Describes a single computed field discovered by {@link analyzeSchema}.
62
+ */
21
63
  export declare type FormulaField = {
64
+ /** JSON path to the field within the form data. Uniform array item positions are represented by {@link ARRAY_INDEX}. */
22
65
  path: (string | number | ArrayIndex)[];
66
+ /** The raw formula string from the schema. */
23
67
  formula: string;
68
+ /** Which values are available when evaluating this field's formula. */
24
69
  contextMode: ContextMode;
25
70
  };
26
71
 
72
+ /**
73
+ * Drop-in replacement for RJSF's `<Form>` with support for computed fields.
74
+ *
75
+ * @remarks
76
+ * Fields marked with a formula key in the JSON schema are evaluated automatically
77
+ * on every data change and rendered as read-only. The `evaluator` prop receives
78
+ * the formula string and a context object, and returns the computed value.
79
+ *
80
+ * @example
81
+ * ```tsx
82
+ * import { FormulaForm } from '@a-ludi/rjsf-formulas'
83
+ * import validator from '@rjsf/validator-ajv8'
84
+ * import { Parser } from 'expr-eval'
85
+ *
86
+ * const parser = new Parser()
87
+ *
88
+ * const schema = {
89
+ * type: 'object' as const,
90
+ * properties: {
91
+ * price: { type: 'number' as const },
92
+ * quantity: { type: 'number' as const },
93
+ * total: { type: 'number' as const, 'x-formula': 'price * quantity' },
94
+ * },
95
+ * }
96
+ *
97
+ * function MyForm() {
98
+ * return (
99
+ * <FormulaForm
100
+ * schema={schema}
101
+ * validator={validator}
102
+ * evaluator={(formula, ctx) => parser.evaluate(formula, ctx)}
103
+ * />
104
+ * )
105
+ * }
106
+ * ```
107
+ */
27
108
  export declare function FormulaForm<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(props: FormulaFormProps<T, S, F>): JSX.Element;
28
109
 
110
+ /**
111
+ * Props accepted by {@link FormulaForm}.
112
+ *
113
+ * Extends all standard RJSF `FormProps` with formula-specific configuration.
114
+ * All formula-specific props are optional except `evaluator`.
115
+ */
29
116
  export declare type FormulaFormProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = FormProps<T, S, F> & {
117
+ /**
118
+ * Evaluates a formula string against a context object and returns the computed value.
119
+ *
120
+ * @remarks
121
+ * May return a plain value or a `Promise`. For user-supplied formulas, **do not use `eval`**
122
+ * — it allows arbitrary code execution. Prefer a sandboxed evaluator such as
123
+ * [`expr-eval`](https://github.com/silentmatt/expr-eval) or
124
+ * [`mathjs`](https://mathjs.org/). For additional isolation, run the evaluator in a Web Worker.
125
+ *
126
+ * @param formula - The formula string from the schema.
127
+ * @param context - Sibling field values, or full form data in extended mode.
128
+ * @returns The computed value, or a Promise resolving to it.
129
+ */
30
130
  evaluator: (formula: string, context: object) => unknown | Promise<unknown>;
131
+ /**
132
+ * Inner RJSF `Form` component to render.
133
+ * Defaults to `Form` from `@rjsf/core`. Swap to use a themed form
134
+ * (e.g. `Form` from `@rjsf/bootstrap-4`).
135
+ */
31
136
  Form?: default_2.ComponentType<FormProps<T, S, F>>;
137
+ /** Schema key that marks a field as computed. Defaults to `'x-formula'`. */
32
138
  formulaKey?: string;
139
+ /** Schema key that selects the context mode for a field. Defaults to `'x-formula-context'`. */
33
140
  formulaContextKey?: string;
141
+ /**
142
+ * Key injected into the extended context carrying the full form data.
143
+ * Defaults to `'__formData__'`. Override if a sibling field uses the same name.
144
+ */
34
145
  formulaDataKey?: string;
146
+ /**
147
+ * Key injected into the extended context carrying the field's resolved path.
148
+ * Defaults to `'__path__'`. Override if a sibling field uses the same name.
149
+ */
35
150
  formulaPathKey?: string;
151
+ /**
152
+ * Maximum number of re-evaluation passes triggered by a single input event.
153
+ * Guards against infinite loops from circular formula dependencies. Defaults to `10`.
154
+ */
36
155
  maxConvergencePasses?: number;
156
+ /**
157
+ * Milliseconds to debounce formula evaluation after a user input event. Defaults to `300`.
158
+ * Set to `0` to disable the debounce delay and evaluate on the next event loop tick.
159
+ */
37
160
  debounceMs?: number;
161
+ /**
162
+ * Called when a formula throws during evaluation.
163
+ * @param path - JSON path of the field whose formula failed.
164
+ * @param error - The error thrown by the evaluator.
165
+ */
38
166
  onFormulaError?: (path: (string | number)[], error: Error) => void;
167
+ /**
168
+ * Called whenever the set of currently-evaluating fields changes.
169
+ * Useful for showing per-field loading indicators.
170
+ * @param loadingPaths - Paths of all fields whose evaluations are in progress.
171
+ */
39
172
  onLoadingChange?: (loadingPaths: (string | number)[][]) => void;
40
173
  };
41
174
 
package/package.json CHANGED
@@ -1,6 +1,17 @@
1
1
  {
2
2
  "name": "@a-ludi/rjsf-formulas",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
+ "description": "RJSF extension for computed fields driven by formulas",
5
+ "author": "Arne Ludwig <arne.ludwig@posteo.de>",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/a-ludi/rjsf-formulas.git"
10
+ },
11
+ "homepage": "https://a-ludi.github.io/rjsf-formulas/",
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
4
15
  "type": "module",
5
16
  "files": [
6
17
  "dist/"
@@ -20,9 +31,11 @@
20
31
  },
21
32
  "scripts": {
22
33
  "build": "vite build && cp dist/index.d.mts dist/index.d.cts",
34
+ "build:docs": "typedoc && vitepress build website",
35
+ "build:demo": "vite build --config demo/vite.config.ts",
23
36
  "dev": "vite --config demo/vite.config.ts",
24
37
  "test": "vitest run",
25
- "prepare": "true",
38
+ "prepare": "bunx husky",
26
39
  "prepublishOnly": "bun run build && bunx publint"
27
40
  },
28
41
  "peerDependencies": {
@@ -45,9 +58,12 @@
45
58
  "rjsf-core-v5": "npm:@rjsf/core@^5",
46
59
  "rjsf-utils-v5": "npm:@rjsf/utils@^5",
47
60
  "rjsf-validator-v5": "npm:@rjsf/validator-ajv8@^5",
61
+ "typedoc": "^0.28.19",
62
+ "typedoc-plugin-markdown": "^4.12.0",
48
63
  "typescript": "^5",
49
64
  "vite": "^6",
50
65
  "vite-plugin-dts": "^4",
66
+ "vitepress": "^1.6.4",
51
67
  "vitest": "^3"
52
68
  },
53
69
  "dependencies": {