@rainyun/cli 0.0.0-stage → 1.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 (68) hide show
  1. package/README.md +176 -2
  2. package/bin/postinstall.mjs +13 -0
  3. package/bin/rainyun-cli.mjs +13 -0
  4. package/catalog/human-names.json +340 -0
  5. package/catalog/list.openapi.json +354 -0
  6. package/catalog/openapi.json +34527 -0
  7. package/catalog/product-commands.json +332 -0
  8. package/catalog/public.openapi.json +1891 -0
  9. package/docs/AGENT_GUIDE.md +64 -0
  10. package/docs/install.md +44 -0
  11. package/docs/product-lists.md +48 -0
  12. package/docs/rgp.md +77 -0
  13. package/docs/terminal-exec.md +111 -0
  14. package/examples/public-panel.json +1 -0
  15. package/examples/public-rcs-price.json +1 -0
  16. package/examples/rca-terminal-input.json +1 -0
  17. package/examples/rcs-get.json +1 -0
  18. package/examples/rcs-list.json +1 -0
  19. package/examples/rcs-reboot.json +1 -0
  20. package/examples/terminal-controls.ndjson +3 -0
  21. package/examples/terminal-input.json +1 -0
  22. package/node_modules/ws/LICENSE +20 -0
  23. package/node_modules/ws/README.md +539 -0
  24. package/node_modules/ws/browser.js +8 -0
  25. package/node_modules/ws/index.js +22 -0
  26. package/node_modules/ws/lib/buffer-util.js +142 -0
  27. package/node_modules/ws/lib/constants.js +19 -0
  28. package/node_modules/ws/lib/event-target.js +292 -0
  29. package/node_modules/ws/lib/extension.js +203 -0
  30. package/node_modules/ws/lib/limiter.js +55 -0
  31. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  32. package/node_modules/ws/lib/receiver.js +751 -0
  33. package/node_modules/ws/lib/sender.js +610 -0
  34. package/node_modules/ws/lib/stream.js +161 -0
  35. package/node_modules/ws/lib/subprotocol.js +62 -0
  36. package/node_modules/ws/lib/validation.js +152 -0
  37. package/node_modules/ws/lib/websocket-server.js +565 -0
  38. package/node_modules/ws/lib/websocket.js +1471 -0
  39. package/node_modules/ws/package.json +74 -0
  40. package/node_modules/ws/wrapper.mjs +21 -0
  41. package/package.json +29 -4
  42. package/skills/rainyun-cli/SKILL.md +46 -0
  43. package/src/api/catalog.mjs +230 -0
  44. package/src/api/http.mjs +222 -0
  45. package/src/api/request.mjs +178 -0
  46. package/src/api/titles.mjs +9 -0
  47. package/src/auth/commands.mjs +192 -0
  48. package/src/auth/store.mjs +162 -0
  49. package/src/cli.mjs +154 -0
  50. package/src/commands/dispatch.mjs +128 -0
  51. package/src/commands/fields.mjs +77 -0
  52. package/src/commands/products.mjs +209 -0
  53. package/src/commands/rgs.mjs +44 -0
  54. package/src/json.mjs +81 -0
  55. package/src/output/business.mjs +188 -0
  56. package/src/output/discovery.mjs +197 -0
  57. package/src/output/examples.mjs +71 -0
  58. package/src/output/format.mjs +164 -0
  59. package/src/output/help.json +181 -0
  60. package/src/output/help.mjs +334 -0
  61. package/src/rgp/commands.mjs +251 -0
  62. package/src/rgp/input.mjs +144 -0
  63. package/src/rgp/operations.json +625 -0
  64. package/src/rgp/result.mjs +103 -0
  65. package/src/rgp/transfer.mjs +213 -0
  66. package/src/terminal/commands.mjs +155 -0
  67. package/src/terminal/session.mjs +233 -0
  68. package/src/terminal/target.mjs +155 -0
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "ws",
3
+ "version": "8.23.0",
4
+ "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
5
+ "keywords": [
6
+ "HyBi",
7
+ "Push",
8
+ "RFC-6455",
9
+ "WebSocket",
10
+ "WebSockets",
11
+ "real-time"
12
+ ],
13
+ "homepage": "https://github.com/websockets/ws",
14
+ "bugs": "https://github.com/websockets/ws/issues",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/websockets/ws.git"
18
+ },
19
+ "author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
20
+ "license": "MIT",
21
+ "main": "index.js",
22
+ "exports": {
23
+ ".": {
24
+ "browser": "./browser.js",
25
+ "import": "./wrapper.mjs",
26
+ "require": "./index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "browser": "browser.js",
31
+ "engines": {
32
+ "node": ">=10.0.0"
33
+ },
34
+ "files": [
35
+ "browser.js",
36
+ "index.js",
37
+ "lib/*.js",
38
+ "wrapper.mjs"
39
+ ],
40
+ "scripts": {
41
+ "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js",
42
+ "integration": "mocha --throw-deprecation test/*.integration.js",
43
+ "lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\""
44
+ },
45
+ "peerDependencies": {
46
+ "bufferutil": "^4.0.1",
47
+ "utf-8-validate": ">=5.0.2"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "bufferutil": {
51
+ "optional": true
52
+ },
53
+ "utf-8-validate": {
54
+ "optional": true
55
+ }
56
+ },
57
+ "devDependencies": {
58
+ "@eslint/js": "^10.0.1",
59
+ "benchmark": "^2.1.4",
60
+ "bufferutil": "^4.0.1",
61
+ "eslint": "^10.0.1",
62
+ "eslint-config-prettier": "^10.0.1",
63
+ "eslint-plugin-prettier": "^5.0.0",
64
+ "globals": "^17.0.0",
65
+ "mocha": "^8.4.0",
66
+ "nyc": "^15.0.0",
67
+ "prettier": "^3.0.0",
68
+ "utf-8-validate": "^6.0.0"
69
+ },
70
+ "allowScripts": {
71
+ "bufferutil": true,
72
+ "utf-8-validate": true
73
+ }
74
+ }
@@ -0,0 +1,21 @@
1
+ import createWebSocketStream from './lib/stream.js';
2
+ import extension from './lib/extension.js';
3
+ import PerMessageDeflate from './lib/permessage-deflate.js';
4
+ import Receiver from './lib/receiver.js';
5
+ import Sender from './lib/sender.js';
6
+ import subprotocol from './lib/subprotocol.js';
7
+ import WebSocket from './lib/websocket.js';
8
+ import WebSocketServer from './lib/websocket-server.js';
9
+
10
+ export {
11
+ createWebSocketStream,
12
+ extension,
13
+ PerMessageDeflate,
14
+ Receiver,
15
+ Sender,
16
+ subprotocol,
17
+ WebSocket,
18
+ WebSocketServer
19
+ };
20
+
21
+ export default WebSocket;
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@rainyun/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Rainyun CLI for agents",
5
+ "type": "module",
6
+ "bin": {
7
+ "rainyun-cli": "bin/rainyun-cli.mjs"
8
+ },
9
+ "engines": {
10
+ "node": ">=22.15.0"
11
+ },
12
+ "files": [
13
+ "bin/",
14
+ "src/",
15
+ "catalog/",
16
+ "skills/",
17
+ "docs/",
18
+ "examples/",
19
+ "README.md"
20
+ ],
21
+ "scripts": {
22
+ "test": "node --test",
23
+ "postinstall": "node ./bin/postinstall.mjs"
24
+ },
25
+ "dependencies": {
26
+ "ws": "8.23.0"
27
+ },
28
+ "bundleDependencies": [
29
+ "ws"
30
+ ]
31
+ }
@@ -0,0 +1,46 @@
1
+ ---
2
+ name: rainyun-cli
3
+ description: 用户想查看或管理自己的雨云资源时使用。通过 rainyun-cli 列出实例、查看套餐和报价、管理游戏面板备份、读取控制台输出,或解释这些操作的失败原因。
4
+ ---
5
+
6
+ # 使用 rainyun-cli 操作雨云
7
+
8
+ ## 官方资料
9
+
10
+ - [雨云百科文档](https://www.rainyun.com/docs)
11
+ - [雨云 CLI 使用指南](https://www.rainyun.com/docs/cli)
12
+
13
+ 把用户的自然语言请求落实到具体资源,并用中文说明结果。例如,用户说“看看我有哪些游戏云服务器”,直接运行下面的查询,按返回内容列出实例编号、名称和状态。如果还有下一页,说明当前列出的是第几页。用户要求列出全部时再逐页取全。
14
+
15
+ ```sh
16
+ rainyun-cli rgs list --page 1 --per-page 20 --json
17
+ ```
18
+
19
+ 以当前安装版本的帮助为准。自动化调用显式加 `--json`。若系统找不到命令,请用户在 Agent 所在环境安装 Node.js 22.15 或更高版本和雨云 CLI,再用 `rainyun-cli --version` 核对。
20
+
21
+ ## 找到正确的操作
22
+
23
+ | 用户要做什么 | 从哪里开始 |
24
+ |---|---|
25
+ | 查询游戏云实例、管理域名等产品操作 | 从产品帮助逐级查找,例如 `rainyun-cli rgs --help --json`。查实例详情用 `rainyun-cli rgs instance get --help --json`。 |
26
+ | 根据中文描述找主 API | 用 `rainyun-cli commands --query 游戏云 --json`,读取 `data.items[].operation_id`。结果有下一页时将 `data.next_offset` 传给 `--offset`。用 `schema` 查看选中接口,再用 `call` 调用。完整接口名从结果复制。 |
27
+ | 管理自研游戏面板的文件、计划任务、备份或容器状态 | 确认实例使用 `k8s_panel`。例如用 `rainyun-cli rgp commands --query backup --json` 找面板备份,用 `rainyun-cli rgp schema backup.restore --json` 查看还原条件。主 API 的 `rgs backup` 与面板备份是不同入口,目标不明确时先核对。 |
28
+ | 查看控制台输出或发送输入 | 先查 `rainyun-cli terminal rgs --help --json` 或 `rainyun-cli terminal rca --help --json`。RCA 需要本机已导入目标应用和容器的连接资料。流式会话的 `--stream` 按行输出 JSON;`input_sent` 仅表明输入已发送。 |
29
+
30
+ ## 执行操作或离线预览
31
+
32
+ 用户要求重启游戏云实例时,从用户提供的信息或实例列表确定目标 ID,直接执行重启。下方的 123 是示例编号,执行前替换为实际目标。
33
+
34
+ ```sh
35
+ rainyun-cli schema rgs.instance.reboot --json
36
+ rainyun-cli rgs instance reboot --id 123 --json
37
+ ```
38
+
39
+ 默认执行的写操作应与用户已授权的动作和目标一致。用户只要预览或演示时加 `--dry-run`,从返回值核对目标、方法和请求体。`is_write` 标明写入风险。需要实际报价时调用对应的价格查询接口。用 `call` 提交复杂参数时,可通过 `--input FILE` 提供 UTF-8 JSON,按 schema 分开填写 `path`、`query` 和 `body`。
40
+
41
+ 公开接口可用 `commands --public` 搜索,默认匿名。只有明确需要账号报价且该接口支持账号身份时,才加 `--authenticated`。私有接口复用 CLI 已配置的凭据。缺凭据时,请用户在自己的终端执行 `rainyun-cli auth login`,或使用宿主已注入的 `RAINYUN_API_KEY`。不要索取聊天中的密钥或打开凭据文件。已配置凭据时,`auth status --json` 查询当前账号,成功后读取 `data.user.id` 和 `data.user.name`。该接口需要 `user:read:self`;仅有产品权限的密钥仍可用于其获准的产品操作。
42
+
43
+ ## 判断操作结果
44
+
45
+ - 普通 HTTP 调用同时检查退出码和 JSON。成功时从 stdout 的 `response` 读取服务端数据;失败时从 stderr 的 `error` 读取 `kind`、`message` 和可用的 `http_status`、`business_code`。向用户报告相关字段,例如“HTTP 400,业务码 404”;保留用户需要的目标编号,避免转发令牌或整份配置。
46
+ - 写入超时或收到 `outcome=unknown` 时,先查目标状态再决定是否重试。RGP 返回 `task_id` 时,用 `rainyun-cli rgp schema task.wait --json` 查看参数,按这次返回的编号跟踪到终态。将任务提交成功、控制台输入已发送和业务操作已完成分别报告。
@@ -0,0 +1,230 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ const names = {
4
+ 'rcs.list': 'get_product_rcs_7f99884d',
5
+ 'rcs.get': 'get_product_rcs_id_829d7c0c',
6
+ 'rcs.reboot': 'post_product_rcs_id_reboot_44578c8a',
7
+ 'rcs.renew': 'post_product_rcs_id_renew_e3495669',
8
+ 'rcs.create': 'post_product_rcs_16b59444',
9
+ 'rcs.price': 'get_product_rcs_price_85b84a78',
10
+ 'site.config': 'public_site_config',
11
+ 'rgs.get': 'get_product_rgs_id_2d2988b0',
12
+ 'rgs.list': 'get_product_rgs_list',
13
+ 'rbm.list': 'get_product_rbm_list',
14
+ 'ros.list': 'get_product_ros_instance_23ab320e',
15
+ 'ros.bucket.list': 'get_product_ros_bucket_b0a5624e',
16
+ 'rca.project.list': 'get_product_rca_project_list',
17
+ 'rca.app.list': 'get_product_rca_app_list',
18
+ };
19
+ export function fail(kind, message, fields = {}) {
20
+ throw Object.assign(new Error(message), { kind, ...fields });
21
+ }
22
+ export function check(condition, message) {
23
+ if (!condition) fail('usage', message);
24
+ }
25
+ export const isWrite = (method) => !['GET', 'HEAD', 'OPTIONS'].includes(method);
26
+ export const isObject = (v) =>
27
+ v !== null && typeof v === 'object' && !Array.isArray(v) && !JSON.isRawJSON(v);
28
+ export function allow(flags, names) {
29
+ for (const key of Object.keys(flags)) check(names.includes(key), 'unexpected flag --' + key);
30
+ }
31
+ export function integer(raw, fallback, min, max, name) {
32
+ if (raw === undefined) return fallback;
33
+ const n = Number(raw);
34
+ check(/^\d+$/.test(raw) && Number.isSafeInteger(n) && n >= min && n <= max, 'invalid --' + name);
35
+ return n;
36
+ }
37
+ let cached;
38
+ export function catalog() {
39
+ if (cached) return cached;
40
+ const components = Object.create(null),
41
+ ops = new Map(),
42
+ routes = new Map();
43
+ for (const file of ['openapi', 'public.openapi', 'list.openapi']) {
44
+ const doc = JSON.parse(
45
+ readFileSync(new URL('../../catalog/' + file + '.json', import.meta.url), 'utf8')
46
+ );
47
+ for (const [group, defs] of Object.entries(doc.components || {})) {
48
+ components[group] ??= Object.create(null);
49
+ for (const [key, value] of Object.entries(defs)) {
50
+ if (
51
+ Object.hasOwn(components[group], key) &&
52
+ JSON.stringify(components[group][key]) !== JSON.stringify(value)
53
+ )
54
+ fail('protocol', 'conflicting catalog definition ' + key);
55
+ components[group][key] = value;
56
+ }
57
+ }
58
+ for (const [path, item] of Object.entries(doc.paths)) {
59
+ for (const [verb, def] of Object.entries(item)) {
60
+ if (verb === 'parameters') continue;
61
+ const id = def.operationId,
62
+ method = verb.toUpperCase();
63
+ const enabled = def['x-api-key-enabled'] === true,
64
+ pub = def['x-public'] === true;
65
+ const old = routes.get(method + ' ' + path);
66
+ const scopes = def['x-api-key-scopes'] || [];
67
+ if (
68
+ !id ||
69
+ (pub && (file !== 'public.openapi' || !Array.isArray(def.security) || def.security.length)) ||
70
+ (!pub && (!enabled || file === 'public.openapi')) ||
71
+ (file === 'list.openapi' &&
72
+ (verb !== 'get' ||
73
+ !scopes.length ||
74
+ JSON.stringify(def.security) !== '[{"BearerAuth":[]}]')) ||
75
+ (old &&
76
+ (file !== 'public.openapi' || old.operation_id !== id || old.api_key_enabled !== enabled)) ||
77
+ (!old && ops.has(id))
78
+ ) {
79
+ fail('protocol', 'inconsistent catalog operation ' + method + ' ' + path);
80
+ }
81
+ const op = {
82
+ authentication: pub ? 'none' : 'api_key',
83
+ api_key_enabled: enabled,
84
+ operation_id: id,
85
+ method,
86
+ path,
87
+ summary: def.summary ?? '',
88
+ scopes,
89
+ };
90
+ const aliases = Object.keys(names).filter((name) => names[name] === id);
91
+ if (aliases.length) op.aliases = aliases;
92
+ if (def.description) op.description = def.description;
93
+ const params = new Map();
94
+ for (const raw of [...(item.parameters || []), ...(def.parameters || [])]) {
95
+ const p = resolve(raw, components);
96
+ const param = { name: p.name, in: p.in, required: !!p.required };
97
+ for (const field of ['description', 'schema', 'x-json-content-schema', 'style', 'explode']) {
98
+ if (p[field] !== undefined && p[field] !== '') param[field] = p[field];
99
+ }
100
+ params.set(p.in + '/' + p.name, param);
101
+ }
102
+ if (params.size) op.parameters = [...params.values()];
103
+ if (def.requestBody) op.request_body = def.requestBody;
104
+ if (def.responses) op.responses = def.responses;
105
+ ops.set(id, op);
106
+ routes.set(method + ' ' + path, op);
107
+ }
108
+ }
109
+ }
110
+ return (cached = {
111
+ ops,
112
+ components,
113
+ items: [...ops.values()].sort((a, b) => (a.operation_id < b.operation_id ? -1 : 1)),
114
+ });
115
+ }
116
+ function component(ref, components) {
117
+ const parts = ref.split('/');
118
+ if (parts.length !== 4 || parts[0] !== '#' || parts[1] !== 'components')
119
+ fail('protocol', 'invalid local reference');
120
+ const [group, name] = parts.slice(2).map((s) => s.replaceAll('~1', '/').replaceAll('~0', '~'));
121
+ const value = components[group]?.[name];
122
+ if (!value) fail('protocol', 'missing component ' + ref);
123
+ return { group, name, value };
124
+ }
125
+ export function resolve(def, components = catalog().components) {
126
+ const seen = new Set();
127
+ while (def?.$ref) {
128
+ if (seen.has(def.$ref)) fail('protocol', 'cyclic catalog reference');
129
+ seen.add(def.$ref);
130
+ def = component(def.$ref, components).value;
131
+ }
132
+ return def;
133
+ }
134
+ export function lookup(name) {
135
+ const op = catalog().ops.get(Object.hasOwn(names, name) ? names[name] : name);
136
+ if (op) return op;
137
+ if (
138
+ [
139
+ 'rca.exec',
140
+ 'rca.logs',
141
+ 'rca.exec-targets',
142
+ 'rgs.exec',
143
+ 'rgs.logs',
144
+ 'post_rca_container_exec',
145
+ 'get_rca_container_logs',
146
+ 'get_rca_exec_targets',
147
+ 'post_rgs_container_exec',
148
+ 'get_rgs_container_logs',
149
+ ].includes(name)
150
+ )
151
+ fail('usage', 'use rainyun-cli terminal --help (RCA requires a local profile import)');
152
+ fail('usage', 'unknown operation ' + name + '; use rainyun-cli commands --query TEXT');
153
+ }
154
+ export function describe(name, responses) {
155
+ const op = { ...lookup(name) };
156
+ if (!responses) delete op.responses;
157
+ const components = Object.create(null);
158
+ function walk(obj) {
159
+ if (obj === null || typeof obj !== 'object') return;
160
+ if (obj.$ref) {
161
+ const { group, name, value } = component(obj.$ref, catalog().components);
162
+ components[group] ??= Object.create(null);
163
+ if (!Object.hasOwn(components[group], name)) {
164
+ components[group][name] = value;
165
+ walk(value);
166
+ }
167
+ }
168
+ for (const v of Object.values(obj)) walk(v);
169
+ }
170
+ walk(op);
171
+ const warnings = [
172
+ 'When authenticating, scopes are AND requirements; account and resource permissions also apply.',
173
+ 'Request-body required fields may be over-reported by the source exporter. The CLI checks body shape, not required fields or business constraints.',
174
+ ];
175
+ if (op.authentication === 'none')
176
+ warnings.push(
177
+ 'This operation defaults to anonymous access without reading credentials. If api_key_enabled is true, --authenticated explicitly selects account-specific access.'
178
+ );
179
+ return {
180
+ ok: true,
181
+ operation: op,
182
+ components,
183
+ scope_mode: 'all',
184
+ is_write: isWrite(op.method),
185
+ requires_yes: false,
186
+ warnings,
187
+ };
188
+ }
189
+ export function commands(flags, titleOf) {
190
+ allow(flags, ['query', 'scope', 'public', 'limit', 'offset']);
191
+ const limit = integer(flags.limit, 20, 1, 100, 'limit');
192
+ const offset = integer(flags.offset, 0, 0, Number.MAX_SAFE_INTEGER, 'offset');
193
+ const query = (flags.query || '').toLowerCase();
194
+ const matches = catalog().items.filter(
195
+ (op) =>
196
+ (!flags.public || op.authentication === 'none') &&
197
+ (!flags.scope || op.scopes.includes(flags.scope)) &&
198
+ [
199
+ op.operation_id,
200
+ ...(op.aliases || []),
201
+ op.path,
202
+ op.summary,
203
+ op.description,
204
+ ...op.scopes,
205
+ titleOf?.(op),
206
+ ]
207
+ .join(' ')
208
+ .toLowerCase()
209
+ .includes(query)
210
+ );
211
+ const items = matches
212
+ .slice(offset, offset + limit)
213
+ .map(({ parameters, request_body, responses, description, ...info }) => ({
214
+ ...info,
215
+ is_write: isWrite(info.method),
216
+ requires_confirmation: false,
217
+ }));
218
+ const more = offset + limit < matches.length;
219
+ return {
220
+ ok: true,
221
+ data: {
222
+ items,
223
+ total: matches.length,
224
+ limit,
225
+ offset,
226
+ has_more: more,
227
+ next_offset: more ? offset + limit : null,
228
+ },
229
+ };
230
+ }
@@ -0,0 +1,222 @@
1
+ import packageInfo from '../../package.json' with { type: 'json' };
2
+ import http from 'node:http';
3
+ import https from 'node:https';
4
+ import { open } from 'node:fs/promises';
5
+ import { basename } from 'node:path';
6
+ import { randomBytes } from 'node:crypto';
7
+ import { Readable } from 'node:stream';
8
+ import { pipeline } from 'node:stream/promises';
9
+ import { check, fail, isObject, isWrite } from './catalog.mjs';
10
+ import { prepare } from './request.mjs';
11
+
12
+ export const defaultBase = 'https://api.v2.rainyun.com';
13
+ export function baseAddress(raw) {
14
+ let u;
15
+ try {
16
+ u = new URL(raw);
17
+ } catch {}
18
+ check(
19
+ /^https?:\/\/[^/]/i.test(raw) &&
20
+ u?.hostname &&
21
+ !/[?#\\\s\u0000-\u001f\u007f]/u.test(raw) &&
22
+ !raw.split('/')[2].includes('@') &&
23
+ u.port !== '0',
24
+ 'invalid --base-url'
25
+ );
26
+ const local =
27
+ u.hostname === 'localhost' || u.hostname === '[::1]' || /^127\.\d+\.\d+\.\d+$/.test(u.hostname);
28
+ check(
29
+ u.protocol === 'https:' || (u.protocol === 'http:' && local),
30
+ '--base-url requires HTTPS or loopback HTTP'
31
+ );
32
+ return u;
33
+ }
34
+ export function duration(text) {
35
+ let rest = String(text),
36
+ value = 0;
37
+ const units = { h: 3600000, m: 60000, s: 1000, ms: 1, us: 0.001, µs: 0.001, μs: 0.001, ns: 0.000001 };
38
+ while (rest.length) {
39
+ const m = /^((?:\d+(?:\.\d*)?|\.\d+))(ms|us|µs|μs|ns|h|m|s)/.exec(rest);
40
+ check(m, 'invalid --timeout duration');
41
+ value += Number(m[1]) * units[m[2]];
42
+ rest = rest.slice(m[0].length);
43
+ }
44
+ check(value > 0 && Number.isFinite(value), '--timeout must be positive');
45
+ return Math.ceil(value);
46
+ }
47
+ async function upload(file) {
48
+ let handle;
49
+ try {
50
+ handle = await open(file);
51
+ const stat = await handle.stat();
52
+ check(stat.isFile(), 'upload must be a regular file');
53
+ const boundary = 'rain-' + randomBytes(16).toString('hex');
54
+ const name = basename(file).replace(/["\\\r\n]/g, '_');
55
+ const pre = Buffer.from(
56
+ '--' +
57
+ boundary +
58
+ '\r\nContent-Disposition: form-data; name="image"; filename="' +
59
+ name +
60
+ '"\r\nContent-Type: application/octet-stream\r\n\r\n'
61
+ );
62
+ const end = Buffer.from('\r\n--' + boundary + '--\r\n');
63
+ async function* chunks() {
64
+ yield pre;
65
+ if (stat.size) yield* handle.createReadStream({ autoClose: false, end: stat.size - 1 });
66
+ yield end;
67
+ }
68
+ return {
69
+ body: Readable.from(chunks()),
70
+ type: 'multipart/form-data; boundary=' + boundary,
71
+ size: pre.length + stat.size + end.length,
72
+ close: () => handle.close(),
73
+ };
74
+ } catch (e) {
75
+ await handle?.close();
76
+ fail('usage', e.kind ? e.message : 'cannot open upload file');
77
+ }
78
+ }
79
+ async function once(url, method, headers, body, signal, onResponse) {
80
+ const client = url.protocol === 'https:' ? https : http;
81
+ let sender;
82
+ const response = new Promise((resolve, reject) => {
83
+ const req = client.request(url, { method, headers, signal, agent: false }, resolve);
84
+ req.once('error', reject);
85
+ if (body instanceof Readable) {
86
+ sender = pipeline(body, req).catch((e) => {
87
+ req.destroy();
88
+ reject(e);
89
+ });
90
+ } else req.end(body);
91
+ });
92
+ try {
93
+ return await onResponse(await response);
94
+ } finally {
95
+ if (body instanceof Readable) body.destroy();
96
+ await sender;
97
+ }
98
+ }
99
+ async function receive(res, op, ctx, max, key) {
100
+ const fields = { operation: op.operation_id, http_status: res.statusCode };
101
+ const uncertain = isWrite(op.method) ? { outcome: 'unknown' } : {};
102
+ let n = 0;
103
+ const chunks = [];
104
+ try {
105
+ for await (const part of res) {
106
+ n += part.length;
107
+ if (BigInt(n) > max)
108
+ fail('protocol', 'response exceeds --max-response-bytes', { ...fields, ...uncertain });
109
+ chunks.push(part);
110
+ }
111
+ } catch (e) {
112
+ if (e.kind) throw e;
113
+ fail('network', 'failed to read response', { ...fields, ...uncertain });
114
+ }
115
+ const bytes = Buffer.concat(chunks);
116
+ let envelope, diagnostic;
117
+ try {
118
+ envelope = ctx.jsonParse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
119
+ diagnostic = { response: envelope };
120
+ } catch {
121
+ diagnostic = {
122
+ response_text: bytes.subarray(0, 4096).toString() + (bytes.length > 4096 ? '… [truncated]' : ''),
123
+ };
124
+ }
125
+ if (key && (bytes.includes(Buffer.from(key)) || containsKey(envelope, key)))
126
+ diagnostic = { response_text: '[响应包含 API Key,已隐藏]' };
127
+ const code = envelope?.code;
128
+ if (!isObject(envelope) || code === undefined || !/^-?\d+$/.test(ctx.jsonStringify(code)))
129
+ fail('protocol', 'response must be a UTF-8 JSON object with an integer business code', {
130
+ ...fields,
131
+ ...diagnostic,
132
+ ...uncertain,
133
+ });
134
+ if (res.statusCode < 200 || res.statusCode >= 300 || String(code) !== '200') {
135
+ const auth =
136
+ [401, 403].includes(res.statusCode) || ['30039', '30093', '10005'].includes(String(code));
137
+ let msg = (typeof envelope.message === 'string' && envelope.message) || 'API request failed';
138
+ if (key) msg = msg.replaceAll(key, '[REDACTED]');
139
+ fail(auth ? 'auth' : 'api', msg, { ...fields, business_code: code, ...diagnostic });
140
+ }
141
+ return { ok: true, ...fields, response: envelope };
142
+ }
143
+ function containsKey(value, key) {
144
+ if (typeof value === 'string') return value.includes(key);
145
+ if (!value || typeof value !== 'object') return false;
146
+ return Object.entries(value).some(([name, child]) => name.includes(key) || containsKey(child, key));
147
+ }
148
+ export async function execute(op, input, flags, ctx) {
149
+ const rawBase = flags['base-url'] ?? ((ctx.env ?? process.env).RAINYUN_API_URL || defaultBase);
150
+ const base = baseAddress(rawBase);
151
+ const timeout = duration(flags.timeout ?? '30s');
152
+ const maxRaw = flags['max-response-bytes'] ?? String(16 << 20);
153
+ check(/^\d+$/.test(maxRaw), 'invalid --max-response-bytes');
154
+ const max = BigInt(maxRaw);
155
+ check(max > 0n && max < 9223372036854775807n, 'invalid --max-response-bytes');
156
+ check(!flags.authenticated || op.api_key_enabled, 'operation does not support API-key authentication');
157
+ const { path, query, headers } = prepare(op, input, ctx);
158
+ const url = new URL(base);
159
+ url.pathname = base.pathname.replace(/\/+$/, '') + path;
160
+ // Go query escaping encodes spaces as plus, and leaves tilde unescaped.
161
+ url.search = query.toString().replaceAll('%7E', '~').replaceAll('*', '%2A');
162
+ const authentication = flags.authenticated ? 'api_key' : op.authentication;
163
+ const hasFiles = !!Object.keys(input.files ?? {}).length;
164
+ if (authentication === 'api_key') headers.Authorization = 'Bearer [REDACTED]';
165
+ if (hasFiles) headers['Content-Type'] = 'multipart/form-data; boundary=<generated>';
166
+ else if (Object.hasOwn(input, 'body')) headers['Content-Type'] = 'application/json';
167
+ if (flags['dry-run'])
168
+ return {
169
+ ok: true,
170
+ dry_run: true,
171
+ operation: op.operation_id,
172
+ method: op.method,
173
+ url: url.href,
174
+ headers,
175
+ body: input.body,
176
+ files: hasFiles ? input.files : undefined,
177
+ is_write: isWrite(op.method),
178
+ requires_yes: false,
179
+ authentication,
180
+ };
181
+ let key = '';
182
+ if (authentication === 'api_key') {
183
+ key = await ctx.getKey(rawBase);
184
+ if (typeof key !== 'string' || !key || /[\s\u0000-\u001f\u007f]/u.test(key))
185
+ fail('auth', 'a valid API key is required');
186
+ headers.Authorization = 'Bearer ' + key;
187
+ }
188
+ const file = hasFiles ? await upload(input.files.image) : null;
189
+ const body =
190
+ file?.body ??
191
+ (Object.hasOwn(input, 'body') ? Buffer.from(ctx.jsonStringify(input.body)) : undefined);
192
+ if (file) headers['Content-Type'] = file.type;
193
+ if (body !== undefined) headers['Content-Length'] = file?.size ?? body.length;
194
+ headers['User-Agent'] = 'rainyun-cli/' + (ctx.version ?? packageInfo.version);
195
+ const deadline = new AbortController();
196
+ const signal = ctx.signal ? AbortSignal.any([ctx.signal, deadline.signal]) : deadline.signal;
197
+ // Long Go-style durations exceed Node's single-timer limit.
198
+ let remaining = timeout,
199
+ timer;
200
+ function schedule() {
201
+ const wait = Math.min(remaining, 2147483647);
202
+ remaining -= wait;
203
+ timer = setTimeout(remaining > 0 ? schedule : () => deadline.abort(), wait);
204
+ timer.unref();
205
+ }
206
+ schedule();
207
+ try {
208
+ return await once(url, op.method, headers, body, signal, (res) =>
209
+ receive(res, op, ctx, max, key)
210
+ );
211
+ } catch (e) {
212
+ if (e.kind) throw e;
213
+ fail(
214
+ 'network',
215
+ signal.aborted ? 'request canceled or timed out' : 'network request failed',
216
+ isWrite(op.method) ? { outcome: 'unknown' } : {}
217
+ );
218
+ } finally {
219
+ clearTimeout(timer);
220
+ await file?.close();
221
+ }
222
+ }