@antdv-next/x-sdk 0.0.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.
@@ -0,0 +1,234 @@
1
+ import XStream from "./x-stream/index.js";
2
+ //#region src/x-request/x-fetch.ts
3
+ var XFetch = async (baseURL, options) => {
4
+ const { fetch: fetchFn = globalThis.fetch, middlewares = {}, ...requestInit } = options;
5
+ if (typeof fetchFn !== "function") throw new Error("The options.fetch must be a typeof fetch function!");
6
+ let fetchArgs = [baseURL, requestInit];
7
+ if (typeof middlewares.onRequest === "function") fetchArgs = await middlewares.onRequest(...fetchArgs);
8
+ let response = await fetchFn(...fetchArgs);
9
+ if (typeof middlewares.onResponse === "function") {
10
+ const modifiedResponse = await middlewares.onResponse(response);
11
+ if (!(modifiedResponse instanceof Response)) throw new Error("The options.onResponse must return a Response instance!");
12
+ response = modifiedResponse;
13
+ }
14
+ if (!response.ok) throw new Error(`Fetch failed with status ${response.status}`);
15
+ if (!response.body) throw new Error("The response body is empty.");
16
+ return response;
17
+ };
18
+ //#endregion
19
+ //#region src/x-request/index.ts
20
+ var globalOptions = {
21
+ manual: false,
22
+ headers: { "Content-Type": "application/json" }
23
+ };
24
+ function setXRequestGlobalOptions(options) {
25
+ Object.assign(globalOptions, options);
26
+ }
27
+ var LastEventId = "Last-Event-ID";
28
+ var AbstractXRequestClass = class {
29
+ baseURL;
30
+ options;
31
+ constructor(baseURL, options) {
32
+ if (!baseURL || typeof baseURL !== "string") throw new Error("The baseURL is not valid!");
33
+ this.baseURL = baseURL;
34
+ this.options = options || {};
35
+ }
36
+ };
37
+ var XRequestClass = class extends AbstractXRequestClass {
38
+ _asyncHandler;
39
+ timeoutHandler;
40
+ _isTimeout = false;
41
+ streamTimeoutHandler;
42
+ _isStreamTimeout = false;
43
+ abortController;
44
+ _isRequesting = false;
45
+ _manual = false;
46
+ lastManualParams;
47
+ retryTimes = 0;
48
+ retryTimer;
49
+ lastEventId = void 0;
50
+ get asyncHandler() {
51
+ return this._asyncHandler;
52
+ }
53
+ get isTimeout() {
54
+ return this._isTimeout;
55
+ }
56
+ set isTimeout(value) {
57
+ this._isTimeout = value;
58
+ }
59
+ get isStreamTimeout() {
60
+ return this._isStreamTimeout;
61
+ }
62
+ set isStreamTimeout(value) {
63
+ this._isStreamTimeout = value;
64
+ }
65
+ get isRequesting() {
66
+ return this._isRequesting;
67
+ }
68
+ get manual() {
69
+ return this._manual;
70
+ }
71
+ constructor(baseURL, options) {
72
+ super(baseURL, options);
73
+ this._manual = options?.manual || false;
74
+ if (!this.manual) this.init();
75
+ }
76
+ run(params) {
77
+ if (this.manual) {
78
+ this.resetRetry();
79
+ this.lastManualParams = params;
80
+ this.init(params);
81
+ return true;
82
+ }
83
+ console.warn("The request is not manual, so it cannot be run!");
84
+ return false;
85
+ }
86
+ abort() {
87
+ clearTimeout(this.timeoutHandler);
88
+ clearTimeout(this.streamTimeoutHandler);
89
+ this.abortController.abort();
90
+ }
91
+ init(extraParams, extraHeaders) {
92
+ this.abortController = new AbortController();
93
+ const { callbacks, params, headers = {}, transformStream, fetch, timeout, streamTimeout, middlewares, streamSeparator, partSeparator, kvSeparator, ...otherOptions } = this.options;
94
+ const margeHeaders = Object.assign({}, globalOptions.headers || {}, headers, extraHeaders || {});
95
+ const requestInit = {
96
+ ...otherOptions,
97
+ method: "POST",
98
+ body: JSON.stringify({
99
+ ...params,
100
+ ...extraParams
101
+ }),
102
+ params: {
103
+ ...params,
104
+ ...extraParams
105
+ },
106
+ headers: margeHeaders,
107
+ signal: this.abortController.signal,
108
+ middlewares
109
+ };
110
+ if (timeout && timeout > 0) this.timeoutHandler = window.setTimeout(() => {
111
+ this.isTimeout = true;
112
+ this.finishRequest();
113
+ callbacks?.onError?.(/* @__PURE__ */ new Error("TimeoutError"));
114
+ }, timeout);
115
+ this.startRequest();
116
+ this._asyncHandler = XFetch(this.baseURL, {
117
+ fetch,
118
+ ...requestInit
119
+ }).then(async (response) => {
120
+ clearTimeout(this.timeoutHandler);
121
+ if (this.isTimeout) return;
122
+ if (transformStream) {
123
+ let transformer = transformStream;
124
+ if (typeof transformStream === "function") transformer = transformStream(this.baseURL, response.headers);
125
+ await this.customResponseHandler(response, callbacks, transformer, streamTimeout, streamSeparator, partSeparator, kvSeparator);
126
+ return;
127
+ }
128
+ const contentType = response.headers.get("content-type") || "";
129
+ switch (contentType.split(";")[0].trim()) {
130
+ case "text/event-stream":
131
+ await this.sseResponseHandler(response, callbacks, streamTimeout, streamSeparator, partSeparator, kvSeparator);
132
+ break;
133
+ case "application/json":
134
+ await this.jsonResponseHandler(response, callbacks);
135
+ break;
136
+ default: throw new Error(`The response content-type: ${contentType} is not support!`);
137
+ }
138
+ }).catch((error) => {
139
+ clearTimeout(this.timeoutHandler);
140
+ this.finishRequest();
141
+ const err = error instanceof Error || error instanceof DOMException ? error : /* @__PURE__ */ new Error("Unknown error!");
142
+ const returnOfOnError = callbacks?.onError?.(err);
143
+ if (err.name !== "AbortError") {
144
+ const retryInterval = typeof returnOfOnError === "number" ? returnOfOnError : this.options.retryInterval;
145
+ if (retryInterval && retryInterval > 0) {
146
+ if (typeof this.options.retryTimes === "number" && this.retryTimes >= this.options.retryTimes) return;
147
+ clearTimeout(this.retryTimer);
148
+ this.retryTimer = setTimeout(() => {
149
+ const extraHeaders = {};
150
+ if (typeof this.lastEventId !== "undefined") extraHeaders[LastEventId] = this.lastEventId;
151
+ this.init(this.lastManualParams, extraHeaders);
152
+ }, retryInterval);
153
+ this.retryTimes = this.retryTimes + 1;
154
+ }
155
+ }
156
+ });
157
+ }
158
+ startRequest() {
159
+ this._isRequesting = true;
160
+ }
161
+ finishRequest() {
162
+ this._isRequesting = false;
163
+ }
164
+ customResponseHandler = async (response, callbacks, transformStream, streamTimeout, streamSeparator, partSeparator, kvSeparator) => {
165
+ const stream = XStream({
166
+ readableStream: response.body,
167
+ transformStream,
168
+ streamSeparator,
169
+ partSeparator,
170
+ kvSeparator
171
+ });
172
+ await this.processStream(stream, response, callbacks, streamTimeout);
173
+ };
174
+ sseResponseHandler = async (response, callbacks, streamTimeout, streamSeparator, partSeparator, kvSeparator) => {
175
+ const stream = XStream({
176
+ readableStream: response.body,
177
+ streamSeparator,
178
+ partSeparator,
179
+ kvSeparator
180
+ });
181
+ await this.processStream(stream, response, callbacks, streamTimeout);
182
+ };
183
+ async processStream(stream, response, callbacks, streamTimeout) {
184
+ const chunks = [];
185
+ const iterator = stream[Symbol.asyncIterator]();
186
+ let result;
187
+ do {
188
+ if (streamTimeout) this.streamTimeoutHandler = window.setTimeout(() => {
189
+ this.isStreamTimeout = true;
190
+ this.finishRequest();
191
+ callbacks?.onError?.(/* @__PURE__ */ new Error("StreamTimeoutError"), void 0, response.headers);
192
+ }, streamTimeout);
193
+ result = await iterator.next();
194
+ clearTimeout(this.streamTimeoutHandler);
195
+ if (this.isStreamTimeout) break;
196
+ if (result.value) {
197
+ chunks.push(result.value);
198
+ callbacks?.onUpdate?.(result.value, response.headers);
199
+ if (typeof result?.value?.id !== "undefined") this.lastEventId = result.value.id;
200
+ }
201
+ } while (!result.done);
202
+ if (streamTimeout) {
203
+ clearTimeout(this.streamTimeoutHandler);
204
+ if (this.isStreamTimeout) {
205
+ this.finishRequest();
206
+ return;
207
+ }
208
+ }
209
+ this.finishRequest();
210
+ callbacks?.onSuccess?.(chunks, response.headers);
211
+ }
212
+ jsonResponseHandler = async (response, callbacks) => {
213
+ const chunk = await response.json();
214
+ if (chunk?.success === false) {
215
+ const error = new Error(chunk.message || "System error");
216
+ error.name = chunk.name || "SystemError";
217
+ callbacks?.onError?.(error, chunk, response.headers);
218
+ } else {
219
+ callbacks?.onUpdate?.(chunk, response.headers);
220
+ this.finishRequest();
221
+ callbacks?.onSuccess?.([chunk], response.headers);
222
+ }
223
+ };
224
+ resetRetry() {
225
+ clearTimeout(this.retryTimer);
226
+ this.retryTimes = 0;
227
+ this.lastEventId = void 0;
228
+ }
229
+ };
230
+ function XRequest(baseURL, options) {
231
+ return new XRequestClass(baseURL, options);
232
+ }
233
+ //#endregion
234
+ export { setXRequestGlobalOptions as i, XRequest as n, XRequestClass as r, AbstractXRequestClass as t };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#fields
3
+ */
4
+ export type SSEFields = "data" | "event" | "id" | "retry";
5
+ /**
6
+ * @example
7
+ * const sseObject = {
8
+ * event: 'delta',
9
+ * data: '{ key: "world!" }',
10
+ * };
11
+ */
12
+ export type SSEOutput = Partial<Record<SSEFields, any>>;
13
+ export interface JSONOutPut extends Partial<Record<SSEFields, any>> {
14
+ success: boolean;
15
+ message?: string;
16
+ name?: string;
17
+ }
18
+ export interface XStreamOptions<Output> {
19
+ /**
20
+ * @description Readable stream of binary data
21
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
22
+ */
23
+ readableStream: ReadableStream<Uint8Array>;
24
+ /**
25
+ * @description Support customizable transformStream to transform streams
26
+ * @default sseTransformStream
27
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/TransformStream
28
+ */
29
+ transformStream?: TransformStream<string, Output>;
30
+ /**
31
+ * @description Separator for stream data parsing
32
+ */
33
+ streamSeparator?: string;
34
+ /**
35
+ * @description Separator for different parts within the stream
36
+ */
37
+ partSeparator?: string;
38
+ /**
39
+ * @description Separator for key-value pairs in the stream data
40
+ */
41
+ kvSeparator?: string;
42
+ }
43
+ export type XReadableStream<R = SSEOutput> = ReadableStream<R> & AsyncGenerator<R>;
44
+ /**
45
+ * @description Transform Uint8Array binary stream to {@link SSEOutput} by default
46
+ * @warning The `XStream` only support the `utf-8` encoding. More encoding support maybe in the future.
47
+ */
48
+ declare function XStream<Output = SSEOutput>(options: XStreamOptions<Output>): XReadableStream<Output>;
49
+ export default XStream;
@@ -0,0 +1,114 @@
1
+ //#region src/x-stream/index.ts
2
+ /**
3
+ * @description default separator for {@link splitStream}
4
+ */
5
+ var DEFAULT_STREAM_SEPARATOR = "\n\n";
6
+ /**
7
+ * @description Default separator for {@link splitPart}
8
+ * @example "event: delta\ndata: {\"key\": \"value\"}"
9
+ */
10
+ var DEFAULT_PART_SEPARATOR = "\n";
11
+ /**
12
+ * @description Default separator for key value, A colon (`:`) is used to separate keys from values
13
+ * @example "event: delta"
14
+ */
15
+ var DEFAULT_KV_SEPARATOR = ":";
16
+ /**
17
+ * Check if a string is not empty or only contains whitespace characters
18
+ */
19
+ var isValidString = (str) => (str ?? "").trim() !== "";
20
+ /**
21
+ * @description A TransformStream inst that splits a stream into parts based on {@link DEFAULT_STREAM_SEPARATOR}
22
+ * @example
23
+ *
24
+ * `event: delta
25
+ * data: { content: 'hello' }
26
+ *
27
+ * event: delta
28
+ * data: { key: 'world!' }
29
+ *
30
+ * `
31
+ */
32
+ function splitStream(streamSeparator = DEFAULT_STREAM_SEPARATOR) {
33
+ let buffer = "";
34
+ return new TransformStream({
35
+ transform(streamChunk, controller) {
36
+ buffer += streamChunk;
37
+ const parts = buffer.split(streamSeparator);
38
+ parts.slice(0, -1).forEach((part) => {
39
+ if (isValidString(part)) controller.enqueue(part);
40
+ });
41
+ buffer = parts[parts.length - 1];
42
+ },
43
+ flush(controller) {
44
+ if (isValidString(buffer)) controller.enqueue(buffer);
45
+ }
46
+ });
47
+ }
48
+ /**
49
+ * @description A TransformStream inst that transforms a part string into {@link SSEOutput}
50
+ * @example part string
51
+ *
52
+ * "event: delta\ndata: { key: 'world!' }\n"
53
+ *
54
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/EventSource
55
+ *
56
+ * When handling responses with `Content-Type: text/event-stream`, the following standard practices are commonly observed:
57
+ * - Double newline characters (`\n\n`) are used to separate individual events.
58
+ * - Single newline characters (`\n`) are employed to separate line within an event.
59
+ */
60
+ function splitPart(partSeparator = DEFAULT_PART_SEPARATOR, kvSeparator = DEFAULT_KV_SEPARATOR) {
61
+ return new TransformStream({ transform(partChunk, controller) {
62
+ const sseEvent = partChunk.split(partSeparator).reduce((acc, line) => {
63
+ const separatorIndex = line.indexOf(kvSeparator);
64
+ if (separatorIndex === -1) {
65
+ console.warn(`The key-value separator "${kvSeparator}" is not found in the sse line: ${line} !`);
66
+ return acc;
67
+ }
68
+ const key = line.slice(0, separatorIndex).trim();
69
+ if (!isValidString(key)) return acc;
70
+ const value = line.slice(separatorIndex + 1).trim();
71
+ return {
72
+ ...acc,
73
+ [key]: value
74
+ };
75
+ }, {});
76
+ if (Object.keys(sseEvent).length === 0) return;
77
+ controller.enqueue(sseEvent);
78
+ } });
79
+ }
80
+ function createDecoderStream() {
81
+ if (typeof TextDecoderStream !== "undefined") return new TextDecoderStream();
82
+ const decoder = new TextDecoder("utf-8");
83
+ return new TransformStream({
84
+ transform(chunk, controller) {
85
+ controller.enqueue(decoder.decode(chunk, { stream: true }));
86
+ },
87
+ flush(controller) {
88
+ controller.enqueue(decoder.decode());
89
+ }
90
+ });
91
+ }
92
+ /**
93
+ * @description Transform Uint8Array binary stream to {@link SSEOutput} by default
94
+ * @warning The `XStream` only support the `utf-8` encoding. More encoding support maybe in the future.
95
+ */
96
+ function XStream(options) {
97
+ const { readableStream, transformStream, streamSeparator, partSeparator, kvSeparator } = options;
98
+ if (!(readableStream instanceof ReadableStream)) throw new Error("The options.readableStream must be an instance of ReadableStream.");
99
+ const decoderStream = createDecoderStream();
100
+ const stream = transformStream ? readableStream.pipeThrough(decoderStream).pipeThrough(transformStream) : readableStream.pipeThrough(decoderStream).pipeThrough(splitStream(streamSeparator)).pipeThrough(splitPart(partSeparator, kvSeparator));
101
+ /** support async iterator */
102
+ stream[Symbol.asyncIterator] = async function* () {
103
+ const reader = this.getReader();
104
+ while (true) {
105
+ const { done, value } = await reader.read();
106
+ if (done) break;
107
+ if (!value) continue;
108
+ yield value;
109
+ }
110
+ };
111
+ return stream;
112
+ }
113
+ //#endregion
114
+ export { XStream as default };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@antdv-next/x-sdk",
3
+ "version": "0.0.1",
4
+ "files": [
5
+ "dist"
6
+ ],
7
+ "type": "module",
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ },
16
+ "./chat-providers": {
17
+ "types": "./dist/chat-providers/index.d.ts",
18
+ "import": "./dist/chat-providers/index.js"
19
+ },
20
+ "./chat-providers/types/model": {
21
+ "types": "./dist/chat-providers/types/model.d.ts",
22
+ "import": "./dist/chat-providers/types/model.js"
23
+ },
24
+ "./x-chat": {
25
+ "types": "./dist/x-chat/index.d.ts",
26
+ "import": "./dist/x-chat/index.js"
27
+ },
28
+ "./x-conversations": {
29
+ "types": "./dist/x-conversations/index.d.ts",
30
+ "import": "./dist/x-conversations/index.js"
31
+ },
32
+ "./x-request": {
33
+ "types": "./dist/x-request/index.d.ts",
34
+ "import": "./dist/x-request/index.js"
35
+ },
36
+ "./x-stream": {
37
+ "types": "./dist/x-stream/index.d.ts",
38
+ "import": "./dist/x-stream/index.js"
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "peerDependencies": {
46
+ "vue": ">=3.5.0"
47
+ },
48
+ "scripts": {
49
+ "type-check": "tsc --project tsconfig.json --noEmit",
50
+ "build": "vp build --config vite.build.config.ts"
51
+ }
52
+ }