@karmaniverous/jeeves-watcher 0.4.2 → 0.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/config.schema.json +38 -11
- package/dist/cjs/index.js +276 -167
- package/dist/cli/jeeves-watcher/index.js +277 -168
- package/dist/index.d.ts +10 -9
- package/dist/index.iife.js +277 -168
- package/dist/index.iife.min.js +1 -1
- package/dist/mjs/index.js +277 -168
- package/package.json +1 -1
package/config.schema.json
CHANGED
|
@@ -145,11 +145,19 @@
|
|
|
145
145
|
}
|
|
146
146
|
]
|
|
147
147
|
},
|
|
148
|
+
"mapHelpers": {
|
|
149
|
+
"description": "Custom JsonMap lib function registration.",
|
|
150
|
+
"allOf": [
|
|
151
|
+
{
|
|
152
|
+
"$ref": "#/definitions/__schema55"
|
|
153
|
+
}
|
|
154
|
+
]
|
|
155
|
+
},
|
|
148
156
|
"logging": {
|
|
149
157
|
"description": "Logging configuration.",
|
|
150
158
|
"allOf": [
|
|
151
159
|
{
|
|
152
|
-
"$ref": "#/definitions/
|
|
160
|
+
"$ref": "#/definitions/__schema57"
|
|
153
161
|
}
|
|
154
162
|
]
|
|
155
163
|
},
|
|
@@ -157,7 +165,7 @@
|
|
|
157
165
|
"description": "Timeout in milliseconds for graceful shutdown.",
|
|
158
166
|
"allOf": [
|
|
159
167
|
{
|
|
160
|
-
"$ref": "#/definitions/
|
|
168
|
+
"$ref": "#/definitions/__schema60"
|
|
161
169
|
}
|
|
162
170
|
]
|
|
163
171
|
},
|
|
@@ -165,7 +173,7 @@
|
|
|
165
173
|
"description": "Maximum consecutive system-level failures before triggering fatal error. Default: Infinity.",
|
|
166
174
|
"allOf": [
|
|
167
175
|
{
|
|
168
|
-
"$ref": "#/definitions/
|
|
176
|
+
"$ref": "#/definitions/__schema61"
|
|
169
177
|
}
|
|
170
178
|
]
|
|
171
179
|
},
|
|
@@ -173,7 +181,7 @@
|
|
|
173
181
|
"description": "Maximum backoff delay in milliseconds for system errors. Default: 60000.",
|
|
174
182
|
"allOf": [
|
|
175
183
|
{
|
|
176
|
-
"$ref": "#/definitions/
|
|
184
|
+
"$ref": "#/definitions/__schema62"
|
|
177
185
|
}
|
|
178
186
|
]
|
|
179
187
|
}
|
|
@@ -636,13 +644,32 @@
|
|
|
636
644
|
}
|
|
637
645
|
},
|
|
638
646
|
"__schema55": {
|
|
647
|
+
"type": "object",
|
|
648
|
+
"properties": {
|
|
649
|
+
"paths": {
|
|
650
|
+
"description": "File paths to JS modules exporting functions to merge into the JsonMap lib.",
|
|
651
|
+
"allOf": [
|
|
652
|
+
{
|
|
653
|
+
"$ref": "#/definitions/__schema56"
|
|
654
|
+
}
|
|
655
|
+
]
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
},
|
|
659
|
+
"__schema56": {
|
|
660
|
+
"type": "array",
|
|
661
|
+
"items": {
|
|
662
|
+
"type": "string"
|
|
663
|
+
}
|
|
664
|
+
},
|
|
665
|
+
"__schema57": {
|
|
639
666
|
"type": "object",
|
|
640
667
|
"properties": {
|
|
641
668
|
"level": {
|
|
642
669
|
"description": "Logging level (trace, debug, info, warn, error, fatal).",
|
|
643
670
|
"allOf": [
|
|
644
671
|
{
|
|
645
|
-
"$ref": "#/definitions/
|
|
672
|
+
"$ref": "#/definitions/__schema58"
|
|
646
673
|
}
|
|
647
674
|
]
|
|
648
675
|
},
|
|
@@ -650,25 +677,25 @@
|
|
|
650
677
|
"description": "Path to log file (logs to stdout if omitted).",
|
|
651
678
|
"allOf": [
|
|
652
679
|
{
|
|
653
|
-
"$ref": "#/definitions/
|
|
680
|
+
"$ref": "#/definitions/__schema59"
|
|
654
681
|
}
|
|
655
682
|
]
|
|
656
683
|
}
|
|
657
684
|
}
|
|
658
685
|
},
|
|
659
|
-
"
|
|
686
|
+
"__schema58": {
|
|
660
687
|
"type": "string"
|
|
661
688
|
},
|
|
662
|
-
"
|
|
689
|
+
"__schema59": {
|
|
663
690
|
"type": "string"
|
|
664
691
|
},
|
|
665
|
-
"
|
|
692
|
+
"__schema60": {
|
|
666
693
|
"type": "number"
|
|
667
694
|
},
|
|
668
|
-
"
|
|
695
|
+
"__schema61": {
|
|
669
696
|
"type": "number"
|
|
670
697
|
},
|
|
671
|
-
"
|
|
698
|
+
"__schema62": {
|
|
672
699
|
"type": "number"
|
|
673
700
|
}
|
|
674
701
|
}
|
package/dist/cjs/index.js
CHANGED
|
@@ -8,6 +8,7 @@ var radash = require('radash');
|
|
|
8
8
|
var node_crypto = require('node:crypto');
|
|
9
9
|
var node_fs = require('node:fs');
|
|
10
10
|
var ignore = require('ignore');
|
|
11
|
+
var jsonmap = require('@karmaniverous/jsonmap');
|
|
11
12
|
var Handlebars = require('handlebars');
|
|
12
13
|
var dayjs = require('dayjs');
|
|
13
14
|
var hastUtilToMdast = require('hast-util-to-mdast');
|
|
@@ -18,7 +19,6 @@ var unified = require('unified');
|
|
|
18
19
|
var chokidar = require('chokidar');
|
|
19
20
|
var cosmiconfig = require('cosmiconfig');
|
|
20
21
|
var zod = require('zod');
|
|
21
|
-
var jsonmap = require('@karmaniverous/jsonmap');
|
|
22
22
|
var googleGenai = require('@langchain/google-genai');
|
|
23
23
|
var pino = require('pino');
|
|
24
24
|
var uuid = require('uuid');
|
|
@@ -657,6 +657,251 @@ class GitignoreFilter {
|
|
|
657
657
|
}
|
|
658
658
|
}
|
|
659
659
|
|
|
660
|
+
/**
|
|
661
|
+
* @module rules/templates
|
|
662
|
+
* Resolves template variables (`${path.to.value}`) in rule `set` objects against file attributes.
|
|
663
|
+
*/
|
|
664
|
+
/**
|
|
665
|
+
* Resolve `${template.vars}` in a value against the given attributes.
|
|
666
|
+
*
|
|
667
|
+
* @param value - The value to resolve.
|
|
668
|
+
* @param attributes - The file attributes for variable lookup.
|
|
669
|
+
* @returns The resolved value.
|
|
670
|
+
*/
|
|
671
|
+
function resolveTemplateVars(value, attributes) {
|
|
672
|
+
if (typeof value !== 'string')
|
|
673
|
+
return value;
|
|
674
|
+
return value.replace(/\$\{([^}]+)\}/g, (_match, varPath) => {
|
|
675
|
+
const current = radash.get(attributes, varPath);
|
|
676
|
+
if (current === null || current === undefined)
|
|
677
|
+
return '';
|
|
678
|
+
return typeof current === 'string' ? current : JSON.stringify(current);
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* Resolve all template variables in a `set` object.
|
|
683
|
+
*
|
|
684
|
+
* @param setObj - The key-value pairs to resolve.
|
|
685
|
+
* @param attributes - The file attributes for variable lookup.
|
|
686
|
+
* @returns The resolved key-value pairs.
|
|
687
|
+
*/
|
|
688
|
+
function resolveSet(setObj, attributes) {
|
|
689
|
+
const result = {};
|
|
690
|
+
for (const [key, value] of Object.entries(setObj)) {
|
|
691
|
+
result[key] = resolveTemplateVars(value, attributes);
|
|
692
|
+
}
|
|
693
|
+
return result;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* @module rules/apply
|
|
698
|
+
* Applies compiled inference rules to file attributes, producing merged metadata via template resolution and JsonMap transforms.
|
|
699
|
+
*/
|
|
700
|
+
/**
|
|
701
|
+
* Create the lib object for JsonMap transformations.
|
|
702
|
+
*
|
|
703
|
+
* @param configDir - Optional config directory for resolving relative file paths in lookups.
|
|
704
|
+
* @returns The lib object.
|
|
705
|
+
*/
|
|
706
|
+
function createJsonMapLib(configDir, customLib) {
|
|
707
|
+
// Cache loaded JSON files within a single applyRules invocation.
|
|
708
|
+
const jsonCache = new Map();
|
|
709
|
+
const loadJson = (filePath) => {
|
|
710
|
+
const resolvedPath = configDir ? node_path.resolve(configDir, filePath) : filePath;
|
|
711
|
+
if (!jsonCache.has(resolvedPath)) {
|
|
712
|
+
const raw = node_fs.readFileSync(resolvedPath, 'utf-8');
|
|
713
|
+
jsonCache.set(resolvedPath, JSON.parse(raw));
|
|
714
|
+
}
|
|
715
|
+
return jsonCache.get(resolvedPath);
|
|
716
|
+
};
|
|
717
|
+
return {
|
|
718
|
+
split: (str, separator) => str.split(separator),
|
|
719
|
+
slice: (arr, start, end) => arr.slice(start, end),
|
|
720
|
+
join: (arr, separator) => arr.join(separator),
|
|
721
|
+
toLowerCase: (str) => str.toLowerCase(),
|
|
722
|
+
replace: (str, search, replacement) => str.replace(search, replacement),
|
|
723
|
+
get: (obj, path) => radash.get(obj, path),
|
|
724
|
+
/**
|
|
725
|
+
* Load a JSON file (relative to configDir) and look up a value by key,
|
|
726
|
+
* optionally drilling into a sub-path.
|
|
727
|
+
*
|
|
728
|
+
* @param filePath - Path to a JSON file (resolved relative to configDir).
|
|
729
|
+
* @param key - Top-level key to look up.
|
|
730
|
+
* @param field - Optional dot-path into the looked-up entry.
|
|
731
|
+
* @returns The resolved value, or null if not found.
|
|
732
|
+
*/
|
|
733
|
+
lookupJson: (filePath, key, field) => {
|
|
734
|
+
const data = loadJson(filePath);
|
|
735
|
+
const entry = data[key];
|
|
736
|
+
if (entry === undefined || entry === null)
|
|
737
|
+
return null;
|
|
738
|
+
if (field)
|
|
739
|
+
return radash.get(entry, field) ?? null;
|
|
740
|
+
return entry;
|
|
741
|
+
},
|
|
742
|
+
/**
|
|
743
|
+
* Map an array of keys through a JSON lookup file, collecting a specific
|
|
744
|
+
* field from each matching entry. Non-matching keys are silently skipped.
|
|
745
|
+
* Array-valued fields are flattened into the result.
|
|
746
|
+
*
|
|
747
|
+
* @param filePath - Path to a JSON file (resolved relative to configDir).
|
|
748
|
+
* @param keys - Array of top-level keys to look up.
|
|
749
|
+
* @param field - Dot-path into each looked-up entry.
|
|
750
|
+
* @returns Flat array of resolved values.
|
|
751
|
+
*/
|
|
752
|
+
mapLookup: (filePath, keys, field) => {
|
|
753
|
+
if (!Array.isArray(keys))
|
|
754
|
+
return [];
|
|
755
|
+
const data = loadJson(filePath);
|
|
756
|
+
const results = [];
|
|
757
|
+
for (const k of keys) {
|
|
758
|
+
if (typeof k !== 'string')
|
|
759
|
+
continue;
|
|
760
|
+
const entry = data[k];
|
|
761
|
+
if (entry === undefined || entry === null)
|
|
762
|
+
continue;
|
|
763
|
+
const val = radash.get(entry, field);
|
|
764
|
+
if (val === undefined || val === null)
|
|
765
|
+
continue;
|
|
766
|
+
if (Array.isArray(val)) {
|
|
767
|
+
for (const item of val) {
|
|
768
|
+
results.push(item);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
else {
|
|
772
|
+
results.push(val);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return results;
|
|
776
|
+
},
|
|
777
|
+
...customLib,
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Load custom JsonMap lib functions from file paths.
|
|
782
|
+
*
|
|
783
|
+
* Each module should default-export an object of functions,
|
|
784
|
+
* or use named exports. Only function-valued exports are merged.
|
|
785
|
+
*
|
|
786
|
+
* @param paths - File paths to custom lib modules.
|
|
787
|
+
* @param configDir - Directory to resolve relative paths against.
|
|
788
|
+
* @returns The merged custom lib functions.
|
|
789
|
+
*/
|
|
790
|
+
async function loadCustomMapHelpers(paths, configDir) {
|
|
791
|
+
const merged = {};
|
|
792
|
+
for (const p of paths) {
|
|
793
|
+
const resolved = node_path.resolve(configDir, p);
|
|
794
|
+
const mod = (await import(resolved));
|
|
795
|
+
const fns = typeof mod.default === 'object' && mod.default !== null
|
|
796
|
+
? mod.default
|
|
797
|
+
: mod;
|
|
798
|
+
for (const [key, val] of Object.entries(fns)) {
|
|
799
|
+
if (typeof val === 'function') {
|
|
800
|
+
merged[key] = val;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
return merged;
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Apply compiled inference rules to file attributes, returning merged metadata and optional rendered content.
|
|
808
|
+
*
|
|
809
|
+
* Rules are evaluated in order; later rules override earlier ones.
|
|
810
|
+
* If a rule has a `map`, the JsonMap transformation is applied after `set` resolution,
|
|
811
|
+
* and map output overrides set output on conflict.
|
|
812
|
+
*
|
|
813
|
+
* @param compiledRules - The compiled rules to evaluate.
|
|
814
|
+
* @param attributes - The file attributes to match against.
|
|
815
|
+
* @param namedMaps - Optional record of named JsonMap definitions.
|
|
816
|
+
* @param logger - Optional logger for warnings (falls back to console.warn).
|
|
817
|
+
* @param templateEngine - Optional template engine for rendering content templates.
|
|
818
|
+
* @param configDir - Optional config directory for resolving .json map file paths.
|
|
819
|
+
* @returns The merged metadata and optional rendered content.
|
|
820
|
+
*/
|
|
821
|
+
async function applyRules(compiledRules, attributes, namedMaps, logger, templateEngine, configDir, customMapLib) {
|
|
822
|
+
// JsonMap's type definitions expect a generic JsonMapLib shape with unary functions.
|
|
823
|
+
// Our helper functions accept multiple args, which JsonMap supports at runtime.
|
|
824
|
+
const lib = createJsonMapLib(configDir, customMapLib);
|
|
825
|
+
let merged = {};
|
|
826
|
+
let renderedContent = null;
|
|
827
|
+
const log = logger ?? console;
|
|
828
|
+
for (const [ruleIndex, { rule, validate }] of compiledRules.entries()) {
|
|
829
|
+
if (validate(attributes)) {
|
|
830
|
+
// Apply set resolution
|
|
831
|
+
const setOutput = resolveSet(rule.set, attributes);
|
|
832
|
+
merged = { ...merged, ...setOutput };
|
|
833
|
+
// Apply map transformation if present
|
|
834
|
+
if (rule.map) {
|
|
835
|
+
let mapDef;
|
|
836
|
+
// Resolve map reference
|
|
837
|
+
if (typeof rule.map === 'string') {
|
|
838
|
+
if (rule.map.endsWith('.json') && configDir) {
|
|
839
|
+
// File path: load from .json file
|
|
840
|
+
try {
|
|
841
|
+
const mapPath = node_path.resolve(configDir, rule.map);
|
|
842
|
+
const raw = node_fs.readFileSync(mapPath, 'utf-8');
|
|
843
|
+
mapDef = JSON.parse(raw);
|
|
844
|
+
}
|
|
845
|
+
catch (error) {
|
|
846
|
+
log.warn(`Failed to load map file "${rule.map}": ${error instanceof Error ? error.message : String(error)}`);
|
|
847
|
+
continue;
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
else {
|
|
851
|
+
mapDef = namedMaps?.[rule.map];
|
|
852
|
+
if (!mapDef) {
|
|
853
|
+
log.warn(`Map reference "${rule.map}" not found in named maps. Skipping map transformation.`);
|
|
854
|
+
continue;
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
else {
|
|
859
|
+
mapDef = rule.map;
|
|
860
|
+
}
|
|
861
|
+
// Execute JsonMap transformation
|
|
862
|
+
try {
|
|
863
|
+
const jsonMap = new jsonmap.JsonMap(mapDef, lib);
|
|
864
|
+
const mapOutput = await jsonMap.transform(attributes);
|
|
865
|
+
if (mapOutput &&
|
|
866
|
+
typeof mapOutput === 'object' &&
|
|
867
|
+
!Array.isArray(mapOutput)) {
|
|
868
|
+
merged = { ...merged, ...mapOutput };
|
|
869
|
+
}
|
|
870
|
+
else {
|
|
871
|
+
log.warn(`JsonMap transformation did not return an object; skipping merge.`);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
catch (error) {
|
|
875
|
+
log.warn(`JsonMap transformation failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
// Render template if present
|
|
879
|
+
if (rule.template && templateEngine) {
|
|
880
|
+
const templateKey = `rule-${String(ruleIndex)}`;
|
|
881
|
+
// Build template context: attributes (with json spread at top) + map output
|
|
882
|
+
const context = {
|
|
883
|
+
...(attributes.json ?? {}),
|
|
884
|
+
...attributes,
|
|
885
|
+
...merged,
|
|
886
|
+
};
|
|
887
|
+
try {
|
|
888
|
+
const result = templateEngine.render(templateKey, context);
|
|
889
|
+
if (result && result.trim()) {
|
|
890
|
+
renderedContent = result;
|
|
891
|
+
}
|
|
892
|
+
else {
|
|
893
|
+
log.warn(`Template for rule ${String(ruleIndex)} rendered empty output. Falling back to raw content.`);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
catch (error) {
|
|
897
|
+
log.warn(`Template render failed for rule ${String(ruleIndex)}: ${error instanceof Error ? error.message : String(error)}. Falling back to raw content.`);
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
return { metadata: merged, renderedContent };
|
|
903
|
+
}
|
|
904
|
+
|
|
660
905
|
/**
|
|
661
906
|
* @module templates/helpers
|
|
662
907
|
* Registers built-in Handlebars helpers for content templates.
|
|
@@ -1185,6 +1430,17 @@ const jeevesWatcherConfigSchema = zod.z.object({
|
|
|
1185
1430
|
})
|
|
1186
1431
|
.optional()
|
|
1187
1432
|
.describe('Custom Handlebars helper registration.'),
|
|
1433
|
+
/** Custom JsonMap lib function registration. */
|
|
1434
|
+
mapHelpers: zod.z
|
|
1435
|
+
.object({
|
|
1436
|
+
/** File paths to custom lib modules (each exports functions to merge into the JsonMap lib). */
|
|
1437
|
+
paths: zod.z
|
|
1438
|
+
.array(zod.z.string())
|
|
1439
|
+
.optional()
|
|
1440
|
+
.describe('File paths to JS modules exporting functions to merge into the JsonMap lib.'),
|
|
1441
|
+
})
|
|
1442
|
+
.optional()
|
|
1443
|
+
.describe('Custom JsonMap lib function registration.'),
|
|
1188
1444
|
/** Logging configuration. */
|
|
1189
1445
|
logging: loggingConfigSchema.optional().describe('Logging configuration.'),
|
|
1190
1446
|
/** Timeout in milliseconds for graceful shutdown. */
|
|
@@ -1675,160 +1931,6 @@ async function extractText(filePath, extension) {
|
|
|
1675
1931
|
return extractPlaintext(filePath);
|
|
1676
1932
|
}
|
|
1677
1933
|
|
|
1678
|
-
/**
|
|
1679
|
-
* @module rules/templates
|
|
1680
|
-
* Resolves template variables (`${path.to.value}`) in rule `set` objects against file attributes.
|
|
1681
|
-
*/
|
|
1682
|
-
/**
|
|
1683
|
-
* Resolve `${template.vars}` in a value against the given attributes.
|
|
1684
|
-
*
|
|
1685
|
-
* @param value - The value to resolve.
|
|
1686
|
-
* @param attributes - The file attributes for variable lookup.
|
|
1687
|
-
* @returns The resolved value.
|
|
1688
|
-
*/
|
|
1689
|
-
function resolveTemplateVars(value, attributes) {
|
|
1690
|
-
if (typeof value !== 'string')
|
|
1691
|
-
return value;
|
|
1692
|
-
return value.replace(/\$\{([^}]+)\}/g, (_match, varPath) => {
|
|
1693
|
-
const current = radash.get(attributes, varPath);
|
|
1694
|
-
if (current === null || current === undefined)
|
|
1695
|
-
return '';
|
|
1696
|
-
return typeof current === 'string' ? current : JSON.stringify(current);
|
|
1697
|
-
});
|
|
1698
|
-
}
|
|
1699
|
-
/**
|
|
1700
|
-
* Resolve all template variables in a `set` object.
|
|
1701
|
-
*
|
|
1702
|
-
* @param setObj - The key-value pairs to resolve.
|
|
1703
|
-
* @param attributes - The file attributes for variable lookup.
|
|
1704
|
-
* @returns The resolved key-value pairs.
|
|
1705
|
-
*/
|
|
1706
|
-
function resolveSet(setObj, attributes) {
|
|
1707
|
-
const result = {};
|
|
1708
|
-
for (const [key, value] of Object.entries(setObj)) {
|
|
1709
|
-
result[key] = resolveTemplateVars(value, attributes);
|
|
1710
|
-
}
|
|
1711
|
-
return result;
|
|
1712
|
-
}
|
|
1713
|
-
|
|
1714
|
-
/**
|
|
1715
|
-
* @module rules/apply
|
|
1716
|
-
* Applies compiled inference rules to file attributes, producing merged metadata via template resolution and JsonMap transforms.
|
|
1717
|
-
*/
|
|
1718
|
-
/**
|
|
1719
|
-
* Create the lib object for JsonMap transformations.
|
|
1720
|
-
*
|
|
1721
|
-
* @returns The lib object.
|
|
1722
|
-
*/
|
|
1723
|
-
function createJsonMapLib() {
|
|
1724
|
-
return {
|
|
1725
|
-
split: (str, separator) => str.split(separator),
|
|
1726
|
-
slice: (arr, start, end) => arr.slice(start, end),
|
|
1727
|
-
join: (arr, separator) => arr.join(separator),
|
|
1728
|
-
toLowerCase: (str) => str.toLowerCase(),
|
|
1729
|
-
replace: (str, search, replacement) => str.replace(search, replacement),
|
|
1730
|
-
get: (obj, path) => radash.get(obj, path),
|
|
1731
|
-
};
|
|
1732
|
-
}
|
|
1733
|
-
/**
|
|
1734
|
-
* Apply compiled inference rules to file attributes, returning merged metadata and optional rendered content.
|
|
1735
|
-
*
|
|
1736
|
-
* Rules are evaluated in order; later rules override earlier ones.
|
|
1737
|
-
* If a rule has a `map`, the JsonMap transformation is applied after `set` resolution,
|
|
1738
|
-
* and map output overrides set output on conflict.
|
|
1739
|
-
*
|
|
1740
|
-
* @param compiledRules - The compiled rules to evaluate.
|
|
1741
|
-
* @param attributes - The file attributes to match against.
|
|
1742
|
-
* @param namedMaps - Optional record of named JsonMap definitions.
|
|
1743
|
-
* @param logger - Optional logger for warnings (falls back to console.warn).
|
|
1744
|
-
* @param templateEngine - Optional template engine for rendering content templates.
|
|
1745
|
-
* @param configDir - Optional config directory for resolving .json map file paths.
|
|
1746
|
-
* @returns The merged metadata and optional rendered content.
|
|
1747
|
-
*/
|
|
1748
|
-
async function applyRules(compiledRules, attributes, namedMaps, logger, templateEngine, configDir) {
|
|
1749
|
-
// JsonMap's type definitions expect a generic JsonMapLib shape with unary functions.
|
|
1750
|
-
// Our helper functions accept multiple args, which JsonMap supports at runtime.
|
|
1751
|
-
const lib = createJsonMapLib();
|
|
1752
|
-
let merged = {};
|
|
1753
|
-
let renderedContent = null;
|
|
1754
|
-
const log = logger ?? console;
|
|
1755
|
-
for (const [ruleIndex, { rule, validate }] of compiledRules.entries()) {
|
|
1756
|
-
if (validate(attributes)) {
|
|
1757
|
-
// Apply set resolution
|
|
1758
|
-
const setOutput = resolveSet(rule.set, attributes);
|
|
1759
|
-
merged = { ...merged, ...setOutput };
|
|
1760
|
-
// Apply map transformation if present
|
|
1761
|
-
if (rule.map) {
|
|
1762
|
-
let mapDef;
|
|
1763
|
-
// Resolve map reference
|
|
1764
|
-
if (typeof rule.map === 'string') {
|
|
1765
|
-
if (rule.map.endsWith('.json') && configDir) {
|
|
1766
|
-
// File path: load from .json file
|
|
1767
|
-
try {
|
|
1768
|
-
const mapPath = node_path.resolve(configDir, rule.map);
|
|
1769
|
-
const raw = node_fs.readFileSync(mapPath, 'utf-8');
|
|
1770
|
-
mapDef = JSON.parse(raw);
|
|
1771
|
-
}
|
|
1772
|
-
catch (error) {
|
|
1773
|
-
log.warn(`Failed to load map file "${rule.map}": ${error instanceof Error ? error.message : String(error)}`);
|
|
1774
|
-
continue;
|
|
1775
|
-
}
|
|
1776
|
-
}
|
|
1777
|
-
else {
|
|
1778
|
-
mapDef = namedMaps?.[rule.map];
|
|
1779
|
-
if (!mapDef) {
|
|
1780
|
-
log.warn(`Map reference "${rule.map}" not found in named maps. Skipping map transformation.`);
|
|
1781
|
-
continue;
|
|
1782
|
-
}
|
|
1783
|
-
}
|
|
1784
|
-
}
|
|
1785
|
-
else {
|
|
1786
|
-
mapDef = rule.map;
|
|
1787
|
-
}
|
|
1788
|
-
// Execute JsonMap transformation
|
|
1789
|
-
try {
|
|
1790
|
-
const jsonMap = new jsonmap.JsonMap(mapDef, lib);
|
|
1791
|
-
const mapOutput = await jsonMap.transform(attributes);
|
|
1792
|
-
if (mapOutput &&
|
|
1793
|
-
typeof mapOutput === 'object' &&
|
|
1794
|
-
!Array.isArray(mapOutput)) {
|
|
1795
|
-
merged = { ...merged, ...mapOutput };
|
|
1796
|
-
}
|
|
1797
|
-
else {
|
|
1798
|
-
log.warn(`JsonMap transformation did not return an object; skipping merge.`);
|
|
1799
|
-
}
|
|
1800
|
-
}
|
|
1801
|
-
catch (error) {
|
|
1802
|
-
log.warn(`JsonMap transformation failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1803
|
-
}
|
|
1804
|
-
}
|
|
1805
|
-
// Render template if present
|
|
1806
|
-
if (rule.template && templateEngine) {
|
|
1807
|
-
const templateKey = `rule-${String(ruleIndex)}`;
|
|
1808
|
-
// Build template context: attributes (with json spread at top) + map output
|
|
1809
|
-
const context = {
|
|
1810
|
-
...(attributes.json ?? {}),
|
|
1811
|
-
...attributes,
|
|
1812
|
-
...merged,
|
|
1813
|
-
};
|
|
1814
|
-
try {
|
|
1815
|
-
const result = templateEngine.render(templateKey, context);
|
|
1816
|
-
if (result && result.trim()) {
|
|
1817
|
-
renderedContent = result;
|
|
1818
|
-
}
|
|
1819
|
-
else {
|
|
1820
|
-
log.warn(`Template for rule ${String(ruleIndex)} rendered empty output. Falling back to raw content.`);
|
|
1821
|
-
}
|
|
1822
|
-
}
|
|
1823
|
-
catch (error) {
|
|
1824
|
-
log.warn(`Template render failed for rule ${String(ruleIndex)}: ${error instanceof Error ? error.message : String(error)}. Falling back to raw content.`);
|
|
1825
|
-
}
|
|
1826
|
-
}
|
|
1827
|
-
}
|
|
1828
|
-
}
|
|
1829
|
-
return { metadata: merged, renderedContent };
|
|
1830
|
-
}
|
|
1831
|
-
|
|
1832
1934
|
/**
|
|
1833
1935
|
* @module rules/attributes
|
|
1834
1936
|
* Builds file attribute objects for rule matching. Pure function: derives attributes from path, stats, and extracted data.
|
|
@@ -1919,14 +2021,14 @@ function compileRules(rules) {
|
|
|
1919
2021
|
* @param configDir - Optional config directory for resolving file paths.
|
|
1920
2022
|
* @returns The merged metadata and intermediate data.
|
|
1921
2023
|
*/
|
|
1922
|
-
async function buildMergedMetadata(filePath, compiledRules, metadataDir, maps, logger, templateEngine, configDir) {
|
|
2024
|
+
async function buildMergedMetadata(filePath, compiledRules, metadataDir, maps, logger, templateEngine, configDir, customMapLib) {
|
|
1923
2025
|
const ext = node_path.extname(filePath);
|
|
1924
2026
|
const stats = await promises.stat(filePath);
|
|
1925
2027
|
// 1. Extract text and structured data
|
|
1926
2028
|
const extracted = await extractText(filePath, ext);
|
|
1927
2029
|
// 2. Build attributes + apply rules
|
|
1928
2030
|
const attributes = buildAttributes(filePath, stats, extracted.frontmatter, extracted.json);
|
|
1929
|
-
const { metadata: inferred, renderedContent } = await applyRules(compiledRules, attributes, maps, logger, templateEngine, configDir);
|
|
2031
|
+
const { metadata: inferred, renderedContent } = await applyRules(compiledRules, attributes, maps, logger, templateEngine, configDir, customMapLib);
|
|
1930
2032
|
// 3. Read enrichment metadata (merge, enrichment wins)
|
|
1931
2033
|
const enrichment = await readMetadata(filePath, metadataDir);
|
|
1932
2034
|
const metadata = {
|
|
@@ -2039,7 +2141,7 @@ class DocumentProcessor {
|
|
|
2039
2141
|
try {
|
|
2040
2142
|
const ext = node_path.extname(filePath);
|
|
2041
2143
|
// 1. Build merged metadata + extract text
|
|
2042
|
-
const { metadata, extracted, renderedContent } = await buildMergedMetadata(filePath, this.compiledRules, this.config.metadataDir, this.config.maps, this.logger, this.templateEngine, this.config.configDir);
|
|
2144
|
+
const { metadata, extracted, renderedContent } = await buildMergedMetadata(filePath, this.compiledRules, this.config.metadataDir, this.config.maps, this.logger, this.templateEngine, this.config.configDir, this.config.customMapLib);
|
|
2043
2145
|
// Use rendered template content if available, otherwise raw extracted text
|
|
2044
2146
|
const textToEmbed = renderedContent ?? extracted.text;
|
|
2045
2147
|
if (!textToEmbed.trim()) {
|
|
@@ -2153,7 +2255,7 @@ class DocumentProcessor {
|
|
|
2153
2255
|
return null;
|
|
2154
2256
|
}
|
|
2155
2257
|
// Build merged metadata (lightweight — no embedding)
|
|
2156
|
-
const { metadata } = await buildMergedMetadata(filePath, this.compiledRules, this.config.metadataDir, this.config.maps, this.logger, this.templateEngine, this.config.configDir);
|
|
2258
|
+
const { metadata } = await buildMergedMetadata(filePath, this.compiledRules, this.config.metadataDir, this.config.maps, this.logger, this.templateEngine, this.config.configDir, this.config.customMapLib);
|
|
2157
2259
|
// Update all chunk payloads
|
|
2158
2260
|
const totalChunks = getChunkCount(existingPayload);
|
|
2159
2261
|
const ids = chunkIds(filePath, totalChunks);
|
|
@@ -2167,21 +2269,20 @@ class DocumentProcessor {
|
|
|
2167
2269
|
}
|
|
2168
2270
|
}
|
|
2169
2271
|
/**
|
|
2170
|
-
* Update compiled inference rules
|
|
2171
|
-
*
|
|
2172
|
-
* @param compiledRules - The newly compiled rules.
|
|
2173
|
-
*/
|
|
2174
|
-
/**
|
|
2175
|
-
* Update compiled inference rules and optionally the template engine.
|
|
2272
|
+
* Update compiled inference rules, template engine, and custom map lib.
|
|
2176
2273
|
*
|
|
2177
2274
|
* @param compiledRules - The newly compiled rules.
|
|
2178
2275
|
* @param templateEngine - Optional updated template engine.
|
|
2276
|
+
* @param customMapLib - Optional updated custom JsonMap lib functions.
|
|
2179
2277
|
*/
|
|
2180
|
-
updateRules(compiledRules, templateEngine) {
|
|
2278
|
+
updateRules(compiledRules, templateEngine, customMapLib) {
|
|
2181
2279
|
this.compiledRules = compiledRules;
|
|
2182
2280
|
if (templateEngine) {
|
|
2183
2281
|
this.templateEngine = templateEngine;
|
|
2184
2282
|
}
|
|
2283
|
+
if (customMapLib !== undefined) {
|
|
2284
|
+
this.config = { ...this.config, customMapLib };
|
|
2285
|
+
}
|
|
2185
2286
|
this.logger.info({ rules: compiledRules.length }, 'Inference rules updated');
|
|
2186
2287
|
}
|
|
2187
2288
|
}
|
|
@@ -3061,12 +3162,17 @@ class JeevesWatcher {
|
|
|
3061
3162
|
const compiledRules = this.factories.compileRules(this.config.inferenceRules ?? []);
|
|
3062
3163
|
const configDir = this.configPath ? node_path.dirname(this.configPath) : '.';
|
|
3063
3164
|
const templateEngine = await buildTemplateEngine(this.config.inferenceRules ?? [], this.config.templates, this.config.templateHelpers?.paths, configDir);
|
|
3165
|
+
// Load custom JsonMap lib functions
|
|
3166
|
+
const customMapLib = this.config.mapHelpers?.paths?.length && configDir
|
|
3167
|
+
? await loadCustomMapHelpers(this.config.mapHelpers.paths, configDir)
|
|
3168
|
+
: undefined;
|
|
3064
3169
|
const processor = this.factories.createDocumentProcessor({
|
|
3065
3170
|
metadataDir: this.config.metadataDir ?? '.jeeves-metadata',
|
|
3066
3171
|
chunkSize: this.config.embedding.chunkSize,
|
|
3067
3172
|
chunkOverlap: this.config.embedding.chunkOverlap,
|
|
3068
3173
|
maps: this.config.maps,
|
|
3069
3174
|
configDir,
|
|
3175
|
+
customMapLib,
|
|
3070
3176
|
}, embeddingProvider, vectorStore, compiledRules, logger, templateEngine);
|
|
3071
3177
|
this.processor = processor;
|
|
3072
3178
|
this.queue = this.factories.createEventQueue({
|
|
@@ -3185,7 +3291,10 @@ class JeevesWatcher {
|
|
|
3185
3291
|
const compiledRules = this.factories.compileRules(newConfig.inferenceRules ?? []);
|
|
3186
3292
|
const reloadConfigDir = node_path.dirname(this.configPath);
|
|
3187
3293
|
const newTemplateEngine = await buildTemplateEngine(newConfig.inferenceRules ?? [], newConfig.templates, newConfig.templateHelpers?.paths, reloadConfigDir);
|
|
3188
|
-
|
|
3294
|
+
const newCustomMapLib = newConfig.mapHelpers?.paths?.length && reloadConfigDir
|
|
3295
|
+
? await loadCustomMapHelpers(newConfig.mapHelpers.paths, reloadConfigDir)
|
|
3296
|
+
: undefined;
|
|
3297
|
+
processor.updateRules(compiledRules, newTemplateEngine, newCustomMapLib);
|
|
3189
3298
|
logger.info({ configPath: this.configPath, rules: compiledRules.length }, 'Config reloaded');
|
|
3190
3299
|
}
|
|
3191
3300
|
catch (error) {
|