xshell 1.0.6 → 1.0.8

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.
@@ -1 +1 @@
1
- {"version":3,"file":"net.browser.js","sourceRoot":"","sources":["net.browser.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAA;AACtC,OAAO,wBAAwB,CAAA,CAAE,gBAAgB;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AA+B1D,MAAM,CAAC,KAAK,UAAU,OAAO,CAAE,GAAiB,EAAE,EAC9C,MAAM,EAEN,OAAO,EAEP,OAAO,EAEP,IAAI,EAEJ,IAAI,GAAG,kBAAkB,EAEzB,IAAI,EAEJ,EAAE,GAAG,MAAM,CAAC,iBAAiB,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,OAAO,EAE7D,GAAG,MACiC,EAAG;IACvC,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAA;IAEjC,IAAI,OAAO;QACP,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE;YACvB,IAAI,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAA;YACxB,IAAI,OAAO,KAAK,KAAK,SAAS;gBAC1B,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAA;YAC7B,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;SACtC;IAEL,IAAI,IAAI,IAAI,CAAC,MAAM;QACf,MAAM,GAAG,MAAM,CAAA;IAEnB,IAAI,IAAI,KAAK,kBAAkB,IAAI,OAAO,IAAI,KAAK,WAAW,IAAI,OAAO,IAAI,KAAK,QAAQ;QACtF,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,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ACA,MAAM,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA,CAAE,4DAA4D;aAC1G;YAAC,OAAO,KAAK,EAAE;gBACZ,MAAM,CAAC,KAAK,CAAC,CAAA;aAChB;QACL,CAAC,CAAC,CAAA;IACN,CAAC;CACJ","sourcesContent":["/// <reference types='tampermonkey' />\n\nimport { t } from './i18n/instance.js'\nimport './prototype.browser.js' // to_time_str()\nimport { assert, concat, genid } from './utils.browser.js'\n\nexport interface RequestOptions {\n method?: 'get' | 'post' | 'put' | 'head' | 'delete' | 'patch'\n \n queries?: Record<string, any>\n \n headers?: Record<string, string>\n \n body?: string | object | HTMLFormElement\n \n type?: 'application/json' | 'application/x-www-form-urlencoded' | 'multipart/form-data'\n \n cors?: boolean\n \n by?: 'fetch' | 'GM_xmlhttpRequest'\n}\n\nexport interface RequestRawOptions extends RequestOptions {\n raw: true\n}\n\n/**\n - url: 可以只有 pathname 部分\n - options:\n - type: `'application/json'` 请求的 content-type 头 (如果有 body)\n - by: `window.GM_xmlhttpRequest ? 'GM_xmlhttpRequest' : 'fetch'` 发起请求所使用的底层方法\n*/\nexport async function request (url: string | URL): Promise<string>\nexport async function request (url: string | URL, options: RequestRawOptions): Promise<Response>\nexport async function request (url: string | URL, options: RequestOptions): Promise<string>\nexport async function request (url: string | URL, {\n method,\n \n queries,\n \n headers,\n \n body,\n \n type = 'application/json',\n \n cors,\n \n by = window.GM_xmlhttpRequest ? 'GM_xmlhttpRequest' : 'fetch',\n \n raw,\n}: RequestOptions & { raw?: boolean } = { }) {\n url = new URL(url, location.href)\n \n if (queries)\n for (const key in queries) {\n let value = queries[key]\n if (typeof value === 'boolean')\n value = value ? '1' : '0'\n url.searchParams.append(key, value)\n }\n \n if (body && !method)\n method = 'post'\n \n if (type === 'application/json' && typeof body !== 'undefined' && typeof body !== 'string')\n body = JSON.stringify(body)\n \n url = url.toString()\n \n if (by === 'fetch') {\n const options: RequestInit = {\n ... method ? { method: method.toUpperCase() } : { },\n \n ... cors ? { mode: 'cors' } : { },\n \n credentials: 'include',\n \n headers: {\n ... body ? { 'content-type': type } : { },\n ... headers,\n },\n \n ... body ? { body: body as string } : { },\n }\n \n const response = await fetch(\n url,\n options\n )\n \n if (!response.ok)\n throw Object.assign(\n new Error(`StatusCodeError: ${response.status}`),\n { url, response, ...options }\n )\n \n if (raw)\n return response\n \n return response.text()\n }\n \n \n return new Promise((resolve, reject) => {\n GM_xmlhttpRequest({\n ... method ? { method: (method as any).toUpperCase() } : { },\n \n url: url as string,\n \n headers: {\n ... body ? { 'content-type': type } : { },\n ... headers,\n },\n \n ... body ? { data: body as string, } : { },\n \n onload (response) {\n if (!(200 <= response.status && response.status <= 299)) {\n reject(\n Object.assign(\n new Error(`StatusCodeError: ${response.status}`), \n { url, queries, method, headers, body, response }\n )\n )\n return\n }\n \n resolve(response.responseText)\n }\n })\n })\n}\n\n\n/** 发起 http 请求并将响应体作为 json 解析 */\nexport async function request_json <T = any> (url: string, options?: RequestOptions): Promise<T> {\n const resp = await request(url, options)\n if (!resp) return\n try {\n return JSON.parse(resp)\n } catch (error) {\n console.error(resp)\n throw error\n }\n}\n\n\n\nlet decoder = new TextDecoder()\n\nlet encoder = new TextEncoder()\n\n\nexport class WebSocketConnectionError extends Error {\n override name = 'WebSocketConnectionError'\n \n websocket: WebSocket\n \n constructor (websocket: WebSocket) {\n super(`${websocket.url} ${t('连接出错了')}`)\n this.websocket = websocket\n }\n}\n\n\n/** 连接 websocket url, 设置各种事件监听器。在 open 事件后 resolve, 返回 websocket \n 遇到 error 时会创建 WebSocketConnectionError, 并作为参数调用 on_error,同时 reject 掉返回的 promise (若此时未 settle) \n - url\n - options:\n - protocols?\n - on_message: 根据 websocket frame 的 opcode 不同 (text frame 或 binary frame),event 中的 data 对应为 ArrayBuffer 或者 string\n https://datatracker.ietf.org/doc/html/rfc6455#section-5.2\n - on_close?\n - on_error? */\nexport async function connect_websocket (\n url: string | URL,\n {\n protocols,\n on_close,\n on_error,\n on_message\n }: {\n protocols?: string | string[]\n on_close? (event: { code: number, reason: string }, websocket: WebSocket): any\n on_error? (error: WebSocketConnectionError, websocket: WebSocket): any\n on_message (data: ArrayBuffer | string, websocket: WebSocket): any\n }\n) {\n let websocket = new WebSocket(url, protocols)\n \n // https://stackoverflow.com/questions/11821096/what-is-the-difference-between-an-arraybuffer-and-a-blob/39951543\n websocket.binaryType = 'arraybuffer'\n \n return new Promise<WebSocket>((resolve, reject) => {\n let settled = false\n \n websocket.addEventListener('open', async event => {\n console.log(\n websocket.url +\n (protocols ? \n ' ' + (\n typeof protocols === 'string' ? protocols : protocols.join(', ').bracket('square')\n ).bracket()\n :\n '') +\n t(' 已连接')\n )\n \n settled = true\n resolve(websocket)\n })\n \n websocket.addEventListener('close', event => {\n if (event.code === 1000)\n console.log(websocket.url + t(' 已正常关闭'))\n else\n console.log(`${websocket.url} ${t('被关闭')}, code: ${event.code}${ event.reason ? `, ${t('原因')}: ${event.reason}` : '' }`)\n on_close?.(event, websocket)\n })\n \n websocket.addEventListener('error', event => {\n const error = new WebSocketConnectionError(websocket)\n \n try {\n on_error?.(error, websocket)\n } catch (error) {\n if (settled)\n throw error\n else {\n settled = true\n reject(error)\n }\n }\n \n if (settled)\n throw error\n else {\n settled = true\n reject(error)\n }\n })\n \n websocket.addEventListener('message', event => {\n on_message(event.data, websocket)\n })\n })\n}\n\n\n/** 接收到消息后的处理函数 \n 返回值可以是:\n - 数组: 会自动被封装为 { id: 相同, data: 返回值, done: true } 这样的消息并调用 websocket.send 将其发送\n - void: 什么都不做\n - 以上的 promise */\nexport type MessageHandler = (message: Message, websocket?: WebSocket) => void | any[] | Promise<void | any[]>\n\n\n/** 二进制消息格式 \n - json.length (小端序): 4 字节\n - json 数据\n - binary 数据\n*/\nexport interface Message <TData extends any[] = any[]> {\n /** rpc id: 在 rpc 系统中认为是唯一的。用来在单个 websocket 连接上复用多个 rpc 请求。多个相同 id 的 message 组成一个请求流 */\n id?: number\n \n /** 只在 rpc 发起时指定被调用的 function name,发起时 rpc 时必传 */\n func?: string\n \n /** 通过这个 flag 主动表明这是发往对方的最后一个 message, 对方可以销毁 handler 了 \n 并非强制,可以不说明,由双方的函数自己约定\n */\n done?: boolean\n \n /** 通知对方这里产生的错误,本质上类似 data 也是一种数据,并不代表 rpc 的结束,后续可能继续有 rpc message 交换 */\n error?: Error\n \n /** data 是一个数组, 作为:\n - rpc 发起方调用 func 的参数,或者请求流 message 携带的数据\n - 结果或者响应流的数据,传给请求发起方\n \n 里面是可序列化为 json 的 js 变量,或者是 Uint8Array \n Uint8Array 的参数处理后被替换为 Uint8Array.byteLength, 并将下标记录在 bins 中\n \n 注意: 数组中如果有 undefined 值,传输到对面会变成 null 值\n */\n data?: TData\n \n /** bins: data 中哪些下标对应的原始值是 Uint8Array 类型的,如: [0, 3] */\n bins?: number[]\n}\n\n/** 通过创建 remote 对象对 websocket rpc 进行抽象 \n 调用方使用 remote.call 进行调用 \n 被调方在创建 remote 对象时传入 funcs 注册处理函数,并使用 remote.handle 方法处理 websocket message \n 未连接时自动连接,断开后自动重连 */\nexport class Remote {\n url: string\n \n /** 主动发起 websocket 连接的客户端 (构造函数传 url) 有这个属性 */\n websocket?: WebSocket\n \n /** 通过 rpc message.func 被调用的 rpc 函数 */\n funcs: Record<string, MessageHandler>\n \n /** map<id, message handler>: 通过 rpc message.id 找到对应的 handler, unary rpc 接收方不需要设置 handlers, 发送方需要 */\n handlers = new Map<number, MessageHandler>()\n \n \n print = false\n \n pconnect: Promise<any>\n \n \n get connected () {\n return this.websocket?.readyState === WebSocket.OPEN\n }\n \n \n static parse <TData extends any[] = any[]> (array_buffer: ArrayBuffer) {\n const buf = new Uint8Array(array_buffer as ArrayBuffer)\n const dv = new DataView(array_buffer)\n \n const len_json = dv.getUint32(0, true)\n \n let offset = 4 + len_json\n \n let message: Message<TData> = JSON.parse(decoder.decode(buf.subarray(4, offset)))\n \n if (message.bins) {\n const { bins } = message\n let { data } = message\n \n for (const ibin of bins) {\n const len_buf = data[ibin]\n data[ibin] = buf.subarray(offset, offset + len_buf)\n offset += len_buf\n }\n }\n \n if (message.error)\n message.error = Object.assign(new Error(), message.error)\n \n return message\n }\n \n \n static pack ({ id, func, data = [ ], done, error }: Message) {\n let data_ = new Array(data.length)\n let bins: number[] = [ ]\n let bufs: Uint8Array[] = [ ]\n \n for (let i = 0; i < data.length; i++) {\n const item = data[i]\n if (item instanceof Uint8Array) {\n bins.push(i)\n bufs.push(item)\n data_[i] = item.length\n } else\n data_[i] = item\n }\n \n const data_json = {\n id,\n ... func ? { func } : { },\n ... done ? { done } : { },\n ... error ? { error } : { },\n ... data_.length ? { data: data_ } : { },\n ... bins.length ? { bins } : { },\n }\n \n const str_json = encoder.encode(JSON.stringify(data_json))\n \n let dv = new DataView(new ArrayBuffer(4))\n \n dv.setUint32(0, str_json.length, true)\n \n return concat([dv, str_json, ... bufs])\n }\n \n \n constructor ({\n url, funcs = { }, websocket\n }: {\n url?: string, funcs?: Remote['funcs'], websocket?: WebSocket\n } = { }) {\n this.url = url\n this.funcs = funcs\n this.websocket = websocket\n }\n \n \n /** 幂等,保证 websocket 已连接,否则抛出异常,不需要手动调用,在其它方法中已默认自动重连 */\n async connect () {\n if (this.connected)\n return\n \n const ptail = this.pconnect\n \n let resolve: () => void\n this.pconnect = new Promise<void>((_resolve, _reject) => {\n resolve = _resolve\n })\n \n await ptail\n \n try {\n if (!this.connected)\n // 保存的 rpc 状态在 this.handlers, 与 websocket 无关,因此即使断开重连也不影响 rpc 的运行,即\n // 底层连接断开后自动重连对上层应该是无感知的,除非再次连接时失败\n this.websocket = await connect_websocket(this.url, { on_message: this.handle.bind(this) })\n } finally {\n resolve()\n }\n }\n \n \n disconnect () {\n this.websocket?.close()\n }\n \n \n /** 接收 websocket 连接的 remote 端必传 websocket 参数;发起端选传,如果传了必须等于 this.websocket \n 发送或连接出错时自动清理 message.id 对应的 handler */\n async send (message: Message, websocket?: WebSocket) {\n try {\n if (this.url) {\n assert(!websocket || websocket === this.websocket)\n await this.connect()\n websocket = this.websocket\n } else {\n assert(websocket)\n if (websocket.readyState !== WebSocket.OPEN)\n throw new Error(t('remote.send(): websocket client 已断开'))\n }\n \n if (!message.id)\n message.id = genid()\n \n websocket.send(Remote.pack(message))\n } catch (error) {\n if (message.id)\n this.handlers.delete(message.id)\n throw error\n }\n }\n \n \n /** 处理接收到的 websocket message 并解析, 根据 id dispatch 到对应的 handler 进行处理 \n 如果 message.done == true 则清理 handler \n 如果 handler 返回了值,则包装为 message 发送 */\n async handle (data: ArrayBuffer, websocket: WebSocket) {\n const message = Remote.parse(data)\n \n const { id, func, done } = message\n \n if (this.print)\n console.log(message)\n \n let handler: MessageHandler\n \n if (func)\n handler = this.funcs[func]\n else {\n handler = this.handlers.get(id)\n if (done)\n this.handlers.delete(id)\n }\n \n try {\n if (handler) {\n const data = await handler(message, websocket)\n if (data)\n await this.send({ id, data }, websocket)\n } else if (message.error)\n throw message.error\n else\n throw new Error(`${t('找不到 rpc handler')}: ${func ? `func: ${func.quote()}` : `id: ${id}`}`)\n } catch (error) {\n // handle 出错并不意味着 rpc 一定会结束,可能 error 是运行中的正常数据,所以不能清理 handler\n \n if (\n websocket.readyState === WebSocket.OPEN &&\n !message.error // 防止无限循环往对方发送 error, 只有在对方无错误时才可以发送\n )\n try { await this.send({ id, error, /* 不能设置 done 清理对面 handler, 理由同上 */ }, websocket) } catch { }\n \n // 再往上层抛出错误没有意义了,上层调用栈是 websocket.on('message') 之类的\n console.log(error)\n }\n }\n \n \n /** 调用 remote 中的 func, 只适用于最简单的一元 rpc (请求, 响应) */\n async call <TReturn extends any[] = any[]> (func: string, args?: any[]) {\n return new Promise<TReturn>(async (resolve, reject) => {\n const id = genid()\n \n this.handlers.set(id, (message: Message<TReturn>) => {\n const { error, data } = message\n if (error)\n reject(error)\n else\n resolve(data)\n this.handlers.delete(id)\n })\n \n try {\n await this.send({ id, func, data: args }) // 不需要 done: true, 因为对面的 remote.handlers 中不会有这个 id 的 handler\n } catch (error) {\n reject(error)\n }\n })\n }\n}\n\n"]}
1
+ {"version":3,"file":"net.browser.js","sourceRoot":"","sources":["net.browser.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAA;AACtC,OAAO,wBAAwB,CAAA,CAAE,gBAAgB;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AA8CjE,KAAK,UAAU,WAAW,CAAE,GAAQ,EAAE,OAAoB,EAAE,OAAe,EAAE,OAAO,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC;IAC/F,IAAI;QACA,OAAO,CAAC,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;QAC7C,OAAO,MAAM,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;KACnC;IAAC,OAAO,KAAK,EAAE;QACZ,IACI,KAAK,IAAI,OAAO;YAChB,KAAK,CAAC,IAAI,KAAK,cAAc,IAAI,CAAC,CAAC,YAAY,EAAE,WAAW,EAAE,iBAAiB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC;YAE5G,MAAM,KAAK,CAAA;aACV;YACD,MAAM,QAAQ,GAAG,CAAC,IAAI,KAAK,CAAA;YAC3B,OAAO,CAAC,GAAG,CAAC,GAAG,GAAG,IAAI,IAAI,QAAQ,IAAI,CAAC,CAAC,MAAM,CAAC,WAAW,KAAK,KAAK,CAAC,MAAM,KAAK,GAAG,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,CAAA;YAChH,MAAM,KAAK,CAAC,IAAI,GAAG,QAAQ,CAAC,CAAA;YAC5B,OAAO,WAAW,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,GAAG,CAAC,CAAC,CAAA;SA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AE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA,CAAE,4DAA4D;aAC1G;YAAC,OAAO,KAAK,EAAE;gBACZ,MAAM,CAAC,KAAK,CAAC,CAAA;aAChB;QACL,CAAC,CAAC,CAAA;IACN,CAAC;CACJ","sourcesContent":["/// <reference types='tampermonkey' />\n\nimport { t } from './i18n/instance.js'\nimport './prototype.browser.js' // to_time_str()\nimport { assert, concat, genid, delay } from './utils.browser.js'\n\n\n// ------------------------------------ fetch, request\nexport interface BasicAuth {\n type: 'basic',\n username: string\n password: string\n}\n\nexport interface BearerAuth {\n type: 'bearer',\n token: string\n}\n\n\nexport interface RequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'HEAD' | 'DELETE' | 'PATCH'\n \n queries?: Record<string, any>\n \n headers?: Record<string, string>\n \n body?: string | Record<string, any> | ArrayBufferView | ArrayBuffer | Blob |\n URLSearchParams | FormData\n \n type?: 'application/json' | 'application/x-www-form-urlencoded' | 'multipart/form-data'\n \n retries?: true | number\n \n timeout?: number\n \n auth?: BasicAuth | BearerAuth\n \n cookies?: Record<string, string>\n \n cors?: boolean\n \n by?: 'fetch' | 'GM_xmlhttpRequest'\n}\n\nexport interface RequestRawOptions extends RequestOptions {\n raw: true\n}\n\n\nasync function fetch_retry (url: URL, options: RequestInit, timeout: number, retries = 0, count = 0): Promise<Response> {\n try {\n options.signal = AbortSignal.timeout(timeout)\n return await fetch(url, options)\n } catch (error) {\n if (\n count >= retries ||\n error.name !== 'TimeoutError' && !['ECONNRESET', 'ETIMEDOUT', 'ESOCKETTIMEDOUT'].includes(error.cause?.code)\n )\n throw error\n else {\n const duration = 2 ** count\n console.log(`${`${'等待'} ${duration} ${t('秒后重试')} fetch (${count}) …`.yellow} ${url.toString().blue.underline}`)\n await delay(1000 * duration)\n return fetch_retry(url, options, timeout, retries, count + 1)\n }\n }\n}\n\n\n/**\n - url: 可以只有 pathname 部分\n - options?:\n - method?: `有 body 时为 POST, 否则为 GET` 'GET' | 'POST' | ···\n - queries?: 添加到 url 上的参数,是 Record<string, any>,true/false 会被转换为 0/1\n - headers?: http 请求头\n - body?: http 请求体,可以是 string, Record<string, any> (会自动 JSON.stringify), ArrayBuffer(View), Blob, \n URLSearchParams (type 为 x-www-form-urlencoded), FormData (type 为 form-data)\n - type?: `'application/json'` 有 body 时设置 http 请求头中的 content-type 头\n - retries?: `false` 可以传入 true (默认 2 次) 或 重试次数\n - timeout?: `5 * 1000`\n - auth?: BasicAuth | BearerAuth\n - raw?: `false` 传入后返回整个 response \n - by: `window.GM_xmlhttpRequest ? 'GM_xmlhttpRequest' : 'fetch'` 发起请求所使用的底层方法 */\nexport async function request (url: string | URL): Promise<string>\nexport async function request (url: string | URL, options: RequestRawOptions): Promise<Response>\nexport async function request (url: string | URL, options: RequestOptions & { encoding: 'binary' }): Promise<ArrayBuffer>\nexport async function request (url: string | URL, options: RequestOptions): Promise<string>\nexport async function request (url: string | URL, {\n method,\n \n queries,\n \n headers,\n \n body,\n \n type = 'application/json',\n \n retries,\n \n timeout = 5 * 1000,\n \n auth,\n \n raw = false,\n \n cors,\n \n by = window.GM_xmlhttpRequest ? 'GM_xmlhttpRequest' : 'fetch',\n}: RequestOptions & { raw?: boolean } = { }) {\n url = new URL(url, location.href)\n \n if (queries)\n for (const key in queries) {\n let value = queries[key]\n if (typeof value === 'boolean')\n value = value ? '1' : '0'\n url.searchParams.append(key, value)\n }\n \n if (body !== undefined && !method)\n method = 'POST'\n \n if (retries === true)\n retries = 2\n \n \n if (by === 'fetch') {\n let options: RequestInit = {\n ... method ? { method } : { },\n \n keepalive: true,\n \n redirect: 'follow',\n \n credentials: 'include',\n \n ... cors ? { mode: 'cors' } : { },\n \n headers: {\n ... body === undefined ? { } : { 'Content-Type': type },\n ... auth ?\n { Authorization: auth.type === 'basic' ? `Basic ${`${auth.username}:${auth.password}`.to_base64()}` : `Bearer ${auth.token}` }\n :\n { },\n ... headers ? \n Object.fromEntries(\n Object.entries(headers)\n .filter(([key, value]) => !key.startsWith(':'))\n ) : { }\n },\n \n // --- body\n body: (() => {\n if (body === undefined)\n return\n \n switch (type) {\n case 'application/json':\n return typeof body === 'string' || \n ArrayBuffer.isView(body) || \n body instanceof ArrayBuffer ||\n body instanceof Blob ?\n body as (string | NodeJS.ArrayBufferView | ArrayBuffer | Blob)\n :\n JSON.stringify(body)\n \n case 'application/x-www-form-urlencoded':\n return body instanceof URLSearchParams ? body : new URLSearchParams(body as Record<string, any>)\n \n case 'multipart/form-data':\n if (body instanceof FormData)\n return body\n else {\n let form = new FormData()\n for (const key in body as Record<string, any>) {\n let value = body[key]\n form.set(key, value)\n }\n return form\n }\n }\n })(),\n }\n \n \n let response = await fetch_retry(url, options, timeout, retries)\n \n if (!response.ok)\n throw Object.assign(\n new Error(`${t('状态码')} ${response.status}, ${t('非')} 2xx`),\n { name: 'StatusCodeError', url, options, response }\n )\n \n if (raw)\n return response\n \n if (!response.body)\n return response.body\n \n return response.text()\n } else\n return new Promise((resolve, reject) => {\n const options: Tampermonkey.Request<any> = {\n ... method ? { method: method as 'GET' | 'POST' | 'HEAD' } : { },\n \n url: url.toString(),\n \n headers: {\n ... body ? { 'content-type': type } : { },\n ... headers,\n },\n \n ... body ? { data: body as string } : { },\n \n onload (response) {\n if (!(200 <= response.status && response.status <= 299)) {\n reject(\n Object.assign(\n new Error(`${t('状态码')} ${response.status}, ${t('非')} 2xx`),\n { name: 'StatusCodeError', url, options, response }\n )\n )\n \n return\n }\n \n resolve(response.responseText)\n }\n }\n \n GM_xmlhttpRequest(options)\n })\n}\n\n\n/** 发起 http 请求并将响应体作为 json 解析 */\nexport async function request_json <T = any> (url: string, options?: RequestOptions): Promise<T> {\n const resp = await request(url, options)\n if (!resp)\n return\n try {\n return JSON.parse(resp)\n } catch (error) {\n console.error(resp)\n throw error\n }\n}\n\n\n\nlet decoder = new TextDecoder()\n\nlet encoder = new TextEncoder()\n\n\nexport class WebSocketConnectionError extends Error {\n override name = 'WebSocketConnectionError'\n \n websocket: WebSocket\n \n constructor (websocket: WebSocket) {\n super(`${websocket.url} ${t('连接出错了')}`)\n this.websocket = websocket\n }\n}\n\n\n/** 连接 websocket url, 设置各种事件监听器。在 open 事件后 resolve, 返回 websocket \n 遇到 error 时会创建 WebSocketConnectionError, 并作为参数调用 on_error,同时 reject 掉返回的 promise (若此时未 settle) \n - url\n - options:\n - protocols?\n - on_message: 根据 websocket frame 的 opcode 不同 (text frame 或 binary frame),event 中的 data 对应为 ArrayBuffer 或者 string\n https://datatracker.ietf.org/doc/html/rfc6455#section-5.2\n - on_close?: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes\n - on_error? */\nexport async function connect_websocket (\n url: string | URL,\n {\n protocols,\n on_close,\n on_error,\n on_message\n }: {\n protocols?: string | string[]\n on_close? (event: { code: number, reason: string }, websocket: WebSocket): any\n on_error? (error: WebSocketConnectionError, websocket: WebSocket): any\n on_message (data: ArrayBuffer | string, websocket: WebSocket): any\n }\n) {\n let websocket = new WebSocket(url, protocols)\n \n // https://stackoverflow.com/questions/11821096/what-is-the-difference-between-an-arraybuffer-and-a-blob/39951543\n websocket.binaryType = 'arraybuffer'\n \n return new Promise<WebSocket>((resolve, reject) => {\n let settled = false\n \n websocket.addEventListener('open', async event => {\n console.log(\n websocket.url +\n (protocols ? \n ' ' + (\n typeof protocols === 'string' ? protocols : protocols.join(', ').bracket('square')\n ).bracket()\n :\n '') +\n t(' 已连接')\n )\n \n settled = true\n resolve(websocket)\n })\n \n websocket.addEventListener('close', event => {\n if (event.code === 1000)\n console.log(websocket.url + t(' 已正常关闭'))\n else\n console.log(`${websocket.url} ${t('被关闭')}, code: ${event.code}${ event.reason ? `, ${t('原因')}: ${event.reason}` : '' }`)\n on_close?.(event, websocket)\n })\n \n websocket.addEventListener('error', event => {\n const error = new WebSocketConnectionError(websocket)\n \n try {\n on_error?.(error, websocket)\n } catch (error) {\n if (settled)\n throw error\n else {\n settled = true\n reject(error)\n }\n }\n \n if (settled)\n throw error\n else {\n settled = true\n reject(error)\n }\n })\n \n websocket.addEventListener('message', event => {\n on_message(event.data, websocket)\n })\n })\n}\n\n\n/** 接收到消息后的处理函数 \n 返回值可以是:\n - 数组: 会自动被封装为 { id: 相同, data: 返回值, done: true } 这样的消息并调用 websocket.send 将其发送\n - void: 什么都不做\n - 以上的 promise */\nexport type MessageHandler = (message: Message, websocket?: WebSocket) => void | any[] | Promise<void | any[]>\n\n\n/** 二进制消息格式 \n - json.length (小端序): 4 字节\n - json 数据\n - binary 数据\n*/\nexport interface Message <TData extends any[] = any[]> {\n /** rpc id: 在 rpc 系统中认为是唯一的。用来在单个 websocket 连接上复用多个 rpc 请求。多个相同 id 的 message 组成一个请求流 */\n id?: number\n \n /** 只在 rpc 发起时指定被调用的 function name,发起时 rpc 时必传 */\n func?: string\n \n /** 通过这个 flag 主动表明这是发往对方的最后一个 message, 对方可以销毁 handler 了 \n 并非强制,可以不说明,由双方的函数自己约定\n */\n done?: boolean\n \n /** 通知对方这里产生的错误,本质上类似 data 也是一种数据,并不代表 rpc 的结束,后续可能继续有 rpc message 交换 */\n error?: Error\n \n /** data 是一个数组, 作为:\n - rpc 发起方调用 func 的参数,或者请求流 message 携带的数据\n - 结果或者响应流的数据,传给请求发起方\n \n 里面是可序列化为 json 的 js 变量,或者是 Uint8Array \n Uint8Array 的参数处理后被替换为 Uint8Array.byteLength, 并将下标记录在 bins 中\n \n 注意: 数组中如果有 undefined 值,传输到对面会变成 null 值\n */\n data?: TData\n \n /** bins: data 中哪些下标对应的原始值是 Uint8Array 类型的,如: [0, 3] */\n bins?: number[]\n}\n\n/** 通过创建 remote 对象对 websocket rpc 进行抽象 \n 调用方使用 remote.call 进行调用 \n 被调方在创建 remote 对象时传入 funcs 注册处理函数,并使用 remote.handle 方法处理 websocket message \n 未连接时自动连接,断开后自动重连 */\nexport class Remote {\n url: string\n \n /** 主动发起 websocket 连接的客户端 (构造函数传 url) 有这个属性 */\n websocket?: WebSocket\n \n /** 通过 rpc message.func 被调用的 rpc 函数 */\n funcs: Record<string, MessageHandler>\n \n /** map<id, message handler>: 通过 rpc message.id 找到对应的 handler, unary rpc 接收方不需要设置 handlers, 发送方需要 */\n handlers = new Map<number, MessageHandler>()\n \n \n print = false\n \n pconnect: Promise<any>\n \n \n get connected () {\n return this.websocket?.readyState === WebSocket.OPEN\n }\n \n \n static parse <TData extends any[] = any[]> (array_buffer: ArrayBuffer) {\n const buf = new Uint8Array(array_buffer as ArrayBuffer)\n const dv = new DataView(array_buffer)\n \n const len_json = dv.getUint32(0, true)\n \n let offset = 4 + len_json\n \n let message: Message<TData> = JSON.parse(decoder.decode(buf.subarray(4, offset)))\n \n if (message.bins) {\n const { bins } = message\n let { data } = message\n \n for (const ibin of bins) {\n const len_buf = data[ibin]\n data[ibin] = buf.subarray(offset, offset + len_buf)\n offset += len_buf\n }\n }\n \n if (message.error)\n message.error = Object.assign(new Error(), message.error)\n \n return message\n }\n \n \n static pack ({ id, func, data = [ ], done, error }: Message) {\n let data_ = new Array(data.length)\n let bins: number[] = [ ]\n let bufs: Uint8Array[] = [ ]\n \n for (let i = 0; i < data.length; i++) {\n const item = data[i]\n if (item instanceof Uint8Array) {\n bins.push(i)\n bufs.push(item)\n data_[i] = item.length\n } else\n data_[i] = item\n }\n \n const data_json = {\n id,\n ... func ? { func } : { },\n ... done ? { done } : { },\n ... error ? { error } : { },\n ... data_.length ? { data: data_ } : { },\n ... bins.length ? { bins } : { },\n }\n \n const str_json = encoder.encode(JSON.stringify(data_json))\n \n let dv = new DataView(new ArrayBuffer(4))\n \n dv.setUint32(0, str_json.length, true)\n \n return concat([dv, str_json, ... bufs])\n }\n \n \n constructor ({\n url, funcs = { }, websocket\n }: {\n url?: string, funcs?: Remote['funcs'], websocket?: WebSocket\n } = { }) {\n this.url = url\n this.funcs = funcs\n this.websocket = websocket\n }\n \n \n /** 幂等,保证 websocket 已连接,否则抛出异常,不需要手动调用,在其它方法中已默认自动重连 */\n async connect () {\n if (this.connected)\n return\n \n const ptail = this.pconnect\n \n let resolve: () => void\n this.pconnect = new Promise<void>((_resolve, _reject) => {\n resolve = _resolve\n })\n \n await ptail\n \n try {\n if (!this.connected)\n // 保存的 rpc 状态在 this.handlers, 与 websocket 无关,因此即使断开重连也不影响 rpc 的运行,即\n // 底层连接断开后自动重连对上层应该是无感知的,除非再次连接时失败\n this.websocket = await connect_websocket(this.url, { on_message: this.handle.bind(this) })\n } finally {\n resolve()\n }\n }\n \n \n disconnect () {\n this.websocket?.close()\n }\n \n \n /** 接收 websocket 连接的 remote 端必传 websocket 参数;发起端选传,如果传了必须等于 this.websocket \n 发送或连接出错时自动清理 message.id 对应的 handler */\n async send (message: Message, websocket?: WebSocket) {\n try {\n if (this.url) {\n assert(!websocket || websocket === this.websocket)\n await this.connect()\n websocket = this.websocket\n } else {\n assert(websocket)\n if (websocket.readyState !== WebSocket.OPEN)\n throw new Error(t('remote.send(): websocket client 已断开'))\n }\n \n if (!message.id)\n message.id = genid()\n \n websocket.send(Remote.pack(message))\n } catch (error) {\n if (message.id)\n this.handlers.delete(message.id)\n throw error\n }\n }\n \n \n /** 处理接收到的 websocket message 并解析, 根据 id dispatch 到对应的 handler 进行处理 \n 如果 message.done == true 则清理 handler \n 如果 handler 返回了值,则包装为 message 发送 */\n async handle (data: ArrayBuffer, websocket: WebSocket) {\n const message = Remote.parse(data)\n \n const { id, func, done } = message\n \n if (this.print)\n console.log(message)\n \n let handler: MessageHandler\n \n if (func)\n handler = this.funcs[func]\n else {\n handler = this.handlers.get(id)\n if (done)\n this.handlers.delete(id)\n }\n \n try {\n if (handler) {\n const data = await handler(message, websocket)\n if (data)\n await this.send({ id, data }, websocket)\n } else if (message.error)\n throw message.error\n else\n throw new Error(`${t('找不到 rpc handler')}: ${func ? `func: ${func.quote()}` : `id: ${id}`}`)\n } catch (error) {\n // handle 出错并不意味着 rpc 一定会结束,可能 error 是运行中的正常数据,所以不能清理 handler\n \n if (\n websocket.readyState === WebSocket.OPEN &&\n !message.error // 防止无限循环往对方发送 error, 只有在对方无错误时才可以发送\n )\n try { await this.send({ id, error, /* 不能设置 done 清理对面 handler, 理由同上 */ }, websocket) } catch { }\n \n // 再往上层抛出错误没有意义了,上层调用栈是 websocket.on('message') 之类的\n console.log(error)\n }\n }\n \n \n /** 调用 remote 中的 func, 只适用于最简单的一元 rpc (请求, 响应) */\n async call <TReturn extends any[] = any[]> (func: string, args?: any[]) {\n return new Promise<TReturn>(async (resolve, reject) => {\n const id = genid()\n \n this.handlers.set(id, (message: Message<TReturn>) => {\n const { error, data } = message\n if (error)\n reject(error)\n else\n resolve(data)\n this.handlers.delete(id)\n })\n \n try {\n await this.send({ id, func, data: args }) // 不需要 done: true, 因为对面的 remote.handlers 中不会有这个 id 的 handler\n } catch (error) {\n reject(error)\n }\n })\n }\n}\n\n"]}
package/net.d.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  /// <reference types="node" resolution-mode="require"/>
2
2
  /// <reference types="cheerio" />
3
- import { default as request_lib } from 'request';
4
- import { default as request_promise } from 'request-promise-native';
3
+ import { FormData, type Response } from 'undici';
5
4
  import { WebSocket } from 'ws';
6
- import { Cookie, MemoryCookieStore } from 'tough-cookie';
5
+ import { Cookie, CookieJar, MemoryCookieStore } from 'tough-cookie';
7
6
  declare module 'tough-cookie' {
8
7
  interface MemoryCookieStore {
9
8
  idx: Record<string, any>;
@@ -17,57 +16,65 @@ export declare enum MyProxy {
17
16
  }
18
17
  export declare const cookies: {
19
18
  store: MemoryCookieStore;
20
- jar: request_lib.CookieJar;
21
- get(domain_or_url: string, str?: boolean): string | Cookie[];
19
+ jar: CookieJar;
20
+ get(domain_or_url: string, str?: boolean): Promise<string> | Cookie[] | Promise<Cookie[]>;
22
21
  };
23
22
  export { Cookie };
24
- export declare const _request: request_lib.RequestAPI<request_promise.RequestPromise<any>, request_promise.RequestPromiseOptions, request_lib.RequiredUriUrl>;
25
- export declare function request_retry(retries: number, request_options: request_promise.OptionsWithUrl): Promise<request_lib.Response>;
23
+ export interface BasicAuth {
24
+ type: 'basic';
25
+ username: string;
26
+ password: string;
27
+ }
28
+ export interface BearerAuth {
29
+ type: 'bearer';
30
+ token: string;
31
+ }
26
32
  export interface RequestOptions {
27
- method?: 'get' | 'post' | 'put' | 'head' | 'delete' | 'patch';
33
+ method?: 'GET' | 'POST' | 'PUT' | 'HEAD' | 'DELETE' | 'PATCH';
28
34
  queries?: Record<string, any>;
29
35
  headers?: Record<string, string>;
30
- body?: string | Record<string, any>;
36
+ body?: string | Record<string, any> | NodeJS.ArrayBufferView | ArrayBuffer | AsyncIterable<Uint8Array> | Iterable<Uint8Array> | URLSearchParams | FormData;
31
37
  type?: 'application/json' | 'application/x-www-form-urlencoded' | 'multipart/form-data';
32
38
  proxy?: boolean | MyProxy | string;
33
39
  encoding?: Encoding;
34
40
  retries?: true | number;
35
41
  timeout?: number;
36
- auth?: {
37
- username: string;
38
- password: string;
39
- };
40
- gzip?: boolean;
42
+ auth?: BasicAuth | BearerAuth;
41
43
  cookies?: Record<string, string>;
42
44
  }
43
45
  export interface RequestRawOptions extends RequestOptions {
44
46
  raw: true;
45
47
  }
46
48
  /**
47
- - url: 必须是完整 url must be full url
48
- - options:
49
- - raw: `false` 传入后返回整个 response
50
- - encoding: `(网页 content-type: charset=gb18030) || 'utf-8'` 传入 'binary' 时返回 buffer `(response content-type: charset=gb18030) || 'utf-8'` when 'binary' then return buffer
51
- - type: `'application/json'` 请求的 content-type 头 (如有 body) request content-type header (if has body)
52
- - proxy: `false`
53
- -true 时使用 MyProxy.socks5 Use MyProxy.socks5 when true
54
- - 为非空 string 作为代理地址 A non-empty string as proxy address
55
- - falsy 值时设为 false set to false for a falsy value
56
- - retries: `false` 可以传入 true (默认 3 次) 或 重试次数 could be true (default 3 times) or retry times
57
- - timeout: `20 * 1000`
58
- - gzip: `raw -> false; else -> true`
59
- */
49
+ - url: 必须是完整 url
50
+ - options?:
51
+ - method?: `有 body 时为 POST, 否则为 GET` 'GET' | 'POST' | ···
52
+ - queries?: 添加到 url 上的参数,是 Record<string, any>,true/false 会被转换为 0/1
53
+ - headers?: http 请求头
54
+ - body?: http 请求体,可以是 string, Record<string, any> (会自动 JSON.stringify), ArrayBuffer(View), (Async)Iterable<Uint8Array>
55
+ URLSearchParams (type x-www-form-urlencoded), FormData (type form-data)
56
+ - type?: `'application/json'` body 时设置 http 请求头中的 content-type 头
57
+ - proxy?: `false` 通过代理发送请求
58
+ - true 时使用 MyProxy.socks5
59
+ - 为非空 string 作为代理地址
60
+ - falsy 值时设为 false
61
+ - encoding?: `根据网页 content-type: charset=gb18030 提取 || 'utf-8'` 传入 'binary' 时返回 ArrayBuffer
62
+ - retries?: `false` 可以传入 true (默认 2 次) 或 重试次数
63
+ - timeout?: `5 * 1000`
64
+ - auth?: BasicAuth | BearerAuth
65
+ - cookies?: 需要额外添加到请求的 cookies, 默认情况下携带了 MemoryCookieStore 中保存的之前 http 响应中的 cookies
66
+ - raw?: `false` 传入后返回整个 response */
60
67
  export declare function request(url: string | URL): Promise<string>;
61
- export declare function request(url: string | URL, options: RequestRawOptions): Promise<request_lib.Response>;
68
+ export declare function request(url: string | URL, options: RequestRawOptions): Promise<Response>;
62
69
  export declare function request(url: string | URL, options: RequestOptions & {
63
70
  encoding: 'binary';
64
- }): Promise<Buffer>;
71
+ }): Promise<ArrayBuffer>;
65
72
  export declare function request(url: string | URL, options: RequestOptions): Promise<string>;
66
- /** 发起 http 请求并将响应体作为 json 解析 make http request and parse body as json */
73
+ /** 发起 http 请求并将响应体作为 json 解析 */
67
74
  export declare function request_json<T = any>(url: string | URL, options?: RequestOptions): Promise<T>;
68
- /** 使用 $.html(cheerio_element) 来获取 outer html use $.html(cheerio_element) to get outer html */
75
+ /** 使用 $.html(cheerio_element) 来获取 outer html */
69
76
  export declare function parse_html(html: string): Promise<cheerio.Root>;
70
- /** 使用 $.html(cheerio_element) 来获取 outer html use $.html(cheerio_element) to get outer html */
77
+ /** 使用 $.html(cheerio_element) 来获取 outer html */
71
78
  export declare function request_page(url: string | URL, options?: RequestOptions): Promise<cheerio.Root>;
72
79
  export declare function to_curl(url: string | URL, { queries, headers, method, body, proxy, exe }?: RequestOptions & {
73
80
  exe?: boolean;
@@ -103,7 +110,7 @@ export { WebSocket };
103
110
  - max_payload?
104
111
  - on_message: 根据 websocket frame 的 opcode 不同 (text frame 或 binary frame),event 中的 data 对应为 ArrayBuffer 或者 string
105
112
  https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
106
- - on_close?
113
+ - on_close?: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
107
114
  - on_error? */
108
115
  export declare function connect_websocket(url: string | URL, { protocols, max_payload, // 8 GB
109
116
  on_close, on_error, on_message }: {
package/net.js CHANGED
@@ -1,23 +1,22 @@
1
- import { default as request_promise } from 'request-promise-native';
2
- import { RequestError } from 'request-promise-native/errors.js';
3
- import promise_retry from 'promise-retry';
1
+ import { fetch, ProxyAgent, FormData } from 'undici';
4
2
  import { WebSocket } from 'ws';
5
3
  import iconv from 'iconv-lite';
6
4
  import qs from 'qs';
7
- import { Cookie, MemoryCookieStore } from 'tough-cookie';
5
+ import { Cookie, CookieJar, MemoryCookieStore } from 'tough-cookie';
6
+ import { CookieAgent, CookieClient } from 'http-cookie-agent/undici';
8
7
  import { t } from './i18n/instance.js';
9
8
  import './prototype.js';
10
- import { inspect, concat, assert, genid } from './utils.js';
9
+ import { inspect, concat, assert, genid, delay } from './utils.js';
11
10
  export var MyProxy;
12
11
  (function (MyProxy) {
13
12
  MyProxy["socks5"] = "http://localhost:10080";
14
13
  MyProxy["whistle"] = "http://localhost:8899";
15
14
  })(MyProxy = MyProxy || (MyProxy = {}));
16
- // ------------------------------------ Fetch, Request
17
- const cookie_store = new MemoryCookieStore();
15
+ // ------------------------------------ fetch, request
16
+ let cookie_store = new MemoryCookieStore();
18
17
  export const cookies = {
19
18
  store: cookie_store,
20
- jar: request_promise.jar(cookie_store),
19
+ jar: new CookieJar(cookie_store),
21
20
  get(domain_or_url, str = false) {
22
21
  if (domain_or_url.startsWith('http'))
23
22
  if (str)
@@ -34,161 +33,178 @@ export const cookies = {
34
33
  },
35
34
  };
36
35
  export { Cookie };
37
- export const _request = request_promise.defaults({
38
- // rejectUnauthorized: false,
39
- /** 防止 302 重定向产生错误 (prevent 302 redirect cause error), which is a boolean to set whether status codes other than 2xx should also reject the promise */
40
- simple: false,
41
- jar: cookies.jar
42
- });
43
- export async function request_retry(retries, request_options) {
44
- return promise_retry({
45
- retries,
46
- minTimeout: 1000,
47
- maxTimeout: Infinity,
48
- factor: 2
49
- }, async (retry, count) => {
50
- try {
51
- return await _request(request_options);
52
- }
53
- catch (error) {
54
- if (!['ECONNRESET', 'ETIMEDOUT', 'ESOCKETTIMEDOUT'].includes(error.cause?.code))
55
- throw error;
56
- if (count <= retries)
57
- console.log(`${`retry (${count}) …`.yellow} ${request_options.url.toString().blue.underline}`);
58
- return retry(error);
36
+ let proxy_agents = {};
37
+ let cookie_agent = new CookieAgent({ cookies: { jar: cookies.jar } });
38
+ async function fetch_retry(url, options, timeout, retries = 0, count = 0) {
39
+ try {
40
+ options.signal = AbortSignal.timeout(timeout);
41
+ return await fetch(url, options);
42
+ }
43
+ catch (error) {
44
+ if (count >= retries ||
45
+ error.name !== 'TimeoutError' && !['ECONNRESET', 'ETIMEDOUT', 'ESOCKETTIMEDOUT'].includes(error.cause?.code))
46
+ throw error;
47
+ else {
48
+ const duration = 2 ** count;
49
+ console.log(`${`等待 ${duration} 秒后重试 fetch (${count}) …`.yellow} ${url.toString().blue.underline}`);
50
+ await delay(1000 * duration);
51
+ return fetch_retry(url, options, timeout, retries, count + 1);
59
52
  }
60
- });
61
- }
62
- export async function request(url, { queries, body, type = 'application/json', proxy, method, headers, encoding, raw = false, retries, timeout = 20 * 1000, auth, gzip, cookies, } = {}) {
63
- url = url.toString();
64
- const _body = body; // for 错误日志
65
- if (body && !method)
66
- method = 'post';
67
- if (type === 'application/json' && typeof body !== 'undefined' && (typeof body !== 'string' && !Buffer.isBuffer(body)))
68
- body = JSON.stringify(body);
69
- // --- proxy
70
- if (proxy) {
71
- if (proxy === true)
72
- proxy = MyProxy.socks5;
73
53
  }
74
- else
75
- proxy = false;
76
- // --- gzip
77
- if (gzip === undefined)
78
- gzip = !raw;
79
- const options = {
80
- url,
81
- ...method ? { method: method.toUpperCase() } : {},
82
- proxy,
83
- gzip,
84
- encoding: null,
85
- resolveWithFullResponse: true,
54
+ }
55
+ export async function request(url, { method, queries, headers, body, type = 'application/json', proxy, encoding, retries, timeout = 5 * 1000, auth, cookies: _cookies, raw = false, } = {}) {
56
+ url = new URL(url);
57
+ if (queries)
58
+ for (const key in queries) {
59
+ let value = queries[key];
60
+ if (typeof value === 'boolean')
61
+ value = value ? '1' : '0';
62
+ url.searchParams.append(key, value);
63
+ }
64
+ if (body !== undefined && !method)
65
+ method = 'POST';
66
+ if (retries === true)
67
+ retries = 2;
68
+ let options = {
69
+ ...method ? { method } : {},
70
+ dispatcher: (() => {
71
+ if (proxy) {
72
+ if (proxy === true)
73
+ proxy = MyProxy.socks5;
74
+ return proxy_agents[proxy] ??= new ProxyAgent({
75
+ uri: proxy,
76
+ factory: (origin, options) => new CookieClient(origin, {
77
+ ...options,
78
+ cookies: { jar: cookies.jar }
79
+ })
80
+ });
81
+ }
82
+ else
83
+ return cookie_agent;
84
+ })(),
85
+ keepalive: true,
86
+ redirect: 'follow',
87
+ credentials: 'include',
86
88
  headers: {
87
- 'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,ja-JP;q=0.6,ja;q=0.5',
88
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
89
- ...body ? { 'content-type': type } : {},
90
- ...cookies ? {
91
- cookie: Object.entries(cookies)
89
+ 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,ja-JP;q=0.6,ja;q=0.5',
90
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
91
+ ...body === undefined ? {} : { 'Content-Type': type },
92
+ ...auth ?
93
+ { Authorization: auth.type === 'basic' ? `Basic ${`${auth.username}:${auth.password}`.to_base64()}` : `Bearer ${auth.token}` }
94
+ :
95
+ {},
96
+ ..._cookies ? {
97
+ cookie: Object.entries(_cookies)
92
98
  .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('; ')
93
99
  } : {},
94
100
  ...headers ?
95
101
  Object.fromEntries(Object.entries(headers)
96
102
  .filter(([key, value]) => !key.startsWith(':'))) : {}
97
103
  },
98
- ...queries ? { qs: queries } : {},
99
104
  // --- body
100
- ...(() => {
101
- if (!body)
102
- return {};
103
- if (type === 'application/x-www-form-urlencoded')
104
- return { form: body };
105
- if (type === 'multipart/form-data')
106
- return { formData: body };
107
- return { body };
105
+ body: (() => {
106
+ if (body === undefined)
107
+ return;
108
+ switch (type) {
109
+ case 'application/json':
110
+ return typeof body === 'string' ||
111
+ ArrayBuffer.isView(body) ||
112
+ body instanceof ArrayBuffer ||
113
+ // 测试 Iterable<Uint8Array>, AsyncIterable<Uint8Array>
114
+ (!Array.isArray(body) && (Symbol.iterator in Object(body) || Symbol.asyncIterator in Object(body))) ?
115
+ body
116
+ :
117
+ JSON.stringify(body);
118
+ case 'application/x-www-form-urlencoded':
119
+ return body instanceof URLSearchParams ? body : new URLSearchParams(body);
120
+ case 'multipart/form-data':
121
+ if (body instanceof FormData)
122
+ return body;
123
+ else {
124
+ let form = new FormData();
125
+ for (const key in body) {
126
+ let value = body[key];
127
+ form.set(key, value);
128
+ }
129
+ return form;
130
+ }
131
+ }
108
132
  })(),
109
- ...timeout ? { timeout } : {},
110
- ...auth ? { auth } : {},
111
133
  };
112
134
  let response;
113
135
  try {
114
- if (retries) {
115
- if (retries === true)
116
- retries = 3;
117
- response = await request_retry(retries, options);
118
- }
119
- else
120
- response = await _request(options);
121
- if (!(200 <= response.statusCode && response.statusCode <= 299))
122
- throw Object.assign(new Error(t('状态码 {{code}}, 非 2xx', { code: response.statusCode })), {
123
- name: 'StatusCodeError',
124
- response,
125
- options
126
- });
136
+ response = await fetch_retry(url, options, timeout, retries);
137
+ if (!response.ok)
138
+ throw Object.assign(new Error(`${t('状态码')} ${response.status}, ${t('非')} 2xx`), { name: 'StatusCodeError' });
127
139
  }
128
140
  catch (error) {
129
- const { name, options: { method, url, uri, qs }, response, } = error;
141
+ error.url = url;
142
+ error.options = options;
143
+ error.response = response;
144
+ let text;
145
+ if (response)
146
+ text = await response.text();
130
147
  error[inspect.custom] = (depth, options, inspect) => {
131
148
  const { colors } = options;
132
- let _method = (method || 'get').toLowerCase();
149
+ let _method = method || 'GET';
133
150
  if (colors)
134
151
  _method = _method.red;
135
- let _url = String(url || uri);
152
+ let _url = url.toString();
136
153
  if (colors)
137
154
  _url = _url.blue.underline;
138
155
  let s = '\n' +
139
156
  `${_method} ${_url}\n`;
140
- if (qs && Object.keys(qs).length) {
157
+ if (queries && Object.keys(queries).length) {
141
158
  let _query = t('请求参数:');
142
159
  if (colors)
143
- _query = _query.blue;
160
+ _query = _query.yellow;
144
161
  s += _query + '\n' +
145
- inspect(qs, options) + '\n';
162
+ inspect(queries, options) + '\n';
146
163
  }
147
- if (_body) {
164
+ if (body !== undefined) {
148
165
  let _body = t('请求体:');
149
166
  if (colors)
150
- _body = _body.blue;
167
+ _body = _body.yellow;
151
168
  s += _body + '\n' +
152
169
  inspect(body, options) + '\n';
153
170
  }
154
- if (name === 'StatusCodeError') {
171
+ if (error.name === 'StatusCodeError') {
155
172
  let _status = t('响应状态码:');
156
173
  if (colors)
157
174
  _status = _status.yellow;
158
- let _code = String(response.statusCode);
175
+ let _code = String(response.status);
159
176
  if (colors)
160
177
  _code = _code.red;
161
- s += _status + ' ' + _code;
178
+ s += _status + ' ' + _code + '\n';
162
179
  }
163
- else if (error instanceof RequestError) {
164
- let _cause = t('响应错误:');
180
+ else if (error.name === 'TimeoutError') {
181
+ let _timeout = t('超过等待时间:');
165
182
  if (colors)
166
- _cause = _cause.yellow;
167
- s += _cause + '\n' +
168
- inspect(error.cause, options);
183
+ _timeout = _timeout.red;
184
+ s += `${_timeout} ${timeout} ms\n`;
169
185
  }
170
- else
171
- s += inspect(error, options);
172
- s += '\n';
173
186
  if (response) {
174
187
  let _headers = t('响应头:');
175
188
  if (colors)
176
189
  _headers = _headers.yellow;
177
- s += _headers + '\n' +
178
- inspect(response.headers) + '\n';
179
- if (response.body) {
190
+ s += _headers + '\n';
191
+ for (const [key, value] of response.headers)
192
+ s += `${key}: ${value}\n`;
193
+ if (text) {
180
194
  let _body = t('响应体:');
181
195
  if (colors)
182
196
  _body = _body.yellow;
183
197
  s += _body + '\n' +
184
- inspect(response.body.toString(), options) + '\n';
198
+ text + '\n';
185
199
  }
186
200
  }
187
201
  let _stack = t('调用栈:');
188
202
  if (colors)
189
203
  _stack = _stack.yellow;
190
- s += _stack + '\n' +
191
- error.stack + '\n' +
204
+ s += _stack + '\n';
205
+ if (error.cause)
206
+ s += inspect(error.cause, options) + '\n';
207
+ s += error.stack + '\n' +
192
208
  '\n';
193
209
  return s;
194
210
  };
@@ -200,13 +216,13 @@ export async function request(url, { queries, body, type = 'application/json', p
200
216
  return response.body;
201
217
  // --- decode body
202
218
  if (encoding === 'binary')
203
- return response.body;
204
- encoding ||= /charset=(.*)/.exec(response.headers['content-type'])?.[1] || 'utf-8';
219
+ return response.arrayBuffer();
220
+ encoding ||= /charset=(.*)/.exec(response.headers.get('content-type'))?.[1] || 'utf-8';
205
221
  if (/utf-?8/i.test(encoding))
206
- return response.body.toString('utf-8');
207
- return iconv.decode(response.body, encoding);
222
+ return response.text();
223
+ return iconv.decode(Buffer.from(await response.arrayBuffer()), encoding);
208
224
  }
209
- /** 发起 http 请求并将响应体作为 json 解析 make http request and parse body as json */
225
+ /** 发起 http 请求并将响应体作为 json 解析 */
210
226
  export async function request_json(url, options) {
211
227
  const resp = await request(url, options);
212
228
  if (!resp)
@@ -219,7 +235,7 @@ export async function request_json(url, options) {
219
235
  throw error;
220
236
  }
221
237
  }
222
- /** 使用 $.html(cheerio_element) 来获取 outer html use $.html(cheerio_element) to get outer html */
238
+ /** 使用 $.html(cheerio_element) 来获取 outer html */
223
239
  export async function parse_html(html) {
224
240
  const { default: cheerio } = await import('cheerio');
225
241
  let $ = cheerio.load(html, { decodeEntities: false });
@@ -245,7 +261,7 @@ export async function parse_html(html) {
245
261
  });
246
262
  return $;
247
263
  }
248
- /** 使用 $.html(cheerio_element) 来获取 outer html use $.html(cheerio_element) to get outer html */
264
+ /** 使用 $.html(cheerio_element) 来获取 outer html */
249
265
  export async function request_page(url, options) {
250
266
  return parse_html(await request(url, options));
251
267
  }
@@ -263,7 +279,7 @@ export function to_curl(url, { queries, headers, method, body, proxy, exe = true
263
279
  // ( proxy ? ' --proxy ' + proxy.quote() : ' --noproxy ' + '*'.quote())
264
280
  // ) +
265
281
  (proxy ? ` --proxy ${proxy.quote()}` : '') +
266
- (method && method !== 'get' ? ` -X ${method.toUpperCase()}` : '') +
282
+ (method && method !== 'GET' ? ` -X ${method}` : '') +
267
283
  (headers ? Object.entries(headers).map(([key, value]) => ' -H ' + `${key}: ${value}`.quote()).join('') : '') +
268
284
  (body ? ' -H ' + 'content-type: application/json'.quote() : '') +
269
285
  (body ? ' --data ' + JSON.stringify(body).quote() : '');
@@ -322,7 +338,7 @@ export { WebSocket };
322
338
  - max_payload?
323
339
  - on_message: 根据 websocket frame 的 opcode 不同 (text frame 或 binary frame),event 中的 data 对应为 ArrayBuffer 或者 string
324
340
  https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
325
- - on_close?
341
+ - on_close?: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
326
342
  - on_error? */
327
343
  export async function connect_websocket(url, { protocols, max_payload = 2 ** 33, // 8 GB
328
344
  on_close, on_error, on_message }) {