@axiom-lattice/client-sdk 1.0.43 → 1.0.44

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,282 @@
1
+ /**
2
+ * Core types for the Axiom Lattice Client SDK
3
+ */
4
+ import { Message, MessageChunk } from "@axiom-lattice/protocols";
5
+ /**
6
+ * Transport method for client-server communication
7
+ * Note: Currently only "ws" is used for tool registration
8
+ */
9
+ export type Transport = "sse" | "ws";
10
+ /**
11
+ * Configuration options for the Client
12
+ */
13
+ export interface ClientConfig {
14
+ /**
15
+ * Base URL for the API
16
+ */
17
+ baseURL: string;
18
+ /**
19
+ * API key for authentication
20
+ */
21
+ apiKey: string;
22
+ /**
23
+ * Assistant identifier
24
+ */
25
+ assistantId: string;
26
+ /**
27
+ * Transport method (Server-Sent Events or WebSocket)
28
+ */
29
+ transport: Transport;
30
+ /**
31
+ * Request timeout in milliseconds (optional, defaults to 30000)
32
+ */
33
+ timeout?: number;
34
+ /**
35
+ * Additional headers to include in requests (optional)
36
+ */
37
+ headers?: Record<string, string>;
38
+ /**
39
+ * Configuration for retry behavior (optional)
40
+ */
41
+ retry?: RetryConfig;
42
+ }
43
+ /**
44
+ * Configuration for retry behavior
45
+ */
46
+ export interface RetryConfig {
47
+ /**
48
+ * Maximum number of retry attempts
49
+ */
50
+ maxRetries: number;
51
+ /**
52
+ * Initial delay between retries in milliseconds
53
+ */
54
+ initialDelayMs: number;
55
+ /**
56
+ * Maximum delay between retries in milliseconds
57
+ */
58
+ maxDelayMs: number;
59
+ /**
60
+ * Factor to multiply delay by after each retry attempt
61
+ */
62
+ backoffFactor: number;
63
+ }
64
+ /**
65
+ * Thread creation options
66
+ */
67
+ export interface CreateThreadOptions {
68
+ /**
69
+ * Optional metadata for the thread
70
+ */
71
+ metadata?: Record<string, any>;
72
+ }
73
+ /**
74
+ * Thread information
75
+ */
76
+ export interface Thread {
77
+ /**
78
+ * Thread identifier
79
+ */
80
+ id: string;
81
+ /**
82
+ * Thread metadata
83
+ */
84
+ metadata?: Record<string, any>;
85
+ /**
86
+ * Thread creation timestamp
87
+ */
88
+ createdAt: string;
89
+ }
90
+ /**
91
+ * Chat send options
92
+ */
93
+ export interface ChatSendOptions {
94
+ /**
95
+ * Thread identifier
96
+ */
97
+ threadId: string;
98
+ /**
99
+ * Messages to send
100
+ */
101
+ messages: Message[];
102
+ /**
103
+ * Files to attach (optional)
104
+ */
105
+ files?: any[];
106
+ /**
107
+ * Command to execute (optional)
108
+ */
109
+ command?: {
110
+ resume?: {
111
+ action: string;
112
+ data: Record<string, any> & {
113
+ config?: {
114
+ thread_id?: string;
115
+ work_log_id?: string;
116
+ };
117
+ };
118
+ message: string;
119
+ };
120
+ update?: any;
121
+ send?: {
122
+ node: string;
123
+ input: any;
124
+ };
125
+ };
126
+ }
127
+ /**
128
+ * Chat stream options
129
+ */
130
+ export interface ChatStreamOptions extends ChatSendOptions {
131
+ /**
132
+ * Whether to run in background (optional)
133
+ */
134
+ background?: boolean;
135
+ /**
136
+ * Whether to return agent state when stream completes (optional)
137
+ */
138
+ enableReturnStateWhenSteamCompleted?: boolean;
139
+ }
140
+ /**
141
+ * Stream callbacks interface
142
+ */
143
+ export interface StreamCallbacks {
144
+ /**
145
+ * Called when a stream event is received
146
+ */
147
+ onEvent: (event: MessageChunk) => void;
148
+ /**
149
+ * Called when the stream completes, with optional agent state
150
+ */
151
+ onComplete?: (state?: AgentState) => void;
152
+ /**
153
+ * Called when an error occurs
154
+ */
155
+ onError?: (error: Error) => void;
156
+ }
157
+ /**
158
+ * Chat response
159
+ */
160
+ export interface ChatResponse {
161
+ /**
162
+ * Response messages
163
+ */
164
+ messages: Message[];
165
+ /**
166
+ * Trace ID for debugging
167
+ */
168
+ traceId?: string;
169
+ }
170
+ /**
171
+ * Tool registration options
172
+ */
173
+ export interface RegisterToolOptions {
174
+ /**
175
+ * Tool name
176
+ */
177
+ name: string;
178
+ /**
179
+ * Tool parameter schema
180
+ */
181
+ schema: object;
182
+ /**
183
+ * Tool handler function
184
+ */
185
+ handler: (params: any) => Promise<any>;
186
+ }
187
+ /**
188
+ * Get messages options
189
+ */
190
+ export interface GetMessagesOptions {
191
+ /**
192
+ * Thread identifier
193
+ */
194
+ threadId: string;
195
+ /**
196
+ * Maximum number of messages to return
197
+ */
198
+ limit?: number;
199
+ /**
200
+ * Message ID to start from (for pagination)
201
+ */
202
+ after?: string;
203
+ /**
204
+ * Whether to return messages in reverse chronological order
205
+ */
206
+ reverse?: boolean;
207
+ }
208
+ /**
209
+ * Thread list options
210
+ */
211
+ export interface ListThreadsOptions {
212
+ /**
213
+ * Maximum number of threads to return
214
+ */
215
+ limit?: number;
216
+ /**
217
+ * Offset for pagination
218
+ */
219
+ offset?: number;
220
+ }
221
+ /**
222
+ * Run options
223
+ */
224
+ export type RunOptions = {
225
+ /**
226
+ * Thread identifier
227
+ */
228
+ threadId: string;
229
+ /**
230
+ * Message to send
231
+ */
232
+ message: string;
233
+ /**
234
+ * Files to attach (optional)
235
+ */
236
+ files?: any[];
237
+ /**
238
+ * Command to execute (optional)
239
+ */
240
+ command?: any;
241
+ /**
242
+ * Whether to stream the response (optional)
243
+ */
244
+ streaming?: boolean;
245
+ /**
246
+ * Whether to run in background (optional)
247
+ */
248
+ background?: boolean;
249
+ /**
250
+ * Whether to return agent state when stream completes (optional)
251
+ */
252
+ enableReturnStateWhenSteamCompleted?: boolean;
253
+ } & Record<string, any>;
254
+ /**
255
+ * Agent state
256
+ */
257
+ export interface AgentState {
258
+ values: {
259
+ messages: Message[];
260
+ [key: string]: any;
261
+ };
262
+ tasks: Array<{
263
+ interrupts: Array<{
264
+ value: any;
265
+ }>;
266
+ }>;
267
+ }
268
+ /**
269
+ * Custom error classes
270
+ */
271
+ export declare class ApiError extends Error {
272
+ statusCode: number;
273
+ responseBody?: any | undefined;
274
+ constructor(message: string, statusCode: number, responseBody?: any | undefined);
275
+ }
276
+ export declare class NetworkError extends Error {
277
+ constructor(message: string);
278
+ }
279
+ export declare class AuthenticationError extends Error {
280
+ constructor(message: string);
281
+ }
282
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EACL,OAAO,EAMP,YAAY,EACb,MAAM,0BAA0B,CAAC;AAElC;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG,KAAK,GAAG,IAAI,CAAC;AAErC;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,SAAS,EAAE,SAAS,CAAC;IAErB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAEjC;;OAEG;IACH,KAAK,CAAC,EAAE,WAAW,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;IAEvB;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,aAAa,EAAE,MAAM,CAAC;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAChC;AAED;;GAEG;AACH,MAAM,WAAW,MAAM;IACrB;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAE/B;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC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B,KAAK,EAAE,GAAG,CAAC;SACZ,CAAC,CAAC;KACJ,CAAC,CAAC;CACJ;AAED;;GAEG;AACH,qBAAa,QAAS,SAAQ,KAAK;IAGxB,UAAU,EAAE,MAAM;IAClB,YAAY,CAAC,EAAE,GAAG;gBAFzB,OAAO,EAAE,MAAM,EACR,UAAU,EAAE,MAAM,EAClB,YAAY,CAAC,EAAE,GAAG,YAAA;CAK5B;AAED,qBAAa,YAAa,SAAQ,KAAK;gBACzB,OAAO,EAAE,MAAM;CAI5B;AAED,qBAAa,mBAAoB,SAAQ,KAAK;gBAChC,OAAO,EAAE,MAAM;CAI5B"}
package/dist/types.js ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Core types for the Axiom Lattice Client SDK
3
+ */
4
+ /**
5
+ * Custom error classes
6
+ */
7
+ export class ApiError extends Error {
8
+ constructor(message, statusCode, responseBody) {
9
+ super(message);
10
+ this.statusCode = statusCode;
11
+ this.responseBody = responseBody;
12
+ this.name = "ApiError";
13
+ }
14
+ }
15
+ export class NetworkError extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "NetworkError";
19
+ }
20
+ }
21
+ export class AuthenticationError extends Error {
22
+ constructor(message) {
23
+ super(message);
24
+ this.name = "AuthenticationError";
25
+ }
26
+ }
27
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAwTH;;GAEG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACjC,YACE,OAAe,EACR,UAAkB,EAClB,YAAkB;QAEzB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHR,eAAU,GAAV,UAAU,CAAQ;QAClB,iBAAY,GAAZ,YAAY,CAAM;QAGzB,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;IACzB,CAAC;CACF;AAED,MAAM,OAAO,YAAa,SAAQ,KAAK;IACrC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;IAC7B,CAAC;CACF;AAED,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC5C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACpC,CAAC;CACF"}
@@ -0,0 +1,56 @@
1
+ import { MessageChunk } from "@axiom-lattice/protocols";
2
+ import { AgentState, ClientConfig, RunOptions } from "./types";
3
+ import { AbstractClient } from "./abstract-client";
4
+ /**
5
+ * WeChat Mini Program client for interacting with the Axiom Lattice Agent Service API
6
+ */
7
+ export declare class WeChatClient extends AbstractClient {
8
+ /**
9
+ * Creates a new WeChatClient instance
10
+ * @param config - Configuration options for the client
11
+ */
12
+ constructor(config: ClientConfig);
13
+ /**
14
+ * Set tenant ID for multi-tenant environments
15
+ * @param tenantId - Tenant identifier
16
+ */
17
+ setTenantId(tenantId: string): void;
18
+ /**
19
+ * Implementation of the abstract makeRequest method for WeChat clients
20
+ * @param url - The URL to make the request to
21
+ * @param options - Request options
22
+ * @returns A promise that resolves to the response data
23
+ */
24
+ protected makeRequest<T>(url: string, options?: {
25
+ method?: string;
26
+ body?: any;
27
+ headers?: Record<string, string>;
28
+ }): Promise<T>;
29
+ /**
30
+ * Implementation of the abstract streamRequest method for WeChat clients
31
+ */
32
+ protected streamRequest(options: RunOptions, onEvent: (event: MessageChunk) => void, onComplete?: (state?: AgentState) => void, onError?: (error: Error) => void): () => void;
33
+ /**
34
+ * Helper method to make WeChat HTTP requests
35
+ * @private
36
+ */
37
+ private request;
38
+ /**
39
+ * Stream run results using WeChat's downloadFile API
40
+ * @param options - Options for streaming run results
41
+ * @param onEvent - Callback function that receives stream events
42
+ * @param onComplete - Optional callback function called when streaming completes
43
+ * @param onError - Optional callback function called when an error occurs
44
+ * @returns A function that can be called to stop the stream
45
+ */
46
+ private streamRun;
47
+ decodeUint8Array(uint8Array: ArrayBuffer): any;
48
+ buf2hex(arrayBuffer: ArrayBuffer): string;
49
+ /**
50
+ * 十六进制字符串转中文
51
+ * @param {String} hex 为十六进制字符串
52
+ * @return {String} 包含中文的字符串
53
+ */
54
+ hexToStr(hex: string): any;
55
+ }
56
+ //# sourceMappingURL=wechat-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wechat-client.d.ts","sourceRoot":"","sources":["../src/wechat-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACL,UAAU,EAMV,YAAY,EAMZ,UAAU,EAEX,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD;;GAEG;AACH,qBAAa,YAAa,SAAQ,cAAc;IAC9C;;;OAGG;gBACS,MAAM,EAAE,YAAY;IAOhC;;;OAGG;IACH,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAInC;;;;;OAKG;cACa,WAAW,CAAC,CAAC,EAC3B,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE;QACR,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,IAAI,CAAC,EAAE,GAAG,CAAC;QACX,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;KAClC,GACA,OAAO,CAAC,CAAC,CAAC;IA2Bb;;OAEG;IACH,SAAS,CAAC,aAAa,CACrB,OAAO,EAAE,UAAU,EACnB,OAAO,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,EACtC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,UAAU,KAAK,IAAI,EACzC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,GAC/B,MAAM,IAAI;IAIb;;;OAGG;YACW,OAAO;IAqDrB;;;;;;;OAOG;IACH,OAAO,CAAC,SAAS;IAyFjB,gBAAgB,CAAC,UAAU,EAAE,WAAW;IAKxC,OAAO,CAAC,WAAW,EAAE,WAAW;IAOhC;;;;OAIG;IACH,QAAQ,CAAC,GAAG,EAAE,MAAM;CAyBrB"}
@@ -0,0 +1,226 @@
1
+ import { ApiError, AuthenticationError, NetworkError, } from "./types";
2
+ import { AbstractClient } from "./abstract-client";
3
+ import encoding from "./wechat_lib/encoding.js";
4
+ /**
5
+ * WeChat Mini Program client for interacting with the Axiom Lattice Agent Service API
6
+ */
7
+ export class WeChatClient extends AbstractClient {
8
+ /**
9
+ * Creates a new WeChatClient instance
10
+ * @param config - Configuration options for the client
11
+ */
12
+ constructor(config) {
13
+ super({
14
+ timeout: 300000,
15
+ ...config,
16
+ });
17
+ }
18
+ /**
19
+ * Set tenant ID for multi-tenant environments
20
+ * @param tenantId - Tenant identifier
21
+ */
22
+ setTenantId(tenantId) {
23
+ this.tenantId = tenantId;
24
+ }
25
+ /**
26
+ * Implementation of the abstract makeRequest method for WeChat clients
27
+ * @param url - The URL to make the request to
28
+ * @param options - Request options
29
+ * @returns A promise that resolves to the response data
30
+ */
31
+ async makeRequest(url, options) {
32
+ // Convert method to WeChat's expected type
33
+ const methodStr = options?.method || "GET";
34
+ const method = methodStr;
35
+ // Build full URL with query parameters if provided
36
+ let fullUrl = `${this.config.baseURL}${url}`;
37
+ // Prepare headers
38
+ const headers = {
39
+ "Content-Type": "application/json",
40
+ Authorization: `Bearer ${this.config.apiKey}`,
41
+ ...this.config.headers,
42
+ ...(options?.headers || {}),
43
+ };
44
+ if (this.tenantId) {
45
+ headers["x-tenant-id"] = this.tenantId;
46
+ }
47
+ return this.request({
48
+ url: fullUrl,
49
+ method,
50
+ data: options?.body,
51
+ });
52
+ }
53
+ /**
54
+ * Implementation of the abstract streamRequest method for WeChat clients
55
+ */
56
+ streamRequest(options, onEvent, onComplete, onError) {
57
+ return this.streamRun(options, onEvent, onComplete, onError);
58
+ }
59
+ /**
60
+ * Helper method to make WeChat HTTP requests
61
+ * @private
62
+ */
63
+ async request(options) {
64
+ const { url, method, data } = options;
65
+ // Prepare headers
66
+ const headers = {
67
+ "Content-Type": "application/json",
68
+ Authorization: `Bearer ${this.config.apiKey}`,
69
+ ...this.config.headers,
70
+ };
71
+ if (this.tenantId) {
72
+ headers["x-tenant-id"] = this.tenantId;
73
+ }
74
+ return new Promise((resolve, reject) => {
75
+ wx.request({
76
+ url,
77
+ method,
78
+ data,
79
+ header: headers,
80
+ timeout: this.config.timeout,
81
+ success: (res) => {
82
+ const statusCode = res.statusCode;
83
+ if (statusCode >= 200 && statusCode < 300) {
84
+ resolve(res.data);
85
+ }
86
+ else if (statusCode === 401) {
87
+ reject(new AuthenticationError(res.data?.message || "Authentication failed"));
88
+ }
89
+ else {
90
+ reject(new ApiError(res.data?.message || "API Error", statusCode, res.data));
91
+ }
92
+ },
93
+ fail: (err) => {
94
+ reject(new NetworkError(`Request failed: ${err.errMsg}`));
95
+ },
96
+ });
97
+ });
98
+ }
99
+ /**
100
+ * Stream run results using WeChat's downloadFile API
101
+ * @param options - Options for streaming run results
102
+ * @param onEvent - Callback function that receives stream events
103
+ * @param onComplete - Optional callback function called when streaming completes
104
+ * @param onError - Optional callback function called when an error occurs
105
+ * @returns A function that can be called to stop the stream
106
+ */
107
+ streamRun(options, onEvent, onComplete, onError) {
108
+ // Prepare headers
109
+ const headers = {
110
+ "Content-Type": "application/json",
111
+ Authorization: `Bearer ${this.config.apiKey}`,
112
+ ...this.config.headers,
113
+ };
114
+ if (this.tenantId) {
115
+ headers["x-tenant-id"] = this.tenantId;
116
+ }
117
+ // Get request parameters from the abstract method
118
+ const requestParams = this.buildStreamRequestParams(options);
119
+ // Create a task ID to track and potentially abort the request
120
+ const taskId = wx.request({
121
+ url: `${this.config.baseURL}${requestParams.url}`,
122
+ method: requestParams.method,
123
+ data: requestParams.body,
124
+ header: headers,
125
+ responseType: "text",
126
+ enableChunked: true,
127
+ success: async () => {
128
+ // This will be called when the connection is established
129
+ // Actual data processing happens in the dataReceived callback
130
+ },
131
+ fail: (err) => {
132
+ if (onError) {
133
+ onError(new Error(`Stream request failed: ${err.errMsg}`));
134
+ }
135
+ },
136
+ complete: async () => {
137
+ if (onComplete) {
138
+ // Fetch agent state before calling onComplete if enabled
139
+ if (options.enableReturnStateWhenSteamCompleted) {
140
+ try {
141
+ const state = await this.getAgentState(options.threadId);
142
+ onComplete(state);
143
+ }
144
+ catch (error) {
145
+ // If getting state fails, still call onComplete without state
146
+ onComplete();
147
+ }
148
+ }
149
+ else {
150
+ // Just call onComplete without state if not enabled
151
+ onComplete();
152
+ }
153
+ }
154
+ },
155
+ // Using WeChat's chunked data capability
156
+ dataReceived: (res) => {
157
+ if (!res.data)
158
+ return;
159
+ // Process the raw data line by line
160
+ const text = this.decodeUint8Array(res.data);
161
+ const lines = text.split("\n");
162
+ for (const line of lines) {
163
+ if (line.trim().startsWith("data: ")) {
164
+ try {
165
+ const eventData = JSON.parse(line.trim().slice(6));
166
+ onEvent(eventData);
167
+ }
168
+ catch (error) {
169
+ if (onError) {
170
+ onError(error instanceof Error ? error : new Error(String(error)));
171
+ }
172
+ }
173
+ }
174
+ }
175
+ },
176
+ });
177
+ // Return a function to abort the request
178
+ return () => {
179
+ wx.abortRequest({
180
+ requestId: taskId,
181
+ success: () => console.log("Stream request aborted"),
182
+ fail: (err) => console.error("Failed to abort stream request:", err.errMsg),
183
+ });
184
+ };
185
+ }
186
+ decodeUint8Array(uint8Array) {
187
+ const data16 = this.buf2hex(uint8Array);
188
+ const requestData = this.hexToStr(data16);
189
+ return requestData;
190
+ }
191
+ buf2hex(arrayBuffer) {
192
+ return Array.prototype.map
193
+ .call(new Uint8Array(arrayBuffer), (x) => ("00" + x.toString(16)).slice(-2))
194
+ .join("");
195
+ }
196
+ /**
197
+ * 十六进制字符串转中文
198
+ * @param {String} hex 为十六进制字符串
199
+ * @return {String} 包含中文的字符串
200
+ */
201
+ hexToStr(hex) {
202
+ // 去掉字符串首尾空格
203
+ let trimedStr = hex.trim();
204
+ // 判断trimedStr前两个字符是否为0x,如果是则截取从第三个字符及后面所有,否则返回全部字符
205
+ let rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x"
206
+ ? trimedStr.substr(2)
207
+ : trimedStr;
208
+ // 得到rawStr的长度
209
+ let len = rawStr.length;
210
+ // 如果长度不能被2整除,那么传入的十六进制值有误,返回空字符
211
+ if (len % 2 !== 0) {
212
+ return "";
213
+ }
214
+ let curCharCode; // 接收每次循环得到的字符
215
+ let resultStr = []; // 存转换后的十进制值数组
216
+ for (let i = 0; i < len; i = i + 2) {
217
+ curCharCode = parseInt(rawStr.substr(i, 2), 16);
218
+ resultStr.push(curCharCode);
219
+ }
220
+ // encoding为空时默认为utf-8
221
+ let bytesView = new Uint8Array(resultStr); // 8 位无符号整数值的类型化数组
222
+ let str = new encoding.TextDecoder().decode(bytesView);
223
+ return str;
224
+ }
225
+ }
226
+ //# sourceMappingURL=wechat-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wechat-client.js","sourceRoot":"","sources":["../src/wechat-client.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,QAAQ,EACR,mBAAmB,EAQnB,YAAY,GAIb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,QAAQ,MAAM,0BAA0B,CAAC;AAChD;;GAEG;AACH,MAAM,OAAO,YAAa,SAAQ,cAAc;IAC9C;;;OAGG;IACH,YAAY,MAAoB;QAC9B,KAAK,CAAC;YACJ,OAAO,EAAE,MAAM;YACf,GAAG,MAAM;SACV,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACH,WAAW,CAAC,QAAgB;QAC1B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED;;;;;OAKG;IACO,KAAK,CAAC,WAAW,CACzB,GAAW,EACX,OAIC;QAED,2CAA2C;QAC3C,MAAM,SAAS,GAAG,OAAO,EAAE,MAAM,IAAI,KAAK,CAAC;QAC3C,MAAM,MA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AC9B,CAAC;QACD,sBAAsB;QACtB,IAAI,SAAS,GAAG,IAAI,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,kBAAkB;QAC7D,IAAI,GAAG,GAAG,IAAI,QAAQ,CAAC,WAAW,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACvD,OAAO,GAAG,CAAC;IACb,CAAC;CACF"}
@@ -0,0 +1,2 @@
1
+ export = global;
2
+ //# sourceMappingURL=encoding-indexes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encoding-indexes.d.ts","sourceRoot":"","sources":["../../src/wechat_lib/encoding-indexes.js"],"names":[],"mappings":""}