(url: string, { onProgress }: { [key: string]: any })
| 27 | }; |
| 28 | |
| 29 | export const fetchScriptBody = async (url: string, { onProgress }: { [key: string]: any }) => { |
| 30 | let origin; |
| 31 | try { |
| 32 | origin = new URL(url).origin; |
| 33 | } catch { |
| 34 | throw new Error(`Invalid url: ${url}`); |
| 35 | } |
| 36 | const response = await fetch(url, { |
| 37 | headers: { |
| 38 | "Cache-Control": "no-cache", |
| 39 | // 参考:加权 Accept-Encoding 值说明 |
| 40 | // https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Accept-Encoding#weighted_accept-encoding_values |
| 41 | "Accept-Encoding": "br;q=1.0, gzip;q=0.8, *;q=0.1", |
| 42 | Origin: origin, |
| 43 | }, |
| 44 | referrer: origin + "/", |
| 45 | }); |
| 46 | |
| 47 | if (!response.ok) { |
| 48 | throw new Error(`Fetch failed with status ${response.status}`); |
| 49 | } |
| 50 | |
| 51 | if (!response.body || !response.headers) { |
| 52 | throw new Error("No response body or headers"); |
| 53 | } |
| 54 | const reader = response.body.getReader(); |
| 55 | |
| 56 | // 读取数据 |
| 57 | let receivedLength = 0; // 当前已接收的长度 |
| 58 | const chunks = []; // 已接收的二进制分片数组(用于组装正文) |
| 59 | while (true) { |
| 60 | const { done, value } = await reader.read(); |
| 61 | |
| 62 | if (done) { |
| 63 | break; |
| 64 | } |
| 65 | |
| 66 | chunks.push(value); |
| 67 | receivedLength += value.length; |
| 68 | onProgress?.({ receivedLength }); |
| 69 | } |
| 70 | |
| 71 | // 合并分片(chunks) |
| 72 | const chunksAll = new Uint8Array(receivedLength); |
| 73 | let position = 0; |
| 74 | for (const chunk of chunks) { |
| 75 | chunksAll.set(chunk, position); |
| 76 | position += chunk.length; |
| 77 | } |
| 78 | |
| 79 | const contentType = response.headers.get("content-type"); |
| 80 | const code = await readRawContent(chunksAll, contentType); |
| 81 | |
| 82 | const metadata = parseMetadata(code); |
| 83 | // 如果不是 UserScript,检测是否为 SkillScript(仅 agent 启用时) |
| 84 | if (!metadata) { |
| 85 | const skillScriptMeta = EnableAgent ? parseSkillScriptMetadata(code) : null; |
| 86 | if (skillScriptMeta) { |
no test coverage detected