@postalsys/email-ai-tools 1.14.10 → 1.14.12
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/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +14 -0
- package/CLAUDE.md +5 -1
- package/lib/api-request.js +194 -0
- package/lib/embeddings-query.js +27 -180
- package/lib/generate-embeddings.js +67 -90
- package/lib/generate-summary.js +24 -128
- package/lib/list-models.js +9 -63
- package/lib/risk-analysis.js +21 -103
- package/lib/token-estimate.js +186 -0
- package/package.json +5 -6
- package/test/api-request.test.js +162 -0
- package/test/dispatcher.test.js +15 -2
- package/test/generate-embeddings.test.js +131 -1
- package/test/helpers/mock-server.js +11 -3
- package/test/token-estimate.test.js +188 -0
package/lib/risk-analysis.js
CHANGED
|
@@ -1,16 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const packageData = require('../package.json');
|
|
4
3
|
const { htmlToText } = require('@postalsys/email-text-tools');
|
|
5
|
-
const
|
|
6
|
-
|
|
7
|
-
const { fetch: fetchCmd, Agent } = require('undici');
|
|
8
|
-
const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
|
|
9
|
-
|
|
10
|
-
const tokenizer = new GPT3Tokenizer({ type: 'gpt3' });
|
|
11
|
-
|
|
12
|
-
const MAX_ALLOWED_TEXT_LENGTH = 64 * 1024;
|
|
13
|
-
const DEFAULT_MAX_ALLOWED_TOKENS = 30000;
|
|
4
|
+
const { apiRequest } = require('./api-request');
|
|
5
|
+
const { fitPrompt, DEFAULT_MAX_ALLOWED_TOKENS } = require('./token-estimate');
|
|
14
6
|
|
|
15
7
|
const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
|
|
16
8
|
|
|
@@ -98,8 +90,6 @@ async function riskAnalysis(message, apiToken, opts) {
|
|
|
98
90
|
text = htmlToText(message.html);
|
|
99
91
|
}
|
|
100
92
|
|
|
101
|
-
let prompt;
|
|
102
|
-
|
|
103
93
|
const headerSeen = new Set();
|
|
104
94
|
const content = {
|
|
105
95
|
headers: []
|
|
@@ -121,52 +111,17 @@ async function riskAnalysis(message, apiToken, opts) {
|
|
|
121
111
|
attachments: [].concat(message.attachments || []).map(attachment => ({ filename: attachment.filename, contentType: attachment.contentType }))
|
|
122
112
|
};
|
|
123
113
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
while (promptText.length) {
|
|
133
|
-
content.text = promptText;
|
|
134
|
-
prompt = `${userPrompt}
|
|
114
|
+
const {
|
|
115
|
+
prompt,
|
|
116
|
+
text: promptText,
|
|
117
|
+
charactersRemoved
|
|
118
|
+
} = fitPrompt({
|
|
119
|
+
text,
|
|
120
|
+
maxTokens: maxAllowedTokens,
|
|
121
|
+
build: bodyText => `${userPrompt}
|
|
135
122
|
|
|
136
|
-
${JSON.stringify(content)}
|
|
137
|
-
|
|
138
|
-
let tokens = tokenizer.encode(prompt);
|
|
139
|
-
if (tokens.text.length <= maxAllowedTokens) {
|
|
140
|
-
break;
|
|
141
|
-
}
|
|
142
|
-
if (promptText.length > 2 * 1024 * 1024) {
|
|
143
|
-
promptText = promptText.substring(0, promptText.length - 1024 * 1024);
|
|
144
|
-
charactersRemoved += 1024 * 1024;
|
|
145
|
-
} else if (promptText.length > 2 * 1024) {
|
|
146
|
-
promptText = promptText.substring(0, promptText.length - 1024);
|
|
147
|
-
charactersRemoved += 1024;
|
|
148
|
-
} else if (promptText.length > 2 * 256) {
|
|
149
|
-
promptText = promptText.substring(0, promptText.length - 256);
|
|
150
|
-
charactersRemoved += 255;
|
|
151
|
-
} else if (promptText.length > 2 * 100) {
|
|
152
|
-
promptText = promptText.substring(0, promptText.length - 100);
|
|
153
|
-
charactersRemoved += 100;
|
|
154
|
-
} else if (promptText.length > 2 * 10) {
|
|
155
|
-
promptText = promptText.substring(0, promptText.length - 10);
|
|
156
|
-
charactersRemoved += 10;
|
|
157
|
-
} else if (promptText.length > 1) {
|
|
158
|
-
promptText = promptText.substring(0, promptText.length - 1);
|
|
159
|
-
charactersRemoved += 1;
|
|
160
|
-
} else {
|
|
161
|
-
throw new Error(`Prompt too long. Removed ${charactersRemoved} characters.`);
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
let headers = {
|
|
166
|
-
'User-Agent': `${packageData.name}/${packageData.version}`,
|
|
167
|
-
Authorization: `Bearer ${apiToken}`,
|
|
168
|
-
'Content-Type': 'application/json'
|
|
169
|
-
};
|
|
123
|
+
${JSON.stringify(Object.assign({}, content, { text: bodyText }))}`
|
|
124
|
+
});
|
|
170
125
|
|
|
171
126
|
let payload = {
|
|
172
127
|
model: gptModel,
|
|
@@ -194,50 +149,13 @@ ${JSON.stringify(content)}`;
|
|
|
194
149
|
payload.top_p = Number(opts.topP);
|
|
195
150
|
}
|
|
196
151
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
headers,
|
|
205
|
-
body: JSON.stringify(payload),
|
|
206
|
-
dispatcher: opts.dispatcher || fetchAgent
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
data = await res.json();
|
|
210
|
-
|
|
211
|
-
if (!res.ok) {
|
|
212
|
-
if (res.status === 429 && ++retries < 5) {
|
|
213
|
-
// try again
|
|
214
|
-
await new Promise(r => setTimeout(r, 1000));
|
|
215
|
-
return await run();
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
if (data && data.error) {
|
|
219
|
-
let error = new Error(data.error.message || data.error);
|
|
220
|
-
if (data.error.code) {
|
|
221
|
-
error.code = data.error.code;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
error.statusCode = res.status;
|
|
225
|
-
throw error;
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
let error = new Error('Failed to run API request');
|
|
229
|
-
error.statusCode = res.status;
|
|
230
|
-
throw error;
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
if (!data) {
|
|
234
|
-
throw new Error(`Failed to POST API request`);
|
|
235
|
-
}
|
|
236
|
-
};
|
|
237
|
-
|
|
238
|
-
const reqStartTime = Date.now();
|
|
239
|
-
await run();
|
|
240
|
-
const reqEndTime = Date.now();
|
|
152
|
+
const { data, time } = await apiRequest(getApiUrl(baseApiUrl, OPENAI_API_URL), {
|
|
153
|
+
apiToken,
|
|
154
|
+
payload,
|
|
155
|
+
dispatcher: opts.dispatcher,
|
|
156
|
+
signal: opts.signal,
|
|
157
|
+
verbose: opts.verbose
|
|
158
|
+
});
|
|
241
159
|
|
|
242
160
|
let values;
|
|
243
161
|
const output =
|
|
@@ -266,8 +184,8 @@ ${JSON.stringify(content)}`;
|
|
|
266
184
|
tokens: data && data.usage && data.usage.total_tokens,
|
|
267
185
|
model: gptModel,
|
|
268
186
|
|
|
269
|
-
_text:
|
|
270
|
-
_time:
|
|
187
|
+
_text: promptText,
|
|
188
|
+
_time: time,
|
|
271
189
|
_cr: charactersRemoved
|
|
272
190
|
});
|
|
273
191
|
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Token counts are estimated from characters instead of running a BPE tokenizer. The GPT-3
|
|
4
|
+
// tokenizer this library used to load does not match current model vocabularies anyway, costs
|
|
5
|
+
// ~15 MB of heap per instance, and is super-linear on long unbroken runs (a 64 KB CJK body took
|
|
6
|
+
// 25 s per encode). The estimate errs on the high side; the model's own context length error
|
|
7
|
+
// stays the backstop for the rare input that tokenizes worse than this.
|
|
8
|
+
|
|
9
|
+
// Prompt fitting: ASCII at 3 characters per token is below what English, code and base64-ish
|
|
10
|
+
// runs actually reach, and every non-ASCII UTF-16 code unit counts as a whole token.
|
|
11
|
+
const PROMPT_ESTIMATE = { charsPerToken: 3, margin: 1.1 };
|
|
12
|
+
|
|
13
|
+
// Input text beyond this many characters is never sent, whatever the token budget
|
|
14
|
+
const MAX_ALLOWED_TEXT_LENGTH = 64 * 1024;
|
|
15
|
+
// Default prompt budget when the caller does not set maxTokens
|
|
16
|
+
const DEFAULT_MAX_ALLOWED_TOKENS = 30000;
|
|
17
|
+
|
|
18
|
+
// Chunk sizing only needs to be roughly right, so it uses a typical English ratio instead.
|
|
19
|
+
const CHUNK_ESTIMATE = { charsPerToken: 4, margin: 1 };
|
|
20
|
+
|
|
21
|
+
// Cost of one UTF-16 code unit in "ASCII character" units
|
|
22
|
+
function charUnits(code, charsPerToken) {
|
|
23
|
+
if (code < 0x20 || code === 0x22 || code === 0x5c) {
|
|
24
|
+
// control characters, quotes and backslashes are escaped when the text is JSON encoded
|
|
25
|
+
return 2;
|
|
26
|
+
}
|
|
27
|
+
if (code < 0x80) {
|
|
28
|
+
return 1;
|
|
29
|
+
}
|
|
30
|
+
return charsPerToken;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Estimates how many tokens a string takes
|
|
35
|
+
*
|
|
36
|
+
* @param {string} str
|
|
37
|
+
* @param {Object} [opts]
|
|
38
|
+
* @param {number} [opts.charsPerToken=3] - ASCII characters per token
|
|
39
|
+
* @param {number} [opts.margin=1.1] - Safety factor applied to the estimate
|
|
40
|
+
* @returns {number} Estimated token count
|
|
41
|
+
*/
|
|
42
|
+
function estimateTokens(str, opts) {
|
|
43
|
+
const { charsPerToken, margin } = Object.assign({}, PROMPT_ESTIMATE, opts);
|
|
44
|
+
str = (str || '').toString();
|
|
45
|
+
|
|
46
|
+
let units = 0;
|
|
47
|
+
for (let i = 0; i < str.length; i++) {
|
|
48
|
+
units += charUnits(str.charCodeAt(i), charsPerToken);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// the epsilon keeps float noise (100 * 1.1 = 110.00000000000001) from adding a token
|
|
52
|
+
return Math.ceil((units / charsPerToken) * margin - 1e-9);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Returns the length of the longest prefix of `str` that fits into `maxTokens` by the same
|
|
57
|
+
* estimate as estimateTokens(). Never ends between the two halves of a surrogate pair.
|
|
58
|
+
*
|
|
59
|
+
* @param {string} str
|
|
60
|
+
* @param {number} maxTokens
|
|
61
|
+
* @param {Object} [opts] - Same as for estimateTokens()
|
|
62
|
+
* @returns {number} Prefix length in UTF-16 code units
|
|
63
|
+
*/
|
|
64
|
+
function fitLength(str, maxTokens, opts) {
|
|
65
|
+
const { charsPerToken, margin } = Object.assign({}, PROMPT_ESTIMATE, opts);
|
|
66
|
+
str = (str || '').toString();
|
|
67
|
+
|
|
68
|
+
if (!(maxTokens > 0)) {
|
|
69
|
+
return 0;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const maxUnits = Math.floor((maxTokens * charsPerToken) / margin);
|
|
73
|
+
|
|
74
|
+
let units = 0;
|
|
75
|
+
let i = 0;
|
|
76
|
+
for (; i < str.length; i++) {
|
|
77
|
+
const cost = charUnits(str.charCodeAt(i), charsPerToken);
|
|
78
|
+
if (units + cost > maxUnits) {
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
units += cost;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return keepSurrogatePair(str, i);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Moves a cut position back by one if it would separate a surrogate pair
|
|
88
|
+
function keepSurrogatePair(str, pos) {
|
|
89
|
+
if (pos > 0 && pos < str.length) {
|
|
90
|
+
const prev = str.charCodeAt(pos - 1);
|
|
91
|
+
if (prev >= 0xd800 && prev <= 0xdbff) {
|
|
92
|
+
return pos - 1;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return pos;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Splits text into chunks of at most `maxTokens` estimated tokens each, preferring to break at
|
|
100
|
+
* whitespace. Characters are never split, unlike slicing BPE token arrays.
|
|
101
|
+
*
|
|
102
|
+
* @param {string} str
|
|
103
|
+
* @param {number} maxTokens
|
|
104
|
+
* @param {Object} [opts] - Same as for estimateTokens(), defaults to the chunk sizing ratio
|
|
105
|
+
* @returns {string[]}
|
|
106
|
+
*/
|
|
107
|
+
function splitByTokens(str, maxTokens, opts) {
|
|
108
|
+
opts = Object.assign({}, CHUNK_ESTIMATE, opts);
|
|
109
|
+
str = (str || '').toString();
|
|
110
|
+
|
|
111
|
+
const chunks = [];
|
|
112
|
+
let rest = str;
|
|
113
|
+
while (rest.length) {
|
|
114
|
+
let len = fitLength(rest, maxTokens, opts);
|
|
115
|
+
if (len >= rest.length) {
|
|
116
|
+
chunks.push(rest);
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (len < 1) {
|
|
121
|
+
// a single character larger than the budget, take it (or its surrogate pair) anyway
|
|
122
|
+
len = keepSurrogatePair(rest, 1) || 2;
|
|
123
|
+
} else {
|
|
124
|
+
// break at the last whitespace if it is not too far back, so words stay whole
|
|
125
|
+
const ws = Math.max(rest.lastIndexOf(' ', len - 1), rest.lastIndexOf('\n', len - 1));
|
|
126
|
+
if (ws >= len / 2) {
|
|
127
|
+
len = ws + 1;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
chunks.push(rest.substring(0, len));
|
|
132
|
+
rest = rest.substring(len);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return chunks;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Cuts `text` so that the prompt built around it fits into `maxTokens` estimated tokens. The
|
|
140
|
+
* text is sized in one step from an estimate of what the rest of the prompt takes.
|
|
141
|
+
*
|
|
142
|
+
* @param {Object} opts
|
|
143
|
+
* @param {string} opts.text - Variable part of the prompt, the only part that gets shortened
|
|
144
|
+
* @param {number} [opts.maxLength=MAX_ALLOWED_TEXT_LENGTH] - Hard cap on the text length
|
|
145
|
+
* @param {number} [opts.maxTokens=DEFAULT_MAX_ALLOWED_TOKENS] - Token budget for the whole prompt
|
|
146
|
+
* @param {Function} opts.build - Returns the full prompt for a given text
|
|
147
|
+
* @returns {{prompt: string, text: string, charactersRemoved: number}}
|
|
148
|
+
* @throws {Error} PROMPT_TOO_LONG if the prompt does not fit even without any text
|
|
149
|
+
*/
|
|
150
|
+
function fitPrompt({ text, maxLength, maxTokens, build }) {
|
|
151
|
+
text = (text || '').toString();
|
|
152
|
+
maxLength = maxLength || MAX_ALLOWED_TEXT_LENGTH;
|
|
153
|
+
maxTokens = maxTokens || DEFAULT_MAX_ALLOWED_TOKENS;
|
|
154
|
+
|
|
155
|
+
let fitted = text.length > maxLength ? text.substring(0, keepSurrogatePair(text, maxLength)) : text;
|
|
156
|
+
|
|
157
|
+
const overheadTokens = estimateTokens(build(''));
|
|
158
|
+
if (overheadTokens > maxTokens) {
|
|
159
|
+
const error = new Error(
|
|
160
|
+
`Unable to fit email content within token limit of ${maxTokens}. ` +
|
|
161
|
+
`Original text length: ${text.length} characters. ` +
|
|
162
|
+
`The prompt without the email text is already estimated at ${overheadTokens} tokens. ` +
|
|
163
|
+
`Consider using a model with larger context window.`
|
|
164
|
+
);
|
|
165
|
+
error.code = 'PROMPT_TOO_LONG';
|
|
166
|
+
error.originalLength = text.length;
|
|
167
|
+
error.charactersRemoved = text.length;
|
|
168
|
+
error.maxAllowedTokens = maxTokens;
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
fitted = fitted.substring(0, fitLength(fitted, maxTokens - overheadTokens));
|
|
173
|
+
|
|
174
|
+
return { prompt: build(fitted), text: fitted, charactersRemoved: text.length - fitted.length };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
module.exports = {
|
|
178
|
+
estimateTokens,
|
|
179
|
+
fitLength,
|
|
180
|
+
fitPrompt,
|
|
181
|
+
keepSurrogatePair,
|
|
182
|
+
splitByTokens,
|
|
183
|
+
CHUNK_ESTIMATE,
|
|
184
|
+
MAX_ALLOWED_TEXT_LENGTH,
|
|
185
|
+
DEFAULT_MAX_ALLOWED_TOKENS
|
|
186
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@postalsys/email-ai-tools",
|
|
3
|
-
"version": "1.14.
|
|
3
|
+
"version": "1.14.12",
|
|
4
4
|
"description": "Email AI tools",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -26,15 +26,14 @@
|
|
|
26
26
|
"eslint": "10.11.0",
|
|
27
27
|
"eslint-config-nodemailer": "1.2.0",
|
|
28
28
|
"eslint-config-prettier": "10.1.8",
|
|
29
|
-
"mailparser": "3.9.
|
|
29
|
+
"mailparser": "3.9.30",
|
|
30
30
|
"prettier": "3.9.9"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@postalsys/email-text-tools": "2.4.
|
|
34
|
-
"
|
|
35
|
-
"libmime": "5.4.4",
|
|
33
|
+
"@postalsys/email-text-tools": "2.4.18",
|
|
34
|
+
"libmime": "5.4.5",
|
|
36
35
|
"linkify-it": "5.0.2",
|
|
37
|
-
"nodemailer": "10.0.
|
|
36
|
+
"nodemailer": "10.0.12",
|
|
38
37
|
"punycode.js": "2.3.1",
|
|
39
38
|
"tlds": "1.261.0",
|
|
40
39
|
"undici": "7.30.0"
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { describe, it, before, after, beforeEach } = require('node:test');
|
|
4
|
+
const assert = require('node:assert/strict');
|
|
5
|
+
const { createMockServer, modelsResponse } = require('./helpers/mock-server');
|
|
6
|
+
const { apiRequest, MAX_RESPONSE_SIZE } = require('../lib/api-request');
|
|
7
|
+
|
|
8
|
+
const HTML_502 = '<html><head><title>502 Bad Gateway</title></head><body><center><h1>502 Bad Gateway</h1></center></body></html>';
|
|
9
|
+
|
|
10
|
+
// A short per-test timeout catches a regression that waits for a long Retry-After instead of failing
|
|
11
|
+
const TIMEOUT = { timeout: 5000 };
|
|
12
|
+
|
|
13
|
+
describe('apiRequest', () => {
|
|
14
|
+
let mock;
|
|
15
|
+
let url;
|
|
16
|
+
|
|
17
|
+
before(async () => {
|
|
18
|
+
mock = await createMockServer();
|
|
19
|
+
url = `${mock.url}/v1/models`;
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
after(async () => {
|
|
23
|
+
await mock.close();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
beforeEach(() => {
|
|
27
|
+
mock.clearRequests();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('sends the token, user agent and JSON payload and returns the parsed body', TIMEOUT, async () => {
|
|
31
|
+
mock.setHandler(() => modelsResponse());
|
|
32
|
+
|
|
33
|
+
const { data, time } = await apiRequest(url, { apiToken: 'secret', payload: { a: 1 } });
|
|
34
|
+
|
|
35
|
+
assert.ok(Array.isArray(data.data));
|
|
36
|
+
assert.equal(typeof time, 'number');
|
|
37
|
+
assert.equal(mock.requests.length, 1);
|
|
38
|
+
assert.equal(mock.requests[0].method, 'POST');
|
|
39
|
+
assert.equal(mock.requests[0].headers.authorization, 'Bearer secret');
|
|
40
|
+
assert.equal(mock.requests[0].headers['content-type'], 'application/json');
|
|
41
|
+
assert.ok(/^@postalsys\/email-ai-tools\//.test(mock.requests[0].headers['user-agent']));
|
|
42
|
+
assert.deepEqual(mock.requests[0].body, { a: 1 });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('reports an HTML 502 with its status code instead of a JSON SyntaxError', TIMEOUT, async () => {
|
|
46
|
+
mock.setHandler(() => ({ status: 502, raw: HTML_502 }));
|
|
47
|
+
|
|
48
|
+
await assert.rejects(
|
|
49
|
+
() => apiRequest(url, { apiToken: 'token' }),
|
|
50
|
+
err => {
|
|
51
|
+
assert.notEqual(err.name, 'SyntaxError');
|
|
52
|
+
assert.equal(err.message, 'Failed to run API request');
|
|
53
|
+
assert.equal(err.statusCode, 502);
|
|
54
|
+
assert.ok(err.responseText.includes('502 Bad Gateway'));
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
);
|
|
58
|
+
assert.equal(mock.requests.length, 1);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('retries an HTML 429 after the Retry-After delay', TIMEOUT, async () => {
|
|
62
|
+
let calls = 0;
|
|
63
|
+
mock.setHandler(() => {
|
|
64
|
+
calls++;
|
|
65
|
+
if (calls === 1) {
|
|
66
|
+
return { status: 429, raw: '<html>Too Many Requests</html>', headers: { 'retry-after-ms': '50' } };
|
|
67
|
+
}
|
|
68
|
+
return modelsResponse();
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
const { data } = await apiRequest(url, { apiToken: 'token' });
|
|
72
|
+
|
|
73
|
+
assert.equal(calls, 2);
|
|
74
|
+
assert.ok(Array.isArray(data.data));
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('fails right away when Retry-After is longer than it is willing to wait', TIMEOUT, async () => {
|
|
78
|
+
mock.setHandler(() => ({ status: 429, raw: '<html>Too Many Requests</html>', headers: { 'Retry-After': '3600' } }));
|
|
79
|
+
|
|
80
|
+
await assert.rejects(
|
|
81
|
+
() => apiRequest(url, { apiToken: 'token' }),
|
|
82
|
+
err => {
|
|
83
|
+
assert.equal(err.statusCode, 429);
|
|
84
|
+
assert.equal(err.retryAfter, 3600);
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
);
|
|
88
|
+
assert.equal(mock.requests.length, 1);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('does not produce "[object Object]" for an error object without a message', TIMEOUT, async () => {
|
|
92
|
+
mock.setHandler(() => ({ status: 400, body: { error: { type: 'invalid_request_error', code: 'bad_input' } } }));
|
|
93
|
+
|
|
94
|
+
await assert.rejects(
|
|
95
|
+
() => apiRequest(url, { apiToken: 'token' }),
|
|
96
|
+
err => {
|
|
97
|
+
assert.ok(!err.message.includes('[object Object]'), err.message);
|
|
98
|
+
assert.ok(err.message.includes('invalid_request_error'));
|
|
99
|
+
assert.equal(err.code, 'bad_input');
|
|
100
|
+
assert.equal(err.statusCode, 400);
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('uses a string error as the message', TIMEOUT, async () => {
|
|
107
|
+
mock.setHandler(() => ({ status: 400, body: { error: 'Model not found' } }));
|
|
108
|
+
|
|
109
|
+
await assert.rejects(
|
|
110
|
+
() => apiRequest(url, { apiToken: 'token' }),
|
|
111
|
+
err => {
|
|
112
|
+
assert.equal(err.message, 'Model not found');
|
|
113
|
+
assert.equal(err.statusCode, 400);
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it('rejects a 200 response that is not JSON with the status and a snippet', TIMEOUT, async () => {
|
|
120
|
+
mock.setHandler(() => ({ status: 200, raw: '<html>Login required</html>' }));
|
|
121
|
+
|
|
122
|
+
await assert.rejects(
|
|
123
|
+
() => apiRequest(url, { apiToken: 'token' }),
|
|
124
|
+
err => {
|
|
125
|
+
assert.equal(err.code, 'InvalidResponse');
|
|
126
|
+
assert.equal(err.statusCode, 200);
|
|
127
|
+
assert.ok(err.responseText.includes('Login required'));
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('rejects a 200 response with a JSON null body', TIMEOUT, async () => {
|
|
134
|
+
mock.setHandler(() => ({ status: 200, raw: 'null' }));
|
|
135
|
+
|
|
136
|
+
await assert.rejects(() => apiRequest(url, { apiToken: 'token' }), { code: 'InvalidResponse', statusCode: 200 });
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('stops reading a response larger than the size cap', TIMEOUT, async () => {
|
|
140
|
+
const big = 'x'.repeat(MAX_RESPONSE_SIZE + 1024);
|
|
141
|
+
mock.setHandler(() => ({ status: 200, raw: big }));
|
|
142
|
+
|
|
143
|
+
await assert.rejects(
|
|
144
|
+
() => apiRequest(url, { apiToken: 'token' }),
|
|
145
|
+
err => {
|
|
146
|
+
assert.equal(err.code, 'ResponseTooLarge');
|
|
147
|
+
assert.equal(err.statusCode, 200);
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('stops waiting for a 429 retry when the signal is aborted', TIMEOUT, async () => {
|
|
154
|
+
mock.setHandler(() => ({ status: 429, raw: '', headers: { 'Retry-After': '10' } }));
|
|
155
|
+
|
|
156
|
+
const controller = new AbortController();
|
|
157
|
+
setTimeout(() => controller.abort(new Error('stopped')), 100);
|
|
158
|
+
|
|
159
|
+
await assert.rejects(() => apiRequest(url, { apiToken: 'token', signal: controller.signal }), { message: 'stopped' });
|
|
160
|
+
assert.equal(mock.requests.length, 1);
|
|
161
|
+
});
|
|
162
|
+
});
|
package/test/dispatcher.test.js
CHANGED
|
@@ -29,7 +29,9 @@ const message = {
|
|
|
29
29
|
text: 'Hello, this is a test email.'
|
|
30
30
|
};
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
// The request behaviour itself is covered in api-request.test.js; these only check that every
|
|
33
|
+
// entry point hands its dispatcher and signal down to it
|
|
34
|
+
describe('request option pass-through', () => {
|
|
33
35
|
let mock;
|
|
34
36
|
let dispatcher;
|
|
35
37
|
|
|
@@ -85,13 +87,24 @@ describe('dispatcher option', () => {
|
|
|
85
87
|
];
|
|
86
88
|
|
|
87
89
|
for (const entry of cases) {
|
|
88
|
-
it(`${entry.name}
|
|
90
|
+
it(`${entry.name} passes the dispatcher and the signal to the request`, { timeout: 5000 }, async () => {
|
|
89
91
|
mock.setHandler(entry.response);
|
|
90
92
|
|
|
91
93
|
await entry.run({ baseApiUrl: mock.url, dispatcher });
|
|
92
94
|
|
|
93
95
|
assert.ok(mock.requests.length >= 1, 'the mock server should have been reached');
|
|
94
96
|
assert.equal(dispatcher.dispatched, mock.requests.length);
|
|
97
|
+
|
|
98
|
+
// aborted while the request is in flight, and the 429 would otherwise be retried
|
|
99
|
+
mock.clearRequests();
|
|
100
|
+
const controller = new AbortController();
|
|
101
|
+
mock.setHandler(() => {
|
|
102
|
+
controller.abort(new Error('stopped'));
|
|
103
|
+
return { status: 429, raw: '', headers: { 'Retry-After': '10' } };
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
await assert.rejects(() => entry.run({ baseApiUrl: mock.url, signal: controller.signal }), { message: 'stopped' });
|
|
107
|
+
assert.equal(mock.requests.length, 1);
|
|
95
108
|
});
|
|
96
109
|
}
|
|
97
110
|
|