huaweicloud-devkit 1.0.2-dev.9 → 1.0.2-next.10

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 (99) hide show
  1. package/.agents/plugins/marketplace.json +20 -20
  2. package/LICENSE +201 -201
  3. package/README.md +178 -138
  4. package/README.zh-CN.md +176 -138
  5. package/bin/setup.cjs +10 -8
  6. package/integrations/opencode/commands/huaweicloud-doctor.md +14 -14
  7. package/integrations/opencode/opencode.json +11 -14
  8. package/integrations/opencode/skills/huaweicloud-core/SKILL.md +32 -32
  9. package/package.json +60 -44
  10. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +31 -44
  11. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +30 -43
  12. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +31 -44
  13. package/plugins/huaweicloud-core/.mcp.json +13 -15
  14. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +31 -44
  15. package/plugins/huaweicloud-core/hooks/hooks.json +26 -26
  16. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +136 -136
  17. package/plugins/huaweicloud-core/safety/policy.json +76 -100
  18. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +227 -199
  19. package/plugins/huaweicloud-core/skills/huawei-apig/SKILL.md +164 -164
  20. package/plugins/huaweicloud-core/skills/huawei-billing/SKILL.md +48 -48
  21. package/plugins/huaweicloud-core/skills/huawei-cbr/SKILL.md +50 -50
  22. package/plugins/huaweicloud-core/skills/huawei-cce/SKILL.md +103 -101
  23. package/plugins/huaweicloud-core/skills/huawei-cloud-eye/SKILL.md +90 -90
  24. package/plugins/huaweicloud-core/skills/huawei-cloud-find-skills/SKILL.md +191 -190
  25. package/plugins/huaweicloud-core/skills/huawei-cloud-find-skills/scripts/search-skills.mjs +171 -124
  26. package/plugins/huaweicloud-core/skills/huawei-cts/SKILL.md +55 -55
  27. package/plugins/huaweicloud-core/skills/huawei-dds-dcs/SKILL.md +70 -70
  28. package/plugins/huaweicloud-core/skills/huawei-deployment/SKILL.md +57 -56
  29. package/plugins/huaweicloud-core/skills/huawei-dew/SKILL.md +106 -97
  30. package/plugins/huaweicloud-core/skills/huawei-dew/references/csms-usage.md +36 -29
  31. package/plugins/huaweicloud-core/skills/huawei-dew/references/kms-usage.md +29 -23
  32. package/plugins/huaweicloud-core/skills/huawei-ecs/SKILL.md +188 -185
  33. package/plugins/huaweicloud-core/skills/huawei-ecs/references/create-instance.md +144 -133
  34. package/plugins/huaweicloud-core/skills/huawei-ecs/references/evs.md +31 -31
  35. package/plugins/huaweicloud-core/skills/huawei-ecs/references/flavors.md +57 -55
  36. package/plugins/huaweicloud-core/skills/huawei-ecs/references/troubleshooting.md +52 -52
  37. package/plugins/huaweicloud-core/skills/huawei-functiongraph/SKILL.md +132 -131
  38. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/apig-event-format.md +60 -58
  39. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/create-function.md +72 -71
  40. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/deploy-workflow.md +119 -119
  41. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/triggers.md +142 -142
  42. package/plugins/huaweicloud-core/skills/huawei-gaussdb/SKILL.md +56 -56
  43. package/plugins/huaweicloud-core/skills/huawei-getting-started/SKILL.md +69 -65
  44. package/plugins/huaweicloud-core/skills/huawei-iam/SKILL.md +111 -111
  45. package/plugins/huaweicloud-core/skills/huawei-iam/references/policy-examples.md +148 -122
  46. package/plugins/huaweicloud-core/skills/huawei-iam/references/quick-ref.md +56 -56
  47. package/plugins/huaweicloud-core/skills/huawei-modelarts/SKILL.md +65 -65
  48. package/plugins/huaweicloud-core/skills/huawei-obs/SKILL.md +134 -127
  49. package/plugins/huaweicloud-core/skills/huawei-obs/references/bucket-create.md +49 -49
  50. package/plugins/huaweicloud-core/skills/huawei-obs/references/bucket-lifecycle.md +31 -26
  51. package/plugins/huaweicloud-core/skills/huawei-obs/references/common-pitfalls.md +101 -100
  52. package/plugins/huaweicloud-core/skills/huawei-obs/references/single-file-share.md +40 -40
  53. package/plugins/huaweicloud-core/skills/huawei-obs/references/static-website.md +56 -56
  54. package/plugins/huaweicloud-core/skills/huawei-rds/SKILL.md +229 -224
  55. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +173 -134
  56. package/plugins/huaweicloud-core/skills/huawei-smn-dms/SKILL.md +69 -69
  57. package/plugins/huaweicloud-core/skills/huawei-vpc/SKILL.md +84 -84
  58. package/plugins/huaweicloud-core/skills/huawei-vpc/references/network.md +77 -76
  59. package/plugins/huaweicloud-core/skills/huawei-vpc/references/security-group.md +60 -59
  60. package/plugins/huaweicloud-core/skills/huawei-vpc/references/subnet.md +50 -50
  61. package/plugins/huaweicloud-core/skills/huawei-waf-aad/SKILL.md +63 -63
  62. package/plugins/huaweicloud-core/skills/huaweicloud-api-and-sdk/SKILL.md +56 -56
  63. package/plugins/huaweicloud-core/skills/huaweicloud-api-and-sdk/agents/openai.yaml +4 -4
  64. package/plugins/huaweicloud-core/skills/huaweicloud-capability-discovery/SKILL.md +56 -47
  65. package/plugins/huaweicloud-core/skills/huaweicloud-capability-discovery/agents/openai.yaml +4 -4
  66. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +138 -128
  67. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/agents/openai.yaml +4 -4
  68. package/plugins/huaweicloud-core/skills/huaweicloud-core/SKILL.md +111 -96
  69. package/plugins/huaweicloud-core/skills/huaweicloud-core/agents/openai.yaml +4 -4
  70. package/plugins/huaweicloud-core/skills/huaweicloud-core/references/report-issue.md +20 -20
  71. package/plugins/huaweicloud-core/skills/huaweicloud-core/references/select.md +30 -28
  72. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +59 -60
  73. package/plugins/huaweicloud-core/skills/huaweicloud-safety/agents/openai.yaml +4 -4
  74. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +83 -83
  75. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/agents/openai.yaml +4 -4
  76. package/plugins/huaweicloud-core/src/auth/agent-registration.mjs +54 -1
  77. package/plugins/huaweicloud-core/src/auth/credentials.mjs +103 -95
  78. package/plugins/huaweicloud-core/src/auth/service.mjs +63 -63
  79. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +3517 -0
  80. package/plugins/huaweicloud-core/src/hcloud-cli.mjs +283 -265
  81. package/plugins/huaweicloud-core/src/icon-library.mjs +171 -0
  82. package/plugins/huaweicloud-core/src/mcp-server.mjs +130 -129
  83. package/plugins/huaweicloud-core/src/proxy/proxy-agent.mjs +68 -0
  84. package/plugins/huaweicloud-core/src/proxy/proxy-config.mjs +94 -0
  85. package/plugins/huaweicloud-core/src/risk-rule-engine.mjs +140 -137
  86. package/plugins/huaweicloud-core/src/safety-policy.mjs +356 -302
  87. package/plugins/huaweicloud-core/src/sandbox/hdkitservice-api.mjs +86 -87
  88. package/plugins/huaweicloud-core/src/sandbox/hwlink-api.mjs +150 -153
  89. package/plugins/huaweicloud-core/src/sandbox/session-manager.mjs +196 -105
  90. package/plugins/huaweicloud-core/src/search-market.mjs +208 -169
  91. package/plugins/huaweicloud-core/src/setup-cli.mjs +2622 -1594
  92. package/plugins/huaweicloud-core/src/tools.mjs +463 -111
  93. package/plugins/huaweicloud-core/src/ws-exec/hwlink-exec-client.js +447 -427
  94. package/plugins/huaweicloud-core/src/ws-exec/hwlink-fair-queue.js +128 -132
  95. package/plugins/huaweicloud-core/src/ws-exec/hwlink-multiplexer.js +215 -227
  96. package/plugins/huaweicloud-core/src/ws-exec/hwlink-packet.js +189 -202
  97. package/plugins/huaweicloud-core/src/ws-exec/hwlink-terminal-channel.js +164 -158
  98. package/plugins/huaweicloud-core/src/ws-exec/index.js +19 -19
  99. package/plugins/huaweicloud-core/src/ws-exec/ws-exec-client.js +338 -338
@@ -1,87 +1,86 @@
1
- import { getCredentials } from './hwlink-api.mjs';
2
-
3
- const HDKIT_BASE_URL =
4
- process.env.HDKITSERVICE_ENDPOINT ||
5
- 'https://devkit.huaweicloud.com/rest/developer/server/hdkitservice/';
6
-
7
- async function hdkitRequest(method, path, body, timeoutMs = 300000) {
8
- const { ak, sk, securitytoken } = getCredentials();
9
-
10
- const headers = {
11
- 'Content-Type': 'application/json',
12
- 'X-HW-AK': ak,
13
- 'X-HW-SK': sk,
14
- };
15
- if (securitytoken) {
16
- headers['X-HW-Security-Token'] = securitytoken;
17
- }
18
-
19
- const url = `${HDKIT_BASE_URL}${path}`;
20
- const controller = new AbortController();
21
- const timer = setTimeout(() => controller.abort(), timeoutMs);
22
-
23
- let resp;
24
- try {
25
- resp = await fetch(url, {
26
- method,
27
- headers,
28
- body: body ? JSON.stringify(body) : undefined,
29
- signal: controller.signal,
30
- });
31
- } finally {
32
- clearTimeout(timer);
33
- }
34
-
35
- const text = await resp.text();
36
- let data;
37
- try {
38
- data = JSON.parse(text);
39
- } catch {
40
- throw new Error(`hdkitservice returned non-JSON (status ${resp.status}): ${text.slice(0, 200)}`);
41
- }
42
-
43
- if (!resp.ok) {
44
- const err = new Error(
45
- data.message || `hdkitservice error: ${data.code || resp.status}`
46
- );
47
- err.code = data.code;
48
- err.status = resp.status;
49
- err.traceId = data.trace_id;
50
- throw err;
51
- }
52
-
53
- return data;
54
- }
55
-
56
- export async function hdkitCheckUser() {
57
- return await hdkitRequest('GET', 'check-user', undefined, 30000);
58
- }
59
-
60
- export async function hdkitSignAgreement() {
61
- return await hdkitRequest('POST', 'sign-agreement', {});
62
- }
63
-
64
- export async function hdkitConnect(options = {}) {
65
- const body = {};
66
- if (options.source) body.source = options.source;
67
- if (options.env) body.env = options.env;
68
- if (options.git) body.git = options.git;
69
- if (options.template_id) body.template_id = options.template_id;
70
- if (options.flavor_id) body.flavor_id = options.flavor_id;
71
-
72
- return await hdkitRequest('POST', 'connect', body);
73
- }
74
-
75
- export async function hdkitCredentials(sessionId, devStageId, enableSts = true) {
76
- const body = { enable_sts: enableSts };
77
- if (sessionId) body.session_id = sessionId;
78
- if (devStageId) body.dev_stage_id = devStageId;
79
-
80
- if (!sessionId && !devStageId) {
81
- throw new Error('session_id or dev_stage_id is required');
82
- }
83
-
84
- return await hdkitRequest('POST', 'credentials', body);
85
- }
86
-
87
-
1
+ import { getCredentials } from './hwlink-api.mjs';
2
+ import { getProxyDispatcher } from '../proxy/proxy-agent.mjs';
3
+
4
+ const HDKIT_BASE_URL =
5
+ process.env.HDKITSERVICE_ENDPOINT || 'https://devkit.huaweicloud.com/rest/developer/server/hdkitservice/';
6
+
7
+ async function hdkitRequest(method, path, body, timeoutMs = 300000) {
8
+ const { ak, sk, securitytoken } = getCredentials();
9
+
10
+ const headers = {
11
+ 'Content-Type': 'application/json',
12
+ 'X-HW-AK': ak,
13
+ 'X-HW-SK': sk,
14
+ };
15
+ if (securitytoken) {
16
+ headers['X-HW-Security-Token'] = securitytoken;
17
+ }
18
+
19
+ const url = `${HDKIT_BASE_URL}${path}`;
20
+ const controller = new AbortController();
21
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
22
+
23
+ let resp;
24
+ try {
25
+ const dispatcher = await getProxyDispatcher(url);
26
+ const fetchOpts = {
27
+ method,
28
+ headers,
29
+ body: body ? JSON.stringify(body) : undefined,
30
+ signal: controller.signal,
31
+ };
32
+ if (dispatcher) fetchOpts.dispatcher = dispatcher;
33
+ resp = await fetch(url, fetchOpts);
34
+ } finally {
35
+ clearTimeout(timer);
36
+ }
37
+
38
+ const text = await resp.text();
39
+ let data;
40
+ try {
41
+ data = JSON.parse(text);
42
+ } catch {
43
+ throw new Error(`hdkitservice returned non-JSON (status ${resp.status}): ${text.slice(0, 200)}`);
44
+ }
45
+
46
+ if (!resp.ok) {
47
+ const err = new Error(data.message || `hdkitservice error: ${data.code || resp.status}`);
48
+ err.code = data.code;
49
+ err.status = resp.status;
50
+ err.traceId = data.traceId; // 后端实际返回驼峰 traceId
51
+ throw err;
52
+ }
53
+
54
+ return data;
55
+ }
56
+
57
+ export async function hdkitCheckUser() {
58
+ return await hdkitRequest('GET', 'check-user', undefined, 30000);
59
+ }
60
+
61
+ export async function hdkitSignAgreement() {
62
+ return await hdkitRequest('POST', 'sign-agreement', {});
63
+ }
64
+
65
+ export async function hdkitConnect(options = {}) {
66
+ const body = {};
67
+ if (options.source) body.source = options.source;
68
+ if (options.env) body.env = options.env;
69
+ if (options.git) body.git = options.git;
70
+ if (options.template_id) body.template_id = options.template_id;
71
+ if (options.flavor_id) body.flavor_id = options.flavor_id;
72
+
73
+ return await hdkitRequest('POST', 'connect', body);
74
+ }
75
+
76
+ export async function hdkitCredentials(sessionId, devStageId, enableSts = true) {
77
+ const body = { enable_sts: enableSts };
78
+ if (sessionId) body.session_id = sessionId;
79
+ if (devStageId) body.dev_stage_id = devStageId;
80
+
81
+ if (!sessionId && !devStageId) {
82
+ throw new Error('session_id or dev_stage_id is required');
83
+ }
84
+
85
+ return await hdkitRequest('POST', 'credentials', body);
86
+ }
@@ -1,153 +1,150 @@
1
- import crypto from 'node:crypto';
2
- import { resolveCredentials } from '../auth/credentials.mjs';
3
-
4
- const BASE_URL = process.env.HWLINK_ENDPOINT || 'https://devstation.myhuaweicloud.com';
5
-
6
- function sha256Hex(data) {
7
- return crypto.createHash('sha256').update(data).digest('hex');
8
- }
9
-
10
- function hmacSha256(key, data) {
11
- return crypto.createHmac('sha256', key).update(data).digest('hex');
12
- }
13
-
14
- function urlEncode(str) {
15
- const hex = (c) => '%' + (c < 16 ? '0' : '') + c.toString(16).toUpperCase();
16
- const noEscape = new Set(
17
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'.split('')
18
- );
19
- let out = '';
20
- for (const ch of str) {
21
- const c = ch.codePointAt(0);
22
- out += noEscape.has(ch) && c < 0x80 ? ch : c < 0x80 ? hex(c) : encodeURIComponent(ch);
23
- }
24
- return out;
25
- }
26
-
27
- function timestamp() {
28
- return new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+/, '') + 'Z';
29
- }
30
-
31
- function sortedQs(query) {
32
- return Object.entries(query)
33
- .sort(([a], [b]) => a.localeCompare(b))
34
- .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
35
- .join('&');
36
- }
37
-
38
- function signRequest(method, path, query, body, ak, sk, securitytoken) {
39
- const ts = timestamp();
40
- const host = new URL(BASE_URL).host;
41
-
42
- const cqs = Object.entries(query)
43
- .sort(([a], [b]) => a.localeCompare(b))
44
- .map(([k, v]) => `${urlEncode(k)}=${urlEncode(v)}`)
45
- .join('&');
46
-
47
- const curi =
48
- '/' +
49
- path
50
- .split('/')
51
- .filter(Boolean)
52
- .map((s) => urlEncode(s))
53
- .join('/') +
54
- '/';
55
-
56
- const signedHeaders = securitytoken
57
- ? 'host;x-sdk-date;x-security-token'
58
- : 'host;x-sdk-date';
59
- const canonicalHeaders = securitytoken
60
- ? `host:${host}\nx-sdk-date:${ts}\nx-security-token:${securitytoken}\n`
61
- : `host:${host}\nx-sdk-date:${ts}\n`;
62
-
63
- const bodyStr = body ? JSON.stringify(body) : '';
64
- const payloadHash = sha256Hex(bodyStr);
65
-
66
- const canonicalRequest = [
67
- method,
68
- curi,
69
- cqs,
70
- canonicalHeaders,
71
- signedHeaders,
72
- payloadHash,
73
- ].join('\n');
74
-
75
- const stringToSign = `SDK-HMAC-SHA256\n${ts}\n${sha256Hex(canonicalRequest)}`;
76
- const signature = hmacSha256(sk, stringToSign);
77
-
78
- const headers = {
79
- host,
80
- 'x-sdk-date': ts,
81
- Authorization: `SDK-HMAC-SHA256 Access=${ak}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
82
- };
83
- if (securitytoken) {
84
- headers['x-security-token'] = securitytoken;
85
- }
86
- return headers;
87
- }
88
-
89
- export function getCredentials() {
90
- const credentials = resolveCredentials();
91
- return { ak: credentials.ak, sk: credentials.sk, securitytoken: credentials.securityToken };
92
- }
93
-
94
- async function apiGet(path, query, ak, sk, securitytoken) {
95
- query = query || {};
96
- const qs = sortedQs(query);
97
- const fullPath = qs ? `${path}?${qs}` : path;
98
- const headers = signRequest('GET', path, query, undefined, ak, sk, securitytoken);
99
- const resp = await fetch(`${BASE_URL}${fullPath}`, { headers });
100
- return { status: resp.status, data: await resp.json() };
101
- }
102
-
103
- async function apiPost(path, body, ak, sk, securitytoken) {
104
- const headers = signRequest('POST', path, {}, body, ak, sk, securitytoken);
105
- const resp = await fetch(`${BASE_URL}${path}`, {
106
- method: 'POST',
107
- headers: { ...headers, 'Content-Type': 'application/json' },
108
- body: JSON.stringify(body),
109
- });
110
- return { status: resp.status, data: await resp.json() };
111
- }
112
-
113
- export async function createConnection(envId, ak, sk, securitytoken) {
114
- const { status, data } = await apiPost(
115
- `/open-api-public/v1/devenvs/${envId}/connections`,
116
- { source: 'CLI' },
117
- ak, sk, securitytoken
118
- );
119
-
120
- if (status !== 200 || data?.error_code !== '0000' || !data?.result?.connection_id) {
121
- throw new Error(`Failed to create connection: ${JSON.stringify(data)}`);
122
- }
123
-
124
- const connectionId = data.result.connection_id;
125
- const maxAttempts = 60;
126
-
127
- for (let i = 0; i < maxAttempts; i++) {
128
- process.stderr.write(`\rWaiting for connection ${connectionId}... (${i}s)`);
129
- const { data: getData } = await apiGet(
130
- `/open-api-public/v1/devenvs/${envId}/connections/${connectionId}`,
131
- {},
132
- ak, sk, securitytoken
133
- );
134
-
135
- if (
136
- getData?.result?.connection_info?.url &&
137
- getData.result.connection_info.extensions?.source != null
138
- ) {
139
- const u = new URL(getData.result.connection_info.url);
140
- u.searchParams.set('source', String(getData.result.connection_info.extensions.source));
141
- process.stderr.write(`\rConnection ${connectionId} established (${i}s).\n`);
142
- return {
143
- wsUrl: u.toString(),
144
- source: getData.result.connection_info.extensions.source,
145
- };
146
- }
147
- await new Promise((resolve) => setTimeout(resolve, 1000));
148
- }
149
-
150
- throw new Error(`Timed out waiting for connection ${connectionId}`);
151
- }
152
-
153
-
1
+ import crypto from 'node:crypto';
2
+ import { resolveCredentials } from '../auth/credentials.mjs';
3
+ import { getProxyDispatcher } from '../proxy/proxy-agent.mjs';
4
+
5
+ const BASE_URL = process.env.HWLINK_ENDPOINT || 'https://devstation.myhuaweicloud.com';
6
+
7
+ function sha256Hex(data) {
8
+ return crypto.createHash('sha256').update(data).digest('hex');
9
+ }
10
+
11
+ function hmacSha256(key, data) {
12
+ return crypto.createHmac('sha256', key).update(data).digest('hex');
13
+ }
14
+
15
+ function urlEncode(str) {
16
+ const hex = (c) => '%' + (c < 16 ? '0' : '') + c.toString(16).toUpperCase();
17
+ const noEscape = new Set('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'.split(''));
18
+ let out = '';
19
+ for (const ch of str) {
20
+ const c = ch.codePointAt(0);
21
+ out += noEscape.has(ch) && c < 0x80 ? ch : c < 0x80 ? hex(c) : encodeURIComponent(ch);
22
+ }
23
+ return out;
24
+ }
25
+
26
+ function timestamp() {
27
+ return new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+/, '') + 'Z';
28
+ }
29
+
30
+ function sortedQs(query) {
31
+ return Object.entries(query)
32
+ .sort(([a], [b]) => a.localeCompare(b))
33
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
34
+ .join('&');
35
+ }
36
+
37
+ function signRequest(method, path, query, body, ak, sk, securitytoken) {
38
+ const ts = timestamp();
39
+ const host = new URL(BASE_URL).host;
40
+
41
+ const cqs = Object.entries(query)
42
+ .sort(([a], [b]) => a.localeCompare(b))
43
+ .map(([k, v]) => `${urlEncode(k)}=${urlEncode(v)}`)
44
+ .join('&');
45
+
46
+ const curi =
47
+ '/' +
48
+ path
49
+ .split('/')
50
+ .filter(Boolean)
51
+ .map((s) => urlEncode(s))
52
+ .join('/') +
53
+ '/';
54
+
55
+ const signedHeaders = securitytoken ? 'host;x-sdk-date;x-security-token' : 'host;x-sdk-date';
56
+ const canonicalHeaders = securitytoken
57
+ ? `host:${host}\nx-sdk-date:${ts}\nx-security-token:${securitytoken}\n`
58
+ : `host:${host}\nx-sdk-date:${ts}\n`;
59
+
60
+ const bodyStr = body ? JSON.stringify(body) : '';
61
+ const payloadHash = sha256Hex(bodyStr);
62
+
63
+ const canonicalRequest = [method, curi, cqs, canonicalHeaders, signedHeaders, payloadHash].join('\n');
64
+
65
+ const stringToSign = `SDK-HMAC-SHA256\n${ts}\n${sha256Hex(canonicalRequest)}`;
66
+ const signature = hmacSha256(sk, stringToSign);
67
+
68
+ const headers = {
69
+ host,
70
+ 'x-sdk-date': ts,
71
+ Authorization: `SDK-HMAC-SHA256 Access=${ak}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
72
+ };
73
+ if (securitytoken) {
74
+ headers['x-security-token'] = securitytoken;
75
+ }
76
+ return headers;
77
+ }
78
+
79
+ export function getCredentials() {
80
+ const credentials = resolveCredentials();
81
+ return { ak: credentials.ak, sk: credentials.sk, securitytoken: credentials.securityToken };
82
+ }
83
+
84
+ async function apiGet(path, query, ak, sk, securitytoken) {
85
+ query = query || {};
86
+ const qs = sortedQs(query);
87
+ const fullPath = qs ? `${path}?${qs}` : path;
88
+ const headers = signRequest('GET', path, query, undefined, ak, sk, securitytoken);
89
+ const url = `${BASE_URL}${fullPath}`;
90
+ const dispatcher = await getProxyDispatcher(url);
91
+ const fetchOpts = { headers };
92
+ if (dispatcher) fetchOpts.dispatcher = dispatcher;
93
+ const resp = await fetch(url, fetchOpts);
94
+ return { status: resp.status, data: await resp.json() };
95
+ }
96
+
97
+ async function apiPost(path, body, ak, sk, securitytoken) {
98
+ const headers = signRequest('POST', path, {}, body, ak, sk, securitytoken);
99
+ const url = `${BASE_URL}${path}`;
100
+ const dispatcher = await getProxyDispatcher(url);
101
+ const fetchOpts = {
102
+ method: 'POST',
103
+ headers: { ...headers, 'Content-Type': 'application/json' },
104
+ body: JSON.stringify(body),
105
+ };
106
+ if (dispatcher) fetchOpts.dispatcher = dispatcher;
107
+ const resp = await fetch(url, fetchOpts);
108
+ return { status: resp.status, data: await resp.json() };
109
+ }
110
+
111
+ export async function createConnection(envId, ak, sk, securitytoken) {
112
+ const { status, data } = await apiPost(
113
+ `/open-api-public/v1/devenvs/${envId}/connections`,
114
+ { source: 'CLI' },
115
+ ak,
116
+ sk,
117
+ securitytoken,
118
+ );
119
+
120
+ if (status !== 200 || data?.error_code !== '0000' || !data?.result?.connection_id) {
121
+ throw new Error(`Failed to create connection: ${JSON.stringify(data)}`);
122
+ }
123
+
124
+ const connectionId = data.result.connection_id;
125
+ const maxAttempts = 60;
126
+
127
+ for (let i = 0; i < maxAttempts; i++) {
128
+ process.stderr.write(`\rWaiting for connection ${connectionId}... (${i}s)`);
129
+ const { data: getData } = await apiGet(
130
+ `/open-api-public/v1/devenvs/${envId}/connections/${connectionId}`,
131
+ {},
132
+ ak,
133
+ sk,
134
+ securitytoken,
135
+ );
136
+
137
+ if (getData?.result?.connection_info?.url && getData.result.connection_info.extensions?.source != null) {
138
+ const u = new URL(getData.result.connection_info.url);
139
+ u.searchParams.set('source', String(getData.result.connection_info.extensions.source));
140
+ process.stderr.write(`\rConnection ${connectionId} established (${i}s).\n`);
141
+ return {
142
+ wsUrl: u.toString(),
143
+ source: getData.result.connection_info.extensions.source,
144
+ };
145
+ }
146
+ await new Promise((resolve) => setTimeout(resolve, 1000));
147
+ }
148
+
149
+ throw new Error(`Timed out waiting for connection ${connectionId}`);
150
+ }