当前浏览的是 v7 预览版文档(v7 尚未正式发布,API 可能随版本调整)。本页是 v7 新增内容,去 v6 正式版文档首页
@ikenxuan/amagi
类型参考

函数

60 个符号,由 scripts/api-extractor.ts 从 packages/core/src/index.ts 抽取

本页 60 个符号由 packages/core/src/index.ts 的导出面在构建期生成, 签名、参数表与源码位置都取自 TypeScript 编译器对源码的解析。全部导出的索引见 类型索引,同一批能力的 SDK 与 HTTP 形态见 SDK 方法页 与 HTTP 端点参考。

assertValidBilibiliParams

验证哔哩哔哩参数,失败抛 ValidationError

assertValidBilibiliParams<T>(methodType: T, params: unknown): zod.infer<typeof BilibiliValidationSchemas[T]>

类型参数:T extends BilibiliMethodType

Prop

Type

返回值:校验通过后的参数

源码:src/validation/index.ts

assertValidDouyinParams

验证抖音参数,失败抛 ValidationError(不产出失败结果)

assertValidDouyinParams<T>(methodType: T, params: unknown): zod.infer<typeof DouyinValidationSchemas[T]>

类型参数:T extends DouyinMethodType

Prop

Type

返回值:校验通过后的参数

源码:src/validation/index.ts

assertValidKuaishouParams

验证快手参数,失败抛 ValidationError

assertValidKuaishouParams<T>(methodType: T, params: unknown): zod.infer<typeof KuaishouValidationSchemas[T]>

类型参数:T extends KuaishouMethodType

Prop

Type

返回值:校验通过后的参数

源码:src/validation/index.ts

assertValidXiaohongshuParams

验证小红书参数,失败抛 ValidationError

assertValidXiaohongshuParams<T>(methodType: T, params: unknown): zod.infer<typeof XiaohongshuValidationSchemas[T]>

类型参数:T extends XiaohongshuMethodType

Prop

Type

返回值:校验通过后的参数

源码:src/validation/index.ts

av2bv

av号转bv号

av2bv(aid: number): `BV1${string}`

Prop

Type

源码:src/platforms/bilibili/sign/bv2av.ts

bv2av

bv号转av号

bv2av(bvid: string): number

Prop

Type

源码:src/platforms/bilibili/sign/bv2av.ts

checkDouyinLoginState

unknown 表示探测失败,而非登录失效;因此刻意不缓存。

checkDouyinLoginState(cookie?: string | null, options: CheckDouyinLoginStateOptions): Promise<DouyinLoginCheck>

Prop

Type

源码:src/platforms/douyin/loginState.ts

checkPassportQrcode

查询抖音扫码登录二维码的状态

状态为 confirmed 时会自动跟随 SSO 跳转领取登录凭证,返回的 cookie 即完整登录态。

已废弃(@deprecated):请用 client.douyin.login.qrcode()(状态归一化为 LoginState.phase,轮询循环在引擎里)。
checkPassportQrcode(options: DouyinPassportQrcodeStatusOptions, cookie?: string, requestConfig?: RequestConfig): Promise<Result<DouyinReturnTypeMap["passportQrcodeStatus"]>>

Prop

Type

返回值:扫码状态与最新会话 cookie

示例

const status = await checkPassportQrcode({ token }, cookie)
// new 未扫码 / scanned 已扫待确认 / verify 需二次验证 / confirmed 登录成功 / expired 已过期
console.log(status.data.status)

源码:src/model/fetchers/douyin/auth.ts

clearDouyinLoginStateCache

清空时也会让进行中的探测失效,避免旧结果回填缓存。

clearDouyinLoginStateCache(): void

源码:src/platforms/douyin/loginState.ts

configureDouyinGuestCache

可选的磁盘缓存。每个网络身份使用一个私有文件;传 null 则 token 只保存在内存中。 自定义 transport 只使用各自作用域内的内存缓存,避免不同代理之间复用磁盘缓存。

configureDouyinGuestCache(filePath: string | null): void

Prop

Type

源码:src/platforms/douyin/guestCredential.ts

createBilibiliRoutes

创建B站路由

createBilibiliRoutes(cookie: string, requestConfig?: RequestConfig): Router

Prop

Type

返回值:Express路由器

源码:src/platforms/bilibili/routes.ts

createBoundBilibiliFetcher

createBoundBilibiliFetcher(cookie: string, requestConfig?: RequestConfig): BoundBilibiliFetcher

Prop

Type

源码:src/model/fetchers/bilibili/index.ts

createBoundDouyinFetcher

创建绑定了 Cookie 和请求配置的抖音 Fetcher

createBoundDouyinFetcher(cookie: string, requestConfig?: RequestConfig): BoundDouyinFetcher

Prop

Type

返回值:绑定了 Cookie 的 Fetcher 对象,调用时无需传递 cookie

示例

import {  } from '@ikenxuan/amagi'

const  = ('your_cookie')
const  = await .({ : '7123456789' })

源码:src/model/fetchers/douyin/index.ts

createBoundKuaishouFetcher

createBoundKuaishouFetcher(cookie: string, requestConfig?: RequestConfig): BoundKuaishouFetcher

Prop

Type

源码:src/model/fetchers/kuaishou/index.ts

createBoundXiaohongshuFetcher

createBoundXiaohongshuFetcher(cookie: string | XiaohongshuSessionInput, requestConfig?: RequestConfig): BoundXiaohongshuFetcher

Prop

Type

源码:src/model/fetchers/xiaohongshu/index.ts

createClient

创建 Amagi 客户端(门面)。

顶层 startServer / events / on / once + 四个平台模块 ({ ...utils, fetcher }):fetcher 方法集合由各平台的端点注册表派生, 统一返回 AmagiResult 信封。

startServer 挂的平台路由同样从 registry 派生(token / host 选项见 server/auth.ts)。第二参 { openapi } 不传时保持默认行为。

createClient(options: ClientOptions): { bilibili: { apiUrls: …; danmaku: …; fetcher: …; login: …; refreshCredential: …; request: …; …其余 1 个成员 }; douyin: { apiUrls: …; credentials: …; fetcher: …; login: …; passport: …; request: …; …其余 1 个成员 }; events: EventBus; kuaishou: { apiUrls: …; fetcher: …; login: …; request: …; sign: … }; on: __type<K>(event: …, listener: …): …; once: __type<K>(event: …, listener: …): …; …其余 2 个成员 }

Prop

Type

源码:src/client/createClient.ts

createDouyinRoutes

创建抖音路由

createDouyinRoutes(cookie: string, requestConfig?: RequestConfig): Router

Prop

Type

返回值:Express路由器

源码:src/platforms/douyin/routes.ts

createErrorResponse

创建失败信封

一般用不到 —— 主路径的失败信封由执行管线构造(错误归因、cause 保留 都在管线内)。需要手工组装 AmagiResult 时用它:createErrorResponse(error, meta)。

createErrorResponse(error: AmagiError, meta: AmagiMeta): AmagiFailure

Prop

Type

返回值:失败信封(message 等价于 error.message)

源码:src/validation/index.ts

createKuaishouRoutes

创建快手路由

createKuaishouRoutes(cookie: string, requestConfig?: RequestConfig): Router

Prop

Type

返回值:Express路由器

源码:src/platforms/kuaishou/routes.ts

createSuccessResponse

创建成功信封

一般用不到 —— 主路径的成功信封由执行管线构造。需要手工组装 AmagiResult 时用它:createSuccessResponse(data, meta)。

createSuccessResponse<T>(data: T, meta: AmagiMeta, message: string): AmagiSuccess<T>

类型参数:T

Prop

Type

返回值:成功信封

源码:src/validation/index.ts

createXiaohongshuRoutes

创建小红书路由

createXiaohongshuRoutes(cookie: string | XiaohongshuSessionInput, requestConfig?: RequestConfig): Router

Prop

Type

返回值:Express路由器

源码:src/platforms/xiaohongshu/routes.ts

emitApiError

发射 API 错误事件

emitApiError(data: Omit<ApiErrorEventData, "timestamp">): void

Prop

Type

源码:src/model/events.ts

emitApiSuccess

发射 API 成功事件

emitApiSuccess(data: Omit<ApiSuccessEventData, "timestamp">): void

Prop

Type

源码:src/model/events.ts

emitHttpRequest

发射 HTTP 请求事件

emitHttpRequest(data: Omit<HttpRequestEventData, "timestamp">): void

Prop

Type

源码:src/model/events.ts

emitHttpResponse

发射 HTTP 响应事件

emitHttpResponse(data: Omit<HttpResponseEventData, "timestamp">): void

Prop

Type

源码:src/model/events.ts

emitLog

发射日志事件

emitLog(level: LogEventData["level"], message: string, ...args: unknown[]): void

Prop

Type

源码:src/model/events.ts

emitLogDebug

发射 debug 级别日志

emitLogDebug(message: string, ...args: unknown[]): void

Prop

Type

源码:src/model/events.ts

emitLogError

发射 error 级别日志

emitLogError(message: string, ...args: unknown[]): void

Prop

Type

源码:src/model/events.ts

emitLogInfo

发射 info 级别日志

emitLogInfo(message: string, ...args: unknown[]): void

Prop

Type

源码:src/model/events.ts

emitLogMark

发射 mark 级别日志 (用于重要标记)

emitLogMark(message: string, ...args: unknown[]): void

Prop

Type

源码:src/model/events.ts

emitLogWarn

发射 warn 级别日志

emitLogWarn(message: string, ...args: unknown[]): void

Prop

Type

源码:src/model/events.ts

emitNetworkError

发射网络错误事件

emitNetworkError(data: Omit<NetworkErrorEventData, "timestamp">): void

Prop

Type

源码:src/model/events.ts

emitNetworkRetry

发射网络重试事件

emitNetworkRetry(data: Omit<NetworkRetryEventData, "timestamp">): void

Prop

Type

源码:src/model/events.ts

fetchData

执行网络请求并返回数据(带自动重试)

已废弃(@deprecated):用 client fetcher / HttpClient。返回的是 ErrorResult, 不是 AmagiResult 信封
fetchData<T>(config: AxiosRequestConfig<T>, maxRetries: number): Promise<T | ErrorResult>

类型参数:T

Prop

Type

返回值:响应数据或错误结果

源码:src/transport/legacy.ts

fetchResponse

执行网络请求并返回完整响应(带自动重试)

已废弃(@deprecated):用 client fetcher / HttpClient。返回的是 ErrorResult, 不是 AmagiResult 信封
fetchResponse<T>(config: AxiosRequestConfig, maxRetries: number): Promise<AxiosResponse<T> | ErrorResult>

类型参数:T

Prop

Type

返回值:完整响应或错误结果

源码:src/transport/legacy.ts

getBilibiliCorrespondPath

生成 correspondPath。

hex(RSA-OAEP-SHA256("refresh_" + ts))。注意 node 的 publicEncrypt 默认 OAEP 摘要是 sha1,这里必须显式 oaepHash: 'sha256',否则服务端解不出。OAEP 带随机 seed,所以 同一个 ts 每次输出都不同 —— 正常,服务端只校验能否解出 refresh_{ts} 且 ts 新鲜。

getBilibiliCorrespondPath(ts: number): string

Prop

Type

返回值:256 位小写 hex 字符串

源码:src/platforms/bilibili/cookieRefresh.ts

handleError

处理错误并返回统一格式

handleError(error: unknown, requestPath?: string): { code: number; data: null; errors: Array<{ field: string; message: string }>; message: string; platform: string; requestPath: string }

Prop

Type

返回值:统一的错误响应格式

源码:src/utils/errors.ts

isDouyinCookieUsable

isDouyinCookieUsable(cookie?: string | null, options: CheckDouyinLoginStateOptions): Promise<boolean>

Prop

Type

源码:src/platforms/douyin/loginState.ts

isFailure

失败信封的类型守卫。

与 isSuccess 对称,list.filter(isFailure) 之后 r.error 是 AmagiError(不带 | undefined),可以直接按 kind 分流。

isFailure<T>(result: AmagiResult<T>): result is AmagiFailure

类型参数:T

Prop

Type

返回值:是失败信封时为 true,并把类型收窄到 AmagiFailure

源码:src/contracts/result.ts

isNetworkErrorResult

判断结果是否为网络错误响应

isNetworkErrorResult(result: unknown): result is ErrorResult

Prop

Type

返回值:是否为网络错误

识别两种形状:success: false 且 error.amagiError 存在(本模块返回的 ErrorResult),或 error.kind === 'network'(v7 失败信封),两代结果都能判。

源码:src/transport/legacy.ts

isSuccess

成功信封的类型守卫。

?: undefined 让「不收窄直接读」不再报错,但收窄不到 T(还是 T | undefined)。数组回调里没有 if 可用,filter 又只认类型谓词 —— 这就是必须有守卫的场景:

import { , type  } from '@ikenxuan/amagi'

declare const : string[]
declare const : (: string) => <<Work>>
interface Work {
  : string
}

const : <Work>[] = await .(.())
const  = .().(() => .)   // Work[]
isSuccess<T>(result: AmagiResult<T>): result is AmagiSuccess<T>

类型参数:T

Prop

Type

返回值:是成功信封时为 true,并把类型收窄到 AmagiSuccess

源码:src/contracts/result.ts

mintDouyinGuestCookie

显式获取服务端签发的游客凭据,缓存未命中时请求抖音首页。

是 mintDouyinGuestHandshake 的串形态,公开出口(经 ./utils.ts 导出)。 返回类型没变(string | null),但返回 null 的判据变了:以前是「没拿到访客 id」, 现在是「这一发什么都没拿到」。服务端只发了 ttwid 而扣下 UIFID_TEMP 时,这里交出 ttwid=… —— 调用方要分「拿到游客凭据」与「只拿到设备标识」请用结构化那一支 (./credential.ts 就是那么做的)。

挑战页不解析、不执行。普通数据端点不会自动触发这条握手,必须由宿主主动调用。

mintDouyinGuestCookie(options: MintDouyinGuestCookieOptions): Promise<string | null>

Prop

Type

返回值:到手的凭据串;失败或一无所得时 null

源码:src/platforms/douyin/guestCredential.ts

normalizeDouyinCookie

修复粘贴进来的 cookie 文本,解析与序列化仍交给共享的 contract。

normalizeDouyinCookie(raw?: string | null): NormalizedDouyinCookie

Prop

Type

源码:src/platforms/douyin/cookie.ts

parseDmSegMobileReply

解析弹幕分段响应

parseDmSegMobileReply(data: ArrayBuffer | Uint8Array): BiliProtobufDanmaku["data"]["elems"][number]

Prop

Type

返回值:解析后的弹幕数据

源码:src/platforms/bilibili/decode/danmaku.ts

parseDouyinCaptcha

从抖音响应里识别验证码挑战并拼出验证页地址。

装在 client/runtime.ts 的 PLATFORM_RUNTIME.douyin.challenge 上, runtime/execute.ts 在 judge 判出 kind: 'risk' 时调用,结果进 error.challenge —— 不受 debug 开关影响。

两条通道,响应头优先(取舍见模块注释):

  1. 响应头:只认 2xx,与 SDK、与 judge 的响应头通道一致。
  2. 响应体:滑块中间页 HTML。不按 2xx 设闸 —— 这一支的挑战就是响应体本身, 不是 SDK 的指令,服务器拿什么状态码回这张页都算数。

头上拼不出地址时继续往下试响应体,而不是直接放弃:两条通道互补,有一条能给出 可打开的地址就不该空手而归。

滑块只中转不绕过:这里只把地址与票据交出去,不含任何识别或轨迹模拟代码; 它也永远不进自动重放(见 anticrawler/solver.ts)。

parseDouyinCaptcha(raw: unknown, http?: { headers: JudgeHeaders; status: number }): RiskChallenge | undefined

Prop

Type

返回值:风控挑战;两条通道都不认时 undefined

源码:src/platforms/douyin/captcha.ts

parseKuaishouCaptcha

从快手响应里识别风控并取出滑块地址。

PC 与 H5 两种格式都认,归一成同一个结果 —— 地址一律是人能直接打开的验证页, H5 那条会把配置接口地址拼进 VERIFY_PAGE_ENTRY。

装在 PLATFORM_RUNTIME.kuaishou.challenge 上由管线自动调用,所以正常路径下 调用方直接读失败信封的 error.challenge 就够,不必自己调这个函数。

parseKuaishouCaptcha(raw: unknown): KuaishouCaptchaChallenge | undefined

Prop

Type

返回值:风控挑战;没命中风控返回 undefined

源码:src/platforms/kuaishou/captcha.ts

parseXiaohongshuCaptcha

从小红书响应头里识别验证码挑战并拼出验证页地址。

装在 client/runtime.ts 的 PLATFORM_RUNTIME.xiaohongshu.challenge 上, runtime/execute.ts 在 judge 判出 kind: 'risk' 时调用,结果进 error.challenge —— 不受 debug 开关影响(若只从 error.raw 取,HTTP 路由那一面结构上拿不到, 理由见 contracts/error.ts 的 RiskChallenge)。所以正常路径下调用方直接读失败 信封的 error.challenge 就够,不必自己调这个函数。

没有 verifyuuid 就什么都不给:没票据的验证页打开只是一个空壳, 宁可不给,也不交出一个过不去的地址。

parseXiaohongshuCaptcha(_raw: unknown, http?: { headers: JudgeHeaders; status: number }): RiskChallenge | undefined

Prop

Type

返回值:风控挑战;响应头里没有验证票据时 undefined

源码:src/platforms/xiaohongshu/captcha.ts

qtparam

生成B站视频流请求参数

qtparam(BASEURL: string, cookie: string): Promise<{ isvip: undefined; QUERY: string; STATUS: string } | { isvip: true; QUERY: string; STATUS: string } | { isvip: false; QUERY: string; STATUS: string }>

Prop

Type

返回值:包含查询参数、登录状态和VIP状态的对象

源码:src/platforms/legacy/bilibili/qtparam.ts

refreshBilibiliCredential

B站 Web 端 Cookie 刷新(登录态续期,官方四步协议)。

只中转不绕过 —— 走的是平台正规续期通道,不涉及任何风控对抗。调用方拿到新的 { cookie, refreshToken } 后必须整组持久化替换旧值:下次刷新从新状态开始, 旧 token 已在第 4 步作废,再用旧 token 刷会 86095。

refreshBilibiliCredential(input: BilibiliRefreshInput, deps: BilibiliRefreshDeps, _options?: RequestConfig): Promise<{ credential: BilibiliRefreshOutput; ok: true } | { error: AmagiError; ok: false }>

Prop

Type

返回值:成功给新凭证;失败给 AmagiError

源码:src/platforms/bilibili/cookieRefresh.ts

renderVerifyPage

把风控 challenge 渲染成自包含的验证页 HTML,调用方自己起 HTTP 服务返回给真人即可。

抖音 challenge 带 jsSdkUrl + verifyData 时默认页内渲染官方滑块,可切到托管模式; 其余情况(快手、小红书、抖音只有 url)只有托管模式。非 http(s) 的地址一律丢弃。

renderVerifyPage(challenge: RiskChallenge, options: VerifyPageOptions): string

Prop

Type

返回值:完整 HTML 文本

源码:src/verify/index.ts

requestPassportQrcode

申请抖音扫码登录二维码

首次调用会自动完成环境指纹初始化(__ac_nonce + ttwid),无需额外准备。

已废弃(@deprecated):请用 client.douyin.login.qrcode()(会话抽象: 取码 / 轮询 / challenge 由引擎编排,expire_time 秒转 expiresAt 毫秒)。
requestPassportQrcode(options?: undefined, cookie?: string, requestConfig?: RequestConfig): Promise<Result<DouyinReturnTypeMap["passportQrcode"]>>

Prop

Type

返回值:二维码令牌、内容与会话 cookie

示例

const qrcode = await requestPassportQrcode()
console.log(qrcode.data.content) // 拿去生成二维码图片

源码:src/model/fetchers/douyin/auth.ts

resolveDouyinCredential

显式解析凭据。没有账号会话时,可通过游客握手补齐缺失的设备标识。

握手会向抖音首页发两次请求(签名纯算,不执行页面脚本)。只想在本地规范化请用 normalizeDouyinCookie,或传 noGuestFallback: true 关闭握手。 needLogin: true 会探测登录态,并始终保留账号凭据,不会用游客凭据替换。

resolveDouyinCredential(cookie?: string | null, options: ResolveOptions): Promise<ResolvedDouyinCredential>

Prop

Type

源码:src/platforms/douyin/credential.ts

sendPassportVerifyCode

向账号绑定手机发送二次验证短信验证码

用于轮询返回 status: 'verify'(即 error_code=2046 / account_flow=verify)的场景。

已废弃(@deprecated):请用 client.douyin.login.qrcode() 的 onChallenge 回调 (challenge.sendCode(),biz_trace_id / verify_way 由引擎维护)。
sendPassportVerifyCode(options: DouyinPassportSendCodeOptions, cookie?: string, requestConfig?: RequestConfig): Promise<Result<DouyinReturnTypeMap["passportSendCode"]>>

Prop

Type

返回值:脱敏手机号、重发等待秒数与追踪 ID

源码:src/model/fetchers/douyin/auth.ts

unwrap

取成功信封的 data,失败就抛。

返回类型是 T,不是 T | undefined —— 这是它与「不收窄直接读 r.data」的 全部区别:愿意让失败沿调用栈往上冒的人用它,不愿意的人继续写 if (r.success)。 管线本身永不 reject(硬约束),unwrap 是调用方显式把失败转成异常。

与 @ikenxuan/amagi/compat 不重叠:unwrap 是单点显式选择(想抛就抛, 一处一处地写);compat 是 v6 语义的整体回填(把整个 fetcher 的返回值换回 v6 信封,含顶层 code)。要 v6 行为用 compat,要 v7 信封加异常用 unwrap。

unwrap<T>(result: AmagiResult<T>): T

类型参数:T

Prop

Type

返回值:成功信封的 data

可能抛出:{AmagiThrownError} 失败信封时抛出:AmagiError 全字段平铺,cause 不丢

源码:src/contracts/result.ts

validateBilibiliParams

验证哔哩哔哩参数(不抛错)

validateBilibiliParams<T>(methodType: T, params: unknown): ValidateOutcome<zod.infer<typeof …[T]>>

类型参数:T extends BilibiliMethodType

Prop

Type

返回值:ValidateOutcome:成功带 value,失败带字段级 issues

源码:src/validation/index.ts

validateDouyinParams

验证抖音参数(不抛错)

validateDouyinParams<T>(methodType: T, params: unknown): ValidateOutcome<zod.infer<typeof …[T]>>

类型参数:T extends DouyinMethodType

Prop

Type

返回值:ValidateOutcome:成功带 value,失败带字段级 issues

源码:src/validation/index.ts

validateKuaishouParams

验证快手参数(不抛错)

validateKuaishouParams<T>(methodType: T, params: unknown): ValidateOutcome<zod.infer<typeof …[T]>>

类型参数:T extends KuaishouMethodType

Prop

Type

返回值:ValidateOutcome:成功带 value,失败带字段级 issues

源码:src/validation/index.ts

validatePassportVerifyCode

提交二次验证的短信验证码

已废弃(@deprecated):请用 client.douyin.login.qrcode() 的 onChallenge 回调 (返回 { code } 即可,biz_trace_id / verify_way 由引擎维护)。
validatePassportVerifyCode(options: DouyinPassportValidateCodeOptions, cookie?: string, requestConfig?: RequestConfig): Promise<Result<DouyinReturnTypeMap["passportValidateCode"]>>

Prop

Type

返回值:验证结果;wrongCode 为 true 表示验证码填错,可以让用户重试

源码:src/model/fetchers/douyin/auth.ts

validateXiaohongshuParams

验证小红书参数(不抛错)

validateXiaohongshuParams<T>(methodType: T, params: unknown): ValidateOutcome<zod.infer<typeof …[T]>>

类型参数:T extends XiaohongshuMethodType

Prop

Type

返回值:ValidateOutcome:成功带 value,失败带字段级 issues

源码:src/validation/index.ts

wbi_sign

对请求链接进行 WBI 签名

wbi_sign(BASEURL: string | URL, cookie: string): Promise<string>

Prop

Type

返回值:返回包含 WBI 签名的查询字符串

可能抛出:当获取 WBI 密钥失败或 URL 解析失败时抛出错误

源码:src/platforms/legacy/bilibili/sign/wbi.ts

On this page