@vectorx/cloud-toolkit 0.5.1 → 1.0.0

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.
@@ -6,32 +6,66 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.outputHelpInfo = void 0;
7
7
  const chalk_1 = __importDefault(require("chalk"));
8
8
  const outputHelpInfo = () => {
9
+ const header = `
10
+ ${chalk_1.default.cyan.bold("小红书云 CLI (rcb) — 命令一览")}
11
+ `;
9
12
  const commands = `
10
- 命令
11
- login [options] 登录小红书云账号
12
- agent [cmd] 开发 AI Agent`;
13
+ ${chalk_1.default.bold("命令")}
14
+ ${chalk_1.default.cyan("login")} [options] 登录 / 管理小红书云账号
15
+ ${chalk_1.default.cyan("logout")} [options] 退出当前登录账号
16
+ ${chalk_1.default.cyan("agent")} [cmd] 开发与构建 AI Agent
17
+ ${chalk_1.default.cyan("fun")} [cmd] 管理 Fun 云函数调试与部署
18
+ ${chalk_1.default.cyan("env")} [cmd] 管理云环境(Environment)
19
+ `;
20
+ const agentCommands = `
21
+ ${chalk_1.default.bold("Agent 子命令")}
22
+ ${chalk_1.default.cyan("rcb agent new")} 创建 AI 智能体模板项目
23
+ ${chalk_1.default.cyan("rcb agent dev")} 启动 AI Agent 本地开发服务器
24
+ ${chalk_1.default.cyan("rcb agent build")} 打包 AI Agent 为可部署的云函数代码
25
+ `;
26
+ const funCommands = `
27
+ ${chalk_1.default.bold("Fun 子命令")}
28
+ ${chalk_1.default.cyan("rcb fun dev")} 本地启动 Fun 云函数调试服务
29
+ ${chalk_1.default.cyan("rcb fun list")} 查看关联云环境 / 函数占位信息(待接入真实查询)
30
+ ${chalk_1.default.cyan("rcb fun deploy")} 将打包好的函数代码部署到云端
31
+ `;
32
+ const envCommands = `
33
+ ${chalk_1.default.bold("Env 子命令")}
34
+ ${chalk_1.default.cyan("rcb env list")} 查看当前账号下的云环境列表
35
+ ${chalk_1.default.cyan("rcb env info -e <envId>")} 查看指定云环境的详情信息
36
+ `;
37
+ const authCommands = `
38
+ ${chalk_1.default.bold("登录与账号管理")}
39
+ ${chalk_1.default.cyan("rcb login")} 交互式登录或配置密钥
40
+ ${chalk_1.default.cyan("rcb logout")} 退出当前账号、清理本地凭证
41
+ `;
13
42
  const options = `
14
- 选项
15
- -v, --version 输出当前版本
16
- -h, --help 查看命令帮助信息`;
43
+ ${chalk_1.default.bold("全局选项")}
44
+ ${chalk_1.default.cyan("-v, --version")} 输出当前 rcb 版本
45
+ ${chalk_1.default.cyan("-h, --help")} 查看命令帮助信息
46
+ `;
17
47
  const tips = `
18
- Tips:
48
+ ${chalk_1.default.bold("使用示例")}
19
49
 
20
- ${chalk_1.default.gray("–")} 登录管理
21
- ${chalk_1.default.cyan("$ rcb login/logout")}
50
+ ${chalk_1.default.gray("–")} 登录管理
51
+ ${chalk_1.default.cyan("$ rcb login --secretId <secretId> --secretKey <secretKey>")}
52
+ ${chalk_1.default.cyan("$ rcb logout")}
22
53
 
23
- ${chalk_1.default.gray("–")} 创建 AI 智能体模版项目
24
- ${chalk_1.default.cyan("$ rcb agent new <appName>")}
54
+ ${chalk_1.default.gray("–")} 创建 AI 智能体模版项目
55
+ ${chalk_1.default.cyan("$ rcb agent new -p my-agent")}
25
56
 
26
- ${chalk_1.default.gray("–")} 启动 AI Agent 开发服务器
27
- ${chalk_1.default.cyan("$ rcb agent dev")}
57
+ ${chalk_1.default.gray("–")} 启动本地开发
58
+ ${chalk_1.default.cyan("$ rcb agent dev")}
59
+ ${chalk_1.default.cyan("$ rcb fun dev")}
28
60
 
29
- ${chalk_1.default.gray("–")} 打包 AI Agent 到云函数代码
30
- ${chalk_1.default.cyan("$ rcb agent build")}
61
+ ${chalk_1.default.gray("–")} 管理云环境
62
+ ${chalk_1.default.cyan("$ rcb env list")}
63
+ ${chalk_1.default.cyan("$ rcb env info -e env-xxxxxx")}
31
64
 
32
- ${chalk_1.default.gray("–")} 查看 AI Agent 命令使用介绍
33
- ${chalk_1.default.cyan("$ rcb agent -h")}
34
- `;
35
- console.log(commands, "\n", options, "\n", tips);
65
+ ${chalk_1.default.gray("–")} 打包与部署函数
66
+ ${chalk_1.default.cyan("$ rcb agent build")}
67
+ ${chalk_1.default.cyan("$ rcb fun deploy")}
68
+ `;
69
+ console.log(header.trimEnd(), "\n", commands.trimEnd(), "\n", agentCommands.trimEnd(), "\n", funCommands.trimEnd(), "\n", envCommands.trimEnd(), "\n", authCommands.trimEnd(), "\n", options.trimEnd(), "\n", tips.trimEnd());
36
70
  };
37
71
  exports.outputHelpInfo = outputHelpInfo;
@@ -15,10 +15,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.request = exports.Request = void 0;
16
16
  const node_fetch_1 = __importDefault(require("node-fetch"));
17
17
  const env_helper_1 = require("./env-helper");
18
+ const cli_apm_1 = require("./tracker/cli-apm");
18
19
  class Request {
19
20
  fetch(options) {
20
21
  return __awaiter(this, void 0, void 0, function* () {
21
22
  const { method = "GET", url, data = {}, headers = {} } = options;
23
+ let requestUrlForReport = url;
22
24
  try {
23
25
  let requestUrl = url;
24
26
  let requestBody;
@@ -34,6 +36,7 @@ class Request {
34
36
  });
35
37
  }
36
38
  requestUrl = queryParams.toString() ? `${url}?${queryParams.toString()}` : url;
39
+ requestUrlForReport = requestUrl;
37
40
  if (method === "POST" && data.body) {
38
41
  requestBody = JSON.stringify(data.body);
39
42
  const contentTypeKey = Object.keys(headers).find((key) => key.toLowerCase() === "content-type");
@@ -49,6 +52,19 @@ class Request {
49
52
  timeout: 1000 * 20,
50
53
  });
51
54
  const responseData = yield response.json();
55
+ if (response.status >= 400) {
56
+ try {
57
+ (0, cli_apm_1.reportCliHttpError)({
58
+ method,
59
+ url: requestUrl,
60
+ status_code: response.status,
61
+ }, {
62
+ message: (responseData && (responseData.msg || responseData.message)) || `HTTP ${response.status}`,
63
+ status: response.status,
64
+ });
65
+ }
66
+ catch (e) { }
67
+ }
52
68
  return {
53
69
  status: response.status,
54
70
  data: responseData,
@@ -56,6 +72,10 @@ class Request {
56
72
  };
57
73
  }
58
74
  catch (error) {
75
+ try {
76
+ (0, cli_apm_1.reportCliHttpError)({ method, url: requestUrlForReport }, error);
77
+ }
78
+ catch (e) { }
59
79
  throw new Error(`请求失败 ${error.message}`);
60
80
  }
61
81
  });
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.printHorizontalTable = printHorizontalTable;
7
+ const cli_table3_1 = __importDefault(require("cli-table3"));
8
+ function printHorizontalTable(head, data = [], options) {
9
+ if (!(data === null || data === void 0 ? void 0 : data.length)) {
10
+ console.log("列表数据为空");
11
+ }
12
+ const table = new cli_table3_1.default(Object.assign({ head, style: { head: ["yellow"] }, colAligns: new Array(head.length).fill("center") }, options));
13
+ data.forEach((item) => {
14
+ table.push(item);
15
+ });
16
+ console.log(table.toString());
17
+ }
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.APM = void 0;
7
+ const endpoints_1 = require("@vectorx/endpoints");
8
+ const node_fetch_1 = __importDefault(require("node-fetch"));
9
+ const uuid_1 = require("uuid");
10
+ const logger_1 = require("../logger");
11
+ const device_1 = require("./device");
12
+ const deviceInfo = (0, device_1.getDeviceInfo)();
13
+ const getUserAgent = () => {
14
+ var _a, _b;
15
+ const electronStr = typeof ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.electron) !== "undefined" ? `Electron/${(_b = process === null || process === void 0 ? void 0 : process.versions) === null || _b === void 0 ? void 0 : _b.electron}` : "";
16
+ const nodeStr = `Node/${process.version}`;
17
+ const osVersion = `${deviceInfo.os_platform}/${deviceInfo.os_version}`;
18
+ const cpu = `CPU/${deviceInfo.cpu_speed}mhz (${deviceInfo.cpu_model}; ${deviceInfo.os_arch})`;
19
+ const mem = `Memory/${deviceInfo.machine_memory}mb`;
20
+ return [electronStr, nodeStr, osVersion, cpu, mem]
21
+ .map((i) => { var _a; return (_a = i === null || i === void 0 ? void 0 : i.trim) === null || _a === void 0 ? void 0 : _a.call(i); })
22
+ .filter(Boolean)
23
+ .join(" ")
24
+ .trim();
25
+ };
26
+ const CONTEXT = {
27
+ context_nameTracker: "nodeT",
28
+ context_platform: deviceInfo.os_platform,
29
+ context_appVersion: (process === null || process === void 0 ? void 0 : process.CLI_VERSION) || "unknown",
30
+ context_osVersion: deviceInfo.os_version,
31
+ context_deviceModel: "",
32
+ context_deviceId: (0, device_1.machineId)(),
33
+ context_package: "",
34
+ context_networkType: "unknow",
35
+ context_matchedPath: "cli",
36
+ context_route: "xhsmp://cli",
37
+ context_userAgent: getUserAgent(),
38
+ context_artifactName: "miniprogram",
39
+ context_networkQuality: "UNKNOWN",
40
+ context_artifactVersion: "UNKNOWN",
41
+ context_userId: "",
42
+ };
43
+ const getApmEndpoint = () => (0, endpoints_1.resolveUrl)("@vectorx/cloud-toolkit", "apmDataEndpoint");
44
+ class APM {
45
+ constructor() {
46
+ this.reportQueue = [];
47
+ this.allowReport = false;
48
+ this.eventSeq = 1;
49
+ this.context = Object.assign({}, CONTEXT);
50
+ this.baseData = {};
51
+ this.timer = null;
52
+ }
53
+ setContext(userId, base = {}) {
54
+ this.context = Object.assign(Object.assign({}, this.context), { context_userId: userId });
55
+ this.baseData = base;
56
+ this.startReport();
57
+ }
58
+ setAppVersion(appVersion) {
59
+ var _a;
60
+ this.context = Object.assign(Object.assign({}, this.context), { context_appVersion: appVersion || ((_a = this.context) === null || _a === void 0 ? void 0 : _a.context_appVersion) });
61
+ }
62
+ startReport() {
63
+ this.allowReport = true;
64
+ this.batchReport();
65
+ }
66
+ getSequence() {
67
+ return {
68
+ context_sdkSeqId: this.eventSeq++,
69
+ context_sdkSessionId: (0, uuid_1.v4)(),
70
+ context_pageSessionId: (0, uuid_1.v4)(),
71
+ clientTime: Date.now(),
72
+ };
73
+ }
74
+ _request(params, retry = true) {
75
+ const list = Array.isArray(params) ? params : [params];
76
+ const merged = list.map((i) => {
77
+ return Object.assign(Object.assign(Object.assign({}, this.context), i.sequence), { measurement_name: i.measurement_name, measurement_data: Object.assign(Object.assign({}, this.baseData), i.measurement_data) });
78
+ });
79
+ return (0, node_fetch_1.default)(getApmEndpoint(), {
80
+ method: "post",
81
+ body: JSON.stringify(merged),
82
+ headers: {
83
+ accept: "*/*",
84
+ "accept-language": "zh-CN,zh;q=0.9",
85
+ batch: "true",
86
+ "biz-type": "apm_fe",
87
+ "cache-control": "no-cache",
88
+ "content-type": "application/json",
89
+ pragma: "no-cache",
90
+ },
91
+ })
92
+ .then((res) => res.json())
93
+ .then((res) => {
94
+ if (res === null || res === void 0 ? void 0 : res.success) {
95
+ logger_1.logger.debug("apm send success", "");
96
+ }
97
+ else {
98
+ throw new Error(res === null || res === void 0 ? void 0 : res.msg);
99
+ }
100
+ })
101
+ .catch((err) => {
102
+ if (retry) {
103
+ setTimeout(() => this._request(params, false), 1000);
104
+ }
105
+ logger_1.logger.log("apm send failed", `${(err === null || err === void 0 ? void 0 : err.message) || null}`, "error");
106
+ });
107
+ }
108
+ batchReport() {
109
+ const queue = [...this.reportQueue];
110
+ this.reportQueue = [];
111
+ while (queue.length) {
112
+ this._request(queue.splice(0, 5));
113
+ }
114
+ }
115
+ report(measurement_name, measurement_data = {}) {
116
+ const params = {
117
+ sequence: this.getSequence(),
118
+ measurement_name,
119
+ measurement_data,
120
+ };
121
+ this.reportQueue.push(params);
122
+ clearTimeout(this.timer);
123
+ if (this.allowReport) {
124
+ if (this.reportQueue.length >= 10) {
125
+ this.batchReport();
126
+ }
127
+ else {
128
+ this.timer = setTimeout(() => {
129
+ this.batchReport();
130
+ }, 300);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ exports.APM = APM;
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CLI_MEASUREMENT_NAME = void 0;
4
+ exports.initCliApm = initCliApm;
5
+ exports.setCliApmCurrentCommand = setCliApmCurrentCommand;
6
+ exports.createCliCommandTracker = createCliCommandTracker;
7
+ exports.reportCliException = reportCliException;
8
+ exports.reportCliHttpError = reportCliHttpError;
9
+ const crypto_1 = require("crypto");
10
+ const apm_1 = require("./apm");
11
+ exports.CLI_MEASUREMENT_NAME = "vectorx_cloud_cli_usage";
12
+ let apm = null;
13
+ let currentCmdPath;
14
+ function safeTruncate(str, max = 200) {
15
+ if (!str)
16
+ return "";
17
+ const s = String(str);
18
+ if (s.length <= max)
19
+ return s;
20
+ return `${s.slice(0, max)}...`;
21
+ }
22
+ function hashError(input) {
23
+ try {
24
+ return (0, crypto_1.createHash)("sha256").update(input).digest("hex").slice(0, 16);
25
+ }
26
+ catch (_a) {
27
+ return undefined;
28
+ }
29
+ }
30
+ function normalizeError(err) {
31
+ var _a, _b, _c, _d;
32
+ const msg = safeTruncate((err === null || err === void 0 ? void 0 : err.errMsg) || (err === null || err === void 0 ? void 0 : err.message) || (typeof (err === null || err === void 0 ? void 0 : err.toString) === "function" ? err.toString() : "") || "Unknown error");
33
+ const code = (_c = (_b = (_a = err === null || err === void 0 ? void 0 : err.code) !== null && _a !== void 0 ? _a : err === null || err === void 0 ? void 0 : err.statusCode) !== null && _b !== void 0 ? _b : err === null || err === void 0 ? void 0 : err.status) !== null && _c !== void 0 ? _c : (_d = err === null || err === void 0 ? void 0 : err.response) === null || _d === void 0 ? void 0 : _d.status;
34
+ const stack = (err === null || err === void 0 ? void 0 : err.stack) ? String(err.stack) : "";
35
+ const h = hashError(stack || msg);
36
+ const lower = msg.toLowerCase();
37
+ let type = "unknown";
38
+ if (typeof code === "number" && code >= 400)
39
+ type = "http";
40
+ if (lower.includes("http") || lower.includes("request") || lower.includes("fetch"))
41
+ type = "http";
42
+ if (lower.includes("token") || lower.includes("login") || lower.includes("auth"))
43
+ type = "auth";
44
+ if (lower.includes("invalid") || lower.includes("参数") || lower.includes("校验"))
45
+ type = "validation";
46
+ return Object.assign(Object.assign(Object.assign({ error_msg: msg }, (code !== undefined ? { error_code: code } : {})), (h ? { error_hash: h } : {})), { error_type: type });
47
+ }
48
+ function initCliApm(options = {}) {
49
+ if (!apm)
50
+ apm = new apm_1.APM();
51
+ if (options.cliVersion) {
52
+ apm.setAppVersion(options.cliVersion);
53
+ }
54
+ apm.setContext(options.userId || "", {});
55
+ }
56
+ function setCliApmCurrentCommand(cmdPath) {
57
+ currentCmdPath = cmdPath;
58
+ }
59
+ function createCliCommandTracker(meta) {
60
+ var _a, _b, _c;
61
+ setCliApmCurrentCommand(meta.cmd_path);
62
+ const base = Object.assign(Object.assign(Object.assign(Object.assign({ event: "command", cmd_path: meta.cmd_path }, (meta.cmd_root ? { cmd_root: meta.cmd_root } : {})), (typeof meta.params_count === "number" ? { params_count: meta.params_count } : {})), (Array.isArray(meta.options_keys) ? { options_keys: JSON.stringify(meta.options_keys) } : {})), { cli_version: (process === null || process === void 0 ? void 0 : process.CLI_VERSION) || "unknown", node_major: Number((_c = (_b = (_a = process.versions) === null || _a === void 0 ? void 0 : _a.node) === null || _b === void 0 ? void 0 : _b.split(".")) === null || _c === void 0 ? void 0 : _c[0]) || undefined, is_ci: process.env.CI ? 1 : 0 });
63
+ return {
64
+ reportSuccess(durationMs) {
65
+ if (!apm)
66
+ return;
67
+ apm.report(exports.CLI_MEASUREMENT_NAME, Object.assign(Object.assign({}, base), { status: 1, duration: durationMs }));
68
+ setCliApmCurrentCommand(undefined);
69
+ },
70
+ reportFail(durationMs, err) {
71
+ if (!apm)
72
+ return;
73
+ const n = normalizeError(err);
74
+ apm.report(exports.CLI_MEASUREMENT_NAME, Object.assign(Object.assign(Object.assign({}, base), { status: 0, duration: durationMs }), n));
75
+ setCliApmCurrentCommand(undefined);
76
+ },
77
+ };
78
+ }
79
+ function reportCliException(source, err) {
80
+ var _a, _b, _c;
81
+ if (!apm)
82
+ return;
83
+ const n = normalizeError(err);
84
+ apm.report(exports.CLI_MEASUREMENT_NAME, Object.assign(Object.assign(Object.assign({ event: "exception", source }, (currentCmdPath ? { cmd_path: currentCmdPath } : {})), { cli_version: (process === null || process === void 0 ? void 0 : process.CLI_VERSION) || "unknown", node_major: Number((_c = (_b = (_a = process.versions) === null || _a === void 0 ? void 0 : _a.node) === null || _b === void 0 ? void 0 : _b.split(".")) === null || _c === void 0 ? void 0 : _c[0]) || undefined, is_ci: process.env.CI ? 1 : 0 }), n));
85
+ }
86
+ function reportCliHttpError(meta, err) {
87
+ var _a, _b, _c;
88
+ if (!apm)
89
+ return;
90
+ let host;
91
+ let path;
92
+ if (meta.url) {
93
+ try {
94
+ const u = new URL(meta.url);
95
+ host = u.host;
96
+ path = u.pathname;
97
+ }
98
+ catch (_d) {
99
+ }
100
+ }
101
+ const n = err ? normalizeError(err) : undefined;
102
+ apm.report(exports.CLI_MEASUREMENT_NAME, Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ event: "http_error" }, (meta.method ? { method: meta.method } : {})), (host ? { host } : {})), (path ? { path } : {})), (typeof meta.status_code === "number" ? { status_code: meta.status_code } : {})), (currentCmdPath ? { cmd_path: currentCmdPath } : {})), { cli_version: (process === null || process === void 0 ? void 0 : process.CLI_VERSION) || "unknown", node_major: Number((_c = (_b = (_a = process.versions) === null || _a === void 0 ? void 0 : _a.node) === null || _b === void 0 ? void 0 : _b.split(".")) === null || _c === void 0 ? void 0 : _c[0]) || undefined, is_ci: process.env.CI ? 1 : 0 }), (n ? n : {})));
103
+ }
@@ -1,134 +1,20 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
4
15
  };
5
16
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.APM = void 0;
7
- const node_fetch_1 = __importDefault(require("node-fetch"));
8
- const uuid_1 = __importDefault(require("uuid"));
9
- const logger_1 = require("../logger");
10
- const device_1 = require("./device");
11
- const deviceInfo = (0, device_1.getDeviceInfo)();
12
- const getUserAgent = () => {
13
- var _a, _b;
14
- const electronStr = typeof ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.electron) !== "undefined" ? `Electron/${(_b = process === null || process === void 0 ? void 0 : process.versions) === null || _b === void 0 ? void 0 : _b.electron}` : "";
15
- const nodeStr = `Node/${process.version}`;
16
- const os_version = `${deviceInfo.os_platform}/${deviceInfo.os_version}`;
17
- const cpu = `CPU/${deviceInfo.cpu_speed}mhz (${deviceInfo.cpu_model}; ${deviceInfo.os_arch})`;
18
- const mem = `Memory/${deviceInfo.machine_memory}mb`;
19
- return [electronStr, nodeStr, os_version, cpu, mem]
20
- .map((i) => { var _a; return (_a = i === null || i === void 0 ? void 0 : i.trim) === null || _a === void 0 ? void 0 : _a.call(i); })
21
- .filter(Boolean)
22
- .join(" ")
23
- .trim();
24
- };
25
- const CONTEXT = {
26
- context_nameTracker: "nodeT",
27
- context_platform: deviceInfo.os_platform,
28
- context_appVersion: "0.0.1",
29
- context_osVersion: deviceInfo.os_version,
30
- context_deviceModel: "",
31
- context_deviceId: (0, device_1.machineId)(),
32
- context_package: "",
33
- context_networkType: "unknow",
34
- context_matchedPath: "cli",
35
- context_route: "xhsmp://cli",
36
- context_userAgent: getUserAgent(),
37
- context_artifactName: "miniprogram",
38
- context_networkQuality: "UNKNOWN",
39
- context_artifactVersion: "UNKNOWN",
40
- context_userId: "",
41
- };
42
- const ENDPOINT = {
43
- development: "https://apm-fe.xiaohongshu.com/api/data",
44
- production: "https://apm-fe.xiaohongshu.com/api/data",
45
- };
46
- class APM {
47
- constructor() {
48
- this.reportQueue = [];
49
- this.allowReport = false;
50
- this.eventSeq = 1;
51
- this.context = Object.assign({}, CONTEXT);
52
- this.baseData = {};
53
- this.timer = null;
54
- }
55
- setContext(userId, base = {}) {
56
- this.context = Object.assign(Object.assign({}, this.context), { context_userId: userId });
57
- this.baseData = base;
58
- this.startReport();
59
- }
60
- startReport() {
61
- this.allowReport = true;
62
- this.bactchReport();
63
- }
64
- getSequence() {
65
- return {
66
- context_sdkSeqId: this.eventSeq++,
67
- context_sdkSessionId: uuid_1.default.v4(),
68
- context_pageSessionId: uuid_1.default.v4(),
69
- clientTime: Date.now(),
70
- };
71
- }
72
- _request(params, retry = true) {
73
- const list = Array.isArray(params) ? params : [params];
74
- const merged = list.map((i) => {
75
- return Object.assign(Object.assign(Object.assign({}, this.context), i.suquence), { measurement_name: i.measurement_name, measurement_data: Object.assign(Object.assign({}, this.baseData), i.measurement_data) });
76
- });
77
- logger_1.logger.debug(`apm before send`, `${JSON.stringify(merged)}`, "warning");
78
- return (0, node_fetch_1.default)(ENDPOINT.development, {
79
- method: "post",
80
- body: JSON.stringify(merged),
81
- headers: {
82
- accept: "*/*",
83
- "accept-language": "zh-CN,zh;q=0.9",
84
- batch: "true",
85
- "biz-type": "apm_fe",
86
- "cache-control": "no-cache",
87
- "content-type": "application/json",
88
- pragma: "no-cache",
89
- },
90
- })
91
- .then((res) => res.json())
92
- .then((res) => {
93
- if (res === null || res === void 0 ? void 0 : res.success) {
94
- logger_1.logger.debug("apm send success", "");
95
- }
96
- else {
97
- throw new Error(res === null || res === void 0 ? void 0 : res.msg);
98
- }
99
- })
100
- .catch((err) => {
101
- if (retry) {
102
- setTimeout(() => this._request(merged, false), 1000);
103
- }
104
- logger_1.logger.log(`apm send failed`, `${(err === null || err === void 0 ? void 0 : err.message) || null}`, "error");
105
- });
106
- }
107
- bactchReport() {
108
- const queue = [...this.reportQueue];
109
- this.reportQueue = [];
110
- while (queue.length) {
111
- this._request(queue.splice(0, 5));
112
- }
113
- }
114
- report(measurement_name, measurement_data = {}) {
115
- const params = {
116
- suquence: this.getSequence(),
117
- measurement_name,
118
- measurement_data,
119
- };
120
- this.reportQueue.push(params);
121
- clearTimeout(this.timer);
122
- if (this.allowReport) {
123
- if (this.reportQueue.length >= 10) {
124
- this.bactchReport();
125
- }
126
- else {
127
- this.timer = setTimeout(() => {
128
- this.bactchReport();
129
- }, 200);
130
- }
131
- }
132
- }
133
- }
134
- exports.APM = APM;
17
+ __exportStar(require("./tracker"), exports);
18
+ __exportStar(require("./device"), exports);
19
+ __exportStar(require("./apm"), exports);
20
+ __exportStar(require("./cli-apm"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vectorx/cloud-toolkit",
3
- "version": "0.5.1",
3
+ "version": "1.0.0",
4
4
  "description": "VectorX Cloud Toolkit",
5
5
  "main": "lib/index.js",
6
6
  "types": "types/index.d.ts",
@@ -21,9 +21,9 @@
21
21
  "node": ">=18.0.0"
22
22
  },
23
23
  "dependencies": {
24
- "@vectorx/agent-simulator": "0.8.1",
25
- "@vectorx/functions-framework": "0.8.1",
24
+ "@vectorx/endpoints": "1.0.0",
26
25
  "archiver": "^5.3.1",
26
+ "cli-table3": "^0.5.1",
27
27
  "cos-nodejs-sdk-v5": "2.x",
28
28
  "crypto": "^1.0.1",
29
29
  "dayjs": "^1.11.13",
@@ -40,6 +40,14 @@
40
40
  "terminal-link": "^2.1.1",
41
41
  "uuid": "^11.1.0"
42
42
  },
43
+ "peerDependencies": {
44
+ "@vectorx/functions-framework": "*"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "@vectorx/functions-framework": {
48
+ "optional": true
49
+ }
50
+ },
43
51
  "devDependencies": {
44
52
  "@types/archiver": "^5.3.2",
45
53
  "@types/node": "^20.11.24",
@@ -1,3 +1,10 @@
1
+ type AgentSimulatorCtor = new (opts: {
2
+ port: number;
3
+ agentServerUrl: string;
4
+ open: boolean;
5
+ }) => {
6
+ start(): Promise<void>;
7
+ };
1
8
  export interface AgentDevOptions {
2
9
  workDir?: string;
3
10
  port?: number;
@@ -6,6 +13,10 @@ export interface AgentDevOptions {
6
13
  open?: boolean;
7
14
  nodePath?: string;
8
15
  enableRedLangfuse?: boolean;
16
+ mode?: "agent" | "fun";
17
+ deps?: {
18
+ AgentSimulator?: AgentSimulatorCtor;
19
+ };
9
20
  }
10
21
  export interface IUploadOptions {
11
22
  version: string;
@@ -56,11 +67,18 @@ export interface IDeployService {
56
67
  }
57
68
  export declare function startRcbFramework(workDir: string, port: number, watch: boolean, nodePath?: string, options?: {
58
69
  enableRedLangfuse?: boolean;
59
- }): Promise<void>;
70
+ mode?: "agent" | "fun";
71
+ }, onLog?: (log: {
72
+ level: "info" | "error" | "warn";
73
+ message: string;
74
+ timestamp: string;
75
+ }) => void): Promise<void>;
60
76
  export declare function startDev(options: AgentDevOptions): Promise<{
61
77
  port: number;
62
78
  simulatorPort: number;
63
- simulator: any;
79
+ simulator: {
80
+ start(): Promise<void>;
81
+ };
64
82
  rcbProcess: any;
65
83
  }>;
66
84
  export declare function build(options: AgentBuildOptions): Promise<BuildResult>;
@@ -68,3 +86,4 @@ export declare function createNew(options: AgentNewOptions): Promise<{
68
86
  projectDir: string;
69
87
  }>;
70
88
  export declare function cleanup(): void;
89
+ export {};
@@ -1,2 +1 @@
1
- declare function getBaseUrl(): string;
2
- export { getBaseUrl };
1
+ export declare function getBaseUrl(): string;
@@ -1,6 +1,8 @@
1
1
  import type { ServiceIdentifier } from "inversify";
2
- import type { IAuthService, IUploadService } from "./types";
2
+ import type { IAuthService, ICloudEnvService, IFunService, IUploadService } from "./types";
3
3
  export declare const SERVICE_IDENTIFIERS: {
4
4
  AuthService: ServiceIdentifier<IAuthService>;
5
5
  UploadService: ServiceIdentifier<IUploadService>;
6
+ CloudEnvService: ServiceIdentifier<ICloudEnvService>;
7
+ FunService: ServiceIdentifier<IFunService>;
6
8
  };
@@ -1,9 +1,11 @@
1
1
  import { container } from "./container";
2
2
  import { SERVICE_IDENTIFIERS } from "./identifiers";
3
- import type { IAuthService, IUploadService } from "./types";
3
+ import type { IAuthService, ICloudEnvService, IFunService, IUploadService } from "./types";
4
4
  export declare class ServiceProvider {
5
5
  static getAuthService(): IAuthService;
6
6
  static getUploadService(): IUploadService;
7
+ static getCloudEnvService(): ICloudEnvService;
8
+ static getFunService(): IFunService;
7
9
  }
8
10
  export { container, SERVICE_IDENTIFIERS };
9
11
  export * from "./types";