@fbp/evaluator 1.1.0 → 1.3.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.
@@ -1,12 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.coreDefinitions = exports.stringConcatDef = exports.stringTemplateDef = exports.flowGuardDef = exports.jsonObjectDef = exports.jsonSelectDef = void 0;
3
+ exports.coreDefinitions = exports.flowCoerceDef = exports.jsonSplitDef = exports.jsonMergeDef = exports.constBooleanDef = exports.constStringDef = exports.stringConcatDef = exports.stringTemplateDef = exports.flowForEachDef = exports.flowFilterDef = exports.flowMergeDef = exports.flowSwitchDef = exports.flowBranchDef = exports.flowGuardDef = exports.jsonObjectDef = exports.jsonSelectDef = void 0;
4
4
  /**
5
5
  * Core node definitions with implementations.
6
6
  * These nodes handle JSON manipulation, flow control, and string operations.
7
7
  */
8
8
  /**
9
- * core/json/select - Extract a value from JSON by path
9
+ * core/json:select - Extract a value from JSON by path
10
10
  *
11
11
  * Props:
12
12
  * - path: string (dot-path like "a.b.c" or "data.user.email")
@@ -60,7 +60,7 @@ exports.jsonSelectDef = {
60
60
  }
61
61
  };
62
62
  /**
63
- * core/json/object - Build a JSON object from named inputs
63
+ * core/json:object - Build a JSON object from named inputs
64
64
  *
65
65
  * This node has dynamic inputs - any input wired to it becomes a key in the output object.
66
66
  * The implementation receives all inputs as a Record<string, any>.
@@ -88,13 +88,15 @@ exports.jsonObjectDef = {
88
88
  }
89
89
  };
90
90
  /**
91
- * core/flow/guard - Stop the flow if a condition fails
91
+ * core/flow:guard - Stop the flow if a condition fails
92
92
  *
93
93
  * Inputs:
94
94
  * - ok: boolean (the condition to check)
95
95
  * - error?: json (optional error info)
96
96
  *
97
- * Outputs:
97
+ * Outputs (only the arm that was taken is emitted — a declared port absent
98
+ * from a completed output is a path not taken, and emitting both arms is what
99
+ * makes both arms run):
98
100
  * - pass: signal (emitted if ok is true)
99
101
  * - fail: signal (emitted if ok is false)
100
102
  * - error: json (the error if failed)
@@ -118,23 +120,316 @@ exports.flowGuardDef = {
118
120
  impl: (inputs) => {
119
121
  const { ok, error } = inputs;
120
122
  if (ok) {
121
- return {
122
- pass: true,
123
- fail: false,
124
- error: null
125
- };
126
- }
127
- else {
128
- return {
129
- pass: false,
130
- fail: true,
131
- error: error || { message: 'Guard condition failed' }
132
- };
123
+ return { pass: true };
124
+ }
125
+ return {
126
+ fail: true,
127
+ error: error || { message: 'Guard condition failed' }
128
+ };
129
+ }
130
+ };
131
+ const COMPARISONS = ['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'truthy', 'empty', 'contains'];
132
+ /**
133
+ * The predicate flow:branch and flow:switch share: an operator plus an expected
134
+ * value, never an expression to evaluate — a graph definition is data, and data
135
+ * that gets executed is a remote-code-execution surface.
136
+ *
137
+ * Kept in step with the worker-side implementation in `@fbp/flow`, which is the
138
+ * same predicate for the same node types: the editor's local preview and a
139
+ * server run must agree on which arm a graph takes.
140
+ */
141
+ const compare = (value, operator, expected) => {
142
+ switch (operator) {
143
+ case 'eq': return value === expected;
144
+ case 'neq': return value !== expected;
145
+ case 'gt': return Number(value) > Number(expected);
146
+ case 'gte': return Number(value) >= Number(expected);
147
+ case 'lt': return Number(value) < Number(expected);
148
+ case 'lte': return Number(value) <= Number(expected);
149
+ case 'truthy': return Boolean(value);
150
+ case 'empty':
151
+ if (value === null || value === undefined)
152
+ return true;
153
+ if (Array.isArray(value) || typeof value === 'string')
154
+ return value.length === 0;
155
+ if (typeof value === 'object')
156
+ return Object.keys(value).length === 0;
157
+ return false;
158
+ case 'contains':
159
+ if (Array.isArray(value))
160
+ return value.includes(expected);
161
+ return String(value ?? '').includes(String(expected ?? ''));
162
+ }
163
+ };
164
+ /**
165
+ * core/flow:branch - Route a value down one of two paths
166
+ *
167
+ * Only the taken port carries a value; the other is absent rather than null, so
168
+ * a downstream node can tell "not taken" from "taken with a null value".
169
+ * `matched` always carries the verdict, for anything that wants the decision
170
+ * without sitting on an arm.
171
+ */
172
+ exports.flowBranchDef = {
173
+ context: 'js',
174
+ name: 'branch',
175
+ category: 'flow',
176
+ icon: 'git-branch',
177
+ inputs: [
178
+ { name: 'value', type: 'any' },
179
+ // Wired only when the comparison value comes from the graph rather than the prop.
180
+ { name: 'expected', type: 'any', optional: true }
181
+ ],
182
+ outputs: [
183
+ { name: 'matched', type: 'boolean' },
184
+ { name: 'true', type: 'any' },
185
+ { name: 'false', type: 'any' }
186
+ ],
187
+ props: [
188
+ { name: 'operator', type: 'string', default: 'truthy' },
189
+ { name: 'expected', type: 'any' }
190
+ ],
191
+ description: 'Route a value down one of two paths by a declared predicate',
192
+ impl: (inputs, props) => {
193
+ const operator = String(props.operator ?? 'truthy');
194
+ if (!COMPARISONS.includes(operator)) {
195
+ throw new Error(`flow:branch: unknown operator "${operator}" (expected one of ${COMPARISONS.join(', ')})`);
196
+ }
197
+ const expected = 'expected' in inputs ? inputs.expected : props.expected;
198
+ const matched = compare(inputs.value, operator, expected);
199
+ return matched
200
+ ? { matched, true: inputs.value }
201
+ : { matched, false: inputs.value };
202
+ }
203
+ };
204
+ /** The number of case ports flow:switch declares. */
205
+ const SWITCH_CASE_PORTS = 6;
206
+ /**
207
+ * core/flow:switch - Route a value to the first matching case, or to `default`
208
+ *
209
+ * Cases are ordered and the first match wins. Case `i` emits on `case_<i>`;
210
+ * the ports are declared up front and fixed in number, because a port a graph
211
+ * cannot name at design time is a port nothing can be wired to.
212
+ */
213
+ exports.flowSwitchDef = {
214
+ context: 'js',
215
+ name: 'switch',
216
+ category: 'flow',
217
+ icon: 'git-fork',
218
+ inputs: [
219
+ { name: 'value', type: 'any' }
220
+ ],
221
+ outputs: [
222
+ { name: 'matched_case', type: 'string' },
223
+ ...Array.from({ length: SWITCH_CASE_PORTS }, (_, i) => ({ name: `case_${i}`, type: 'any' })),
224
+ { name: 'default', type: 'any' }
225
+ ],
226
+ props: [
227
+ { name: 'cases', type: 'json', default: [] },
228
+ { name: 'operator', type: 'string', default: 'eq' }
229
+ ],
230
+ description: 'Route a value to the first matching case, or to default',
231
+ impl: (inputs, props) => {
232
+ const rawCases = props.cases ?? [];
233
+ if (!Array.isArray(rawCases)) {
234
+ throw new Error('flow:switch: props.cases must be an array of { operator, expected }');
235
+ }
236
+ if (rawCases.length > SWITCH_CASE_PORTS) {
237
+ throw new Error(`flow:switch: ${rawCases.length} cases exceeds the ${SWITCH_CASE_PORTS} declared case ports`);
133
238
  }
239
+ const fallbackOperator = String(props.operator ?? 'eq');
240
+ for (let i = 0; i < rawCases.length; i++) {
241
+ const branchCase = rawCases[i];
242
+ if (branchCase === null || typeof branchCase !== 'object') {
243
+ throw new Error(`flow:switch: case ${i} must be an object of { operator, expected }`);
244
+ }
245
+ const operator = String(branchCase.operator ?? fallbackOperator);
246
+ if (!COMPARISONS.includes(operator)) {
247
+ throw new Error(`flow:switch: case ${i} has unknown operator "${operator}" (expected one of ${COMPARISONS.join(', ')})`);
248
+ }
249
+ if (compare(inputs.value, operator, branchCase.expected)) {
250
+ return { matched_case: String(i), [`case_${i}`]: inputs.value };
251
+ }
252
+ }
253
+ return { matched_case: 'default', default: inputs.value };
134
254
  }
135
255
  };
136
256
  /**
137
- * core/string/template - Build a string from a template with placeholders
257
+ * core/flow:merge - Rejoin two branch arms into one path
258
+ *
259
+ * The counterpart of a lazy branch: whichever arm produced a value wins, and
260
+ * `source` names it so a graph can tell which path it is now carrying. `a` wins
261
+ * a tie, which only happens when the inputs are not exclusive arms at all.
262
+ */
263
+ exports.flowMergeDef = {
264
+ context: 'js',
265
+ name: 'merge',
266
+ category: 'flow',
267
+ icon: 'git-merge',
268
+ inputs: [
269
+ // Optional on purpose: a merge runs on whichever arm arrived, and a branch
270
+ // arm that was not taken never produces one.
271
+ { name: 'a', type: 'any', optional: true },
272
+ { name: 'b', type: 'any', optional: true }
273
+ ],
274
+ outputs: [
275
+ { name: 'value', type: 'any' },
276
+ { name: 'source', type: 'string' }
277
+ ],
278
+ props: [],
279
+ description: 'Rejoin two branch arms into one path',
280
+ impl: (inputs) => {
281
+ if (inputs.a !== undefined) {
282
+ return { value: inputs.a, source: 'a' };
283
+ }
284
+ if (inputs.b !== undefined) {
285
+ return { value: inputs.b, source: 'b' };
286
+ }
287
+ throw new Error('flow:merge: neither input arrived — nothing to merge');
288
+ }
289
+ };
290
+ /** Read a dot-path out of one collection element, for the nodes that key on a field. */
291
+ const selectPath = (item, path) => {
292
+ if (path === '')
293
+ return item;
294
+ return path.split('.').reduce((acc, segment) => {
295
+ if (acc === null || typeof acc !== 'object')
296
+ return undefined;
297
+ return acc[segment];
298
+ }, item);
299
+ };
300
+ const requireArray = (node, items) => {
301
+ if (!Array.isArray(items)) {
302
+ throw new Error(`${node}: items must be an array (received ${items === null ? 'null' : typeof items})`);
303
+ }
304
+ return items;
305
+ };
306
+ /**
307
+ * core/flow:filter - Narrow a collection by a declared predicate
308
+ *
309
+ * Same predicate vocabulary as flow:branch, applied per element — `path`
310
+ * compares a field of each element so a list of rows can be filtered without a
311
+ * per-item node. `items`, `dropped` and `empty` are lazy ports: a survivor lane
312
+ * only runs when something survived and a rejects lane only when something was
313
+ * rejected, so the "nothing to do" case is a path rather than a length test.
314
+ */
315
+ exports.flowFilterDef = {
316
+ context: 'js',
317
+ name: 'filter',
318
+ category: 'flow',
319
+ icon: 'filter',
320
+ inputs: [
321
+ { name: 'items', type: 'json' },
322
+ // Wired only when the comparison value comes from the graph rather than the prop.
323
+ { name: 'expected', type: 'any', optional: true }
324
+ ],
325
+ outputs: [
326
+ { name: 'items', type: 'json' },
327
+ { name: 'dropped', type: 'json' },
328
+ { name: 'empty', type: 'boolean' },
329
+ { name: 'kept_count', type: 'number' },
330
+ { name: 'dropped_count', type: 'number' }
331
+ ],
332
+ props: [
333
+ { name: 'operator', type: 'string', default: 'truthy' },
334
+ { name: 'expected', type: 'any' },
335
+ { name: 'path', type: 'string', default: '' }
336
+ ],
337
+ description: 'Narrow a collection by a declared predicate',
338
+ impl: (inputs, props) => {
339
+ const operator = String(props.operator ?? 'truthy');
340
+ if (!COMPARISONS.includes(operator)) {
341
+ throw new Error(`flow:filter: unknown operator "${operator}" (expected one of ${COMPARISONS.join(', ')})`);
342
+ }
343
+ const items = requireArray('flow:filter', inputs.items);
344
+ const path = String(props.path ?? '');
345
+ const expected = 'expected' in inputs ? inputs.expected : props.expected;
346
+ const kept = [];
347
+ const dropped = [];
348
+ for (const item of items) {
349
+ if (compare(selectPath(item, path), operator, expected)) {
350
+ kept.push(item);
351
+ }
352
+ else {
353
+ dropped.push(item);
354
+ }
355
+ }
356
+ const outputs = {
357
+ kept_count: kept.length,
358
+ dropped_count: dropped.length
359
+ };
360
+ if (kept.length > 0)
361
+ outputs.items = kept;
362
+ else
363
+ outputs.empty = true;
364
+ if (dropped.length > 0)
365
+ outputs.dropped = dropped;
366
+ return outputs;
367
+ }
368
+ };
369
+ /** The ceiling flow:for_each refuses to plan beyond unless a graph raises it. */
370
+ const DEFAULT_MAX_SHARDS = 64;
371
+ /**
372
+ * core/flow:for_each - Turn a collection into an ordered, keyed fan-out plan
373
+ *
374
+ * Each element becomes a shard descriptor `{ index, total, item, key }`. The key
375
+ * is a declared field of the element (falling back to its index) because a
376
+ * shard's identity is what lets a retry land on the same shard; duplicate or
377
+ * missing keys fail the node rather than producing an unaddressable plan, and so
378
+ * does a collection larger than `max_shards` — a truncated plan is work that
379
+ * never ran with nothing saying so. `shards` is absent for an empty collection,
380
+ * where `empty` is present instead, so a graph never fans out over nothing.
381
+ */
382
+ exports.flowForEachDef = {
383
+ context: 'js',
384
+ name: 'for_each',
385
+ category: 'flow',
386
+ icon: 'list-ordered',
387
+ inputs: [
388
+ { name: 'items', type: 'json' }
389
+ ],
390
+ outputs: [
391
+ { name: 'shards', type: 'json' },
392
+ { name: 'empty', type: 'boolean' },
393
+ { name: 'total', type: 'number' }
394
+ ],
395
+ props: [
396
+ { name: 'key', type: 'string', default: '' },
397
+ { name: 'max_shards', type: 'number', default: DEFAULT_MAX_SHARDS }
398
+ ],
399
+ description: 'Turn a collection into an ordered, keyed fan-out plan',
400
+ impl: (inputs, props) => {
401
+ const items = requireArray('flow:for_each', inputs.items);
402
+ const maxShards = Number(props.max_shards ?? DEFAULT_MAX_SHARDS);
403
+ if (!Number.isFinite(maxShards) || maxShards < 1) {
404
+ throw new Error(`flow:for_each: max_shards must be a positive number (received ${String(props.max_shards)})`);
405
+ }
406
+ if (items.length > maxShards) {
407
+ throw new Error(`flow:for_each: ${items.length} items exceeds max_shards ${maxShards} — raise the ceiling or filter the collection first`);
408
+ }
409
+ const keyPath = String(props.key ?? '');
410
+ const total = items.length;
411
+ const shards = items.map((item, index) => {
412
+ if (keyPath === '') {
413
+ return { index, total, item, key: String(index) };
414
+ }
415
+ const keyValue = selectPath(item, keyPath);
416
+ if (keyValue === null || keyValue === undefined || keyValue === '') {
417
+ throw new Error(`flow:for_each: item ${index} has no value at key path "${keyPath}" — a shard without a stable key cannot be retried`);
418
+ }
419
+ return { index, total, item, key: String(keyValue) };
420
+ });
421
+ const keys = shards.map((shard) => shard.key);
422
+ const duplicate = keys.find((key, index) => keys.indexOf(key) !== index);
423
+ if (duplicate !== undefined) {
424
+ throw new Error(`flow:for_each: key "${duplicate}" appears more than once at key path "${keyPath}" — shard keys must be unique`);
425
+ }
426
+ return total === 0
427
+ ? { total, empty: true }
428
+ : { total, shards };
429
+ }
430
+ };
431
+ /**
432
+ * core/string:template - Build a string from a template with placeholders
138
433
  *
139
434
  * Props:
140
435
  * - template: string (template with {{placeholder}} syntax)
@@ -175,7 +470,7 @@ exports.stringTemplateDef = {
175
470
  }
176
471
  };
177
472
  /**
178
- * core/string/concat - Concatenate strings with an optional separator
473
+ * core/string:concat - Concatenate strings with an optional separator
179
474
  *
180
475
  * Props:
181
476
  * - prefix: string (optional prefix)
@@ -209,10 +504,118 @@ exports.stringConcatDef = {
209
504
  return { value: `${prefix}${value}${suffix}` };
210
505
  }
211
506
  };
507
+ exports.constStringDef = {
508
+ context: 'js',
509
+ name: 'string',
510
+ category: 'const',
511
+ icon: 'type',
512
+ outputs: [{ name: 'value', type: 'string' }],
513
+ props: [{ name: 'value', type: 'string', default: '' }],
514
+ description: 'Outputs a constant string value',
515
+ impl: (_inputs, props) => ({
516
+ value: props.value ?? ''
517
+ })
518
+ };
519
+ exports.constBooleanDef = {
520
+ context: 'js',
521
+ name: 'boolean',
522
+ category: 'const',
523
+ icon: 'toggle',
524
+ outputs: [{ name: 'value', type: 'boolean' }],
525
+ props: [{ name: 'value', type: 'boolean', default: false }],
526
+ description: 'Outputs a constant boolean value',
527
+ impl: (_inputs, props) => ({
528
+ value: props.value ?? false
529
+ })
530
+ };
531
+ exports.jsonMergeDef = {
532
+ context: 'js',
533
+ name: 'merge',
534
+ category: 'json',
535
+ icon: 'git-merge',
536
+ inputs: [
537
+ { name: 'a', type: 'json' },
538
+ { name: 'b', type: 'json' }
539
+ ],
540
+ outputs: [
541
+ { name: 'value', type: 'json' }
542
+ ],
543
+ description: 'Merge two JSON objects',
544
+ impl: (inputs) => ({
545
+ value: { ...(inputs.a || {}), ...(inputs.b || {}) }
546
+ })
547
+ };
548
+ exports.jsonSplitDef = {
549
+ context: 'js',
550
+ name: 'split',
551
+ category: 'json',
552
+ icon: 'scissors',
553
+ inputs: [
554
+ { name: 'obj', type: 'json' }
555
+ ],
556
+ outputs: [
557
+ { name: 'selected', type: 'json' },
558
+ { name: 'rest', type: 'json' }
559
+ ],
560
+ props: [
561
+ { name: 'keys', type: 'string', default: '' }
562
+ ],
563
+ description: 'Split a JSON object by key list',
564
+ impl: (inputs, props) => {
565
+ const obj = inputs.obj || {};
566
+ const keyList = (props.keys || '').split(',').map((k) => k.trim()).filter(Boolean);
567
+ const keySet = new Set(keyList);
568
+ const selected = {};
569
+ const rest = {};
570
+ for (const [k, v] of Object.entries(obj)) {
571
+ if (keySet.has(k))
572
+ selected[k] = v;
573
+ else
574
+ rest[k] = v;
575
+ }
576
+ return { selected, rest };
577
+ }
578
+ };
579
+ exports.flowCoerceDef = {
580
+ context: 'js',
581
+ name: 'coerce',
582
+ category: 'flow',
583
+ icon: 'repeat',
584
+ inputs: [
585
+ { name: 'value', type: 'any' }
586
+ ],
587
+ outputs: [
588
+ { name: 'value', type: 'any' }
589
+ ],
590
+ props: [
591
+ { name: 'type', type: 'string', default: 'string' }
592
+ ],
593
+ description: 'Convert a value to a different type',
594
+ impl: (inputs, props) => {
595
+ const { value } = inputs;
596
+ switch (props.type) {
597
+ case 'number': return { value: Number(value) || 0 };
598
+ case 'string': return { value: String(value ?? '') };
599
+ case 'boolean': return { value: Boolean(value) };
600
+ case 'json': return { value: typeof value === 'string' ? JSON.parse(value) : value };
601
+ default: return { value };
602
+ }
603
+ }
604
+ };
212
605
  exports.coreDefinitions = [
606
+ exports.constStringDef,
607
+ exports.constBooleanDef,
213
608
  exports.jsonSelectDef,
214
609
  exports.jsonObjectDef,
610
+ exports.jsonMergeDef,
611
+ exports.jsonSplitDef,
215
612
  exports.flowGuardDef,
613
+ exports.flowBranchDef,
614
+ exports.flowSwitchDef,
615
+ exports.flowMergeDef,
616
+ exports.flowFilterDef,
617
+ exports.flowForEachDef,
618
+ exports.flowCoerceDef,
216
619
  exports.stringTemplateDef,
217
620
  exports.stringConcatDef
218
621
  ];
@@ -5,4 +5,5 @@ import type { NodeDefinitionWithImpl } from '../types';
5
5
  export declare const constNumberDef: NodeDefinitionWithImpl;
6
6
  export declare const addDef: NodeDefinitionWithImpl;
7
7
  export declare const multiplyDef: NodeDefinitionWithImpl;
8
+ export declare const subtractDef: NodeDefinitionWithImpl;
8
9
  export declare const mathDefinitions: NodeDefinitionWithImpl[];
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mathDefinitions = exports.multiplyDef = exports.addDef = exports.constNumberDef = void 0;
3
+ exports.mathDefinitions = exports.subtractDef = exports.multiplyDef = exports.addDef = exports.constNumberDef = void 0;
4
4
  /**
5
5
  * Math node definitions with implementations for testing.
6
6
  */
@@ -46,8 +46,24 @@ exports.multiplyDef = {
46
46
  product: (inputs.a ?? 0) * (inputs.b ?? 0)
47
47
  })
48
48
  };
49
+ exports.subtractDef = {
50
+ context: 'js',
51
+ name: 'subtract',
52
+ category: 'math',
53
+ icon: 'minus',
54
+ inputs: [
55
+ { name: 'a', type: 'number' },
56
+ { name: 'b', type: 'number' }
57
+ ],
58
+ outputs: [{ name: 'difference', type: 'number' }],
59
+ description: 'Subtracts b from a',
60
+ impl: (inputs) => ({
61
+ difference: (inputs.a ?? 0) - (inputs.b ?? 0)
62
+ })
63
+ };
49
64
  exports.mathDefinitions = [
50
65
  exports.constNumberDef,
51
66
  exports.addDef,
52
- exports.multiplyDef
67
+ exports.multiplyDef,
68
+ exports.subtractDef
53
69
  ];