@higher.archi/boe 1.0.25 → 1.0.27

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.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Sentiment Engine Compiler
3
+ *
4
+ * Validates sentiment rulesets, normalizes lexicon keys to lowercase,
5
+ * and resolves config defaults.
6
+ */
7
+ import type { SentimentRuleSet, CompiledSentimentRuleSet } from './types';
8
+ /**
9
+ * Compile and validate a sentiment ruleset.
10
+ */
11
+ export declare function compileSentimentRuleSet(ruleSet: SentimentRuleSet): CompiledSentimentRuleSet;
12
+ //# sourceMappingURL=compiler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compiler.d.ts","sourceRoot":"","sources":["../../../src/engines/sentiment/compiler.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EACV,gBAAgB,EAChB,wBAAwB,EAKzB,MAAM,SAAS,CAAC;AAGjB;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,gBAAgB,GACxB,wBAAwB,CAuE1B"}
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ /**
3
+ * Sentiment Engine Compiler
4
+ *
5
+ * Validates sentiment rulesets, normalizes lexicon keys to lowercase,
6
+ * and resolves config defaults.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.compileSentimentRuleSet = compileSentimentRuleSet;
10
+ const errors_1 = require("../../core/errors");
11
+ const types_1 = require("./types");
12
+ /**
13
+ * Compile and validate a sentiment ruleset.
14
+ */
15
+ function compileSentimentRuleSet(ruleSet) {
16
+ if (!ruleSet.id) {
17
+ throw new errors_1.CompilationError('Sentiment ruleset requires an id');
18
+ }
19
+ if (ruleSet.mode !== 'sentiment') {
20
+ throw new errors_1.CompilationError(`Expected mode 'sentiment', got '${ruleSet.mode}'`);
21
+ }
22
+ if (!ruleSet.lexiconConfig || !ruleSet.lexiconConfig.lexicon) {
23
+ throw new errors_1.CompilationError('Sentiment ruleset requires a lexiconConfig with a lexicon');
24
+ }
25
+ const lexiconKeys = Object.keys(ruleSet.lexiconConfig.lexicon);
26
+ if (lexiconKeys.length === 0) {
27
+ throw new errors_1.CompilationError('Lexicon must contain at least one entry');
28
+ }
29
+ // Compile the lexicon
30
+ const lexicon = compileLexicon(ruleSet.lexiconConfig);
31
+ // Resolve config defaults
32
+ const config = {
33
+ capsBoost: ruleSet.config?.capsBoost ?? types_1.SENTIMENT_DEFAULTS.capsBoost,
34
+ exclamationBoost: ruleSet.config?.exclamationBoost ?? types_1.SENTIMENT_DEFAULTS.exclamationBoost,
35
+ negationWindow: ruleSet.config?.negationWindow ?? types_1.SENTIMENT_DEFAULTS.negationWindow
36
+ };
37
+ switch (ruleSet.strategy) {
38
+ case 'token-level':
39
+ return {
40
+ id: ruleSet.id,
41
+ name: ruleSet.name,
42
+ mode: 'sentiment',
43
+ strategy: 'token-level',
44
+ lexicon,
45
+ config
46
+ };
47
+ case 'document-level': {
48
+ const pattern = ruleSet.sentenceSplitPattern ?? '[.!?]+';
49
+ return {
50
+ id: ruleSet.id,
51
+ name: ruleSet.name,
52
+ mode: 'sentiment',
53
+ strategy: 'document-level',
54
+ lexicon,
55
+ config,
56
+ sentenceSplitPattern: new RegExp(pattern)
57
+ };
58
+ }
59
+ case 'aspect-based': {
60
+ if (!ruleSet.aspects || ruleSet.aspects.length === 0) {
61
+ throw new errors_1.CompilationError('Aspect-based strategy requires at least one aspect');
62
+ }
63
+ const aspects = ruleSet.aspects.map(a => a.toLowerCase());
64
+ return {
65
+ id: ruleSet.id,
66
+ name: ruleSet.name,
67
+ mode: 'sentiment',
68
+ strategy: 'aspect-based',
69
+ lexicon,
70
+ config,
71
+ aspects
72
+ };
73
+ }
74
+ default:
75
+ throw new errors_1.CompilationError(`Unknown sentiment strategy: '${ruleSet.strategy}'`);
76
+ }
77
+ }
78
+ function compileLexicon(input) {
79
+ // Normalize all keys to lowercase
80
+ const lexicon = {};
81
+ for (const [key, value] of Object.entries(input.lexicon)) {
82
+ lexicon[key.toLowerCase()] = value;
83
+ }
84
+ const boosters = {};
85
+ if (input.boosters) {
86
+ for (const [key, value] of Object.entries(input.boosters)) {
87
+ boosters[key.toLowerCase()] = value;
88
+ }
89
+ }
90
+ const negation = new Set((input.negation ?? []).map(w => w.toLowerCase()));
91
+ const idioms = {};
92
+ let idiomMaxLength = 0;
93
+ if (input.idioms) {
94
+ for (const [key, value] of Object.entries(input.idioms)) {
95
+ const normalized = key.toLowerCase();
96
+ idioms[normalized] = value;
97
+ const wordCount = normalized.split(/\s+/).length;
98
+ if (wordCount > idiomMaxLength) {
99
+ idiomMaxLength = wordCount;
100
+ }
101
+ }
102
+ }
103
+ return {
104
+ lexicon,
105
+ boosters,
106
+ negation,
107
+ idioms,
108
+ _idiomMaxLength: idiomMaxLength
109
+ };
110
+ }
111
+ //# sourceMappingURL=compiler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compiler.js","sourceRoot":"","sources":["../../../src/engines/sentiment/compiler.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;AAiBH,0DAyEC;AAxFD,8CAAqD;AAUrD,mCAA6C;AAE7C;;GAEG;AACH,SAAgB,uBAAuB,CACrC,OAAyB;IAEzB,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC;QAChB,MAAM,IAAI,yBAAgB,CAAC,kCAAkC,CAAC,CAAC;IACjE,CAAC;IAED,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;QACjC,MAAM,IAAI,yBAAgB,CAAC,mCAAmC,OAAO,CAAC,IAAI,GAAG,CAAC,CAAC;IACjF,CAAC;IAED,IAAI,CAAC,OAAO,CAAC,aAAa,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;QAC7D,MAAM,IAAI,yBAAgB,CAAC,2DAA2D,CAAC,CAAC;IAC1F,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,CAAC,IAAI,CAA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EF,MAAM,MAAM,GAA2B,EAAE,CAAC;IAC1C,IAAI,cAAc,GAAG,CAAC,CAAC;IACvB,IAAI,KAAK,CAAC,MAAM,EAAE,CAAC;QACjB,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;YACxD,MAAM,UAAU,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;YACrC,MAAM,CAAC,UAAU,CAAC,GAAG,KAAK,CAAC;YAC3B,MAAM,SAAS,GAAG,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC;YACjD,IAAI,SAAS,GAAG,cAAc,EAAE,CAAC;gBAC/B,cAAc,GAAG,SAAS,CAAC;YAC7B,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO;QACL,OAAO;QACP,QAAQ;QACR,QAAQ;QACR,MAAM;QACN,eAAe,EAAE,cAAc;KAChC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Sentiment Engine
3
+ *
4
+ * Text sentiment analysis engine that scores text using dictionary-lookup
5
+ * and heuristic rules. Supports token-level, document-level, and aspect-based
6
+ * analysis strategies with injectable lexicon configuration.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * const engine = new SentimentEngine();
11
+ * engine.add({ type: 'Review', data: { text: 'The product is absolutely fantastic!' } });
12
+ *
13
+ * const result = engine.execute(compiledRuleset);
14
+ * console.log(result.compound); // 0.85 (positive)
15
+ * ```
16
+ */
17
+ import { WorkingMemory, Fact, FactInput, FactChange } from '../../core';
18
+ import type { CompiledSentimentRuleSet, SentimentOptions, SentimentResult, IngestResult } from './types';
19
+ export declare class SentimentEngine {
20
+ private wm;
21
+ private strategy;
22
+ private _stream;
23
+ constructor(workingMemory?: WorkingMemory);
24
+ add<T = Record<string, any>>(input: FactInput<T>): Fact<T>;
25
+ remove(factId: string): Fact | undefined;
26
+ update<T = Record<string, any>>(input: FactInput<T>): Fact<T>;
27
+ get(factId: string): Fact | undefined;
28
+ getByType(type: string): Fact[];
29
+ getAll(): Fact[];
30
+ has(factId: string): boolean;
31
+ size(): number;
32
+ clear(): void;
33
+ getChanges(): FactChange[];
34
+ clearChanges(): void;
35
+ /**
36
+ * Execute a sentiment analysis ruleset.
37
+ *
38
+ * Extracts text from all facts in working memory, applies the configured
39
+ * sentiment strategy, and returns compound scores with token-level detail.
40
+ *
41
+ * @param ruleSet - Compiled sentiment ruleset
42
+ * @param options - Runtime options (onToken callback)
43
+ * @returns Sentiment result with compound score, label, and detail
44
+ */
45
+ execute(ruleSet: CompiledSentimentRuleSet, options?: SentimentOptions): SentimentResult;
46
+ /**
47
+ * Score a single text incrementally without touching working memory.
48
+ *
49
+ * Each call scores the provided text, updates a running accumulator,
50
+ * and returns both the individual score and the current aggregate.
51
+ * The compiled ruleset must stay the same across calls (matched by id).
52
+ * Call `resetStream()` to start a new stream.
53
+ *
54
+ * @param text - Raw text to score
55
+ * @param ruleSet - Compiled sentiment ruleset
56
+ * @param options - Runtime options (onToken callback)
57
+ * @returns IngestResult with item-level and aggregate scores
58
+ */
59
+ ingest(text: string, ruleSet: CompiledSentimentRuleSet, options?: SentimentOptions): IngestResult;
60
+ /**
61
+ * Get the current streaming aggregate without ingesting new text.
62
+ * Returns null if no texts have been ingested yet.
63
+ */
64
+ getStreamResult(): SentimentResult | null;
65
+ /**
66
+ * Reset the streaming accumulator. Does not affect working memory.
67
+ */
68
+ resetStream(): void;
69
+ getWorkingMemory(): WorkingMemory;
70
+ }
71
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../../src/engines/sentiment/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EACL,aAAa,EACb,IAAI,EACJ,SAAS,EACT,UAAU,EACX,MAAM,YAAY,CAAC;AAEpB,OAAO,KAAK,EACV,wB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
+ "use strict";
2
+ /**
3
+ * Sentiment Engine
4
+ *
5
+ * Text sentiment analysis engine that scores text using dictionary-lookup
6
+ * and heuristic rules. Supports token-level, document-level, and aspect-based
7
+ * analysis strategies with injectable lexicon configuration.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const engine = new SentimentEngine();
12
+ * engine.add({ type: 'Review', data: { text: 'The product is absolutely fantastic!' } });
13
+ *
14
+ * const result = engine.execute(compiledRuleset);
15
+ * console.log(result.compound); // 0.85 (positive)
16
+ * ```
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.SentimentEngine = void 0;
20
+ const core_1 = require("../../core");
21
+ const types_1 = require("./types");
22
+ const strategy_1 = require("./strategy");
23
+ function round(value, decimals) {
24
+ const factor = Math.pow(10, decimals);
25
+ return Math.round(value * factor) / factor;
26
+ }
27
+ class SentimentEngine {
28
+ wm;
29
+ strategy;
30
+ _stream = null;
31
+ constructor(workingMemory) {
32
+ this.wm = workingMemory ?? new core_1.WorkingMemory();
33
+ this.strategy = new strategy_1.SentimentExecutor();
34
+ }
35
+ // ========================================
36
+ // IWorkingMemory Implementation
37
+ // ========================================
38
+ add(input) {
39
+ return this.wm.add(input);
40
+ }
41
+ remove(factId) {
42
+ return this.wm.remove(factId);
43
+ }
44
+ update(input) {
45
+ return this.wm.update(input);
46
+ }
47
+ get(factId) {
48
+ return this.wm.get(factId);
49
+ }
50
+ getByType(type) {
51
+ return this.wm.getByType(type);
52
+ }
53
+ getAll() {
54
+ return this.wm.getAll();
55
+ }
56
+ has(factId) {
57
+ return this.wm.has(factId);
58
+ }
59
+ size() {
60
+ return this.wm.size();
61
+ }
62
+ clear() {
63
+ this.wm.clear();
64
+ }
65
+ getChanges() {
66
+ return this.wm.getChanges();
67
+ }
68
+ clearChanges() {
69
+ this.wm.clearChanges();
70
+ }
71
+ // ========================================
72
+ // Engine Execution
73
+ // ========================================
74
+ /**
75
+ * Execute a sentiment analysis ruleset.
76
+ *
77
+ * Extracts text from all facts in working memory, applies the configured
78
+ * sentiment strategy, and returns compound scores with token-level detail.
79
+ *
80
+ * @param ruleSet - Compiled sentiment ruleset
81
+ * @param options - Runtime options (onToken callback)
82
+ * @returns Sentiment result with compound score, label, and detail
83
+ */
84
+ execute(ruleSet, options = {}) {
85
+ return this.strategy.run(ruleSet, this.wm, options);
86
+ }
87
+ // ========================================
88
+ // Streaming Ingest
89
+ // ========================================
90
+ /**
91
+ * Score a single text incrementally without touching working memory.
92
+ *
93
+ * Each call scores the provided text, updates a running accumulator,
94
+ * and returns both the individual score and the current aggregate.
95
+ * The compiled ruleset must stay the same across calls (matched by id).
96
+ * Call `resetStream()` to start a new stream.
97
+ *
98
+ * @param text - Raw text to score
99
+ * @param ruleSet - Compiled sentiment ruleset
100
+ * @param options - Runtime options (onToken callback)
101
+ * @returns IngestResult with item-level and aggregate scores
102
+ */
103
+ ingest(text, ruleSet, options = {}) {
104
+ // Initialize or validate stream state
105
+ if (!this._stream || this._stream.ruleSetId !== ruleSet.id) {
106
+ this._stream = {
107
+ ruleSetId: ruleSet.id,
108
+ strategy: ruleSet.strategy,
109
+ compoundSum: 0,
110
+ count: 0,
111
+ posTokens: 0,
112
+ negTokens: 0,
113
+ neuTokens: 0,
114
+ totalTokens: 0,
115
+ aspectAccumulators: new Map(),
116
+ lastResult: null
117
+ };
118
+ }
119
+ // Score just this text
120
+ const itemResult = this.strategy.scoreText(ruleSet, text, options);
121
+ // Update running accumulators
122
+ const s = this._stream;
123
+ s.compoundSum += itemResult.compound;
124
+ s.count++;
125
+ // Update token proportion accumulators
126
+ const itemTokenTotal = itemResult.tokens?.length
127
+ ?? itemResult.sentences?.reduce((n, sent) => n + sent.tokens.length, 0)
128
+ ?? itemResult.aspects?.reduce((n, a) => n + a.sentences.reduce((m, sent) => m + sent.tokens.length, 0), 0)
129
+ ?? 0;
130
+ if (itemTokenTotal > 0) {
131
+ s.posTokens += Math.round(itemResult.positive * itemTokenTotal);
132
+ s.negTokens += Math.round(itemResult.negative * itemTokenTotal);
133
+ s.neuTokens += Math.round(itemResult.neutral * itemTokenTotal);
134
+ s.totalTokens += itemTokenTotal;
135
+ }
136
+ // Update aspect accumulators if aspect-based
137
+ if (itemResult.aspects) {
138
+ for (const aspect of itemResult.aspects) {
139
+ if (aspect.sentences.length === 0)
140
+ continue;
141
+ let acc = s.aspectAccumulators.get(aspect.aspect);
142
+ if (!acc) {
143
+ acc = { compoundSum: 0, count: 0 };
144
+ s.aspectAccumulators.set(aspect.aspect, acc);
145
+ }
146
+ acc.compoundSum += aspect.compound;
147
+ acc.count++;
148
+ }
149
+ }
150
+ // Compute aggregate
151
+ const aggCompound = round(s.compoundSum / s.count, 4);
152
+ const aggPositive = s.totalTokens > 0 ? round(s.posTokens / s.totalTokens, 4) : 0;
153
+ const aggNegative = s.totalTokens > 0 ? round(s.negTokens / s.totalTokens, 4) : 0;
154
+ const aggNeutral = s.totalTokens > 0 ? round(s.neuTokens / s.totalTokens, 4) : 0;
155
+ // Build aggregate aspect results if applicable
156
+ let aggAspects;
157
+ if (s.aspectAccumulators.size > 0) {
158
+ aggAspects = [];
159
+ for (const [aspect, acc] of s.aspectAccumulators) {
160
+ const aspectCompound = round(acc.compoundSum / acc.count, 4);
161
+ aggAspects.push({
162
+ aspect,
163
+ compound: aspectCompound,
164
+ label: (0, types_1.resolveSentimentLabel)(aspectCompound),
165
+ sentences: []
166
+ });
167
+ }
168
+ }
169
+ const aggregate = {
170
+ compound: aggCompound,
171
+ label: (0, types_1.resolveSentimentLabel)(aggCompound),
172
+ positive: aggPositive,
173
+ negative: aggNegative,
174
+ neutral: aggNeutral,
175
+ aspects: aggAspects,
176
+ strategy: ruleSet.strategy,
177
+ executionTimeMs: itemResult.executionTimeMs
178
+ };
179
+ s.lastResult = aggregate;
180
+ return {
181
+ ...aggregate,
182
+ itemCompound: itemResult.compound,
183
+ itemLabel: itemResult.label,
184
+ totalIngested: s.count
185
+ };
186
+ }
187
+ /**
188
+ * Get the current streaming aggregate without ingesting new text.
189
+ * Returns null if no texts have been ingested yet.
190
+ */
191
+ getStreamResult() {
192
+ return this._stream?.lastResult ?? null;
193
+ }
194
+ /**
195
+ * Reset the streaming accumulator. Does not affect working memory.
196
+ */
197
+ resetStream() {
198
+ this._stream = null;
199
+ }
200
+ // ========================================
201
+ // Utility Methods
202
+ // ========================================
203
+ getWorkingMemory() {
204
+ return this.wm;
205
+ }
206
+ }
207
+ exports.SentimentEngine = SentimentEngine;
208
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../../src/engines/sentiment/engine.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,qCAKoB;AAUpB,mCAAgD;AAEhD,yCAA+C;AAE/C,SAAS,KAAK,CAAC,KAAa,EAAE,QAAgB;IAC5C,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;IACtC,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,MAAM,CAAC,GAAG,MAAM,CAAC;AAC7C,CAAC;AAkBD,MAAa,eAAe;IAClB,EAAE,CAAgB;IAClB,QAAQ,CAAoB;IAC5B,OAAO,GAAuB,IAAI,CAAC;IAE3C,YAAY,aAA6B;QACvC,IAAI,CAAC,EAAE,GAAG,aAAa,IAAI,IAAI,oBAAa,EAAE,CAAC;QAC/C,IAAI,CAAC,QAAQ,GAAG,IAAI,4BAAiB,EAAE,CAAC;IAC1C,CAAC;IAED,2CAA2C;IAC3C,gCAAgC;IAChC,2CAA2C;IAE3C,GAAG,CAA0B,KAAmB;QAC9C,OAAO,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED,MAAM,CAAC,MAAc;QACnB,OAAO,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAChC,CAAC;IAED,MAAM,CAA0B,KAAmB;QACjD,O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Aa,EAAE,CAAC,CAAC,KAAK;SACvB,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,eAAe;QACb,OAAO,IAAI,CAAC,OAAO,EAAE,UAAU,IAAI,IAAI,CAAC;IAC1C,CAAC;IAED;;OAEG;IACH,WAAW;QACT,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;IACtB,CAAC;IAED,2CAA2C;IAC3C,kBAAkB;IAClB,2CAA2C;IAE3C,gBAAgB;QACd,OAAO,IAAI,CAAC,EAAE,CAAC;IACjB,CAAC;CACF;AAxND,0CAwNC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Sentiment Engine -- Text Sentiment Analysis
3
+ */
4
+ export type { SentimentStrategy, SentimentLabel, SentimentLexicon, CompiledSentimentLexicon, SentimentConfig, TokenLevelSentimentRuleSet, DocumentLevelSentimentRuleSet, AspectBasedSentimentRuleSet, SentimentRuleSet, CompiledTokenLevelSentimentRuleSet, CompiledDocumentLevelSentimentRuleSet, CompiledAspectBasedSentimentRuleSet, CompiledSentimentRuleSet, TokenModifier, TokenScore, SentenceResult, AspectResult, SentimentResult, SentimentOptions, IngestResult } from './types';
5
+ export { SENTIMENT_DEFAULTS, resolveSentimentLabel } from './types';
6
+ export { compileSentimentRuleSet } from './compiler';
7
+ export { SentimentExecutor, sentimentStrategy } from './strategy';
8
+ export { SentimentEngine } from './engine';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/engines/sentiment/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,YAAY,EACV,iBAAiB,EACjB,cAAc,EACd,gBAAgB,EAChB,wBAAwB,EACxB,eAAe,EACf,0BAA0B,EAC1B,6BAA6B,EAC7B,2BAA2B,EAC3B,gBAAgB,EAChB,kCAAkC,EAClC,qCAAqC,EACrC,mCAAmC,EACnC,wBAAwB,EACxB,aAAa,EACb,UAAU,EACV,cAAc,EACd,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,YAAY,EACb,MAAM,SAAS,CAAC;AAGjB,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACtB,MAAM,SAAS,CAAC;AAGjB,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAGrD,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAGlE,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /**
3
+ * Sentiment Engine -- Text Sentiment Analysis
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SentimentEngine = exports.sentimentStrategy = exports.SentimentExecutor = exports.compileSentimentRuleSet = exports.resolveSentimentLabel = exports.SENTIMENT_DEFAULTS = void 0;
7
+ // Constants & utilities
8
+ var types_1 = require("./types");
9
+ Object.defineProperty(exports, "SENTIMENT_DEFAULTS", { enumerable: true, get: function () { return types_1.SENTIMENT_DEFAULTS; } });
10
+ Object.defineProperty(exports, "resolveSentimentLabel", { enumerable: true, get: function () { return types_1.resolveSentimentLabel; } });
11
+ // Compiler
12
+ var compiler_1 = require("./compiler");
13
+ Object.defineProperty(exports, "compileSentimentRuleSet", { enumerable: true, get: function () { return compiler_1.compileSentimentRuleSet; } });
14
+ // Strategy
15
+ var strategy_1 = require("./strategy");
16
+ Object.defineProperty(exports, "SentimentExecutor", { enumerable: true, get: function () { return strategy_1.SentimentExecutor; } });
17
+ Object.defineProperty(exports, "sentimentStrategy", { enumerable: true, get: function () { return strategy_1.sentimentStrategy; } });
18
+ // Engine
19
+ var engine_1 = require("./engine");
20
+ Object.defineProperty(exports, "SentimentEngine", { enumerable: true, get: function () { return engine_1.SentimentEngine; } });
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/engines/sentiment/index.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AA0BH,wBAAwB;AACxB,iCAGiB;AAFf,2GAAA,kBAAkB,OAAA;AAClB,8GAAA,qBAAqB,OAAA;AAGvB,WAAW;AACX,uCAAqD;AAA5C,mHAAA,uBAAuB,OAAA;AAEhC,WAAW;AACX,uCAAkE;AAAzD,6GAAA,iBAAiB,OAAA;AAAE,6GAAA,iBAAiB,OAAA;AAE7C,SAAS;AACT,mCAA2C;AAAlC,yGAAA,eAAe,OAAA"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Sentiment Engine Strategy
3
+ *
4
+ * Core execution logic for all sentiment strategies:
5
+ * - token-level: Score individual tokens in the full text
6
+ * - document-level: Split into sentences, score each, average compounds
7
+ * - aspect-based: Match sentences to aspect terms, score per aspect
8
+ */
9
+ import type { IWorkingMemory } from '../../core';
10
+ import type { CompiledSentimentRuleSet, SentimentOptions, SentimentResult } from './types';
11
+ export declare class SentimentExecutor {
12
+ run(ruleSet: CompiledSentimentRuleSet, wm: IWorkingMemory, options?: SentimentOptions): SentimentResult;
13
+ /** Score a single text string directly (no WorkingMemory involved) */
14
+ scoreText(ruleSet: CompiledSentimentRuleSet, text: string, options?: SentimentOptions, startTime?: number): SentimentResult;
15
+ private runTokenLevel;
16
+ private runDocumentLevel;
17
+ private runAspectBased;
18
+ }
19
+ /** Singleton instance */
20
+ export declare const sentimentStrategy: SentimentExecutor;
21
+ //# sourceMappingURL=strategy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strategy.d.ts","sourceRoot":"","sources":["../../../src/engines/sentiment/strategy.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAQ,MAAM,YAAY,CAAC;AAEvD,OAAO,KAAK,EACV,wBAAwB,EAKxB,gBAAgB,EAChB,eAAe,EAKhB,MAAM,SAAS,CAAC;AAiQjB,qBAAa,iBAAiB;IAC5B,GAAG,CACD,OAAO,EAAE,wBAAwB,EACjC,EAAE,EAAE,cAAc,EAClB,OAAO,GAAE,gBAAqB,GAC7B,eAAe;IAWlB,sEAAsE;IACtE,SAAS,CACP,OAAO,EAAE,wBAAwB,EACjC,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,gBAAqB,EAC9B,SAAS,GAAE,MAA0B,GACpC,eAAe;IAiBlB,OAAO,CAAC,aAAa;IAiCrB,OAAO,CAAC,gBAAgB;IAiExB,OAAO,CAAC,cAAc;CAoEvB;AA0BD,yBAAyB;AACzB,eAAO,MAAM,iBAAiB,mBAA0B,CAAC"}