data-primals-engine 1.4.2 → 1.4.3

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/src/filter.js CHANGED
@@ -1,261 +1,273 @@
1
- import safeRegex from 'safe-regex';
2
- /**
3
- * Evaluates a single condition against form data.
4
- * @param {object} currentModelDef - The definition of the current model.
5
- * @param {object} condition - The condition to evaluate.
6
- * @param {object} formData - The form data.
7
- * @param {object[]} allModels - An array of all model definitions.
8
- * @param {object} user - The current user.
9
- * @returns {boolean} - True if the condition is met, false otherwise.
10
- */
11
- const evaluateSingleCondition = (currentModelDef, condition, formData, allModels, user) => {
12
- // Condition est directement un filtre MongoDB, donc on l'applique
13
- // en utilisant les opérateurs et les valeurs qu'il contient.
14
-
15
- if (!condition || typeof condition !== 'object') {
16
- console.warn("[Client Eval] Condition is not an object:", condition);
17
- return true; // Permissive default
18
- }
19
-
20
- // Si la condition est de la forme {field: value}, on la transforme en {$eq: value}
21
- if (!Object.keys(condition)[0].startsWith('$') && typeof condition[Object.keys(condition)[0]] !== 'object') {
22
- const fieldName = Object.keys(condition)[0];
23
- const value = condition[fieldName];
24
- return evaluateSingleCondition(currentModelDef, {[fieldName]: {$eq: value}}, formData, allModels, user);
25
- }
26
-
27
- // Gestion des opérateurs d'agrégation (commencent par $)
28
- const operator = Object.keys(condition)[0];
29
- if (operator === '$eq' && Array.isArray(condition[operator])) {
30
- // Cas spécial pour {$eq: ['$field', value]}
31
- const [fieldPath, expectedValue] = condition[operator];
32
- if (typeof fieldPath === 'string' && fieldPath.startsWith('$')) {
33
- const fieldName = fieldPath.substring(1); // Enlève le $ devant
34
- return formData[fieldName] == expectedValue;
35
- }
36
- }
37
-
38
- // Si la condition contient des opérateurs logiques, on les gère ici
39
- if (condition.$and || condition.$or || condition.$not || condition.$nor) {
40
- console.warn("[Client Eval] Condition logique détectée dans evaluateSingleCondition, ce n'est pas attendu. Devrait être géré par isConditionMet.");
41
- return true; // Permissive default
42
- }
43
-
44
- if (condition.$find) {
45
- const fieldName = Object.keys(condition)[0];
46
- const fieldValue = formData[fieldName];
47
- const findCondition = condition.$find;
48
-
49
- if (!Array.isArray(fieldValue)) return false;
50
-
51
- return fieldValue.some(item => {
52
- // Gestion spéciale pour la syntaxe $eq: ["$$this.field", value]
53
- if (findCondition.$eq && Array.isArray(findCondition.$eq)) {
54
- const [fieldPath, value] = findCondition.$eq;
55
- if (fieldPath.startsWith("$$this.")) {
56
- const fieldToCheck = fieldPath.replace("$$this.", "");
57
- return item[fieldToCheck] == value;
58
- }
59
- }
60
-
61
- // Sinon, évaluation normale
62
- const tempData = { ...item };
63
- return evaluateSingleCondition(currentModelDef, findCondition, tempData, allModels, user);
64
- });
65
- }
66
-
67
- // Si la condition contient un opérateur $exists, on le gère ici
68
- if (condition.$exists !== undefined) {
69
- const fieldName = Object.keys(condition)[0]; // Récupérer le nom du champ
70
- const shouldExist = condition.$exists; // Récupérer la valeur de $exists (true ou false)
71
- const exists = Object.prototype.hasOwnProperty.call(formData, fieldName) && formData[fieldName] !== undefined && formData[fieldName] !== null;
72
- return exists === shouldExist;
73
- }
74
-
75
- // Si la condition contient un opérateur $find, on le gère ici
76
- if (condition.$find) {
77
- // Récupérer le nom du champ
78
- const fieldName = Object.keys(condition)[0];
79
- const fieldValue = formData[fieldName];
80
- try {
81
- // Assuming evaluateSingleCondition handles $find
82
- return evaluateSingleCondition(currentModelDef, condition.$find, formData, allModels, user);
83
- } catch (error) {
84
- console.error("Error evaluating $find condition:", condition, error);
85
- return false;
86
- }
87
- }
88
-
89
- // Récupérer le nom du champ et la condition
90
- const fieldName = Object.keys(condition)[0];
91
- const fieldValue = condition[fieldName];
92
-
93
- // Récupérer la définition du champ
94
- const fieldDef = currentModelDef?.fields.find(f => f.name === fieldName);
95
-
96
- // Si la définition du champ n'est pas trouvée, on retourne true
97
- if (!fieldDef) {
98
- console.warn(`[Client Eval] Field definition not found for field: ${fieldName}`);
99
- return true; // Permissive default
100
- }
101
-
102
- let targetValue = formData[fieldName];
103
- let processedConditionValue = fieldValue;
104
-
105
- // 1. Handle $exists (on the first field)
106
- // 2. Convert condition value based on operator's expected input type
107
- const fieldType = fieldDef?.type; // Type of the first field
108
-
109
- try {
110
- processedConditionValue = convertValueType(fieldValue, fieldType);
111
- } catch (e) {
112
- logClientEvalWarning(`Error converting value type: ${e.message}`, condition);
113
- return false;
114
- }
115
-
116
- return evaluateComparison(fieldValue, targetValue, processedConditionValue, condition);
117
-
118
- function logClientEvalWarning(message, details) {
119
- console.warn(`[Client Eval] ${message}:`, details);
120
- }
121
-
122
- function convertValueType(value, inputType) {
123
- switch (inputType) {
124
- case 'number':
125
- const numValue = parseFloat(value);
126
- if (isNaN(numValue)) {
127
- throw new Error(`Invalid number value: ${value}`);
128
- }
129
- return numValue;
130
- case 'boolean':
131
- return String(value).toLowerCase() === 'true';
132
- case 'csv':
133
- return String(value).split(',').map(item => item.trim()).filter(Boolean);
134
- case 'text':
135
- default:
136
- return String(value);
137
- }
138
- }
139
-
140
- function evaluateComparison(operator, targetValue, processedConditionValue, condition) {
141
- try {
142
- switch (typeof operator === 'object' ? Object.keys(operator)[0] : null) {
143
- case '$eq': return targetValue === processedConditionValue;
144
- case '$ne': return targetValue !== processedConditionValue;
145
- case '$gt': return targetValue > processedConditionValue;
146
- case '$lt': return targetValue < processedConditionValue;
147
- case '$gte': return targetValue >= processedConditionValue;
148
- case '$lte': return targetValue <= processedConditionValue;
149
- case '$regex':
150
- if (typeof targetValue !== 'string') return false;
151
- if (typeof processedConditionValue !== 'string') return false;
152
- try {
153
- if( safeRegex(processedConditionValue)) {
154
- const regex = new RegExp(processedConditionValue, 'i');
155
- return regex.test(targetValue);
156
- }
157
- return false;
158
- } catch (e) {
159
- logClientEvalWarning(`Invalid regex pattern: ${processedConditionValue}`, condition);
160
- return false;
161
- }
162
- case '$in':
163
- return Array.isArray(processedConditionValue) && processedConditionValue.includes(String(targetValue));
164
- case '$nin':
165
- return !Array.isArray(processedConditionValue) || !processedConditionValue.includes(String(targetValue));
166
- default:
167
- logClientEvalWarning(`Unhandled operator in client evaluation logic: ${operator}`, condition);
168
- return true; // Permissive default
169
- }
170
- } catch (evalError) {
171
- logClientEvalWarning(`Error during client condition evaluation: ${operator}, targetValue=${targetValue}, processedConditionValue=${processedConditionValue}`, condition);
172
- return false;
173
- }
174
- }
175
- };
176
-
177
- export const isConditionMet = (model, cond, formData, allModels, user) => {
178
- const condition = cond;
179
-
180
- if (!condition) return true;
181
-
182
- if (typeof condition !== 'object' || condition === null) {
183
- return true;
184
- }
185
-
186
- // Cas spécial: Évaluation sans modèle (ex: pour les webhooks où la condition est déjà résolue)
187
- // Dans ce mode, la condition doit être un objet avec un seul opérateur.
188
- if (!model) {
189
- const keys = Object.keys(condition);
190
- if (keys.length !== 1 || !keys[0].startsWith('$')) {
191
- console.warn('[isConditionMet] Condition invalide pour une évaluation sans modèle. Attendu : { "$opérateur": [...] }. Reçu :', condition);
192
- return false; // Plus sûr que true pour éviter les faux positifs
193
- }
194
-
195
- const operator = keys[0];
196
- const operands = condition[operator];
197
-
198
- switch (operator) {
199
- // Opérateurs logiques (récursifs)
200
- case '$and':
201
- return Array.isArray(operands) && operands.every(sub => isConditionMet(null, sub, formData, allModels, user));
202
- case '$or':
203
- return Array.isArray(operands) && operands.some(sub => isConditionMet(null, sub, formData, allModels, user));
204
- case '$not':
205
- return !isConditionMet(null, operands, formData, allModels, user);
206
- case '$nor':
207
- return Array.isArray(operands) && !operands.some(sub => isConditionMet(null, sub, formData, allModels, user));
208
-
209
- // Opérateurs de comparaison (terminaux)
210
- case '$eq':
211
- return Array.isArray(operands) && operands[0] === operands[1];
212
- case '$ne':
213
- return Array.isArray(operands) && operands[0] !== operands[1];
214
- case '$in':
215
- return Array.isArray(operands) && Array.isArray(operands[1]) && operands[1].includes(operands[0]);
216
- case '$nin':
217
- return Array.isArray(operands) && Array.isArray(operands[1]) && !operands[1].includes(operands[0]);
218
- case '$gt':
219
- return Array.isArray(operands) && operands[0] > operands[1];
220
- case '$gte':
221
- return Array.isArray(operands) && operands[0] >= operands[1];
222
- case '$lt':
223
- return Array.isArray(operands) && operands[0] < operands[1];
224
- case '$lte':
225
- return Array.isArray(operands) && operands[0] <= operands[1];
226
-
227
- default:
228
- console.warn(`[isConditionMet] Opérateur non supporté '${operator}' pour une évaluation sans modèle.`);
229
- return false;
230
- }
231
- }
232
-
233
- // --- Logique existante pour l'évaluation AVEC modèle ---
234
-
235
- if (condition.$and && Array.isArray(condition.$and)) {
236
- if (condition.$and.length === 0) return true;
237
- return condition.$and.every(sub => isConditionMet(model, sub, formData, allModels, user));
238
- }
239
- if (condition.$or && Array.isArray(condition.$or)) {
240
- if (condition.$or.length === 0) return false;
241
- return condition.$or.some(sub => isConditionMet(model, sub, formData, allModels, user));
242
- }
243
- if (condition.$not) {
244
- return !isConditionMet(model, condition.$not, formData, allModels, user);
245
- }
246
- if (condition.$nor && Array.isArray(condition.$nor)) {
247
- if (condition.$nor.length === 0) return true;
248
- return !condition.$nor.some(sub => isConditionMet(model, sub, formData, allModels, user));
249
- }
250
-
251
- // Cas 3: Syntaxe d'agrégation {$eq: ['$field', value]}
252
- if (Object.keys(condition).length === 1) {
253
- const operator = Object.keys(condition)[0];
254
- if (operator.startsWith('$') && operator !== '$find' &&
255
- Array.isArray(condition[operator])) {
256
- return evaluateSingleCondition(model, condition, formData, allModels, user);
257
- }
258
- }
259
-
260
- return evaluateSingleCondition(model, condition, formData, allModels, user);
1
+
2
+ let safeRegex = null; // Par défaut, aucune fonction de validation n'est définie.
3
+
4
+ /**
5
+ * Permet d'injecter une fonction de validation de regex (côté serveur).
6
+ * @param {function} validator - La fonction qui valide une regex, ex: la fonction du module 'safe-regex'.
7
+ */
8
+ export function setSafeRegex(validator) {
9
+ safeRegex = validator;
10
+ }
11
+
12
+ /**
13
+ * Evaluates a single condition against form data.
14
+ * @param {object} currentModelDef - The definition of the current model.
15
+ * @param {object} condition - The condition to evaluate.
16
+ * @param {object} formData - The form data.
17
+ * @param {object[]} allModels - An array of all model definitions.
18
+ * @param {object} user - The current user.
19
+ * @returns {boolean} - True if the condition is met, false otherwise.
20
+ */
21
+ const evaluateSingleCondition = (currentModelDef, condition, formData, allModels, user, checkRegex =true) => {
22
+ // Condition est directement un filtre MongoDB, donc on l'applique
23
+ // en utilisant les opérateurs et les valeurs qu'il contient.
24
+
25
+ if (!condition || typeof condition !== 'object') {
26
+ console.warn("[Client Eval] Condition is not an object:", condition);
27
+ return true; // Permissive default
28
+ }
29
+
30
+ // Si la condition est de la forme {field: value}, on la transforme en {$eq: value}
31
+ if (!Object.keys(condition)[0].startsWith('$') && typeof condition[Object.keys(condition)[0]] !== 'object') {
32
+ const fieldName = Object.keys(condition)[0];
33
+ const value = condition[fieldName];
34
+ return evaluateSingleCondition(currentModelDef, {[fieldName]: {$eq: value}}, formData, allModels, user);
35
+ }
36
+
37
+ // Gestion des opérateurs d'agrégation (commencent par $)
38
+ const operator = Object.keys(condition)[0];
39
+ if (operator === '$eq' && Array.isArray(condition[operator])) {
40
+ // Cas spécial pour {$eq: ['$field', value]}
41
+ const [fieldPath, expectedValue] = condition[operator];
42
+ if (typeof fieldPath === 'string' && fieldPath.startsWith('$')) {
43
+ const fieldName = fieldPath.substring(1); // Enlève le $ devant
44
+ return formData[fieldName] == expectedValue;
45
+ }
46
+ }
47
+
48
+ // Si la condition contient des opérateurs logiques, on les gère ici
49
+ if (condition.$and || condition.$or || condition.$not || condition.$nor) {
50
+ console.warn("[Client Eval] Condition logique détectée dans evaluateSingleCondition, ce n'est pas attendu. Devrait être géré par isConditionMet.");
51
+ return true; // Permissive default
52
+ }
53
+
54
+ if (condition.$find) {
55
+ const fieldName = Object.keys(condition)[0];
56
+ const fieldValue = formData[fieldName];
57
+ const findCondition = condition.$find;
58
+
59
+ if (!Array.isArray(fieldValue)) return false;
60
+
61
+ return fieldValue.some(item => {
62
+ // Gestion spéciale pour la syntaxe $eq: ["$$this.field", value]
63
+ if (findCondition.$eq && Array.isArray(findCondition.$eq)) {
64
+ const [fieldPath, value] = findCondition.$eq;
65
+ if (fieldPath.startsWith("$$this.")) {
66
+ const fieldToCheck = fieldPath.replace("$$this.", "");
67
+ return item[fieldToCheck] == value;
68
+ }
69
+ }
70
+
71
+ // Sinon, évaluation normale
72
+ const tempData = { ...item };
73
+ return evaluateSingleCondition(currentModelDef, findCondition, tempData, allModels, user);
74
+ });
75
+ }
76
+
77
+ // Si la condition contient un opérateur $exists, on le gère ici
78
+ if (condition.$exists !== undefined) {
79
+ const fieldName = Object.keys(condition)[0]; // Récupérer le nom du champ
80
+ const shouldExist = condition.$exists; // Récupérer la valeur de $exists (true ou false)
81
+ const exists = Object.prototype.hasOwnProperty.call(formData, fieldName) && formData[fieldName] !== undefined && formData[fieldName] !== null;
82
+ return exists === shouldExist;
83
+ }
84
+
85
+ // Si la condition contient un opérateur $find, on le gère ici
86
+ if (condition.$find) {
87
+ // Récupérer le nom du champ
88
+ const fieldName = Object.keys(condition)[0];
89
+ const fieldValue = formData[fieldName];
90
+ try {
91
+ // Assuming evaluateSingleCondition handles $find
92
+ return evaluateSingleCondition(currentModelDef, condition.$find, formData, allModels, user);
93
+ } catch (error) {
94
+ console.error("Error evaluating $find condition:", condition, error);
95
+ return false;
96
+ }
97
+ }
98
+
99
+ // Récupérer le nom du champ et la condition
100
+ const fieldName = Object.keys(condition)[0];
101
+ const fieldValue = condition[fieldName];
102
+
103
+ // Récupérer la définition du champ
104
+ const fieldDef = currentModelDef?.fields.find(f => f.name === fieldName);
105
+
106
+ // Si la définition du champ n'est pas trouvée, on retourne true
107
+ if (!fieldDef) {
108
+ console.warn(`[Client Eval] Field definition not found for field: ${fieldName}`);
109
+ return true; // Permissive default
110
+ }
111
+
112
+ let targetValue = formData[fieldName];
113
+ let processedConditionValue = fieldValue;
114
+
115
+ // 1. Handle $exists (on the first field)
116
+ // 2. Convert condition value based on operator's expected input type
117
+ const fieldType = fieldDef?.type; // Type of the first field
118
+
119
+ try {
120
+ processedConditionValue = convertValueType(fieldValue, fieldType);
121
+ } catch (e) {
122
+ logClientEvalWarning(`Error converting value type: ${e.message}`, condition);
123
+ return false;
124
+ }
125
+
126
+ return evaluateComparison(fieldValue, targetValue, processedConditionValue, condition);
127
+
128
+ function logClientEvalWarning(message, details) {
129
+ console.warn(`[Client Eval] ${message}:`, details);
130
+ }
131
+
132
+ function convertValueType(value, inputType) {
133
+ switch (inputType) {
134
+ case 'number':
135
+ const numValue = parseFloat(value);
136
+ if (isNaN(numValue)) {
137
+ throw new Error(`Invalid number value: ${value}`);
138
+ }
139
+ return numValue;
140
+ case 'boolean':
141
+ return String(value).toLowerCase() === 'true';
142
+ case 'csv':
143
+ return String(value).split(',').map(item => item.trim()).filter(Boolean);
144
+ case 'text':
145
+ default:
146
+ return String(value);
147
+ }
148
+ }
149
+
150
+ function evaluateComparison(operator, targetValue, processedConditionValue, condition) {
151
+ try {
152
+ switch (typeof operator === 'object' ? Object.keys(operator)[0] : null) {
153
+ case '$eq': return targetValue === processedConditionValue;
154
+ case '$ne': return targetValue !== processedConditionValue;
155
+ case '$gt': return targetValue > processedConditionValue;
156
+ case '$lt': return targetValue < processedConditionValue;
157
+ case '$gte': return targetValue >= processedConditionValue;
158
+ case '$lte': return targetValue <= processedConditionValue;
159
+ case '$regex':
160
+ if (typeof targetValue !== 'string') return false;
161
+ if (typeof processedConditionValue !== 'string') return false;
162
+ try {
163
+ // On vérifie si la fonction a été injectée ET si la regex est sûre.
164
+ // Côté client, `safeRegex` sera null, donc la vérification est simplement ignorée.
165
+ if( checkRegex && safeRegex && safeRegex(processedConditionValue)) {
166
+ const regex = new RegExp(processedConditionValue, 'i');
167
+ return regex.test(targetValue);
168
+ }
169
+ return false;
170
+ } catch (e) {
171
+ logClientEvalWarning(`Invalid regex pattern: ${processedConditionValue}`, condition);
172
+ return false;
173
+ }
174
+ case '$in':
175
+ return Array.isArray(processedConditionValue) && processedConditionValue.includes(String(targetValue));
176
+ case '$nin':
177
+ return !Array.isArray(processedConditionValue) || !processedConditionValue.includes(String(targetValue));
178
+ default:
179
+ logClientEvalWarning(`Unhandled operator in client evaluation logic: ${operator}`, condition);
180
+ return true; // Permissive default
181
+ }
182
+ } catch (evalError) {
183
+ logClientEvalWarning(`Error during client condition evaluation: ${operator}, targetValue=${targetValue}, processedConditionValue=${processedConditionValue}`, condition);
184
+ return false;
185
+ }
186
+ }
187
+ };
188
+
189
+ export const isConditionMet = (model, cond, formData, allModels, user,checkRegex=true) => {
190
+ const condition = cond;
191
+
192
+ if (!condition) return true;
193
+
194
+ if (typeof condition !== 'object' || condition === null) {
195
+ return true;
196
+ }
197
+
198
+ // Cas spécial: Évaluation sans modèle (ex: pour les webhooks où la condition est déjà résolue)
199
+ // Dans ce mode, la condition doit être un objet avec un seul opérateur.
200
+ if (!model) {
201
+ const keys = Object.keys(condition);
202
+ if (keys.length !== 1 || !keys[0].startsWith('$')) {
203
+ console.warn('[isConditionMet] Condition invalide pour une évaluation sans modèle. Attendu : { "$opérateur": [...] }. Reçu :', condition);
204
+ return false; // Plus sûr que true pour éviter les faux positifs
205
+ }
206
+
207
+ const operator = keys[0];
208
+ const operands = condition[operator];
209
+
210
+ switch (operator) {
211
+ // Opérateurs logiques (récursifs)
212
+ case '$and':
213
+ return Array.isArray(operands) && operands.every(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
214
+ case '$or':
215
+ return Array.isArray(operands) && operands.some(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
216
+ case '$not':
217
+ return !isConditionMet(null, operands, formData, allModels, user);
218
+ case '$nor':
219
+ return Array.isArray(operands) && !operands.some(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
220
+
221
+ // Opérateurs de comparaison (terminaux)
222
+ case '$eq':
223
+ return Array.isArray(operands) && operands[0] === operands[1];
224
+ case '$ne':
225
+ return Array.isArray(operands) && operands[0] !== operands[1];
226
+ case '$in':
227
+ return Array.isArray(operands) && Array.isArray(operands[1]) && operands[1].includes(operands[0]);
228
+ case '$nin':
229
+ return Array.isArray(operands) && Array.isArray(operands[1]) && !operands[1].includes(operands[0]);
230
+ case '$gt':
231
+ return Array.isArray(operands) && operands[0] > operands[1];
232
+ case '$gte':
233
+ return Array.isArray(operands) && operands[0] >= operands[1];
234
+ case '$lt':
235
+ return Array.isArray(operands) && operands[0] < operands[1];
236
+ case '$lte':
237
+ return Array.isArray(operands) && operands[0] <= operands[1];
238
+
239
+ default:
240
+ console.warn(`[isConditionMet] Opérateur non supporté '${operator}' pour une évaluation sans modèle.`);
241
+ return false;
242
+ }
243
+ }
244
+
245
+ // --- Logique existante pour l'évaluation AVEC modèle ---
246
+
247
+ if (condition.$and && Array.isArray(condition.$and)) {
248
+ if (condition.$and.length === 0) return true;
249
+ return condition.$and.every(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
250
+ }
251
+ if (condition.$or && Array.isArray(condition.$or)) {
252
+ if (condition.$or.length === 0) return false;
253
+ return condition.$or.some(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
254
+ }
255
+ if (condition.$not) {
256
+ return !isConditionMet(model, condition.$not, formData, allModels, user,checkRegex);
257
+ }
258
+ if (condition.$nor && Array.isArray(condition.$nor)) {
259
+ if (condition.$nor.length === 0) return true;
260
+ return !condition.$nor.some(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
261
+ }
262
+
263
+ // Cas 3: Syntaxe d'agrégation {$eq: ['$field', value]}
264
+ if (Object.keys(condition).length === 1) {
265
+ const operator = Object.keys(condition)[0];
266
+ if (operator.startsWith('$') && operator !== '$find' &&
267
+ Array.isArray(condition[operator])) {
268
+ return evaluateSingleCondition(model, condition, formData, allModels, user,checkRegex);
269
+ }
270
+ }
271
+
272
+ return evaluateSingleCondition(model, condition, formData, allModels, user, checkRegex);
261
273
  };