@auipage/model 0.2.0 → 0.2.1

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/dist/index.js CHANGED
@@ -1,718 +1,770 @@
1
- /*! @auipage/model v0.2.0 */
2
- // 极简 EventEmitter:on / off / emit,供 Response 复用
3
- class Emitter {
4
- constructor() {
5
- this._events = Object.create(null);
6
- }
7
-
8
- on(event, listener) {
9
- if (typeof listener !== 'function') return this;
10
- const list = this._events[event] || (this._events[event] = []);
11
- list.push(listener);
12
- return this;
13
- }
14
-
15
- off(event, listener) {
16
- const list = this._events[event];
17
- if (!list) return this;
18
- const idx = list.indexOf(listener);
19
- if (idx >= 0) list.splice(idx, 1);
20
- if (list.length === 0) delete this._events[event];
21
- return this;
22
- }
23
- emit(event, ...args) {
24
- const list = this._events[event];
25
- if (!list || list.length === 0) return false;
26
- // 复制一份再触发,避免 off 回调过程中影响本次派发
27
- for (const fn of list.slice()) {
28
- try {
29
- fn.apply(null, args);
30
- } catch (e) {
31
- // 单个监听器异常不影响其它监听器,也不再冒泡成进程级异常
32
- console.error(e);
33
- }
34
- }
35
- return true;
36
- }
1
+ /*! @auipage/model v0.2.1 */
2
+ // 极简 EventEmitter:on / off / emit,供 Response 复用
3
+ class Emitter {
4
+ constructor() {
5
+ this._events = Object.create(null);
6
+ }
7
+
8
+ on(event, listener) {
9
+ if (typeof listener !== 'function') return this;
10
+ const list = this._events[event] || (this._events[event] = []);
11
+ list.push(listener);
12
+ return this;
13
+ }
14
+
15
+ off(event, listener) {
16
+ const list = this._events[event];
17
+ if (!list) return this;
18
+ const idx = list.indexOf(listener);
19
+ if (idx >= 0) list.splice(idx, 1);
20
+ if (list.length === 0) delete this._events[event];
21
+ return this;
22
+ }
23
+
24
+ emit(event, ...args) {
25
+ const list = this._events[event];
26
+ if (!list || list.length === 0) return false;
27
+ // 复制一份再触发,避免 off 回调过程中影响本次派发
28
+ for (const fn of list.slice()) {
29
+ try {
30
+ fn.apply(null, args);
31
+ } catch (e) {
32
+ // 单个监听器异常不影响其它监听器,也不再冒泡成进程级异常
33
+ console.error(e);
34
+ }
35
+ }
36
+ return true;
37
+ }
37
38
  }
38
39
 
39
- // Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
40
-
41
- class Response extends Emitter {
42
- constructor() {
43
- super();
44
- this.status = 0;
45
- this.headers = {};
46
- this.ok = false;
47
- this._done = false; // 标记是否已经 end/error,防止重复触发
48
- this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
49
- this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
50
- this._cancel = null; // 由 createFetch 注入,用于中断底层请求
51
- this._errorPending = null; // 消费者还没来得及注册时就发生的错误,注册后补发
52
- }
53
-
54
- // 注册监听;error 是一次性终态,注册时若已发生则补发
55
- on(event, listener) {
56
- super.on(event, listener);
57
- if (event === 'error' && this._errorPending) {
58
- const err = this._errorPending;
59
- this._errorPending = null;
60
- // 异步补发,避免在注册栈里同步回调
61
- queueMicrotask(() => this.emit('error', err));
62
- }
63
- return this;
64
- }
65
-
66
- // 主动取消请求,失败统一从 error 事件返回
67
- cancel() {
68
- if (this._cancel) this._cancel();
69
- return this;
70
- }
71
-
72
- // 统一读取响应头:浏览器是 Headers 对象,Node 是普通对象
73
- header(name) {
74
- const headers = this.headers;
75
- if (!headers) return undefined;
76
- if (typeof headers.get === 'function') return headers.get(name) ?? undefined;
77
- return headers[name];
78
- }
79
-
80
- // 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
81
- _push(type, payload) {
82
- if (this._done && type !== 'error') return;
83
-
84
- // SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
85
- if (type === 'data' && this._sseMode) {
86
- this._sseBuffer += payload;
87
-
88
- // 按 \n\n 分割出完整事件,最后一段可能不完整
89
- const parts = this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);
90
- this._sseBuffer = parts.pop();
91
-
92
- for (const part of parts) {
93
- const payload = this._extractSSEData(part);
94
- if (payload !== null) {
95
- this.emit('data', payload);
96
- }
97
- }
98
- return;
99
- }
100
-
101
- if (type === 'end') {
102
- // SSE 模式下,flush 缓冲区残留
103
- if (this._sseMode && this._sseBuffer.trim()) {
104
- const payload = this._extractSSEData(this._sseBuffer);
105
- if (payload !== null) {
106
- this.emit('data', payload);
107
- }
108
- this._sseBuffer = '';
109
- }
110
- this._done = true;
111
- }
112
- if (type === 'error') {
113
- this._done = true;
114
- const listeners = this._events && this._events['error'];
115
- if (!listeners || listeners.length === 0) {
116
- // 消费者还没注册监听,先缓存,注册时补发
117
- this._errorPending = payload;
118
- return;
119
- }
120
- }
121
-
122
- this.emit(type, payload);
123
- }
124
-
125
- // 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
126
- _extractSSEData(raw) {
127
- const dataLines = [];
128
- for (const line of raw.split('\n')) {
129
- if (line.startsWith('data:')) {
130
- dataLines.push(line.replace(/^data:\s*/, '').replace(/\r$/, ''));
131
- }
132
- }
133
- if (dataLines.length === 0) return null;
134
- return dataLines.join('\n');
135
- }
40
+ // Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
41
+
42
+ class Response extends Emitter {
43
+ constructor() {
44
+ super();
45
+ this.status = 0;
46
+ this.headers = {};
47
+ this.ok = false;
48
+ this._done = false; // 标记是否已经 end/error,防止重复触发
49
+ this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
50
+ this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
51
+ this._cancel = null; // 由 createFetch 注入,用于中断底层请求
52
+ this._errorPending = null; // 消费者还没来得及注册时就发生的错误,注册后补发
53
+ }
54
+
55
+ // 注册监听;error 是一次性终态,注册时若已发生则补发
56
+ on(event, listener) {
57
+ super.on(event, listener);
58
+ if (event === 'error' && this._errorPending) {
59
+ const err = this._errorPending;
60
+ this._errorPending = null;
61
+ // 异步补发,避免在注册栈里同步回调
62
+ queueMicrotask(() => this.emit('error', err));
63
+ }
64
+ return this;
65
+ }
66
+
67
+ // 主动取消请求,失败统一从 error 事件返回
68
+ cancel() {
69
+ if (this._cancel) this._cancel();
70
+ return this;
71
+ }
72
+
73
+ // 统一读取响应头:浏览器是 Headers 对象,Node 是普通对象
74
+ header(name) {
75
+ const headers = this.headers;
76
+ if (!headers) return undefined;
77
+ if (typeof headers.get === 'function') return headers.get(name) ?? undefined;
78
+ return headers[name];
79
+ }
80
+
81
+ // 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
82
+ _push(type, payload) {
83
+ if (this._done && type !== 'error') return;
84
+
85
+ // SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
86
+ if (type === 'data' && this._sseMode) {
87
+ this._sseBuffer += payload;
88
+
89
+ // 按 \n\n 分割出完整事件,最后一段可能不完整
90
+ const parts = this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);
91
+ this._sseBuffer = parts.pop();
92
+
93
+ for (const part of parts) {
94
+ const payload = this._extractSSEData(part);
95
+ if (payload !== null) {
96
+ this.emit('data', payload);
97
+ }
98
+ }
99
+ return;
100
+ }
101
+
102
+ if (type === 'end') {
103
+ // SSE 模式下,flush 缓冲区残留
104
+ if (this._sseMode && this._sseBuffer.trim()) {
105
+ const payload = this._extractSSEData(this._sseBuffer);
106
+ if (payload !== null) {
107
+ this.emit('data', payload);
108
+ }
109
+ this._sseBuffer = '';
110
+ }
111
+ this._done = true;
112
+ }
113
+ if (type === 'error') {
114
+ this._done = true;
115
+ const listeners = this._events && this._events['error'];
116
+ if (!listeners || listeners.length === 0) {
117
+ // 消费者还没注册监听,先缓存,注册时补发
118
+ this._errorPending = payload;
119
+ return;
120
+ }
121
+ }
122
+
123
+ this.emit(type, payload);
124
+ }
125
+
126
+ // 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
127
+ _extractSSEData(raw) {
128
+ const dataLines = [];
129
+ for (const line of raw.split('\n')) {
130
+ if (line.startsWith('data:')) {
131
+ dataLines.push(line.replace(/^data:\s*/, '').replace(/\r$/, ''));
132
+ }
133
+ }
134
+ if (dataLines.length === 0) return null;
135
+ return dataLines.join('\n');
136
+ }
136
137
  }
137
138
 
138
- // fetch 工厂:注入 adapter,返回对外的 fetch 函数
139
-
140
- // 只有普通对象才自动 JSON 序列化,ArrayBufferView / Blob / FormData 等保持原样
141
- function isPlainBody(body) {
142
- return Object.prototype.toString.call(body) === '[object Object]';
143
- }
144
-
145
- function createFetch(adapter) {
146
- return function fetch(options) {
147
- // 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
148
- return new Promise((resolve, reject) => {
149
- if (!options || !options.url) {
150
- reject(new Error('fetch: options.url is required'));
151
- return;
152
- }
153
-
154
- // 请求体是普通对象时自动序列化,避免 Node 端 req.write(object) 抛 TypeError
155
- if (isPlainBody(options.body)) {
156
- options = Object.assign({}, options, { body: JSON.stringify(options.body) });
157
- }
158
-
159
- const response = new Response();
160
- const controller = typeof AbortController === 'function' ? new AbortController() : null;
161
- let timer = null;
162
- let failed = false;
163
-
164
- response._cancel = () => { if (controller) controller.abort(); };
165
-
166
- // adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
167
- // 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
168
- queueMicrotask(() => resolve(response));
169
- const clearTimer = () => {
170
- if (timer) {
171
- clearTimeout(timer);
172
- timer = null;
173
- }
174
- };
175
- const hooks = {
176
- onResponse(meta) {
177
- if (meta && typeof meta.status === 'number') {
178
- response.status = meta.status;
179
- response.ok = meta.status >= 200 && meta.status < 300;
180
- }
181
- if (meta && meta.headers) {
182
- response.headers = meta.headers;
183
-
184
- // 自动检测 SSE:浏览器 Headers 对象用 get(),Node 的 plain object 用 []
185
- const contentType =
186
- (typeof meta.headers.get === 'function' && meta.headers.get('content-type')) ||
187
- meta.headers['content-type'] ||
188
- '';
189
- if (contentType.includes('text/event-stream')) {
190
- response._sseMode = true;
191
- }
192
- }
193
-
194
- // 非 2xx 单独通知:不占用 error 事件、不锁 _done,错误体照常投递
195
- if (response.status >= 400) {
196
- response.emit('http-error', { status: response.status, headers: response.headers });
197
- }
198
- },
199
- onData(chunk) {
200
- response._push('data', chunk);
201
- },
202
- onEnd() {
203
- clearTimer();
204
- response._push('end');
205
- },
206
- onError(err) {
207
- if (failed) return;
208
- failed = true;
209
- clearTimer();
210
- // 错误同时通过 error 事件 和 catch 暴露,避免遗漏
211
- response._push('error', err);
212
- reject(err);
213
- }
214
- };
215
- const abortWith = (err) => {
216
- if (controller) controller.abort();
217
- hooks.onError(err);
218
- };
219
-
220
- // 超时:到点先中断底层请求,再走统一错误通道
221
- if (options.timeout > 0) {
222
- timer = setTimeout(() => {
223
- timer = null;
224
- abortWith(new Error('fetch: 请求超时(' + options.timeout + 'ms)'));
225
- }, options.timeout);
226
- }
227
-
228
- // 外部 signal
229
- if (options.signal) {
230
- if (options.signal.aborted) {
231
- abortWith(new Error('fetch: 请求已取消'));
232
- return;
233
- }
234
- options.signal.addEventListener('abort', () => {
235
- abortWith(new Error('fetch: 请求已取消'));
236
- });
237
- }
238
-
239
- // 把内部 controller 的 signal 交给 adapter,adapter 可据此中断底层请求
240
- const requestOptions = controller ? Object.assign({}, options, { signal: controller.signal }) : options;
241
-
242
- let ret;
243
- try {
244
- ret = adapter(requestOptions, hooks);
245
- } catch (err) {
246
- hooks.onError(err);
247
- return;
248
- }
249
- // adapter 允许返回 Promise,失败也要走同一条错误通道
250
- if (ret && typeof ret.then === 'function') ret.then(null, hooks.onError);
251
- });
252
- };
139
+ // fetch 工厂:注入 adapter,返回对外的 fetch 函数
140
+
141
+ // 只有普通对象才自动 JSON 序列化,ArrayBufferView / Blob / FormData 等保持原样
142
+ function isPlainBody(body) {
143
+ return Object.prototype.toString.call(body) === '[object Object]';
253
144
  }
254
145
 
255
- // 浏览器环境适配器:基于原生 fetch + ReadableStream
256
- // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
257
- function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
258
- const { url, method = 'GET', headers = {}, body, signal } = options;
259
-
260
- if (typeof fetch !== 'function') {
261
- onError(new Error('Global fetch is not available in this environment'));
262
- return;
263
- }
264
-
265
- fetch(url, { method, headers, body, signal })
266
- .then(async (res) => {
267
- if (typeof onResponse === 'function') {
268
- onResponse({
269
- status: res.status || 0,
270
- headers: res.headers || {}
271
- });
272
- }
273
-
274
- // 没有 body(例如 204)直接结束
275
- if (!res.body) {
276
- onEnd();
277
- return;
278
- }
279
- const reader = res.body.getReader();
280
- const decoder = new TextDecoder('utf-8');
281
-
282
- // 循环读取流直到 done
283
- // 用 async IIFE 形式启动,错误统一走 onError
284
- (async () => {
285
- try {
286
- // eslint-disable-next-line no-constant-condition
287
- while (true) {
288
- const { value, done } = await reader.read();
289
- if (done) {
290
- onEnd();
291
- return;
292
- }
293
- // value 是 Uint8Array,解码为字符串
294
- onData(decoder.decode(value, { stream: true }));
295
- }
296
- } catch (err) {
297
- onError(err);
298
- }
299
- })();
300
- })
301
- .catch((err) => onError(err));
146
+ function createFetch(adapter) {
147
+ return function fetch(options) {
148
+ // 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
149
+ return new Promise((resolve, reject) => {
150
+ if (!options || !options.url) {
151
+ reject(new Error('fetch: options.url is required'));
152
+ return;
153
+ }
154
+
155
+ // 请求体是普通对象时自动序列化,避免 Node 端 req.write(object) 抛 TypeError
156
+ if (isPlainBody(options.body)) {
157
+ options = Object.assign({}, options, { body: JSON.stringify(options.body) });
158
+ }
159
+
160
+ const response = new Response();
161
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
162
+ let timer = null;
163
+ let failed = false;
164
+
165
+ response._cancel = () => { if (controller) controller.abort(); };
166
+
167
+ // adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
168
+ // 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
169
+ queueMicrotask(() => resolve(response));
170
+
171
+ const clearTimer = () => {
172
+ if (timer) {
173
+ clearTimeout(timer);
174
+ timer = null;
175
+ }
176
+ };
177
+
178
+ const hooks = {
179
+ onResponse(meta) {
180
+ if (meta && typeof meta.status === 'number') {
181
+ response.status = meta.status;
182
+ response.ok = meta.status >= 200 && meta.status < 300;
183
+ }
184
+ if (meta && meta.headers) {
185
+ response.headers = meta.headers;
186
+
187
+ // 自动检测 SSE:浏览器 Headers 对象用 get(),Node 的 plain object 用 []
188
+ const contentType =
189
+ (typeof meta.headers.get === 'function' && meta.headers.get('content-type')) ||
190
+ meta.headers['content-type'] ||
191
+ '';
192
+ if (contentType.includes('text/event-stream')) {
193
+ response._sseMode = true;
194
+ }
195
+ }
196
+
197
+ // 非 2xx 单独通知:不占用 error 事件、不锁 _done,错误体照常投递
198
+ if (response.status >= 400) {
199
+ response.emit('http-error', { status: response.status, headers: response.headers });
200
+ }
201
+ },
202
+ onData(chunk) {
203
+ response._push('data', chunk);
204
+ },
205
+ onEnd() {
206
+ clearTimer();
207
+ response._push('end');
208
+ },
209
+ onError(err) {
210
+ if (failed) return;
211
+ failed = true;
212
+ clearTimer();
213
+ // 错误同时通过 error 事件 和 catch 暴露,避免遗漏
214
+ response._push('error', err);
215
+ reject(err);
216
+ }
217
+ };
218
+
219
+ const abortWith = (err) => {
220
+ if (controller) controller.abort();
221
+ hooks.onError(err);
222
+ };
223
+
224
+ // 超时:到点先中断底层请求,再走统一错误通道
225
+ if (options.timeout > 0) {
226
+ timer = setTimeout(() => {
227
+ timer = null;
228
+ abortWith(new Error('fetch: 请求超时(' + options.timeout + 'ms)'));
229
+ }, options.timeout);
230
+ }
231
+
232
+ // 外部 signal
233
+ if (options.signal) {
234
+ if (options.signal.aborted) {
235
+ abortWith(new Error('fetch: 请求已取消'));
236
+ return;
237
+ }
238
+ options.signal.addEventListener('abort', () => {
239
+ abortWith(new Error('fetch: 请求已取消'));
240
+ });
241
+ }
242
+
243
+ // 把内部 controller 的 signal 交给 adapter,adapter 可据此中断底层请求
244
+ const requestOptions = controller ? Object.assign({}, options, { signal: controller.signal }) : options;
245
+
246
+ let ret;
247
+ try {
248
+ ret = adapter(requestOptions, hooks);
249
+ } catch (err) {
250
+ hooks.onError(err);
251
+ return;
252
+ }
253
+ // adapter 允许返回 Promise,失败也要走同一条错误通道
254
+ if (ret && typeof ret.then === 'function') ret.then(null, hooks.onError);
255
+ });
256
+ };
302
257
  }
303
258
 
304
- // Node 环境适配器:基于 http / https,天然流式输出
305
- // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
306
- // 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
307
- // 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
308
- async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
309
- const [{ default: http }, { default: https }, { URL }] = await Promise.all([
310
- import('http'),
311
- import('https'),
312
- import('url')
313
- ]);
314
- const { url, method = 'GET', headers = {}, body, signal } = options;
315
-
316
- let parsed;
317
- try {
318
- parsed = new URL(url);
319
- } catch (e) {
320
- onError(e);
321
- return;
322
- }
323
-
324
- const isHttps = parsed.protocol === 'https:';
325
- const lib = isHttps ? https : http;
326
-
327
- const reqOptions = {
328
- method,
329
- hostname: parsed.hostname,
330
- port: parsed.port || (isHttps ? 443 : 80),
331
- path: parsed.pathname + parsed.search,
332
- headers
333
- };
334
- const req = lib.request(reqOptions, (res) => {
335
- // 把 status / headers 同步给 Response(若上游关心)
336
- if (typeof onResponse === 'function') {
337
- onResponse({
338
- status: res.statusCode || 0,
339
- headers: res.headers || {}
340
- });
341
- }
342
-
343
- res.setEncoding('utf8');
344
- res.on('data', (chunk) => onData(chunk));
345
- res.on('end', () => onEnd());
346
- res.on('error', (err) => onError(err));
347
- });
348
-
349
- req.on('error', (err) => onError(err));
350
- // 取消 / 超时:直接中断底层请求,错误从 req 的 error 事件返回
351
- if (signal) {
352
- if (signal.aborted) {
353
- onError(new Error('请求已取消'));
354
- return;
355
- }
356
- signal.addEventListener('abort', () => {
357
- req.destroy(new Error('请求已取消'));
358
- });
359
- }
360
-
361
- if (body != null) {
362
- req.write(body);
363
- }
364
- req.end();
259
+ // 浏览器环境适配器:基于原生 fetch + ReadableStream
260
+ // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
261
+ function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
262
+ const { url, method = 'GET', headers = {}, body, signal } = options;
263
+
264
+ if (typeof fetch !== 'function') {
265
+ onError(new Error('Global fetch is not available in this environment'));
266
+ return;
267
+ }
268
+
269
+ fetch(url, { method, headers, body, signal })
270
+ .then(async (res) => {
271
+ if (typeof onResponse === 'function') {
272
+ onResponse({
273
+ status: res.status || 0,
274
+ headers: res.headers || {}
275
+ });
276
+ }
277
+
278
+ // 没有 body(例如 204)直接结束
279
+ if (!res.body) {
280
+ onEnd();
281
+ return;
282
+ }
283
+
284
+ const reader = res.body.getReader();
285
+ const decoder = new TextDecoder('utf-8');
286
+
287
+ // 循环读取流直到 done
288
+ // 用 async IIFE 形式启动,错误统一走 onError
289
+ (async () => {
290
+ try {
291
+ // eslint-disable-next-line no-constant-condition
292
+ while (true) {
293
+ const { value, done } = await reader.read();
294
+ if (done) {
295
+ onEnd();
296
+ return;
297
+ }
298
+ // value 是 Uint8Array,解码为字符串
299
+ onData(decoder.decode(value, { stream: true }));
300
+ }
301
+ } catch (err) {
302
+ onError(err);
303
+ }
304
+ })();
305
+ })
306
+ .catch((err) => onError(err));
365
307
  }
366
308
 
367
- // 入口:环境判断 + 选择 adapter,构造并导出 fetch
368
-
369
- // 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
370
- const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
371
-
372
- const adapter = isBrowser ? browserAdapter : nodeAdapter;
373
-
309
+ // Node 环境适配器:基于 http / https,天然流式输出
310
+ // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
311
+ // 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
312
+ // 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
313
+ async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
314
+ const [{ default: http }, { default: https }, { URL }] = await Promise.all([
315
+ import('http'),
316
+ import('https'),
317
+ import('url')
318
+ ]);
319
+
320
+ const { url, method = 'GET', headers = {}, body, signal } = options;
321
+
322
+ let parsed;
323
+ try {
324
+ parsed = new URL(url);
325
+ } catch (e) {
326
+ onError(e);
327
+ return;
328
+ }
329
+
330
+ const isHttps = parsed.protocol === 'https:';
331
+ const lib = isHttps ? https : http;
332
+
333
+ const reqOptions = {
334
+ method,
335
+ hostname: parsed.hostname,
336
+ port: parsed.port || (isHttps ? 443 : 80),
337
+ path: parsed.pathname + parsed.search,
338
+ headers
339
+ };
340
+
341
+ const req = lib.request(reqOptions, (res) => {
342
+ // 把 status / headers 同步给 Response(若上游关心)
343
+ if (typeof onResponse === 'function') {
344
+ onResponse({
345
+ status: res.statusCode || 0,
346
+ headers: res.headers || {}
347
+ });
348
+ }
349
+
350
+ res.setEncoding('utf8');
351
+ res.on('data', (chunk) => onData(chunk));
352
+ res.on('end', () => onEnd());
353
+ res.on('error', (err) => onError(err));
354
+ });
355
+
356
+ req.on('error', (err) => onError(err));
357
+
358
+ // 取消 / 超时:直接中断底层请求,错误从 req 的 error 事件返回
359
+ if (signal) {
360
+ if (signal.aborted) {
361
+ onError(new Error('请求已取消'));
362
+ return;
363
+ }
364
+ signal.addEventListener('abort', () => {
365
+ req.destroy(new Error('请求已取消'));
366
+ });
367
+ }
368
+
369
+ if (body != null) {
370
+ req.write(body);
371
+ }
372
+ req.end();
373
+ }
374
+
375
+ // 入口:环境判断 + 选择 adapter,构造并导出 fetch
376
+
377
+ // 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
378
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
379
+
380
+ const adapter = isBrowser ? browserAdapter : nodeAdapter;
381
+
374
382
  const fetch$1 = createFetch(adapter);
375
383
 
376
- // 字符串转 JSON,适配 LLM 返回的各种流式格式:
377
- // 单条 JSON(含 pretty-printed 的多行)、带 "data: " 前缀的 SSE、多条 SSE 事件、NDJSON
378
- function stripDataPrefix(text) {
379
- return text.replace(/^data:\s*/, "");
380
- }
381
-
382
- function tryParse(text) {
383
- try {
384
- return { value: JSON.parse(text) };
385
- } catch (e) {
386
- return null;
387
- }
388
- }
389
-
390
- function parseOne(text, origin) {
391
- const parsed = tryParse(stripDataPrefix(text.trim()));
392
- if (!parsed) throw new SyntaxError("模型返回无法解析:" + String(origin).slice(0, 120));
393
- return parsed.value;
394
- }
395
-
396
- // 错误响应体({"error":{...}})直接抛出,交给调用方转成 reject
397
- function checkError(result) {
398
- if (Array.isArray(result)) {
399
- for (const item of result) {
400
- if (item && item.error) throw item.error;
401
- }
402
- return result;
403
- }
404
- if (result && result.error) throw result.error;
405
- return result;
406
- }
407
-
408
- function parseString (value) {
409
- let text = String(value == null ? "" : value).trim();
410
-
411
- // 结束标记:可能单独出现,也可能紧跟在最后一条事件后面
412
- text = text.replace(/data:\s*\[DONE\]$/, "").trim();
413
- if (text === "" || text === "[DONE]") return [];
414
- // 单条:带 data: 前缀或裸 JSON
415
- let single = tryParse(stripDataPrefix(text)) || tryParse(text);
416
- if (single) return checkError(single.value);
417
-
418
- // 多条 SSE 事件,以 "\n\ndata: " 分隔
419
- const parts = text.split(/\r?\n\r?\ndata: /);
420
- if (parts.length > 1) return checkError(parts.map(part => parseOne(part, text)));
421
- // NDJSON:逐行 JSON(跳过空行和 ":" 注释行)
422
- const lines = text.split(/\r?\n/).filter(line => line.trim() && !line.trim().startsWith(":"));
423
- if (lines.length > 1) return checkError(lines.map(line => parseOne(line, text)));
424
-
425
- throw new SyntaxError("模型返回无法解析:" + text.slice(0, 120));
384
+ // 字符串转 JSON,适配 LLM 返回的各种流式格式:
385
+ // 单条 JSON(含 pretty-printed 的多行)、带 "data: " 前缀的 SSE、多条 SSE 事件、NDJSON
386
+ function stripDataPrefix(text) {
387
+ return text.replace(/^data:\s*/, "");
388
+ }
389
+
390
+ function tryParse(text) {
391
+ try {
392
+ return { value: JSON.parse(text) };
393
+ } catch (e) {
394
+ return null;
395
+ }
426
396
  }
427
397
 
428
- // 解析 LLM 返回的推理内容(reasoning / reasoning_content)
429
- // 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
430
- function parseReasoning(reasoning, content) {
431
- if (!/<\/think>/.test(reasoning)) return reasoning;
432
-
433
- const parts = reasoning.split("</think>");
434
- const thinkPart = parts[0].replace("<think>", "");
435
- return {
436
- reasoning: thinkPart,
437
- content: parts[1] + (content || "")
438
- };
439
- }
440
-
441
- const OPEN = "<think>";
442
- const CLOSE = "</think>";
443
-
444
- // 计算文本尾部与标签前缀的最长匹配长度
445
- // 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
446
- function partialTagLength(text, tag) {
447
- const max = Math.min(tag.length - 1, text.length);
448
- for (let len = max; len > 0; len--) {
449
- if (text.endsWith(tag.slice(0, len))) return len;
450
- }
451
- return 0;
452
- }
453
-
454
- // 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
455
- // 这里把它剥离出来:思考片段归 thinkback,其余归正文
456
- // 流式时标签可能分散在多个 chunk,依赖 state.inThink / state.thinkBuf 跨 chunk 记录状态
457
- // 返回 { thinking, content }
458
- function extractThink(content, state) {
459
- const buf = (state.thinkBuf || "") + content;
460
- state.thinkBuf = "";
461
-
462
- // 正处于思考块内:寻找 </think>
463
- if (state.inThink) {
464
- const end = buf.indexOf(CLOSE);
465
- if (end === -1) {
466
- const hold = partialTagLength(buf, CLOSE);
467
- state.thinkBuf = buf.slice(buf.length - hold);
468
- return { thinking: buf.slice(0, buf.length - hold), content: "" };
469
- }
470
- state.inThink = false;
471
- const rest = extractThink(buf.slice(end + CLOSE.length), state);
472
- return { thinking: buf.slice(0, end) + rest.thinking, content: rest.content };
473
- }
474
-
475
- // 正常正文:寻找 <think>
476
- const start = buf.indexOf(OPEN);
477
- if (start === -1) {
478
- const hold = partialTagLength(buf, OPEN);
479
- state.thinkBuf = buf.slice(buf.length - hold);
480
- return { thinking: "", content: buf.slice(0, buf.length - hold) };
481
- }
482
-
483
- const end = buf.indexOf(CLOSE, start);
484
- if (end !== -1) {
485
- const rest = extractThink(buf.slice(end + CLOSE.length), state);
486
- return {
487
- thinking: buf.slice(start + OPEN.length, end) + rest.thinking,
488
- content: buf.slice(0, start) + rest.content
489
- };
490
- }
491
-
492
- // 有 <think> 无 </think>:进入思考态
493
- state.inThink = true;
494
- const body = buf.slice(start + OPEN.length);
495
- const hold = partialTagLength(body, CLOSE);
496
- state.thinkBuf = body.slice(body.length - hold);
497
- return { thinking: body.slice(0, body.length - hold), content: buf.slice(0, start) };
498
- }
499
-
500
- // 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
501
- function flushThink(state) {
502
- const buf = state.thinkBuf || "";
503
- state.thinkBuf = "";
504
- return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
398
+ function parseOne(text, origin) {
399
+ const parsed = tryParse(stripDataPrefix(text.trim()));
400
+ if (!parsed) throw new SyntaxError("模型返回无法解析:" + String(origin).slice(0, 120));
401
+ return parsed.value;
505
402
  }
506
403
 
507
- // 新调用的槽位:保留原始字段形状,只保证 function.arguments 是字符串
508
- function normalizeCall(toolCall) {
509
- const fn = toolCall.function || {};
510
- return {
511
- ...toolCall,
512
- function: {
513
- ...fn,
514
- arguments: typeof fn.arguments === "string" ? fn.arguments : ""
515
- }
516
- };
517
- }
518
-
519
- // 续片:按 index 优先归并,否则追加到最后一个槽位
520
- function mergeToolCall(state, toolCall) {
521
- if (!state._toolSlots) state._toolSlots = new Map();
522
-
523
- const calls = state.tool_calls;
524
- const index = typeof toolCall.index === "number" ? toolCall.index : null;
525
- const hasId = typeof toolCall.id === "string" && toolCall.id !== "";
526
-
527
- // 带 id 视为新调用;同 id 重复下发时复用已有槽位
528
- if (hasId) {
529
- const exist = calls.find(call => call.id === toolCall.id);
530
- if (exist) {
531
- appendArguments(exist, toolCall);
532
- return;
533
- }
534
- const slot = normalizeCall(toolCall);
535
- calls.push(slot);
536
- if (index !== null) state._toolSlots.set(index, slot);
537
- return;
538
- }
539
-
540
- let slot = index !== null ? state._toolSlots.get(index) : null;
541
- if (!slot && calls.length) slot = calls[calls.length - 1];
542
-
543
- // 首片就没有 id:建占位槽位,后续分片补齐参数
544
- if (!slot) {
545
- slot = normalizeCall(toolCall);
546
- calls.push(slot);
547
- if (index !== null) state._toolSlots.set(index, slot);
548
- return;
549
- }
550
-
551
- appendArguments(slot, toolCall);
552
- }
553
-
554
- function appendArguments(slot, toolCall) {
555
- const fn = toolCall.function || {};
556
- if (fn.name && !slot.function.name) slot.function.name = fn.name;
557
- if (typeof fn.arguments === "string") slot.function.arguments += fn.arguments;
558
- }
559
-
560
- // 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
561
- function handleChoices(choices, { logback, thinkback }, state) {
562
- if (!Array.isArray(choices)) return;
563
-
564
- for (let i = 0; i < choices.length; i++) {
565
- const delta = choices[i].delta;
566
-
567
- // 推理内容(reasoning / reasoning_content 字段)
568
- let reasoning = delta.reasoning || delta.reasoning_content;
569
- if (reasoning) {
570
- const parsed = parseReasoning(reasoning, delta.content);
571
- if (typeof parsed === "object") {
572
- reasoning = parsed.reasoning;
573
- delta.content = parsed.content;
574
- }
575
- if (thinkback) thinkback(reasoning);
576
- }
577
-
578
- // 正文内容:剥离混在 content 中的 <think>...</think> 思考片段
579
- if (delta.content) {
580
- const extracted = extractThink(delta.content, state);
581
- if (extracted.thinking && thinkback) thinkback(extracted.thinking);
582
- if (extracted.content) {
583
- if (logback) logback(extracted.content);
584
- state.content += extracted.content;
585
- }
586
- }
587
-
588
- // 工具调用分片
589
- if (Array.isArray(delta.tool_calls)) {
590
- for (const toolCall of delta.tool_calls) {
591
- mergeToolCall(state, toolCall);
592
- }
593
- }
594
- }
595
- }
596
-
597
- // 流结束时调用:把 <think> 标签截断残留冲刷到对应回调
598
- function flushThinkBuffer(state, { logback, thinkback }) {
599
- const flushed = flushThink(state);
600
- if (flushed.thinking && thinkback) thinkback(flushed.thinking);
601
- if (flushed.content) {
602
- if (logback) logback(flushed.content);
603
- state.content += flushed.content;
604
- }
404
+ // 错误响应体({"error":{...}})直接抛出,交给调用方转成 reject
405
+ function checkError(result) {
406
+ if (Array.isArray(result)) {
407
+ for (const item of result) {
408
+ if (item && item.error) throw item.error;
409
+ }
410
+ return result;
411
+ }
412
+ if (result && result.error) throw result.error;
413
+ return result;
605
414
  }
606
415
 
607
- // 统一把各种错误形态收敛成 Error,保证 Promise 一定 settle
608
- function toError(value, fallback) {
609
- if (value instanceof Error) return value;
610
- if (value && typeof value.message === "string") return new Error(value.message);
611
- try {
612
- return new Error(String(value));
613
- } catch (e) {
614
- return new Error(fallback || "模型请求失败");
615
- }
616
- }
617
-
618
- // HTTP 错误:尽量带出响应体里的 error.message,方便定位
619
- function errorFromHttp(meta, body) {
620
- const status = meta && meta.status;
621
- let detail = "";
622
-
623
- if (body) {
624
- try {
625
- const parsed = JSON.parse(body);
626
- const raw = parsed && parsed.error;
627
- detail = (raw && (raw.message || raw)) || "";
628
- } catch (e) {
629
- detail = String(body).slice(0, 200);
630
- }
631
- if (detail && typeof detail !== "string") detail = JSON.stringify(detail);
632
- }
633
-
634
- return new Error("模型服务返回 HTTP " + status + (detail ? ":" + detail : ""));
635
- }
636
-
637
- function completions(params, logback, thinkback) {
638
- return new Promise((resolve, reject) => {
639
- const state = { content: "", tool_calls: [] };
640
- const callbacks = { logback, thinkback };
641
-
642
- let buffer = "";
643
- let httpError = null;
644
- let streamError = null;
645
- let settled = false;
646
-
647
- const finish = (fn, value) => {
648
- if (settled) return;
649
- settled = true;
650
- fn(value);
651
- };
652
- const fail = value => finish(reject, toError(value, "模型请求失败"));
653
- const body = {
654
- model: this.model,
655
- messages: params.messages,
656
- tools: params.tools ? params.tools.map(tool => tool.description) : [],
657
- stream: params.stream,
658
- };
659
- const temperature = params.temperature != null ? params.temperature : this.temperature;
660
- const topP = params.topP != null ? params.topP : this.topP;
661
- const maxTokens = params.maxTokens != null ? params.maxTokens : this.maxTokens;
662
- if (temperature != null) body.temperature = temperature;
663
- if (topP != null) body.top_p = topP;
664
- if (maxTokens != null) body.max_tokens = maxTokens;
665
- fetch$1({
666
- url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
667
- method: "POST",
668
- headers: {
669
- "Authorization": `Bearer ${this.apiKey}`,
670
- "Content-Type": "application/json",
671
- },
672
- body: JSON.stringify(body),
673
- timeout: params.timeout != null ? params.timeout : this.timeout,
674
- signal: params.signal
675
- }).then(res => {
676
-
677
- // 非 2xx:非流式等错误体读完再判,流式直接中断
678
- res.on("http-error", meta => {
679
- httpError = meta;
680
- if (params.stream) fail(errorFromHttp(meta));
681
- });
682
-
683
- // 数据流
684
- res.on("data", chunk => {
685
- if (settled) return;
686
- if (!params.stream) {
687
- buffer += chunk;
688
- return;
689
- }
690
- let parsed;
691
- try {
692
- parsed = parseString(chunk.toString());
693
- } catch (e) {
694
- streamError = e;
695
- fail(e);
696
- return;
697
- }
698
- try {
699
- const items = Array.isArray(parsed) ? parsed : [parsed];
700
- for (const item of items) handleChoices(item.choices, callbacks, state);
701
- } catch (e) {
702
- fail(e);
703
- }
704
- });
705
-
706
- // 结束
707
- res.on("end", () => {
708
- if (!params.stream) {
709
- if (httpError) {
710
- fail(errorFromHttp(httpError, buffer));
711
- return;
712
- }
713
- try {
714
- const parsed = parseString(buffer);
715
- const choices = parsed && parsed.choices;
716
- if (!choices || !choices[0] || !choices[0].message) {
717
- throw new Error("模型响应缺少 choices[0].message");
718
- }
719
- handleChoices([{ delta: choices[0].message }], callbacks, state);
720
- } catch (e) {
721
- fail(e);
722
- return;
723
- }
724
- } else if (streamError) {
725
- fail(streamError);
726
- return;
727
- } else if (httpError) {
728
- fail(errorFromHttp(httpError));
729
- return;
730
- }
731
-
732
- // 冲刷 <think> 标签截断残留
733
- flushThinkBuffer(state, callbacks);
734
- finish(resolve, { content: state.content, tool_calls: state.tool_calls });
735
- });
736
-
737
- res.on("error", err => fail(err));
738
- }).catch(err => fail(err));
739
-
740
- });
416
+ function parseString (value) {
417
+ let text = String(value == null ? "" : value).trim();
418
+
419
+ // 结束标记:可能单独出现,也可能紧跟在最后一条事件后面
420
+ text = text.replace(/data:\s*\[DONE\]$/, "").trim();
421
+ if (text === "" || text === "[DONE]") return [];
422
+
423
+ // 单条:带 data: 前缀或裸 JSON
424
+ let single = tryParse(stripDataPrefix(text)) || tryParse(text);
425
+ if (single) return checkError(single.value);
426
+
427
+ // 多条 SSE 事件,以 "\n\ndata: " 分隔
428
+ const parts = text.split(/\r?\n\r?\ndata: /);
429
+ if (parts.length > 1) return checkError(parts.map(part => parseOne(part, text)));
430
+
431
+ // NDJSON:逐行 JSON(跳过空行和 ":" 注释行)
432
+ const lines = text.split(/\r?\n/).filter(line => line.trim() && !line.trim().startsWith(":"));
433
+ if (lines.length > 1) return checkError(lines.map(line => parseOne(line, text)));
434
+
435
+ throw new SyntaxError("模型返回无法解析:" + text.slice(0, 120));
436
+ }
437
+
438
+ // 解析 LLM 返回的推理内容(reasoning / reasoning_content)
439
+ // 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
440
+ function parseReasoning(reasoning, content) {
441
+ if (!/<\/think>/.test(reasoning)) return reasoning;
442
+
443
+ const parts = reasoning.split("</think>");
444
+ const thinkPart = parts[0].replace("<think>", "");
445
+ return {
446
+ reasoning: thinkPart,
447
+ content: parts[1] + (content || "")
448
+ };
449
+ }
450
+
451
+ const OPEN = "<think>";
452
+ const CLOSE = "</think>";
453
+
454
+ // 计算文本尾部与标签前缀的最长匹配长度
455
+ // 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
456
+ function partialTagLength(text, tag) {
457
+ const max = Math.min(tag.length - 1, text.length);
458
+ for (let len = max; len > 0; len--) {
459
+ if (text.endsWith(tag.slice(0, len))) return len;
460
+ }
461
+ return 0;
462
+ }
463
+
464
+ // 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
465
+ // 这里把它剥离出来:思考片段归 thinkback,其余归正文
466
+ // 流式时标签可能分散在多个 chunk,依赖 state.inThink / state.thinkBuf 跨 chunk 记录状态
467
+ // 返回 { thinking, content }
468
+ function extractThink(content, state) {
469
+ const buf = (state.thinkBuf || "") + content;
470
+ state.thinkBuf = "";
471
+
472
+ // 正处于思考块内:寻找 </think>
473
+ if (state.inThink) {
474
+ const end = buf.indexOf(CLOSE);
475
+ if (end === -1) {
476
+ const hold = partialTagLength(buf, CLOSE);
477
+ state.thinkBuf = buf.slice(buf.length - hold);
478
+ return { thinking: buf.slice(0, buf.length - hold), content: "" };
479
+ }
480
+ state.inThink = false;
481
+ const rest = extractThink(buf.slice(end + CLOSE.length), state);
482
+ return { thinking: buf.slice(0, end) + rest.thinking, content: rest.content };
483
+ }
484
+
485
+ // 正常正文:寻找 <think>
486
+ const start = buf.indexOf(OPEN);
487
+ if (start === -1) {
488
+ const hold = partialTagLength(buf, OPEN);
489
+ state.thinkBuf = buf.slice(buf.length - hold);
490
+ return { thinking: "", content: buf.slice(0, buf.length - hold) };
491
+ }
492
+
493
+ const end = buf.indexOf(CLOSE, start);
494
+ if (end !== -1) {
495
+ const rest = extractThink(buf.slice(end + CLOSE.length), state);
496
+ return {
497
+ thinking: buf.slice(start + OPEN.length, end) + rest.thinking,
498
+ content: buf.slice(0, start) + rest.content
499
+ };
500
+ }
501
+
502
+ // 有 <think> 无 </think>:进入思考态
503
+ state.inThink = true;
504
+ const body = buf.slice(start + OPEN.length);
505
+ const hold = partialTagLength(body, CLOSE);
506
+ state.thinkBuf = body.slice(body.length - hold);
507
+ return { thinking: body.slice(0, body.length - hold), content: buf.slice(0, start) };
508
+ }
509
+
510
+ // 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
511
+ function flushThink(state) {
512
+ const buf = state.thinkBuf || "";
513
+ state.thinkBuf = "";
514
+ return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
515
+ }
516
+
517
+ // 新调用的槽位:保留原始字段形状,只保证 function.arguments 是字符串
518
+ function normalizeCall(toolCall) {
519
+ const fn = toolCall.function || {};
520
+ return {
521
+ ...toolCall,
522
+ function: {
523
+ ...fn,
524
+ arguments: typeof fn.arguments === "string" ? fn.arguments : ""
525
+ }
526
+ };
527
+ }
528
+
529
+ // 续片:按 index 优先归并,否则追加到最后一个槽位
530
+ function mergeToolCall(state, toolCall) {
531
+ if (!state._toolSlots) state._toolSlots = new Map();
532
+
533
+ const calls = state.tool_calls;
534
+ const index = typeof toolCall.index === "number" ? toolCall.index : null;
535
+ const hasId = typeof toolCall.id === "string" && toolCall.id !== "";
536
+
537
+ // 带 id 视为新调用;同 id 重复下发时复用已有槽位
538
+ if (hasId) {
539
+ const exist = calls.find(call => call.id === toolCall.id);
540
+ if (exist) {
541
+ appendArguments(exist, toolCall);
542
+ return;
543
+ }
544
+ const slot = normalizeCall(toolCall);
545
+ calls.push(slot);
546
+ if (index !== null) state._toolSlots.set(index, slot);
547
+ return;
548
+ }
549
+
550
+ let slot = index !== null ? state._toolSlots.get(index) : null;
551
+ if (!slot && calls.length) slot = calls[calls.length - 1];
552
+
553
+ // 首片就没有 id:建占位槽位,后续分片补齐参数
554
+ if (!slot) {
555
+ slot = normalizeCall(toolCall);
556
+ calls.push(slot);
557
+ if (index !== null) state._toolSlots.set(index, slot);
558
+ return;
559
+ }
560
+
561
+ appendArguments(slot, toolCall);
562
+ }
563
+
564
+ function appendArguments(slot, toolCall) {
565
+ const fn = toolCall.function || {};
566
+ if (fn.name && !slot.function.name) slot.function.name = fn.name;
567
+ if (typeof fn.arguments === "string") slot.function.arguments += fn.arguments;
568
+ }
569
+
570
+ // 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
571
+ function handleChoices(choices, { logback, thinkback }, state) {
572
+ if (!Array.isArray(choices)) return;
573
+
574
+ for (let i = 0; i < choices.length; i++) {
575
+ const delta = choices[i].delta;
576
+
577
+ // 推理内容(reasoning / reasoning_content 字段)
578
+ let reasoning = delta.reasoning || delta.reasoning_content;
579
+ if (reasoning) {
580
+ const parsed = parseReasoning(reasoning, delta.content);
581
+ if (typeof parsed === "object") {
582
+ reasoning = parsed.reasoning;
583
+ delta.content = parsed.content;
584
+ }
585
+ if (thinkback) thinkback(reasoning);
586
+ }
587
+
588
+ // 正文内容:剥离混在 content 中的 <think>...</think> 思考片段
589
+ if (delta.content) {
590
+ const extracted = extractThink(delta.content, state);
591
+ if (extracted.thinking && thinkback) thinkback(extracted.thinking);
592
+ if (extracted.content) {
593
+ if (logback) logback(extracted.content);
594
+ state.content += extracted.content;
595
+ }
596
+ }
597
+
598
+ // 工具调用分片
599
+ if (Array.isArray(delta.tool_calls)) {
600
+ for (const toolCall of delta.tool_calls) {
601
+ mergeToolCall(state, toolCall);
602
+ }
603
+ }
604
+ }
605
+ }
606
+
607
+ // 流结束时调用:把 <think> 标签截断残留冲刷到对应回调
608
+ function flushThinkBuffer(state, { logback, thinkback }) {
609
+ const flushed = flushThink(state);
610
+ if (flushed.thinking && thinkback) thinkback(flushed.thinking);
611
+ if (flushed.content) {
612
+ if (logback) logback(flushed.content);
613
+ state.content += flushed.content;
614
+ }
615
+ }
616
+
617
+ // 统一把各种错误形态收敛成 Error,保证 Promise 一定 settle
618
+ function toError(value, fallback) {
619
+ if (value instanceof Error) return value;
620
+ if (value && typeof value.message === "string") return new Error(value.message);
621
+ try {
622
+ return new Error(String(value));
623
+ } catch (e) {
624
+ return new Error(fallback || "模型请求失败");
625
+ }
626
+ }
627
+
628
+ // HTTP 错误:尽量带出响应体里的 error.message,方便定位
629
+ function errorFromHttp(meta, body) {
630
+ const status = meta && meta.status;
631
+ let detail = "";
632
+
633
+ if (body) {
634
+ try {
635
+ const parsed = JSON.parse(body);
636
+ const raw = parsed && parsed.error;
637
+ detail = (raw && (raw.message || raw)) || "";
638
+ } catch (e) {
639
+ detail = String(body).slice(0, 200);
640
+ }
641
+ if (detail && typeof detail !== "string") detail = JSON.stringify(detail);
642
+ }
643
+
644
+ return new Error("模型服务返回 HTTP " + status + (detail ? ":" + detail : ""));
645
+ }
646
+
647
+ function completions(params, logback, thinkback) {
648
+ return new Promise((resolve, reject) => {
649
+
650
+ const state = { content: "", tool_calls: [] };
651
+ const callbacks = { logback, thinkback };
652
+
653
+ let buffer = "";
654
+ let httpError = null;
655
+ let streamError = null;
656
+ let settled = false;
657
+
658
+ const finish = (fn, value) => {
659
+ if (settled) return;
660
+ settled = true;
661
+ fn(value);
662
+ };
663
+ const fail = value => finish(reject, toError(value, "模型请求失败"));
664
+
665
+ const body = {
666
+ model: this.model,
667
+ messages: params.messages,
668
+ tools: params.tools ? params.tools.map(tool => tool.description) : [],
669
+ stream: params.stream,
670
+ };
671
+ const temperature = params.temperature != null ? params.temperature : this.temperature;
672
+ const topP = params.topP != null ? params.topP : this.topP;
673
+ const maxTokens = params.maxTokens != null ? params.maxTokens : this.maxTokens;
674
+ if (temperature != null) body.temperature = temperature;
675
+ if (topP != null) body.top_p = topP;
676
+ if (maxTokens != null) body.max_tokens = maxTokens;
677
+
678
+ fetch$1({
679
+ url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
680
+ method: "POST",
681
+ headers: {
682
+ "Authorization": `Bearer ${this.apiKey}`,
683
+ "Content-Type": "application/json",
684
+ },
685
+ body: JSON.stringify(body),
686
+ timeout: params.timeout != null ? params.timeout : this.timeout,
687
+ signal: params.signal
688
+ }).then(res => {
689
+
690
+ // 非 2xx:非流式等错误体读完再判,流式直接中断
691
+ res.on("http-error", meta => {
692
+ httpError = meta;
693
+ if (params.stream) fail(errorFromHttp(meta));
694
+ });
695
+
696
+ // 数据流
697
+ res.on("data", chunk => {
698
+ if (settled) return;
699
+ if (!params.stream) {
700
+ buffer += chunk;
701
+ return;
702
+ }
703
+ let parsed;
704
+ try {
705
+ parsed = parseString(chunk.toString());
706
+ } catch (e) {
707
+ streamError = e;
708
+ fail(e);
709
+ return;
710
+ }
711
+ try {
712
+ const items = Array.isArray(parsed) ? parsed : [parsed];
713
+ for (const item of items) handleChoices(item.choices, callbacks, state);
714
+ } catch (e) {
715
+ fail(e);
716
+ }
717
+ });
718
+
719
+ // 结束
720
+ res.on("end", () => {
721
+ if (!params.stream) {
722
+ if (httpError) {
723
+ fail(errorFromHttp(httpError, buffer));
724
+ return;
725
+ }
726
+ try {
727
+ const parsed = parseString(buffer);
728
+ const choices = parsed && parsed.choices;
729
+ if (!choices || !choices[0] || !choices[0].message) {
730
+ throw new Error("模型响应缺少 choices[0].message");
731
+ }
732
+ handleChoices([{ delta: choices[0].message }], callbacks, state);
733
+ } catch (e) {
734
+ fail(e);
735
+ return;
736
+ }
737
+ } else if (streamError) {
738
+ fail(streamError);
739
+ return;
740
+ } else if (httpError) {
741
+ fail(errorFromHttp(httpError));
742
+ return;
743
+ }
744
+
745
+ // 冲刷 <think> 标签截断残留
746
+ flushThinkBuffer(state, callbacks);
747
+ finish(resolve, { content: state.content, tool_calls: state.tool_calls });
748
+ });
749
+
750
+ res.on("error", err => fail(err));
751
+ }).catch(err => fail(err));
752
+
753
+ });
754
+ }
755
+
756
+ function Model(fields) {
757
+ this.model = fields.model;
758
+ this.apiKey = fields.apiKey;
759
+ this.baseURL = fields.baseURL;
760
+
761
+ // 可选请求参数:显式传入才写进请求体,保持旧行为不变
762
+ this.temperature = fields.temperature;
763
+ this.topP = fields.topP;
764
+ this.maxTokens = fields.maxTokens;
765
+ this.timeout = fields.timeout;
741
766
  }
742
767
 
743
- function Model(fields) {
744
- this.model = fields.model;
745
- this.apiKey = fields.apiKey;
746
- this.baseURL = fields.baseURL;
747
-
748
- // 可选请求参数:显式传入才写进请求体,保持旧行为不变
749
- this.temperature = fields.temperature;
750
- this.topP = fields.topP;
751
- this.maxTokens = fields.maxTokens;
752
- this.timeout = fields.timeout;
753
- }
754
-
755
768
  Model.prototype.completions = completions;
756
769
 
757
770
  export { Model };