@earthchen/xianyu-sdk
v0.4.0
Published
TypeScript SDK for Xianyu (Goofish) APIs — HTTP, WebSocket messaging, and QR code login
Readme
@earthchen/xianyu-sdk
TypeScript SDK for Xianyu (Goofish/闲鱼) — wraps the platform's MTOP HTTP API, WebSocket real-time messaging, and QR-code login. Targets Node.js servers.
Features
- HTTP / MTOP — 26 typed methods covering auth, item publishing/lifecycle, orders, shipping, ratings, blacklist, account notifications, and user lookups.
- WebSocket real-time — typed dispatch (
onMessage/onChat/onCard/onCardUpdate/onSystemTip) withitemId, decodedcontentType('text' | 'image'), andimageUrlspopulated. - Card messages —
[卡片消息]marker auto-routes toonCardwithcardTitleextracted fromdxCard.item.main.exContent.title. - QR login —
qrcodeLogin()runs the full flow via HTTP only (no browser). - Cookie store — pluggable
CookieStoreinterface;MemoryCookieStoreandFileCookieStoreprovided. - Lifecycle hooks —
onClose/onErrorexposed; the SDK does not auto-reconnect (callers own backoff viacalculateRetryDelay). - Dual ESM + CJS build via
tsup.
Installation
pnpm add @earthchen/xianyu-sdkRequires Node.js >= 18.
Quick Start
import { XianyuClient, FileCookieStore, makeText } from '@earthchen/xianyu-sdk';
const store = new FileCookieStore('~/.xianyu/cookies.json');
const cookies = await store.load();
const client = new XianyuClient({ cookies });
client.onMessage(async (msg, ws) => {
console.log(`${msg.sendUserName}: ${msg.message}`);
await client.live.sendMessage(
msg.conversationId,
msg.sendUserId,
makeText('收到!'),
);
});
await client.connect();Programmatic Login
import { XianyuClient } from '@earthchen/xianyu-sdk';
const client = await XianyuClient.qrcodeLogin({
onQrUrl(url) {
// Render the QR in your UI
console.log('QR:', url);
},
onStatusChange(status, desc, remaining) {
console.log(`[${status}] ${desc}`);
},
});API Overview
XianyuClient
| Symbol | Description |
|---|---|
| new XianyuClient({ cookies, deviceId?, cookieStore?, logger? }) | Construct from cookies |
| XianyuClient.qrcodeLogin(options?) | Static — QR login returns instance |
| XianyuClient.buildInitialCookies() | Static — bootstrap pre-login cookies |
| client.api | XianyuApi instance (26 MTOP methods) |
| client.live | XianyuLive instance |
| client.onMessage(handler) | Unified message callback |
| client.onChat / onCard / onCardUpdate / onSystemTip | Typed message callbacks |
| client.onClose(cb) / client.onError(cb) | WS lifecycle hooks |
| client.connect() / client.disconnect() | WS connection |
| client.saveCookies() | Persist cookies via CookieStore |
XianyuApi — selected methods
| Method | MTOP endpoint |
|---|---|
| getToken() / refreshToken() | Auth |
| getItemInfo(itemId) | mtop.taobao.idle.pc.detail |
| publish(imagesPaths, desc, price, delivery) | mtop.idle.pc.idleitem.publish |
| deleteItem(itemId) / batchOfflineItems(ids) / polishItem(itemId) | Item lifecycle |
| confirmShipping({ orderId, ... }) / freeshipping({...}) | Shipping |
| getOrderDetail(orderId) / closeOrderBySeller(orderId) | Orders |
| listSoldOrders({...}) / listRefunds({...}) / listPendingRates({...}) | Reporting |
| addToBlacklist(cid) / queryBlacklist(cid) / removeFromBlacklist(cid) | Blacklist |
| getUserByCid(cid, { isOwner? }) | User lookup |
| closeAccountNotice() | Notifications |
All MTOP methods route through the internal mtopPost() helper. A typed variant mtopPostTyped<T>() returns MtopResponse<T> for callers that want a typed data shape.
XianyuLive — message types
Inbound messages carry a messageType discriminator: 'chat' | 'card' | 'cardUpdate' | 'systemTip'. Chat messages expose itemId, contentType ('text' | 'image'), and imageUrls. Card messages carry cardTitle. System tips are filtered out of the chat flow but still fire onSystemTip.
Helpers
| Export | Purpose |
|---|---|
| parseRecord(record) | Parse a decrypted sync record into a ReceivedMessage |
| parseCardMessage(record) / parseCardUpdateMessage(record) | Same for card shapes |
| isChatMessage / isCardMessage / isCardUpdateMessage / isSystemTipMessage | Classifiers |
| extractMessageId(record) | Dedup key |
| extractCardTitle(record) | Card title extraction |
| decodeSyncData(raw) | Decode sync data string (base64+JSON or decrypt+JSON) |
| extractAccountUserIdFromCookie(cookies) | Pull unb from cookies |
| validateCookies(cookies) | Pre-flight cookie check |
| parseCookieString / formatCookieString | Cookie codec |
| canonicalGoofishItemUrl(itemId) | Build item URL |
| calculateRetryDelay(attempt, kind?) | Backoff for reconnection |
CLI
npx xianyu-login
npx xianyu-login --output ./cookies.jsonThe QR-login CLI writes cookies to ~/.xianyu/cookies.json by default.
文档
| 文档 | 内容 |
|---|---|
| docs/API.md | 全部 26 个 MTOP HTTP 方法的签名、endpoint、payload 备注 |
| docs/MESSAGING.md | WebSocket 消息类型联合、分类器、解析器、[卡片消息] 重定向 |
| docs/LIFECYCLE.md | 连接生命周期、onClose / onError、重连退避、Cookie 持久化 |
| AGENTS.md | 给 AI agent 看的项目约定、架构、文件变更指引(中文) |
License
MIT
