mcp-server-weisheng-scrm 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.
Files changed (40) hide show
  1. package/README.md +92 -0
  2. package/dist/config.d.ts +8 -0
  3. package/dist/config.js +13 -0
  4. package/dist/core/api-catalog.d.ts +20 -0
  5. package/dist/core/api-catalog.js +96 -0
  6. package/dist/core/cache.d.ts +11 -0
  7. package/dist/core/cache.js +27 -0
  8. package/dist/core/doc-fetcher.d.ts +11 -0
  9. package/dist/core/doc-fetcher.js +69 -0
  10. package/dist/core/doc-parser.d.ts +9 -0
  11. package/dist/core/doc-parser.js +31 -0
  12. package/dist/core/file-uploader.d.ts +14 -0
  13. package/dist/core/file-uploader.js +74 -0
  14. package/dist/core/http-client.d.ts +23 -0
  15. package/dist/core/http-client.js +117 -0
  16. package/dist/core/identity.d.ts +16 -0
  17. package/dist/core/identity.js +47 -0
  18. package/dist/core/param-splitter.d.ts +13 -0
  19. package/dist/core/param-splitter.js +89 -0
  20. package/dist/core/param-validator.d.ts +6 -0
  21. package/dist/core/param-validator.js +148 -0
  22. package/dist/core/proxy-forwarder.d.ts +18 -0
  23. package/dist/core/proxy-forwarder.js +104 -0
  24. package/dist/core/token-manager.d.ts +16 -0
  25. package/dist/core/token-manager.js +84 -0
  26. package/dist/exceptions.d.ts +32 -0
  27. package/dist/exceptions.js +53 -0
  28. package/dist/index.d.ts +7 -0
  29. package/dist/index.js +90 -0
  30. package/dist/tools/call-api.d.ts +11 -0
  31. package/dist/tools/call-api.js +81 -0
  32. package/dist/tools/check-identity.d.ts +9 -0
  33. package/dist/tools/check-identity.js +23 -0
  34. package/dist/tools/fetch-api-doc.d.ts +9 -0
  35. package/dist/tools/fetch-api-doc.js +26 -0
  36. package/dist/tools/list-apis.d.ts +8 -0
  37. package/dist/tools/list-apis.js +12 -0
  38. package/dist/tools/upload-image.d.ts +8 -0
  39. package/dist/tools/upload-image.js +12 -0
  40. package/package.json +29 -0
package/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # weisheng-scrm-mcp
2
+
3
+
4
+
5
+ ## Getting started
6
+
7
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
8
+
9
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
10
+
11
+ ## Add your files
12
+
13
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
14
+ - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
15
+
16
+ ```
17
+ cd existing_repo
18
+ git remote add origin https://gitlab.wshmi.com/basellm/weisheng-scrm-mcp.git
19
+ git branch -M main
20
+ git push -uf origin main
21
+ ```
22
+
23
+ ## Integrate with your tools
24
+
25
+ - [ ] [Set up project integrations](http://gitlab.wshmi.com/basellm/weisheng-scrm-mcp/-/settings/integrations)
26
+
27
+ ## Collaborate with your team
28
+
29
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
30
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
31
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
32
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
33
+ - [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
34
+
35
+ ## Test and Deploy
36
+
37
+ Use the built-in continuous integration in GitLab.
38
+
39
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
40
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
41
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
42
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
43
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
44
+
45
+ ***
46
+
47
+ # Editing this README
48
+
49
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
50
+
51
+ ## Suggestions for a good README
52
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
53
+
54
+ ## Name
55
+ Choose a self-explaining name for your project.
56
+
57
+ ## Description
58
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
59
+
60
+ ## Badges
61
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
62
+
63
+ ## Visuals
64
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
65
+
66
+ ## Installation
67
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
68
+
69
+ ## Usage
70
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
71
+
72
+ ## Support
73
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
74
+
75
+ ## Roadmap
76
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
77
+
78
+ ## Contributing
79
+ State if you are open to contributions and what your requirements are for accepting them.
80
+
81
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
82
+
83
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
84
+
85
+ ## Authors and acknowledgment
86
+ Show your appreciation to those who have contributed to the project.
87
+
88
+ ## License
89
+ For open source projects, say how it is licensed.
90
+
91
+ ## Project status
92
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * MCP Server 配置模块
3
+ */
4
+ export interface ServerConfig {
5
+ appKey: string;
6
+ baseUrl: string;
7
+ }
8
+ export declare function loadConfig(): ServerConfig;
package/dist/config.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * MCP Server 配置模块
3
+ */
4
+ const DEFAULT_BASE_URL = "https://open.wshoto.com";
5
+ export function loadConfig() {
6
+ const appKey = process.env.SCRM_APP_KEY || "";
7
+ if (!appKey) {
8
+ throw new ConfigError("缺少必填环境变量 SCRM_APP_KEY", { env_var: "SCRM_APP_KEY" });
9
+ }
10
+ const baseUrl = (process.env.SCRM_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
11
+ return { appKey, baseUrl };
12
+ }
13
+ import { ConfigError } from "./exceptions.js";
@@ -0,0 +1,20 @@
1
+ /**
2
+ * API 目录管理模块
3
+ *
4
+ * 从 SCRM 开放平台分页全量拉取 API 目录,使用 SimpleCache 做内存缓存,
5
+ * 支持按关键词模糊搜索和按 doc_url 精确查找。
6
+ */
7
+ import type { SimpleCache } from "./cache.js";
8
+ import type { HttpClient } from "./http-client.js";
9
+ export declare class ApiCatalog {
10
+ private readonly httpClient;
11
+ private readonly cache;
12
+ private static readonly CACHE_TTL;
13
+ private static readonly FETCH_PAGE_SIZE;
14
+ constructor(httpClient: HttpClient, cache: SimpleCache);
15
+ getApiList(keyword: string): Promise<Record<string, unknown>[]>;
16
+ findApiByDocUrl(docUrl: string): Promise<Record<string, unknown>>;
17
+ private ensureCache;
18
+ private fetchAllFromRemote;
19
+ private static fuzzyMatch;
20
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * API 目录管理模块
3
+ *
4
+ * 从 SCRM 开放平台分页全量拉取 API 目录,使用 SimpleCache 做内存缓存,
5
+ * 支持按关键词模糊搜索和按 doc_url 精确查找。
6
+ */
7
+ export class ApiCatalog {
8
+ httpClient;
9
+ cache;
10
+ static CACHE_TTL = 7200; // 缓存有效期:2小时
11
+ static FETCH_PAGE_SIZE = 100; // 每页拉取条数
12
+ constructor(httpClient, cache) {
13
+ this.httpClient = httpClient;
14
+ this.cache = cache;
15
+ }
16
+ async getApiList(keyword) {
17
+ // Step 1: 确保缓存中有全量 API 目录
18
+ const allRecords = await this.ensureCache();
19
+ // Step 2: 按关键词模糊匹配
20
+ const matched = ApiCatalog.fuzzyMatch(allRecords, keyword);
21
+ // Step 3: 精简返回字段
22
+ return matched.map((record) => ({
23
+ api_name: record["api_name"] ?? "",
24
+ description: record["description"] ?? "",
25
+ doc_url: record["doc_url"] ?? "",
26
+ api_type: record["api_type"] ?? "",
27
+ }));
28
+ }
29
+ async findApiByDocUrl(docUrl) {
30
+ // Step 1: 确保缓存中有全量 API 目录
31
+ const allRecords = await this.ensureCache();
32
+ // Step 2: 精确匹配 doc_url
33
+ const matched = allRecords.filter((r) => r["doc_url"] === docUrl);
34
+ // Step 3: 唯一性校验
35
+ if (matched.length === 0) {
36
+ throw new Error(`未找到 doc_url=${docUrl} 对应的 API`);
37
+ }
38
+ if (matched.length > 1) {
39
+ throw new Error(`doc_url=${docUrl} 匹配到多条 API 记录,数据异常`);
40
+ }
41
+ return matched[0];
42
+ }
43
+ async ensureCache() {
44
+ const cached = this.cache.get("api_list");
45
+ if (cached != null) {
46
+ return cached;
47
+ }
48
+ return this.fetchAllFromRemote();
49
+ }
50
+ async fetchAllFromRemote() {
51
+ const allRecords = [];
52
+ let total = null;
53
+ let pageIndex = 1;
54
+ // Step 1: 循环分页拉取直到全量
55
+ while (total === null || allRecords.length < total) {
56
+ const resp = await this.httpClient.postJson("/openapi/claw/api/page", {
57
+ current_index: pageIndex,
58
+ page_size: ApiCatalog.FETCH_PAGE_SIZE,
59
+ }, { retryOnAuthError: true });
60
+ const data = (resp["data"] ?? resp);
61
+ const records = (data["records"] ?? []);
62
+ allRecords.push(...records);
63
+ // Step 2: 从首次响应中获取总条数
64
+ if (total === null) {
65
+ total = data["total"] ?? 0;
66
+ }
67
+ pageIndex++;
68
+ }
69
+ // Step 3: 按 id 去重
70
+ const seenIds = new Set();
71
+ const uniqueRecords = [];
72
+ for (const record of allRecords) {
73
+ const recordId = record["id"];
74
+ if (recordId != null && !seenIds.has(recordId)) {
75
+ seenIds.add(recordId);
76
+ uniqueRecords.push(record);
77
+ }
78
+ }
79
+ // Step 4: 写入缓存
80
+ this.cache.set("api_list", uniqueRecords, ApiCatalog.CACHE_TTL);
81
+ return uniqueRecords;
82
+ }
83
+ static fuzzyMatch(records, keyword) {
84
+ // Step 1: 拆分关键词并去除空白
85
+ const keywords = keyword.split(",").map((kw) => kw.trim()).filter(Boolean);
86
+ // Step 2: 无关键词则返回全量
87
+ if (keywords.length === 0) {
88
+ return records;
89
+ }
90
+ // Step 3: 对每条记录,检查 api_name 是否包含任一关键词(不区分大小写)
91
+ return records.filter((record) => {
92
+ const apiName = (String(record["api_name"] ?? "")).toLowerCase();
93
+ return keywords.some((kw) => apiName.includes(kw.toLowerCase()));
94
+ });
95
+ }
96
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * 简单内存缓存模块
3
+ */
4
+ export declare class SimpleCache {
5
+ private store;
6
+ private readDocs;
7
+ get(key: string): unknown;
8
+ set(key: string, value: unknown, ttl?: number): void;
9
+ addReadDoc(docUrl: string): void;
10
+ isDocRead(docUrl: string): boolean;
11
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * 简单内存缓存模块
3
+ */
4
+ export class SimpleCache {
5
+ store = new Map();
6
+ readDocs = new Set();
7
+ get(key) {
8
+ const entry = this.store.get(key);
9
+ if (!entry)
10
+ return null;
11
+ if (entry.expireAt > 0 && Date.now() / 1000 > entry.expireAt) {
12
+ this.store.delete(key);
13
+ return null;
14
+ }
15
+ return entry.value;
16
+ }
17
+ set(key, value, ttl = 0) {
18
+ const expireAt = ttl > 0 ? Date.now() / 1000 + ttl : 0;
19
+ this.store.set(key, { value, expireAt });
20
+ }
21
+ addReadDoc(docUrl) {
22
+ this.readDocs.add(docUrl);
23
+ }
24
+ isDocRead(docUrl) {
25
+ return this.readDocs.has(docUrl);
26
+ }
27
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * 文档拉取模块
3
+ *
4
+ * 负责从远程 URL 拉取文档原文,使用 fetch 异步请求。
5
+ */
6
+ export declare class DocFetcher {
7
+ private static readonly DEFAULT_TIMEOUT;
8
+ private static readonly DEFAULT_MAX_BYTES;
9
+ fetch(url: string): Promise<Record<string, unknown>>;
10
+ private static detectEncoding;
11
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * 文档拉取模块
3
+ *
4
+ * 负责从远程 URL 拉取文档原文,使用 fetch 异步请求。
5
+ */
6
+ import { NetworkError, ValidationError } from "../exceptions.js";
7
+ export class DocFetcher {
8
+ static DEFAULT_TIMEOUT = 30_000;
9
+ static DEFAULT_MAX_BYTES = 50 * 1024 * 1024;
10
+ async fetch(url) {
11
+ // Step 1: 校验 URL 协议
12
+ if (!url.startsWith("http://") && !url.startsWith("https://")) {
13
+ throw new ValidationError(`不支持的 URL 协议,仅支持 http/https: ${url}`);
14
+ }
15
+ // Step 2: 发起 GET 请求
16
+ let response;
17
+ try {
18
+ response = await fetch(url, {
19
+ signal: AbortSignal.timeout(DocFetcher.DEFAULT_TIMEOUT),
20
+ redirect: "follow",
21
+ });
22
+ if (!response.ok) {
23
+ throw new NetworkError(`HTTP 请求失败,状态码: ${response.status}`, { url, status_code: response.status });
24
+ }
25
+ }
26
+ catch (e) {
27
+ if (e instanceof NetworkError || e instanceof ValidationError)
28
+ throw e;
29
+ throw new NetworkError(`网络请求失败: ${e}`, { url });
30
+ }
31
+ // Step 3: 读取响应体,判断截断
32
+ const contentBytes = new Uint8Array(await response.arrayBuffer());
33
+ const truncated = contentBytes.length > DocFetcher.DEFAULT_MAX_BYTES;
34
+ const finalBytes = truncated ? contentBytes.slice(0, DocFetcher.DEFAULT_MAX_BYTES) : contentBytes;
35
+ // Step 4: 检测编码并解码
36
+ const contentTypeHeader = response.headers.get("content-type");
37
+ const encoding = DocFetcher.detectEncoding(contentTypeHeader);
38
+ let decoder;
39
+ try {
40
+ decoder = new TextDecoder(encoding, { fatal: false });
41
+ }
42
+ catch {
43
+ // 不支持的 charset 退回 utf-8
44
+ decoder = new TextDecoder("utf-8", { fatal: false });
45
+ }
46
+ const content = decoder.decode(finalBytes);
47
+ return {
48
+ url: response.url,
49
+ final_url: response.url,
50
+ status: response.status,
51
+ content_type: contentTypeHeader,
52
+ encoding,
53
+ length: finalBytes.length,
54
+ truncated,
55
+ content,
56
+ };
57
+ }
58
+ static detectEncoding(contentType) {
59
+ if (!contentType)
60
+ return "utf-8";
61
+ for (const part of contentType.split(";")) {
62
+ const trimmed = part.trim().toLowerCase();
63
+ if (trimmed.startsWith("charset=")) {
64
+ return trimmed.split("=", 2)[1].trim();
65
+ }
66
+ }
67
+ return "utf-8";
68
+ }
69
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * 文档解析模块
3
+ *
4
+ * 负责从文档内容中提取 FIELD_INPUT_SPEC 结构化字段定义。
5
+ */
6
+ export declare function extractFieldInputSpec(content: string): {
7
+ field_input_spec: Record<string, unknown> | null;
8
+ warnings: string[];
9
+ };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * 文档解析模块
3
+ *
4
+ * 负责从文档内容中提取 FIELD_INPUT_SPEC 结构化字段定义。
5
+ */
6
+ export function extractFieldInputSpec(content) {
7
+ const warnings = [];
8
+ const marker = "## FIELD_INPUT_SPEC";
9
+ // Step 1: 查找 FIELD_INPUT_SPEC 标记位置
10
+ const markerIndex = content.indexOf(marker);
11
+ if (markerIndex === -1) {
12
+ return { field_input_spec: null, warnings };
13
+ }
14
+ // Step 2: 取标记之后的内容,定位 JSON 行
15
+ const afterMarker = content.slice(markerIndex + marker.length);
16
+ const lines = afterMarker.trim().split("\n");
17
+ if (lines.length === 0) {
18
+ warnings.push("FIELD_INPUT_SPEC 标记后无内容");
19
+ return { field_input_spec: null, warnings };
20
+ }
21
+ // Step 3: 解析 JSON
22
+ const jsonLine = lines[0].trim();
23
+ try {
24
+ const spec = JSON.parse(jsonLine);
25
+ return { field_input_spec: spec, warnings };
26
+ }
27
+ catch (e) {
28
+ warnings.push(`FIELD_INPUT_SPEC JSON 解析失败: ${e}`);
29
+ return { field_input_spec: null, warnings };
30
+ }
31
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * 文件上传模块
3
+ *
4
+ * 将本地文件通过 multipart/form-data 上传到 SCRM 平台(COS),返回公网 URL 和 file_id。
5
+ */
6
+ import type { HttpClient } from "./http-client.js";
7
+ export declare class FileUploader {
8
+ private readonly httpClient;
9
+ private static readonly UPLOAD_PATH;
10
+ constructor(httpClient: HttpClient);
11
+ upload(filePath: string): Promise<Record<string, unknown>>;
12
+ private static buildMultipartBody;
13
+ private static guessMimeType;
14
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * 文件上传模块
3
+ *
4
+ * 将本地文件通过 multipart/form-data 上传到 SCRM 平台(COS),返回公网 URL 和 file_id。
5
+ */
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import * as crypto from "node:crypto";
9
+ import { ValidationError } from "../exceptions.js";
10
+ export class FileUploader {
11
+ httpClient;
12
+ static UPLOAD_PATH = "/openapi/document/upload/bind";
13
+ constructor(httpClient) {
14
+ this.httpClient = httpClient;
15
+ }
16
+ async upload(filePath) {
17
+ // Step 1: 校验文件路径
18
+ if (!fs.existsSync(filePath)) {
19
+ throw new ValidationError(`文件不存在: ${filePath}`, { file_path: filePath });
20
+ }
21
+ const stat = fs.statSync(filePath);
22
+ if (!stat.isFile()) {
23
+ throw new ValidationError(`路径不是文件: ${filePath}`, { file_path: filePath });
24
+ }
25
+ // Step 2: 构建 multipart/form-data 请求体
26
+ const { body, contentType } = FileUploader.buildMultipartBody(filePath);
27
+ // Step 3: 发送上传请求
28
+ const response = await this.httpClient.postMultipart(FileUploader.UPLOAD_PATH, body, contentType);
29
+ // Step 4: 从响应 data 中提取 url 和 file_id
30
+ const data = (response["data"] ?? {});
31
+ return {
32
+ url: data["url"] ?? "",
33
+ file_id: data["file_id"] ?? null,
34
+ };
35
+ }
36
+ static buildMultipartBody(filePath, fileField = "file") {
37
+ const boundary = crypto.randomUUID().replace(/-/g, "");
38
+ const contentType = `multipart/form-data; boundary=${boundary}`;
39
+ const filename = path.basename(filePath);
40
+ const fileContent = fs.readFileSync(filePath);
41
+ const mimeType = FileUploader.guessMimeType(filePath);
42
+ const parts = [];
43
+ const encoder = new TextEncoder();
44
+ parts.push(encoder.encode(`--${boundary}\r\n`));
45
+ parts.push(encoder.encode(`Content-Disposition: form-data; name="${fileField}"; filename="${filename}"\r\n`));
46
+ parts.push(encoder.encode(`Content-Type: ${mimeType}\r\n`));
47
+ parts.push(encoder.encode("\r\n"));
48
+ parts.push(fileContent);
49
+ parts.push(encoder.encode(`\r\n--${boundary}--\r\n`));
50
+ // 合并所有 parts
51
+ const totalLength = parts.reduce((sum, p) => sum + p.length, 0);
52
+ const body = new Uint8Array(totalLength);
53
+ let offset = 0;
54
+ for (const part of parts) {
55
+ body.set(part, offset);
56
+ offset += part.length;
57
+ }
58
+ return { body, contentType };
59
+ }
60
+ static guessMimeType(filePath) {
61
+ const ext = path.extname(filePath).toLowerCase();
62
+ const mimeMap = {
63
+ ".jpg": "image/jpeg",
64
+ ".jpeg": "image/jpeg",
65
+ ".png": "image/png",
66
+ ".gif": "image/gif",
67
+ ".webp": "image/webp",
68
+ ".svg": "image/svg+xml",
69
+ ".pdf": "application/pdf",
70
+ ".txt": "text/plain",
71
+ };
72
+ return mimeMap[ext] || "application/octet-stream";
73
+ }
74
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * HTTP 客户端模块
3
+ *
4
+ * 封装 SCRM 开放平台接口调用,支持 GET/POST/multipart,
5
+ * 遇到 token 失效时自动刷新并重试读请求。
6
+ */
7
+ import type { SimpleCache } from "./cache.js";
8
+ import type { TokenManager } from "./token-manager.js";
9
+ export declare class HttpClient {
10
+ private readonly tokenManager;
11
+ private readonly cache;
12
+ private static readonly AUTH_ERROR_CODES;
13
+ constructor(tokenManager: TokenManager, cache: SimpleCache);
14
+ getJson(path: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
15
+ postJson(path: string, payload: Record<string, unknown>, options?: {
16
+ retryOnAuthError?: boolean;
17
+ }): Promise<Record<string, unknown>>;
18
+ postMultipart(path: string, body: Uint8Array, contentType: string): Promise<Record<string, unknown>>;
19
+ private executeWithAuthRetry;
20
+ private buildUrl;
21
+ private shouldRefreshToken;
22
+ private execute;
23
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * HTTP 客户端模块
3
+ *
4
+ * 封装 SCRM 开放平台接口调用,支持 GET/POST/multipart,
5
+ * 遇到 token 失效时自动刷新并重试读请求。
6
+ */
7
+ import { NetworkError, ScrmError } from "../exceptions.js";
8
+ export class HttpClient {
9
+ tokenManager;
10
+ cache;
11
+ static AUTH_ERROR_CODES = new Set([10001, 10010, 10011]);
12
+ constructor(tokenManager, cache) {
13
+ this.tokenManager = tokenManager;
14
+ this.cache = cache;
15
+ }
16
+ async getJson(path, params) {
17
+ const self = this;
18
+ async function requestFactory() {
19
+ const token = await self.tokenManager.getToken();
20
+ let url = self.buildUrl(path, token);
21
+ if (params) {
22
+ const filtered = Object.entries(params).filter(([, v]) => v != null);
23
+ if (filtered.length > 0) {
24
+ const qs = new URLSearchParams(filtered.map(([k, v]) => [k, String(v)])).toString();
25
+ const sep = url.includes("?") ? "&" : "?";
26
+ url = `${url}${sep}${qs}`;
27
+ }
28
+ }
29
+ return { url, method: "GET" };
30
+ }
31
+ return this.executeWithAuthRetry(requestFactory, true);
32
+ }
33
+ async postJson(path, payload, options) {
34
+ const self = this;
35
+ const retryOnAuthError = options?.retryOnAuthError ?? false;
36
+ async function requestFactory() {
37
+ const token = await self.tokenManager.getToken();
38
+ const url = self.buildUrl(path, token);
39
+ return {
40
+ url,
41
+ method: "POST",
42
+ body: JSON.stringify(payload),
43
+ headers: { "Content-Type": "application/json; charset=utf-8" },
44
+ };
45
+ }
46
+ return this.executeWithAuthRetry(requestFactory, retryOnAuthError);
47
+ }
48
+ async postMultipart(path, body, contentType) {
49
+ const self = this;
50
+ async function requestFactory() {
51
+ const token = await self.tokenManager.getToken();
52
+ const url = self.buildUrl(path, token);
53
+ return { url, method: "POST", body, headers: { "Content-Type": contentType } };
54
+ }
55
+ return this.executeWithAuthRetry(requestFactory, false);
56
+ }
57
+ async executeWithAuthRetry(requestFactory, retryOnAuthError) {
58
+ // Step 1: 先用当前 token 执行请求
59
+ let authError = null;
60
+ try {
61
+ return await this.execute(await requestFactory());
62
+ }
63
+ catch (exc) {
64
+ if (!(exc instanceof ScrmError) || !this.shouldRefreshToken(exc)) {
65
+ throw exc;
66
+ }
67
+ authError = exc;
68
+ }
69
+ // Step 2: 发生 token 失效时强制刷新
70
+ await this.tokenManager.getToken(true);
71
+ // Step 3: 写请求禁止自动重放,只刷新 token 供后续请求使用
72
+ if (!retryOnAuthError) {
73
+ throw authError;
74
+ }
75
+ // Step 4: 读请求使用新 token 重建请求并重试一次
76
+ return this.execute(await requestFactory());
77
+ }
78
+ buildUrl(path, token) {
79
+ const cleanPath = path.startsWith("/") ? path : `/${path}`;
80
+ return `${this.tokenManager.baseUrl}${cleanPath}?access_token=${token}`;
81
+ }
82
+ shouldRefreshToken(exc) {
83
+ const code = exc.details["code"];
84
+ if (code == null)
85
+ return false;
86
+ return HttpClient.AUTH_ERROR_CODES.has(code);
87
+ }
88
+ async execute(req) {
89
+ let response;
90
+ try {
91
+ response = await fetch(req.url, {
92
+ method: req.method,
93
+ body: req.body,
94
+ headers: req.headers,
95
+ signal: AbortSignal.timeout(30_000),
96
+ });
97
+ }
98
+ catch (e) {
99
+ throw new NetworkError(`接口请求失败: ${e}`, { url: req.url, method: req.method });
100
+ }
101
+ const text = await response.text();
102
+ let payload;
103
+ try {
104
+ payload = JSON.parse(text);
105
+ }
106
+ catch (e) {
107
+ throw new NetworkError("接口返回了非 JSON 内容", {
108
+ status: response.status,
109
+ body: text,
110
+ });
111
+ }
112
+ if (payload["code"] !== 0) {
113
+ throw new ScrmError(payload["msg"] || "接口返回失败", { code: payload["code"], response: payload });
114
+ }
115
+ return payload;
116
+ }
117
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * 身份管理模块
3
+ *
4
+ * 调用 /openapi/auth/check_super_user 获取用户身份(超管/分管/员工),
5
+ * 使用 SimpleCache 做内存缓存。
6
+ */
7
+ import type { SimpleCache } from "./cache.js";
8
+ import type { HttpClient } from "./http-client.js";
9
+ export declare class Identity {
10
+ private readonly httpClient;
11
+ private readonly cache;
12
+ private static readonly CACHE_TTL;
13
+ constructor(httpClient: HttpClient, cache: SimpleCache);
14
+ getIdentity(userId: string): Promise<Record<string, unknown>>;
15
+ private refresh;
16
+ }