@jterrazz/intelligence 1.6.1 → 3.0.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.
- package/README.md +69 -165
- package/dist/index.cjs +649 -1625
- package/dist/index.d.ts +5 -12
- package/dist/index.js +5 -12
- package/dist/index.js.map +1 -1
- package/dist/middleware/__tests__/logging.middleware.test.js +390 -0
- package/dist/middleware/__tests__/logging.middleware.test.js.map +1 -0
- package/dist/middleware/logging.middleware.d.ts +21 -0
- package/dist/middleware/logging.middleware.js +296 -0
- package/dist/middleware/logging.middleware.js.map +1 -0
- package/dist/parsing/__tests__/create-schema-prompt.test.js +53 -0
- package/dist/parsing/__tests__/create-schema-prompt.test.js.map +1 -0
- package/dist/parsing/__tests__/parse-object.test.d.ts +1 -0
- package/dist/parsing/__tests__/parse-object.test.js +193 -0
- package/dist/parsing/__tests__/parse-object.test.js.map +1 -0
- package/dist/parsing/__tests__/parse-text.test.d.ts +1 -0
- package/dist/parsing/__tests__/parse-text.test.js +159 -0
- package/dist/parsing/__tests__/parse-text.test.js.map +1 -0
- package/dist/parsing/create-schema-prompt.d.ts +28 -0
- package/dist/parsing/create-schema-prompt.js +42 -0
- package/dist/parsing/create-schema-prompt.js.map +1 -0
- package/dist/parsing/parse-object.d.ts +33 -0
- package/dist/parsing/parse-object.js +360 -0
- package/dist/parsing/parse-object.js.map +1 -0
- package/dist/parsing/parse-text.d.ts +14 -0
- package/dist/parsing/parse-text.js +80 -0
- package/dist/parsing/parse-text.js.map +1 -0
- package/dist/providers/openrouter.provider.d.ts +36 -0
- package/dist/providers/openrouter.provider.js +58 -0
- package/dist/providers/openrouter.provider.js.map +1 -0
- package/package.json +15 -14
- package/dist/adapters/agents/autonomous-agent.adapter.d.ts +0 -30
- package/dist/adapters/agents/autonomous-agent.adapter.js +0 -400
- package/dist/adapters/agents/autonomous-agent.adapter.js.map +0 -1
- package/dist/adapters/agents/basic-agent.adapter.d.ts +0 -27
- package/dist/adapters/agents/basic-agent.adapter.js +0 -339
- package/dist/adapters/agents/basic-agent.adapter.js.map +0 -1
- package/dist/adapters/agents/retryable-agent.adapter.d.ts +0 -20
- package/dist/adapters/agents/retryable-agent.adapter.js +0 -263
- package/dist/adapters/agents/retryable-agent.adapter.js.map +0 -1
- package/dist/adapters/models/openrouter-model.adapter.d.ts +0 -38
- package/dist/adapters/models/openrouter-model.adapter.js +0 -89
- package/dist/adapters/models/openrouter-model.adapter.js.map +0 -1
- package/dist/adapters/prompts/__tests__/__snapshots__/presets.test.ts.snap +0 -120
- package/dist/adapters/prompts/__tests__/presets.test.js +0 -31
- package/dist/adapters/prompts/__tests__/presets.test.js.map +0 -1
- package/dist/adapters/prompts/library/categories/domain.d.ts +0 -11
- package/dist/adapters/prompts/library/categories/domain.js +0 -12
- package/dist/adapters/prompts/library/categories/domain.js.map +0 -1
- package/dist/adapters/prompts/library/categories/format.d.ts +0 -10
- package/dist/adapters/prompts/library/categories/format.js +0 -11
- package/dist/adapters/prompts/library/categories/format.js.map +0 -1
- package/dist/adapters/prompts/library/categories/foundations.d.ts +0 -12
- package/dist/adapters/prompts/library/categories/foundations.js +0 -13
- package/dist/adapters/prompts/library/categories/foundations.js.map +0 -1
- package/dist/adapters/prompts/library/categories/language.d.ts +0 -11
- package/dist/adapters/prompts/library/categories/language.js +0 -12
- package/dist/adapters/prompts/library/categories/language.js.map +0 -1
- package/dist/adapters/prompts/library/categories/persona.d.ts +0 -13
- package/dist/adapters/prompts/library/categories/persona.js +0 -14
- package/dist/adapters/prompts/library/categories/persona.js.map +0 -1
- package/dist/adapters/prompts/library/categories/response.d.ts +0 -9
- package/dist/adapters/prompts/library/categories/response.js +0 -10
- package/dist/adapters/prompts/library/categories/response.js.map +0 -1
- package/dist/adapters/prompts/library/categories/tone.d.ts +0 -9
- package/dist/adapters/prompts/library/categories/tone.js +0 -10
- package/dist/adapters/prompts/library/categories/tone.js.map +0 -1
- package/dist/adapters/prompts/library/categories/verbosity.d.ts +0 -8
- package/dist/adapters/prompts/library/categories/verbosity.js +0 -9
- package/dist/adapters/prompts/library/categories/verbosity.js.map +0 -1
- package/dist/adapters/prompts/library/index.d.ts +0 -68
- package/dist/adapters/prompts/library/index.js +0 -26
- package/dist/adapters/prompts/library/index.js.map +0 -1
- package/dist/adapters/prompts/library/presets.d.ts +0 -17
- package/dist/adapters/prompts/library/presets.js +0 -45
- package/dist/adapters/prompts/library/presets.js.map +0 -1
- package/dist/adapters/prompts/system-prompt.adapter.d.ts +0 -9
- package/dist/adapters/prompts/system-prompt.adapter.js +0 -57
- package/dist/adapters/prompts/system-prompt.adapter.js.map +0 -1
- package/dist/adapters/prompts/user-prompt.adapter.d.ts +0 -9
- package/dist/adapters/prompts/user-prompt.adapter.js +0 -57
- package/dist/adapters/prompts/user-prompt.adapter.js.map +0 -1
- package/dist/adapters/tools/safe-tool.adapter.d.ts +0 -27
- package/dist/adapters/tools/safe-tool.adapter.js +0 -283
- package/dist/adapters/tools/safe-tool.adapter.js.map +0 -1
- package/dist/adapters/utils/__tests__/ai-response-parser.test.js +0 -289
- package/dist/adapters/utils/__tests__/ai-response-parser.test.js.map +0 -1
- package/dist/adapters/utils/ai-response-parser-error.d.ts +0 -8
- package/dist/adapters/utils/ai-response-parser-error.js +0 -136
- package/dist/adapters/utils/ai-response-parser-error.js.map +0 -1
- package/dist/adapters/utils/ai-response-parser.d.ts +0 -60
- package/dist/adapters/utils/ai-response-parser.js +0 -347
- package/dist/adapters/utils/ai-response-parser.js.map +0 -1
- package/dist/ports/agent.port.d.ts +0 -17
- package/dist/ports/agent.port.js +0 -7
- package/dist/ports/agent.port.js.map +0 -1
- package/dist/ports/model.port.d.ts +0 -10
- package/dist/ports/model.port.js +0 -5
- package/dist/ports/model.port.js.map +0 -1
- package/dist/ports/prompt.port.d.ts +0 -9
- package/dist/ports/prompt.port.js +0 -5
- package/dist/ports/prompt.port.js.map +0 -1
- package/dist/ports/tool.port.d.ts +0 -11
- package/dist/ports/tool.port.js +0 -5
- package/dist/ports/tool.port.js.map +0 -1
- /package/dist/{adapters/prompts/__tests__/presets.test.d.ts → middleware/__tests__/logging.middleware.test.d.ts} +0 -0
- /package/dist/{adapters/utils/__tests__/ai-response-parser.test.d.ts → parsing/__tests__/create-schema-prompt.test.d.ts} +0 -0
|
@@ -1,283 +0,0 @@
|
|
|
1
|
-
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
2
|
-
try {
|
|
3
|
-
var info = gen[key](arg);
|
|
4
|
-
var value = info.value;
|
|
5
|
-
} catch (error) {
|
|
6
|
-
reject(error);
|
|
7
|
-
return;
|
|
8
|
-
}
|
|
9
|
-
if (info.done) {
|
|
10
|
-
resolve(value);
|
|
11
|
-
} else {
|
|
12
|
-
Promise.resolve(value).then(_next, _throw);
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
function _async_to_generator(fn) {
|
|
16
|
-
return function() {
|
|
17
|
-
var self = this, args = arguments;
|
|
18
|
-
return new Promise(function(resolve, reject) {
|
|
19
|
-
var gen = fn.apply(self, args);
|
|
20
|
-
function _next(value) {
|
|
21
|
-
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
|
|
22
|
-
}
|
|
23
|
-
function _throw(err) {
|
|
24
|
-
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
|
|
25
|
-
}
|
|
26
|
-
_next(undefined);
|
|
27
|
-
});
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
function _class_call_check(instance, Constructor) {
|
|
31
|
-
if (!(instance instanceof Constructor)) {
|
|
32
|
-
throw new TypeError("Cannot call a class as a function");
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
function _defineProperties(target, props) {
|
|
36
|
-
for(var i = 0; i < props.length; i++){
|
|
37
|
-
var descriptor = props[i];
|
|
38
|
-
descriptor.enumerable = descriptor.enumerable || false;
|
|
39
|
-
descriptor.configurable = true;
|
|
40
|
-
if ("value" in descriptor) descriptor.writable = true;
|
|
41
|
-
Object.defineProperty(target, descriptor.key, descriptor);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
function _create_class(Constructor, protoProps, staticProps) {
|
|
45
|
-
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
|
|
46
|
-
if (staticProps) _defineProperties(Constructor, staticProps);
|
|
47
|
-
return Constructor;
|
|
48
|
-
}
|
|
49
|
-
function _define_property(obj, key, value) {
|
|
50
|
-
if (key in obj) {
|
|
51
|
-
Object.defineProperty(obj, key, {
|
|
52
|
-
value: value,
|
|
53
|
-
enumerable: true,
|
|
54
|
-
configurable: true,
|
|
55
|
-
writable: true
|
|
56
|
-
});
|
|
57
|
-
} else {
|
|
58
|
-
obj[key] = value;
|
|
59
|
-
}
|
|
60
|
-
return obj;
|
|
61
|
-
}
|
|
62
|
-
function _instanceof(left, right) {
|
|
63
|
-
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
64
|
-
return !!right[Symbol.hasInstance](left);
|
|
65
|
-
} else {
|
|
66
|
-
return left instanceof right;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
function _ts_generator(thisArg, body) {
|
|
70
|
-
var f, y, t, _ = {
|
|
71
|
-
label: 0,
|
|
72
|
-
sent: function() {
|
|
73
|
-
if (t[0] & 1) throw t[1];
|
|
74
|
-
return t[1];
|
|
75
|
-
},
|
|
76
|
-
trys: [],
|
|
77
|
-
ops: []
|
|
78
|
-
}, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
79
|
-
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
|
|
80
|
-
return this;
|
|
81
|
-
}), g;
|
|
82
|
-
function verb(n) {
|
|
83
|
-
return function(v) {
|
|
84
|
-
return step([
|
|
85
|
-
n,
|
|
86
|
-
v
|
|
87
|
-
]);
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
function step(op) {
|
|
91
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
92
|
-
while(g && (g = 0, op[0] && (_ = 0)), _)try {
|
|
93
|
-
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
94
|
-
if (y = 0, t) op = [
|
|
95
|
-
op[0] & 2,
|
|
96
|
-
t.value
|
|
97
|
-
];
|
|
98
|
-
switch(op[0]){
|
|
99
|
-
case 0:
|
|
100
|
-
case 1:
|
|
101
|
-
t = op;
|
|
102
|
-
break;
|
|
103
|
-
case 4:
|
|
104
|
-
_.label++;
|
|
105
|
-
return {
|
|
106
|
-
value: op[1],
|
|
107
|
-
done: false
|
|
108
|
-
};
|
|
109
|
-
case 5:
|
|
110
|
-
_.label++;
|
|
111
|
-
y = op[1];
|
|
112
|
-
op = [
|
|
113
|
-
0
|
|
114
|
-
];
|
|
115
|
-
continue;
|
|
116
|
-
case 7:
|
|
117
|
-
op = _.ops.pop();
|
|
118
|
-
_.trys.pop();
|
|
119
|
-
continue;
|
|
120
|
-
default:
|
|
121
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
|
122
|
-
_ = 0;
|
|
123
|
-
continue;
|
|
124
|
-
}
|
|
125
|
-
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
|
126
|
-
_.label = op[1];
|
|
127
|
-
break;
|
|
128
|
-
}
|
|
129
|
-
if (op[0] === 6 && _.label < t[1]) {
|
|
130
|
-
_.label = t[1];
|
|
131
|
-
t = op;
|
|
132
|
-
break;
|
|
133
|
-
}
|
|
134
|
-
if (t && _.label < t[2]) {
|
|
135
|
-
_.label = t[2];
|
|
136
|
-
_.ops.push(op);
|
|
137
|
-
break;
|
|
138
|
-
}
|
|
139
|
-
if (t[2]) _.ops.pop();
|
|
140
|
-
_.trys.pop();
|
|
141
|
-
continue;
|
|
142
|
-
}
|
|
143
|
-
op = body.call(thisArg, _);
|
|
144
|
-
} catch (e) {
|
|
145
|
-
op = [
|
|
146
|
-
6,
|
|
147
|
-
e
|
|
148
|
-
];
|
|
149
|
-
y = 0;
|
|
150
|
-
} finally{
|
|
151
|
-
f = t = 0;
|
|
152
|
-
}
|
|
153
|
-
if (op[0] & 5) throw op[1];
|
|
154
|
-
return {
|
|
155
|
-
value: op[0] ? op[1] : void 0,
|
|
156
|
-
done: true
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
import { DynamicStructuredTool, DynamicTool } from 'langchain/tools';
|
|
161
|
-
/**
|
|
162
|
-
* Safe tool adapter that provides error handling and logging for LangChain tools
|
|
163
|
-
*/ export var SafeToolAdapter = /*#__PURE__*/ function() {
|
|
164
|
-
"use strict";
|
|
165
|
-
function SafeToolAdapter(config) {
|
|
166
|
-
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
|
|
167
|
-
_class_call_check(this, SafeToolAdapter);
|
|
168
|
-
_define_property(this, "config", void 0);
|
|
169
|
-
_define_property(this, "options", void 0);
|
|
170
|
-
_define_property(this, "dynamicTool", void 0);
|
|
171
|
-
this.config = config;
|
|
172
|
-
this.options = options;
|
|
173
|
-
var logger = options.logger, schema = options.schema;
|
|
174
|
-
if (schema) {
|
|
175
|
-
// Use DynamicStructuredTool for parameterized tools
|
|
176
|
-
this.dynamicTool = new DynamicStructuredTool({
|
|
177
|
-
description: config.description,
|
|
178
|
-
func: function(args) {
|
|
179
|
-
return _async_to_generator(function() {
|
|
180
|
-
var error, errorMessage;
|
|
181
|
-
return _ts_generator(this, function(_state) {
|
|
182
|
-
switch(_state.label){
|
|
183
|
-
case 0:
|
|
184
|
-
_state.trys.push([
|
|
185
|
-
0,
|
|
186
|
-
2,
|
|
187
|
-
,
|
|
188
|
-
3
|
|
189
|
-
]);
|
|
190
|
-
return [
|
|
191
|
-
4,
|
|
192
|
-
config.execute(args)
|
|
193
|
-
];
|
|
194
|
-
case 1:
|
|
195
|
-
return [
|
|
196
|
-
2,
|
|
197
|
-
_state.sent()
|
|
198
|
-
];
|
|
199
|
-
case 2:
|
|
200
|
-
error = _state.sent();
|
|
201
|
-
errorMessage = _instanceof(error, Error) ? error.message : String(error);
|
|
202
|
-
logger === null || logger === void 0 ? void 0 : logger.error("Unexpected error in ".concat(config.name), {
|
|
203
|
-
args: args,
|
|
204
|
-
error: errorMessage,
|
|
205
|
-
toolName: config.name
|
|
206
|
-
});
|
|
207
|
-
return [
|
|
208
|
-
2,
|
|
209
|
-
"Tool ".concat(config.name, " failed to execute")
|
|
210
|
-
];
|
|
211
|
-
case 3:
|
|
212
|
-
return [
|
|
213
|
-
2
|
|
214
|
-
];
|
|
215
|
-
}
|
|
216
|
-
});
|
|
217
|
-
})();
|
|
218
|
-
},
|
|
219
|
-
name: config.name,
|
|
220
|
-
schema: schema
|
|
221
|
-
});
|
|
222
|
-
} else {
|
|
223
|
-
// Use DynamicTool for simple tools
|
|
224
|
-
this.dynamicTool = new DynamicTool({
|
|
225
|
-
description: config.description,
|
|
226
|
-
func: function() {
|
|
227
|
-
return _async_to_generator(function() {
|
|
228
|
-
var error, errorMessage;
|
|
229
|
-
return _ts_generator(this, function(_state) {
|
|
230
|
-
switch(_state.label){
|
|
231
|
-
case 0:
|
|
232
|
-
_state.trys.push([
|
|
233
|
-
0,
|
|
234
|
-
2,
|
|
235
|
-
,
|
|
236
|
-
3
|
|
237
|
-
]);
|
|
238
|
-
return [
|
|
239
|
-
4,
|
|
240
|
-
config.execute()
|
|
241
|
-
];
|
|
242
|
-
case 1:
|
|
243
|
-
return [
|
|
244
|
-
2,
|
|
245
|
-
_state.sent()
|
|
246
|
-
];
|
|
247
|
-
case 2:
|
|
248
|
-
error = _state.sent();
|
|
249
|
-
errorMessage = _instanceof(error, Error) ? error.message : String(error);
|
|
250
|
-
logger === null || logger === void 0 ? void 0 : logger.error("Unexpected error in ".concat(config.name), {
|
|
251
|
-
error: errorMessage,
|
|
252
|
-
toolName: config.name
|
|
253
|
-
});
|
|
254
|
-
return [
|
|
255
|
-
2,
|
|
256
|
-
"Tool ".concat(config.name, " failed to execute")
|
|
257
|
-
];
|
|
258
|
-
case 3:
|
|
259
|
-
return [
|
|
260
|
-
2
|
|
261
|
-
];
|
|
262
|
-
}
|
|
263
|
-
});
|
|
264
|
-
})();
|
|
265
|
-
},
|
|
266
|
-
name: config.name
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
_create_class(SafeToolAdapter, [
|
|
271
|
-
{
|
|
272
|
-
/**
|
|
273
|
-
* Get the underlying LangChain DynamicTool instance
|
|
274
|
-
*/ key: "getDynamicTool",
|
|
275
|
-
value: function getDynamicTool() {
|
|
276
|
-
return this.dynamicTool;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
]);
|
|
280
|
-
return SafeToolAdapter;
|
|
281
|
-
}();
|
|
282
|
-
|
|
283
|
-
//# sourceMappingURL=safe-tool.adapter.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/adapters/tools/safe-tool.adapter.ts"],"sourcesContent":["import type { LoggerPort } from '@jterrazz/logger';\nimport { DynamicStructuredTool, DynamicTool } from 'langchain/tools';\nimport type { z } from 'zod/v4';\n\nimport type { ToolPort } from '../../ports/tool.port.js';\n\nexport interface SafeToolOptions<T> {\n logger?: LoggerPort;\n schema?: z.ZodSchema<T>;\n}\n\nexport type ToolConfig<T = void> = {\n description: string;\n execute: ToolFunction<T>;\n name: string;\n};\n\nexport type ToolFunction<T = void> = T extends void\n ? () => Promise<string>\n : (args: T) => Promise<string>;\n\n/**\n * Safe tool adapter that provides error handling and logging for LangChain tools\n */\nexport class SafeToolAdapter<T = void> implements ToolPort {\n private readonly dynamicTool: DynamicStructuredTool<z.ZodSchema<T>> | DynamicTool;\n\n constructor(\n private readonly config: ToolConfig<T>,\n private readonly options: SafeToolOptions<T> = {},\n ) {\n const { logger, schema } = options;\n\n if (schema) {\n // Use DynamicStructuredTool for parameterized tools\n this.dynamicTool = new DynamicStructuredTool({\n description: config.description,\n func: async (args: T) => {\n try {\n return await (config.execute as ToolFunction<T>)(args);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n logger?.error(`Unexpected error in ${config.name}`, {\n args,\n error: errorMessage,\n toolName: config.name,\n });\n\n return `Tool ${config.name} failed to execute`;\n }\n },\n name: config.name,\n schema: schema,\n });\n } else {\n // Use DynamicTool for simple tools\n this.dynamicTool = new DynamicTool({\n description: config.description,\n func: async () => {\n try {\n return await (config.execute as ToolFunction<void>)();\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n logger?.error(`Unexpected error in ${config.name}`, {\n error: errorMessage,\n toolName: config.name,\n });\n\n return `Tool ${config.name} failed to execute`;\n }\n },\n name: config.name,\n });\n }\n }\n\n /**\n * Get the underlying LangChain DynamicTool instance\n */\n getDynamicTool(): DynamicStructuredTool<z.ZodSchema<unknown>> | DynamicTool {\n return this.dynamicTool as DynamicStructuredTool<z.ZodSchema<unknown>> | DynamicTool;\n }\n}\n"],"names":["DynamicStructuredTool","DynamicTool","SafeToolAdapter","config","options","dynamicTool","logger","schema","description","func","args","error","errorMessage","execute","Error","message","String","name","toolName","getDynamicTool"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,qBAAqB,EAAEC,WAAW,QAAQ,kBAAkB;AAoBrE;;CAEC,GACD,OAAO,IAAA,AAAMC,gCAAN;;aAAMA,gBAIL,AAAiBC,MAAqB;YACtC,AAAiBC,UAAjB,iEAA+C,CAAC;gCAL3CF;;;QACT,uBAAiBG,eAAjB,KAAA;aAGqBF,SAAAA;aACAC,UAAAA;QAEjB,IAAQE,SAAmBF,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@ -1,289 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from '@jterrazz/test';
|
|
2
|
-
import { z } from 'zod/v4';
|
|
3
|
-
import { AIResponseParser } from '../ai-response-parser.js';
|
|
4
|
-
import { AIResponseParserError } from '../ai-response-parser-error.js';
|
|
5
|
-
// Test data
|
|
6
|
-
var testSchema = z.object({
|
|
7
|
-
content: z.string(),
|
|
8
|
-
tags: z.array(z.string()),
|
|
9
|
-
title: z.string()
|
|
10
|
-
});
|
|
11
|
-
var validJson = {
|
|
12
|
-
content: 'Test content',
|
|
13
|
-
tags: [
|
|
14
|
-
'test',
|
|
15
|
-
'ai'
|
|
16
|
-
],
|
|
17
|
-
title: 'Test Article'
|
|
18
|
-
};
|
|
19
|
-
var validJsonString = JSON.stringify(validJson);
|
|
20
|
-
describe('AIResponseParser', function() {
|
|
21
|
-
describe('parse', function() {
|
|
22
|
-
it('should parse valid JSON object', function() {
|
|
23
|
-
// Given - a valid JSON object string and parser
|
|
24
|
-
var text = validJsonString;
|
|
25
|
-
var parser = new AIResponseParser(testSchema);
|
|
26
|
-
// When - parsing the string
|
|
27
|
-
var result = parser.parse(text);
|
|
28
|
-
// Then - it should return the parsed object
|
|
29
|
-
expect(result).toEqual(validJson);
|
|
30
|
-
});
|
|
31
|
-
it('should parse JSON object with surrounding text', function() {
|
|
32
|
-
// Given - a JSON object string with surrounding text and parser
|
|
33
|
-
var text = "Here's the article: ".concat(validJsonString, " - end of article");
|
|
34
|
-
var parser = new AIResponseParser(testSchema);
|
|
35
|
-
// When - parsing the string
|
|
36
|
-
var result = parser.parse(text);
|
|
37
|
-
// Then - it should return the parsed object
|
|
38
|
-
expect(result).toEqual(validJson);
|
|
39
|
-
});
|
|
40
|
-
it('should parse array response', function() {
|
|
41
|
-
// Given - a JSON array string and array parser
|
|
42
|
-
var arraySchema = z.array(z.string());
|
|
43
|
-
var text = '["test", "ai", "content"]';
|
|
44
|
-
var parser = new AIResponseParser(arraySchema);
|
|
45
|
-
// When - parsing the string
|
|
46
|
-
var result = parser.parse(text);
|
|
47
|
-
// Then - it should return the parsed array
|
|
48
|
-
expect(result).toEqual([
|
|
49
|
-
'test',
|
|
50
|
-
'ai',
|
|
51
|
-
'content'
|
|
52
|
-
]);
|
|
53
|
-
});
|
|
54
|
-
it('should parse primitive string value', function() {
|
|
55
|
-
// Given - a JSON string value and string parser
|
|
56
|
-
var text = '"test string"';
|
|
57
|
-
var parser = new AIResponseParser(z.string());
|
|
58
|
-
// When - parsing the string
|
|
59
|
-
var result = parser.parse(text);
|
|
60
|
-
// Then - it should return the parsed string
|
|
61
|
-
expect(result).toBe('test string');
|
|
62
|
-
});
|
|
63
|
-
it('should parse primitive number value', function() {
|
|
64
|
-
// Given - a JSON number value and number parser
|
|
65
|
-
var text = '42';
|
|
66
|
-
var parser = new AIResponseParser(z.number());
|
|
67
|
-
// When - parsing the string
|
|
68
|
-
var result = parser.parse(text);
|
|
69
|
-
// Then - it should return the parsed number
|
|
70
|
-
expect(result).toBe(42);
|
|
71
|
-
});
|
|
72
|
-
it('should parse primitive boolean value', function() {
|
|
73
|
-
// Given - a JSON boolean value and boolean parser
|
|
74
|
-
var text = 'true';
|
|
75
|
-
var parser = new AIResponseParser(z["boolean"]());
|
|
76
|
-
// When - parsing the string
|
|
77
|
-
var result = parser.parse(text);
|
|
78
|
-
// Then - it should return the parsed boolean
|
|
79
|
-
expect(result).toBe(true);
|
|
80
|
-
});
|
|
81
|
-
it('should parse primitive null value', function() {
|
|
82
|
-
// Given - a JSON null value and null parser
|
|
83
|
-
var text = 'null';
|
|
84
|
-
var parser = new AIResponseParser(z["null"]());
|
|
85
|
-
// When - parsing the string
|
|
86
|
-
var result = parser.parse(text);
|
|
87
|
-
// Then - it should return the parsed null
|
|
88
|
-
expect(result).toBeNull();
|
|
89
|
-
});
|
|
90
|
-
it('should throw ResponseParsingError when JSON is invalid', function() {
|
|
91
|
-
// Given - an invalid JSON string and parser
|
|
92
|
-
var text = '{invalid json}';
|
|
93
|
-
var parser = new AIResponseParser(testSchema);
|
|
94
|
-
// When/Then - parsing the string should throw a ResponseParsingError
|
|
95
|
-
expect(function() {
|
|
96
|
-
return parser.parse(text);
|
|
97
|
-
}).toThrow(AIResponseParserError);
|
|
98
|
-
});
|
|
99
|
-
it('should throw ResponseParsingError when schema validation fails', function() {
|
|
100
|
-
// Given - an invalid JSON object and parser
|
|
101
|
-
var invalidJson = {
|
|
102
|
-
// Should be string
|
|
103
|
-
content: 'Test content',
|
|
104
|
-
tags: [
|
|
105
|
-
'test',
|
|
106
|
-
'ai'
|
|
107
|
-
],
|
|
108
|
-
title: 123
|
|
109
|
-
};
|
|
110
|
-
var text = JSON.stringify(invalidJson);
|
|
111
|
-
var parser = new AIResponseParser(testSchema);
|
|
112
|
-
// When/Then - parsing the string should throw a ResponseParsingError
|
|
113
|
-
expect(function() {
|
|
114
|
-
return parser.parse(text);
|
|
115
|
-
}).toThrow(AIResponseParserError);
|
|
116
|
-
});
|
|
117
|
-
it('should throw ResponseParsingError when no object found in text', function() {
|
|
118
|
-
// Given - a text without a JSON object and parser
|
|
119
|
-
var text = 'No JSON object here';
|
|
120
|
-
var parser = new AIResponseParser(testSchema);
|
|
121
|
-
// When/Then - parsing the string should throw a ResponseParsingError
|
|
122
|
-
expect(function() {
|
|
123
|
-
return parser.parse(text);
|
|
124
|
-
}).toThrow(AIResponseParserError);
|
|
125
|
-
});
|
|
126
|
-
it('should throw ResponseParsingError when no array found in text', function() {
|
|
127
|
-
// Given - a text without a JSON array and array parser
|
|
128
|
-
var text = 'No array here';
|
|
129
|
-
var arraySchema = z.array(z.string());
|
|
130
|
-
var parser = new AIResponseParser(arraySchema);
|
|
131
|
-
// When/Then - parsing the string should throw a ResponseParsingError
|
|
132
|
-
expect(function() {
|
|
133
|
-
return parser.parse(text);
|
|
134
|
-
}).toThrow(AIResponseParserError);
|
|
135
|
-
});
|
|
136
|
-
it('should throw ResponseParsingError for unsupported schema type', function() {
|
|
137
|
-
// Given - a text with an unsupported schema type and parser
|
|
138
|
-
var text = 'test';
|
|
139
|
-
var unsupportedSchema = z.union([
|
|
140
|
-
z.string(),
|
|
141
|
-
z.number()
|
|
142
|
-
]);
|
|
143
|
-
var parser = new AIResponseParser(unsupportedSchema);
|
|
144
|
-
// When/Then - parsing the string should throw a ResponseParsingError
|
|
145
|
-
expect(function() {
|
|
146
|
-
return parser.parse(text);
|
|
147
|
-
}).toThrow(AIResponseParserError);
|
|
148
|
-
});
|
|
149
|
-
it('should include original text in error when parsing fails', function() {
|
|
150
|
-
// Given - an invalid JSON string and parser
|
|
151
|
-
var text = '{invalid json}';
|
|
152
|
-
var parser = new AIResponseParser(testSchema);
|
|
153
|
-
// When - parsing the string
|
|
154
|
-
try {
|
|
155
|
-
parser.parse(text);
|
|
156
|
-
throw new Error('Should have thrown an error');
|
|
157
|
-
} catch (error) {
|
|
158
|
-
// Then - the error should include the original text
|
|
159
|
-
expect(error).toBeInstanceOf(AIResponseParserError);
|
|
160
|
-
expect(error.text).toBe(text);
|
|
161
|
-
}
|
|
162
|
-
});
|
|
163
|
-
it('should handle text with newlines in JSON object', function() {
|
|
164
|
-
// Given - a JSON object with newlines and parser
|
|
165
|
-
var textWithNewlines = '{\n "content": "Test\ncontent\nwith\nnewlines",\n "tags": ["test", "ai"],\n "title": "Test\nArticle"\n }';
|
|
166
|
-
var parser = new AIResponseParser(testSchema);
|
|
167
|
-
// When - parsing the string
|
|
168
|
-
var result = parser.parse(textWithNewlines);
|
|
169
|
-
// Then - it should return the parsed object
|
|
170
|
-
expect(result).toEqual({
|
|
171
|
-
content: 'Test content with newlines',
|
|
172
|
-
tags: [
|
|
173
|
-
'test',
|
|
174
|
-
'ai'
|
|
175
|
-
],
|
|
176
|
-
title: 'Test Article'
|
|
177
|
-
});
|
|
178
|
-
});
|
|
179
|
-
it('should handle text with newlines in surrounding text', function() {
|
|
180
|
-
// Given - a text with newlines around the JSON object and parser
|
|
181
|
-
var textWithNewlines = "Here's the\narticle:\n".concat(validJsonString, "\n- end of\narticle");
|
|
182
|
-
var parser = new AIResponseParser(testSchema);
|
|
183
|
-
// When - parsing the string
|
|
184
|
-
var result = parser.parse(textWithNewlines);
|
|
185
|
-
// Then - it should return the parsed object
|
|
186
|
-
expect(result).toEqual(validJson);
|
|
187
|
-
});
|
|
188
|
-
it('should handle text with multiple consecutive newlines and spaces', function() {
|
|
189
|
-
// Given - a text with multiple consecutive newlines and spaces and parser
|
|
190
|
-
var textWithNewlines = "Here's the\n\n article: \n\n".concat(validJsonString, "\n\n");
|
|
191
|
-
var parser = new AIResponseParser(testSchema);
|
|
192
|
-
// When - parsing the string
|
|
193
|
-
var result = parser.parse(textWithNewlines);
|
|
194
|
-
// Then - it should return the parsed object
|
|
195
|
-
expect(result).toEqual(validJson);
|
|
196
|
-
});
|
|
197
|
-
it('should handle escaped characters in JSON', function() {
|
|
198
|
-
// Given - a JSON string with escaped characters and parser
|
|
199
|
-
var text = '{"content": "Test\\ncontent\\twith\\r\\nescapes", "tags": ["test\\u0020ai", "escaped\\"quotes\\""], "title": "Test\\\\Article"}';
|
|
200
|
-
var parser = new AIResponseParser(testSchema);
|
|
201
|
-
// When - parsing the string
|
|
202
|
-
var result = parser.parse(text);
|
|
203
|
-
// Then - it should return the parsed object
|
|
204
|
-
expect(result).toEqual({
|
|
205
|
-
content: 'Test\ncontent\twith\r\nescapes',
|
|
206
|
-
tags: [
|
|
207
|
-
'test ai',
|
|
208
|
-
'escaped"quotes"'
|
|
209
|
-
],
|
|
210
|
-
title: 'Test\\Article'
|
|
211
|
-
});
|
|
212
|
-
});
|
|
213
|
-
it('should handle escaped characters in markdown code blocks', function() {
|
|
214
|
-
// Given - a markdown code block with escaped characters and parser
|
|
215
|
-
var text = '```json\n{"content": "Test\\nContent", "tags": ["test\\u0020ai"], "title": "Test\\\\Title"}\n```';
|
|
216
|
-
var parser = new AIResponseParser(testSchema);
|
|
217
|
-
// When - parsing the string
|
|
218
|
-
var result = parser.parse(text);
|
|
219
|
-
// Then - it should return the parsed object
|
|
220
|
-
expect(result).toEqual({
|
|
221
|
-
content: 'Test\nContent',
|
|
222
|
-
tags: [
|
|
223
|
-
'test ai'
|
|
224
|
-
],
|
|
225
|
-
title: 'Test\\Title'
|
|
226
|
-
});
|
|
227
|
-
});
|
|
228
|
-
it('should handle escaped characters in markdown code blocks', function() {
|
|
229
|
-
// Given - a markdown code block with escaped characters and array parser
|
|
230
|
-
var text = '```json\n [\n{"content": "Test\\nContent", "tags": ["test\\u0020ai"], "title": "Test\\\\Title"}\n]\n```';
|
|
231
|
-
var arraySchema = z.array(testSchema);
|
|
232
|
-
var parser = new AIResponseParser(arraySchema);
|
|
233
|
-
// When - parsing the string
|
|
234
|
-
var result = parser.parse(text);
|
|
235
|
-
// Then - it should return the parsed array
|
|
236
|
-
expect(result).toEqual([
|
|
237
|
-
{
|
|
238
|
-
content: 'Test\nContent',
|
|
239
|
-
tags: [
|
|
240
|
-
'test ai'
|
|
241
|
-
],
|
|
242
|
-
title: 'Test\\Title'
|
|
243
|
-
}
|
|
244
|
-
]);
|
|
245
|
-
});
|
|
246
|
-
it('should parse complex NBA trade analysis JSON with escaped quotes', function() {
|
|
247
|
-
// Given - a complex JSON object with nested structures and escaped quotes in markdown
|
|
248
|
-
var complexSchema = z.object({
|
|
249
|
-
category: z.string(),
|
|
250
|
-
countries: z.array(z.string()),
|
|
251
|
-
perspectives: z.array(z.object({
|
|
252
|
-
holisticDigest: z.string(),
|
|
253
|
-
tags: z.object({
|
|
254
|
-
discourse_type: z.string(),
|
|
255
|
-
stance: z.string()
|
|
256
|
-
})
|
|
257
|
-
})),
|
|
258
|
-
synopsis: z.string()
|
|
259
|
-
});
|
|
260
|
-
var text = '```json\n{\n "category": "sports",\n "countries": [\n "us"\n ],\n "perspectives": [\n {\n "holisticDigest": "The NBA offseason has seen a massive blockbuster trade as the Phoenix Suns have sent Kevin Durant to the Houston Rockets. The Rockets are acquiring Durant in exchange for Jalen Green, Dillon Brooks, the No. 10 pick in the 2025 NBA draft, and five second-round picks. This move significantly boosts the Rockets\' championship aspirations, positioning them as immediate contenders in the Western Conference alongside established teams. Durant, a future Hall of Famer, is expected to provide elite scoring and shot creation, addressing the Rockets\' previous offensive struggles in the half-court, particularly in the playoffs. Durant\'s decision to list Houston as a preferred destination suggests a potential long-term commitment, with an extension likely upon the opening of the new league year. For the Suns, this trade represents a pivot towards rebuilding, allowing them to acquire young talent and draft assets after their "Big 3" experiment failed to yield a championship. The Suns\' return is viewed by some analysts as lacking compared to Durant\'s caliber, but it does provide them with a reset and a chance to retool around Devin Booker and the draft picks. The specifics of the deal, including Dillon Brooks\' contract and the distribution of second-round picks, have also been highlighted as key elements enabling the trade to go through. The Rockets\' odds to win the NBA title have shortened considerably following the acquisition.",\n "tags": {\n "discourse_type": "mainstream",\n "stance": "neutral"\n }\n }\n ],\n "synopsis": "This collection of articles reports on a major NBA trade where the Phoenix Suns have sent veteran superstar Kevin Durant to the Houston Rockets. The Rockets have acquired Durant in exchange for a package that includes young players Jalen Green and Dillon Brooks, as well as the No. 10 pick in the 2025 NBA draft and five second-round picks. The trade is seen as a significant move that immediately elevates the Rockets into championship contention in the Western Conference. For the Suns, the deal signals a shift towards rebuilding, acquiring young assets and draft capital after their pursuit of a championship with Durant did not come to fruition. Analysis within the articles discusses the potential impact of Durant on the Rockets\' offense and their championship odds, as well as the Suns\' strategy in moving forward after this blockbuster deal. The player himself was reportedly informed of the trade while on stage at an event, offering a brief, somewhat non-committal reaction to the news."\n}\n```';
|
|
261
|
-
var parser = new AIResponseParser(complexSchema);
|
|
262
|
-
// When - parsing the string
|
|
263
|
-
var result = parser.parse(text);
|
|
264
|
-
// Then - it should return the parsed object with escaped quotes properly handled
|
|
265
|
-
expect(result).toEqual({
|
|
266
|
-
category: 'sports',
|
|
267
|
-
countries: [
|
|
268
|
-
'us'
|
|
269
|
-
],
|
|
270
|
-
perspectives: [
|
|
271
|
-
{
|
|
272
|
-
holisticDigest: expect.stringContaining('The NBA offseason has seen a massive blockbuster trade'),
|
|
273
|
-
tags: {
|
|
274
|
-
discourse_type: 'mainstream',
|
|
275
|
-
stance: 'neutral'
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
],
|
|
279
|
-
synopsis: expect.stringContaining('This collection of articles reports on a major NBA trade')
|
|
280
|
-
});
|
|
281
|
-
// Additional verification for escaped quotes handling
|
|
282
|
-
expect(result.perspectives[0].holisticDigest).toContain('"Big 3" experiment');
|
|
283
|
-
expect(result.perspectives[0].holisticDigest).toContain("Rockets' championship aspirations");
|
|
284
|
-
expect(result.perspectives[0].holisticDigest).toContain("Durant's decision");
|
|
285
|
-
});
|
|
286
|
-
});
|
|
287
|
-
});
|
|
288
|
-
|
|
289
|
-
//# sourceMappingURL=ai-response-parser.test.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/adapters/utils/__tests__/ai-response-parser.test.ts"],"sourcesContent":["import { describe, expect, it } from '@jterrazz/test';\nimport { z } from 'zod/v4';\n\nimport { AIResponseParser } from '../ai-response-parser.js';\nimport { AIResponseParserError } from '../ai-response-parser-error.js';\n\n// Test data\nconst testSchema = z.object({\n content: z.string(),\n tags: z.array(z.string()),\n title: z.string(),\n});\n\nconst validJson = {\n content: 'Test content',\n tags: ['test', 'ai'],\n title: 'Test Article',\n};\n\nconst validJsonString = JSON.stringify(validJson);\n\ndescribe('AIResponseParser', () => {\n describe('parse', () => {\n it('should parse valid JSON object', () => {\n // Given - a valid JSON object string and parser\n const text = validJsonString;\n const parser = new AIResponseParser(testSchema);\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed object\n expect(result).toEqual(validJson);\n });\n\n it('should parse JSON object with surrounding text', () => {\n // Given - a JSON object string with surrounding text and parser\n const text = `Here's the article: ${validJsonString} - end of article`;\n const parser = new AIResponseParser(testSchema);\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed object\n expect(result).toEqual(validJson);\n });\n\n it('should parse array response', () => {\n // Given - a JSON array string and array parser\n const arraySchema = z.array(z.string());\n const text = '[\"test\", \"ai\", \"content\"]';\n const parser = new AIResponseParser(arraySchema);\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed array\n expect(result).toEqual(['test', 'ai', 'content']);\n });\n\n it('should parse primitive string value', () => {\n // Given - a JSON string value and string parser\n const text = '\"test string\"';\n const parser = new AIResponseParser(z.string());\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed string\n expect(result).toBe('test string');\n });\n\n it('should parse primitive number value', () => {\n // Given - a JSON number value and number parser\n const text = '42';\n const parser = new AIResponseParser(z.number());\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed number\n expect(result).toBe(42);\n });\n\n it('should parse primitive boolean value', () => {\n // Given - a JSON boolean value and boolean parser\n const text = 'true';\n const parser = new AIResponseParser(z.boolean());\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed boolean\n expect(result).toBe(true);\n });\n\n it('should parse primitive null value', () => {\n // Given - a JSON null value and null parser\n const text = 'null';\n const parser = new AIResponseParser(z.null());\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed null\n expect(result).toBeNull();\n });\n\n it('should throw ResponseParsingError when JSON is invalid', () => {\n // Given - an invalid JSON string and parser\n const text = '{invalid json}';\n const parser = new AIResponseParser(testSchema);\n\n // When/Then - parsing the string should throw a ResponseParsingError\n expect(() => parser.parse(text)).toThrow(AIResponseParserError);\n });\n\n it('should throw ResponseParsingError when schema validation fails', () => {\n // Given - an invalid JSON object and parser\n const invalidJson = {\n // Should be string\n content: 'Test content',\n tags: ['test', 'ai'],\n title: 123,\n };\n const text = JSON.stringify(invalidJson);\n const parser = new AIResponseParser(testSchema);\n\n // When/Then - parsing the string should throw a ResponseParsingError\n expect(() => parser.parse(text)).toThrow(AIResponseParserError);\n });\n\n it('should throw ResponseParsingError when no object found in text', () => {\n // Given - a text without a JSON object and parser\n const text = 'No JSON object here';\n const parser = new AIResponseParser(testSchema);\n\n // When/Then - parsing the string should throw a ResponseParsingError\n expect(() => parser.parse(text)).toThrow(AIResponseParserError);\n });\n\n it('should throw ResponseParsingError when no array found in text', () => {\n // Given - a text without a JSON array and array parser\n const text = 'No array here';\n const arraySchema = z.array(z.string());\n const parser = new AIResponseParser(arraySchema);\n\n // When/Then - parsing the string should throw a ResponseParsingError\n expect(() => parser.parse(text)).toThrow(AIResponseParserError);\n });\n\n it('should throw ResponseParsingError for unsupported schema type', () => {\n // Given - a text with an unsupported schema type and parser\n const text = 'test';\n const unsupportedSchema = z.union([z.string(), z.number()]);\n const parser = new AIResponseParser(unsupportedSchema);\n\n // When/Then - parsing the string should throw a ResponseParsingError\n expect(() => parser.parse(text)).toThrow(AIResponseParserError);\n });\n\n it('should include original text in error when parsing fails', () => {\n // Given - an invalid JSON string and parser\n const text = '{invalid json}';\n const parser = new AIResponseParser(testSchema);\n\n // When - parsing the string\n try {\n parser.parse(text);\n throw new Error('Should have thrown an error');\n } catch (error) {\n // Then - the error should include the original text\n expect(error).toBeInstanceOf(AIResponseParserError);\n expect((error as AIResponseParserError).text).toBe(text);\n }\n });\n\n it('should handle text with newlines in JSON object', () => {\n // Given - a JSON object with newlines and parser\n const textWithNewlines = `{\n \"content\": \"Test\\ncontent\\nwith\\nnewlines\",\n \"tags\": [\"test\", \"ai\"],\n \"title\": \"Test\\nArticle\"\n }`;\n const parser = new AIResponseParser(testSchema);\n\n // When - parsing the string\n const result = parser.parse(textWithNewlines);\n\n // Then - it should return the parsed object\n expect(result).toEqual({\n content: 'Test content with newlines',\n tags: ['test', 'ai'],\n title: 'Test Article',\n });\n });\n\n it('should handle text with newlines in surrounding text', () => {\n // Given - a text with newlines around the JSON object and parser\n const textWithNewlines = `Here's the\\narticle:\\n${validJsonString}\\n- end of\\narticle`;\n const parser = new AIResponseParser(testSchema);\n\n // When - parsing the string\n const result = parser.parse(textWithNewlines);\n\n // Then - it should return the parsed object\n expect(result).toEqual(validJson);\n });\n\n it('should handle text with multiple consecutive newlines and spaces', () => {\n // Given - a text with multiple consecutive newlines and spaces and parser\n const textWithNewlines = `Here's the\\n\\n article: \\n\\n${validJsonString}\\n\\n`;\n const parser = new AIResponseParser(testSchema);\n\n // When - parsing the string\n const result = parser.parse(textWithNewlines);\n\n // Then - it should return the parsed object\n expect(result).toEqual(validJson);\n });\n\n it('should handle escaped characters in JSON', () => {\n // Given - a JSON string with escaped characters and parser\n const text =\n '{\"content\": \"Test\\\\ncontent\\\\twith\\\\r\\\\nescapes\", \"tags\": [\"test\\\\u0020ai\", \"escaped\\\\\"quotes\\\\\"\"], \"title\": \"Test\\\\\\\\Article\"}';\n const parser = new AIResponseParser(testSchema);\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed object\n expect(result).toEqual({\n content: 'Test\\ncontent\\twith\\r\\nescapes',\n tags: ['test ai', 'escaped\"quotes\"'],\n title: 'Test\\\\Article',\n });\n });\n\n it('should handle escaped characters in markdown code blocks', () => {\n // Given - a markdown code block with escaped characters and parser\n const text =\n '```json\\n{\"content\": \"Test\\\\nContent\", \"tags\": [\"test\\\\u0020ai\"], \"title\": \"Test\\\\\\\\Title\"}\\n```';\n const parser = new AIResponseParser(testSchema);\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed object\n expect(result).toEqual({\n content: 'Test\\nContent',\n tags: ['test ai'],\n title: 'Test\\\\Title',\n });\n });\n\n it('should handle escaped characters in markdown code blocks', () => {\n // Given - a markdown code block with escaped characters and array parser\n const text =\n '```json\\n [\\n{\"content\": \"Test\\\\nContent\", \"tags\": [\"test\\\\u0020ai\"], \"title\": \"Test\\\\\\\\Title\"}\\n]\\n```';\n const arraySchema = z.array(testSchema);\n const parser = new AIResponseParser(arraySchema);\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed array\n expect(result).toEqual([\n {\n content: 'Test\\nContent',\n tags: ['test ai'],\n title: 'Test\\\\Title',\n },\n ]);\n });\n\n it('should parse complex NBA trade analysis JSON with escaped quotes', () => {\n // Given - a complex JSON object with nested structures and escaped quotes in markdown\n const complexSchema = z.object({\n category: z.string(),\n countries: z.array(z.string()),\n perspectives: z.array(\n z.object({\n holisticDigest: z.string(),\n tags: z.object({\n discourse_type: z.string(),\n stance: z.string(),\n }),\n }),\n ),\n synopsis: z.string(),\n });\n\n const text =\n '```json\\n{\\n \"category\": \"sports\",\\n \"countries\": [\\n \"us\"\\n ],\\n \"perspectives\": [\\n {\\n \"holisticDigest\": \"The NBA offseason has seen a massive blockbuster trade as the Phoenix Suns have sent Kevin Durant to the Houston Rockets. The Rockets are acquiring Durant in exchange for Jalen Green, Dillon Brooks, the No. 10 pick in the 2025 NBA draft, and five second-round picks. This move significantly boosts the Rockets\\' championship aspirations, positioning them as immediate contenders in the Western Conference alongside established teams. Durant, a future Hall of Famer, is expected to provide elite scoring and shot creation, addressing the Rockets\\' previous offensive struggles in the half-court, particularly in the playoffs. Durant\\'s decision to list Houston as a preferred destination suggests a potential long-term commitment, with an extension likely upon the opening of the new league year. For the Suns, this trade represents a pivot towards rebuilding, allowing them to acquire young talent and draft assets after their \"Big 3\" experiment failed to yield a championship. The Suns\\' return is viewed by some analysts as lacking compared to Durant\\'s caliber, but it does provide them with a reset and a chance to retool around Devin Booker and the draft picks. The specifics of the deal, including Dillon Brooks\\' contract and the distribution of second-round picks, have also been highlighted as key elements enabling the trade to go through. The Rockets\\' odds to win the NBA title have shortened considerably following the acquisition.\",\\n \"tags\": {\\n \"discourse_type\": \"mainstream\",\\n \"stance\": \"neutral\"\\n }\\n }\\n ],\\n \"synopsis\": \"This collection of articles reports on a major NBA trade where the Phoenix Suns have sent veteran superstar Kevin Durant to the Houston Rockets. The Rockets have acquired Durant in exchange for a package that includes young players Jalen Green and Dillon Brooks, as well as the No. 10 pick in the 2025 NBA draft and five second-round picks. The trade is seen as a significant move that immediately elevates the Rockets into championship contention in the Western Conference. For the Suns, the deal signals a shift towards rebuilding, acquiring young assets and draft capital after their pursuit of a championship with Durant did not come to fruition. Analysis within the articles discusses the potential impact of Durant on the Rockets\\' offense and their championship odds, as well as the Suns\\' strategy in moving forward after this blockbuster deal. The player himself was reportedly informed of the trade while on stage at an event, offering a brief, somewhat non-committal reaction to the news.\"\\n}\\n```';\n\n const parser = new AIResponseParser(complexSchema);\n\n // When - parsing the string\n const result = parser.parse(text);\n\n // Then - it should return the parsed object with escaped quotes properly handled\n expect(result).toEqual({\n category: 'sports',\n countries: ['us'],\n perspectives: [\n {\n holisticDigest: expect.stringContaining(\n 'The NBA offseason has seen a massive blockbuster trade',\n ),\n tags: {\n discourse_type: 'mainstream',\n stance: 'neutral',\n },\n },\n ],\n synopsis: expect.stringContaining(\n 'This collection of articles reports on a major NBA trade',\n ),\n });\n\n // Additional verification for escaped quotes handling\n expect(result.perspectives[0].holisticDigest).toContain('\"Big 3\" experiment');\n expect(result.perspectives[0].holisticDigest).toContain(\n \"Rockets' championship aspirations\",\n );\n expect(result.perspectives[0].holisticDigest).toContain(\"Durant's decision\");\n });\n });\n});\n"],"names":["describe","expect","it","z","AIResponseParser","AIResponseParserError","testSchema","object","content","string","tags","array","title","validJson","validJsonString","JSON","stringify","text","parser","result","parse","toEqual","arraySchema","toBe","number","boolean","null","toBeNull","toThrow","invalidJson","unsupportedSchema","union","Error","error","toBeInstanceOf","textWithNewlines","complexSchema","category","countries","perspectives","holisticDigest","discourse_type","stance","synopsis","stringContaining","toContain"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,iBAAiB;AACtD,SAASC,CAAC,QAAQ,SAAS;AAE3B,SAASC,gBAAgB,QAAQ,2BAA2B;AAC5D,SAASC,qBAAqB,QAAQ,iCAAiC;AAEvE,YAAY;AACZ,IAAMC,aAAaH,EAAEI,MAAM,CAAC;IACxBC,SAASL,EAAEM,MAAM;IACjBC,MAAMP,EAAEQ,KAAK,CAACR,EAAEM,MAAM;IACtBG,OAAOT,EAAEM,MAAM;AACnB;AAEA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ACtF,IAAMkC,gBAAgBjC,EAAEI,MAAM,CAAC;gBAC3B8B,UAAUlC,EAAEM,MAAM;gBAClB6B,WAAWnC,EAAEQ,KAAK,CAACR,EAAEM,MAAM;gBAC3B8B,cAAcpC,EAAEQ,KAAK,CACjBR,EAAEI,MAAM,CAAC;oBACLiC,gBAAgBrC,EAAEM,MAAM;oBACxBC,MAAMP,EAAEI,MAAM,CAAC;wBACXkC,gBAAgBtC,EAAEM,MAAM;wBACxBiC,QAAQvC,EAAEM,MAAM;oBACpB;gBACJ;gBAEJkC,UAAUxC,EAAEM,MAAM;YACtB;YAEA,IAAMQ,OACF;YAEJ,IAAMC,SAAS,IAAId,iBAAiBgC;YAEpC,4BAA4B;YAC5B,IAAMjB,SAASD,OAAOE,KAAK,CAACH;YAE5B,iFAAiF;YACjFhB,OAAOkB,QAAQE,OAAO,CAAC;gBACnBgB,UAAU;gBACVC,WAAW;oBAAC;iBAAK;gBACjBC,cAAc;oBACV;wBACIC,gBAAgBvC,OAAO2C,gBAAgB,CACnC;wBAEJlC,MAAM;4BACF+B,gBAAgB;4BAChBC,QAAQ;wBACZ;oBACJ;iBACH;gBACDC,UAAU1C,OAAO2C,gBAAgB,CAC7B;YAER;YAEA,sDAAsD;YACtD3C,OAAOkB,OAAOoB,YAAY,CAAC,EAAE,CAACC,cAAc,EAAEK,SAAS,CAAC;YACxD5C,OAAOkB,OAAOoB,YAAY,CAAC,EAAE,CAACC,cAAc,EAAEK,SAAS,CACnD;YAEJ5C,OAAOkB,OAAOoB,YAAY,CAAC,EAAE,CAACC,cAAc,EAAEK,SAAS,CAAC;QAC5D;IACJ;AACJ"}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Custom error for AI response parsing failures
|
|
3
|
-
*/
|
|
4
|
-
export declare class AIResponseParserError extends Error {
|
|
5
|
-
readonly cause?: unknown | undefined;
|
|
6
|
-
readonly text?: string | undefined;
|
|
7
|
-
constructor(message: string, cause?: unknown | undefined, text?: string | undefined);
|
|
8
|
-
}
|