#!/usr/bin/env node import { execFileSync } from "node:child_process"; import { homedir } from "node:os"; import { resolve } from "node:path"; import { attachmentManifest, contentDigest, createDraftIdentity, normalize, preview, readStdin, writeJsonAtomic, } from "./intake-lib.mjs"; const intakeHome = resolve( process.env.EASYAI_INTAKE_HOME ?? homedir(), ".easyai-intake", ); try { const value = normalize(await readStdin()); const auth = lark(["auth", "status", "--json", "--verify"]); const user = auth.identities?.user; if (!user?.verified || !user.openId) throw new Error("当前电脑未完成飞书用户授权"); const attachments = await attachmentManifest(value.attachments); const identity = createDraftIdentity(user.openId); const preparedAt = new Date().toISOString(); const draft = { schema_version: 2, status_code: "prepared", draft_id: identity.draft_id, submission_key: identity.submission_key, owner_open_id: user.openId, confirmation_token_hash: identity.confirmation_token_hash, content_digest: contentDigest(value, user.openId, attachments), value, attachments, prepared_at: preparedAt, }; await writeJsonAtomic( resolve(intakeHome, "drafts", `${identity.draft_id}.json`), draft, ); console.log( JSON.stringify( { ok: true, schema_version: 2, status_code: "prepared", draft_id: identity.draft_id, preview: preview(value, attachments), confirmation_token: identity.confirmation_token, submission_key: identity.submission_key, prepared_at: preparedAt, }, null, 2, ), ); } catch (error) { console.error( JSON.stringify({ ok: false, error: error instanceof Error ? error.message : "未知错误", }), ); process.exitCode = 1; } function lark(args) { try { const output = execFileSync(process.env.EASYAI_LARK_CLI ?? "lark-cli", args, { encoding: "utf8", env: { ...process.env, LARKSUITE_CLI_NO_UPDATE_NOTIFIER: "1", LARKSUITE_CLI_NO_SKILLS_NOTIFIER: "1", }, stdio: ["ignore", "pipe", "pipe"], }); return unwrapLark(output); } catch (error) { for (const output of [error?.stdout, error?.stderr]) { const message = larkErrorMessage(output); if (message) throw new Error(message); } throw error; } } function unwrapLark(output) { const envelope = JSON.parse(output); if (envelope.ok === false) throw new Error(larkErrorMessage(output) ?? "飞书 CLI 调用失败"); return envelope.data ?? envelope; } function larkErrorMessage(output) { if (typeof output !== "string" || !output.trim()) return undefined; try { const envelope = JSON.parse(output); if (envelope.ok !== false) return undefined; return ( [envelope.error?.message, envelope.error?.hint] .filter(Boolean) .join(": ") || undefined ); } catch { return undefined; } }