Spaces:
Running
Running
File size: 5,909 Bytes
90f0300 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | import { spawn } from 'node:child_process';
import fs from 'node:fs/promises';
import path from 'node:path';
export const LARK_CLI = 'lark-cli';
const LARK_DOMAIN = 'https://open.feishu.cn';
let larkCliCommandPath = '';
async function pathExists(candidate) {
try {
await fs.access(candidate);
return true;
} catch {
return false;
}
}
export async function resolveLarkCliCommand() {
if (larkCliCommandPath) {
return larkCliCommandPath;
}
const candidates = [];
if (process.env.LARK_CLI_PATH) {
candidates.push(process.env.LARK_CLI_PATH);
}
if (process.platform === 'win32') {
if (process.env.APPDATA) {
candidates.push(path.join(process.env.APPDATA, 'npm', 'node_modules', '@larksuite', 'cli', 'bin', 'lark-cli.exe'));
candidates.push(path.join(process.env.APPDATA, 'npm', 'lark-cli.cmd'));
}
const pathValue = process.env.Path || process.env.PATH || '';
for (const dir of pathValue.split(path.delimiter).filter(Boolean)) {
candidates.push(path.join(dir, 'lark-cli.exe'));
candidates.push(path.join(dir, 'lark-cli.cmd'));
}
}
for (const candidate of candidates) {
if (await pathExists(candidate)) {
larkCliCommandPath = candidate;
return candidate;
}
}
larkCliCommandPath = LARK_CLI;
return LARK_CLI;
}
export function larkCliEnvironment(baseEnv = process.env) {
const env = { ...baseEnv };
const appId = String(env.LARK_APP_ID || env.CODEXMOBILE_FEISHU_APP_ID || '').trim();
const appSecret = String(env.LARK_APP_SECRET || env.CODEXMOBILE_FEISHU_APP_SECRET || '').trim();
if (appId) {
env.LARK_APP_ID = appId;
}
if (appSecret) {
env.LARK_APP_SECRET = appSecret;
}
env.LARK_DOMAIN = String(env.LARK_DOMAIN || LARK_DOMAIN).trim() || LARK_DOMAIN;
env.LARK_CLI_NO_PROXY = '1';
env.NO_PROXY = '*';
env.no_proxy = '*';
for (const key of ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy']) {
delete env[key];
}
return env;
}
export function prependPathEntry(env, dir) {
const current = env.Path || env.PATH || '';
const next = [dir, current].filter(Boolean).join(path.delimiter);
env.Path = next;
env.PATH = next;
}
function windowsCmdQuote(value) {
return `"${String(value || '').replace(/"/g, '""').replace(/\r?\n/g, ' ')}"`;
}
export function larkCliSpawnOptions(command, args) {
if (process.platform === 'win32' && /\.cmd$|\.bat$/i.test(command)) {
return {
command: process.env.ComSpec || 'cmd.exe',
args: ['/d', '/c', ['call', windowsCmdQuote(command), ...args.map(windowsCmdQuote)].join(' ')],
windowsVerbatimArguments: true
};
}
return {
command,
args,
windowsVerbatimArguments: false
};
}
export function redacted(value) {
return String(value || '')
.replace(/"appSecret"\s*:\s*"[^"]+"/gi, '"appSecret":"****"')
.replace(/"access[_-]?token"\s*:\s*"[^"]+"/gi, '"accessToken":"****"')
.replace(/"refresh[_-]?token"\s*:\s*"[^"]+"/gi, '"refreshToken":"****"')
.replace(/\b(u|ur|t)-[A-Za-z0-9._-]{20,}\b/g, '$1-[hidden]')
.replace(/sk-[A-Za-z0-9._-]+/g, 'sk-[hidden]');
}
function parseJsonObject(text) {
const value = String(text || '').trim();
if (!value) {
return null;
}
try {
return JSON.parse(value);
} catch {
const start = value.indexOf('{');
const end = value.lastIndexOf('}');
if (start >= 0 && end > start) {
try {
return JSON.parse(value.slice(start, end + 1));
} catch {
return null;
}
}
}
return null;
}
export function larkError(message, details = {}) {
const error = new Error(message);
Object.assign(error, details);
return error;
}
export async function runLarkCli(args, options = {}) {
const { input = '', timeoutMs = 15000, cwd = process.cwd() } = options;
const command = await resolveLarkCliCommand();
const spawnOptions = larkCliSpawnOptions(command, args);
return await new Promise((resolve) => {
let stdout = '';
let stderr = '';
let settled = false;
let child = null;
try {
child = spawn(spawnOptions.command, spawnOptions.args, {
cwd,
env: larkCliEnvironment(),
windowsHide: true,
windowsVerbatimArguments: spawnOptions.windowsVerbatimArguments
});
} catch (error) {
resolve({ ok: false, code: null, signal: '', stdout: '', stderr: '', json: null, error: error.message });
return;
}
const timeout = setTimeout(() => {
if (settled) {
return;
}
settled = true;
child.kill();
resolve({
ok: false,
code: null,
signal: 'timeout',
stdout: redacted(stdout),
stderr: redacted(stderr),
json: parseJsonObject(stdout),
error: `lark-cli timed out after ${timeoutMs}ms`
});
}, timeoutMs);
child.stdout?.on('data', (chunk) => {
stdout += chunk.toString('utf8');
});
child.stderr?.on('data', (chunk) => {
stderr += chunk.toString('utf8');
});
child.on('error', (error) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timeout);
resolve({
ok: false,
code: null,
signal: '',
stdout: redacted(stdout),
stderr: redacted(stderr),
json: null,
error: error.message
});
});
child.on('close', (code, signal) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timeout);
resolve({
ok: code === 0,
code,
signal,
stdout: redacted(stdout),
stderr: redacted(stderr),
json: parseJsonObject(stdout),
error: code === 0 ? '' : redacted(stderr || stdout || `lark-cli exited with code ${code}`)
});
});
if (input && child.stdin) {
child.stdin.write(input);
}
child.stdin?.end();
});
}
|