Wiki Saikou
SUPER COOL api package for MediaWiki
- 同时兼容浏览器&Node.js 环境 -
- Support both browser and Node.js environment -
本库提供了与原版 new mw.Api() 非常相似的 api 请求封装。让你在非 MediaWiki 环境中轻松实现各种 wiki 操作。使用 TypeScript 编写~
The library provides the out of box accessing to MediaWiki API in both browsers & Node.js, and the syntax is very similar to vanilla new mw.Api(). TypeScript definition included~
特色功能 Features
- Similar API to the vanilla
new mw.Api() - Parameter Schema automatic compliance:
{ "foo": ["bar", "baz"], watch: false }→{ "foo": "bar|baz" } - Token caching and retry mechanism
- TypeScript support
- With unit tests
- User authentication supports out of the box *(also applicable to Node.js!)
开箱即用 Out of box
通过 NPM 包安装 Installa via NPM
# Via pnpm:
pnpm add wiki-saikou
# Yarn? sure:
yarn add wiki-saikou
# Or just npm:
npm install wiki-saikou
Then, import it to your project:
import { MediaWikiApi } from 'wiki-saikou'
const api = new MediaWikiApi('https://zh.moegirl.org.cn/api.php')
// ...
在浏览器中直接使用 Use directly in the browser
<!-- Method 1: Using ES Module (recommended) -->
<script type="module">
import { MediaWikiApi } from 'https://esm.run/wiki-saikou'
const api = new MediaWikiApi('https://zh.moegirl.org.cn/api.php')
// ...
</script>
<!-- Method 2: Using UMD bundle -->
<script src="https://cdn.jsdelivr.net/npm/wiki-saikou/lib/index.umd.js"></script>
<script>
const { MediaWikiApi } = window.WikiSaikou
const api = new MediaWikiApi('https://zh.moegirl.org.cn/api.php')
// ...
</script>
<!-- Method 3: Using import maps (experimental) -->
<script type="importmap">
{
"imports": {
"wiki-saikou": "https://esm.run/wiki-saikou"
}
}
</script>
<script type="module">
import { MediaWikiApi } from 'wiki-saikou'
const api = new MediaWikiApi('https://zh.moegirl.org.cn/api.php')
// ...
</script>
Deno via CDN
import { MediaWikiApi } from 'https://esm.run/wiki-saikou/node'
const api = new MediaWikiApi('https://zh.moegirl.org.cn/api.php')
// ...
使用方法 Usage
You can find sample code snippets in unit test folder.
It's similar to the new mw.Api().
入口文件 Entry file
// automatically imports the correct entry file based on the environment
import { MediaWikiApi } from 'wiki-saikou'
// specify the entry file manually
import { MediaWikiApi } from 'wiki-saikou/node'
import { MediaWikiApi } from 'wiki-saikou/browser'
Constructor
new MediaWikiApi(config: WikiSaikouInitConfig)
interface WikiSaikouConfig {
/**
* @default undefined // required in Node.js environment
* @default `${wgServer}${wgScriptPath}/api.php` // in MW pages
* @description The MediaWiki API endpoint, e.g. "https://www.mediawiki.org/w/api.php"
* @optional In real MediaWiki browser pages, `baseURL` can be omitted and will be inferred automatically based on `window.mw`
*/
baseURL: string
/**
* Transport/runtime options passed to the underlying Fexios instance (headers, fetch, credentials, etc.).
* @default { responseType: 'json' }
*/
fexiosConfigs: Partial<FexiosConfigs>
/**
* Default query parameters merged into every request.
* @default { action: 'query' }
*/
defaultParams: MwApiParams
/**
* When true, responses whose JSON body contains `error`/`errors` will throw `MediaWikiApiError` even if HTTP status is 2xx.
* @default false
*/
throwOnApiError: boolean
}
Deprecated (for backward compatibility):
new MediaWikiApi(baseURL: string, options?: Partial<FexiosConfigs>, defaultParams?: MwApiParams)
Core requests
get<T = any>(query: MwApiParams, options?: WikiSaikouRequestOptions): Promise<FexiosFinalContext<MwApiResponse<T>>>- Performs a GET request.
querywill be merged withconfig.defaultParams. - Supports
retry(maximum total attempts including the initial request, defaultconfig.retry ?? 1),shouldRetry,retryDelay,onRetry, andsignal. Transport errors are not retried by default unlessshouldRetryis provided.
- Performs a GET request.
post<T = any>(body: MwApiParams | URLSearchParams | FormData, options?: WikiSaikouRequestOptions): Promise<FexiosFinalContext<MwApiResponse<T>>>- Performs a POST request. Body and query are normalized to API-friendly formats.
- Supports
retry(maximum total attempts including the initial request, defaultconfig.retry ?? 1),shouldRetry,retryDelay,onRetry, andsignal. Transport errors are not retried by default unlessshouldRetryis provided.
postWithToken<T = any>(tokenType: MwTokenName, body: MwApiParams | URLSearchParams | FormData, options?: { tokenName?: string; retry?: number; retryDelay?: RetryDelayOption; onRetry?: (error: Error, retryCount: number) => void; shouldRetry?: ShouldRetryOption; signal?: AbortSignal; noCache?: boolean; fexiosOptions?: Partial<FexiosRequestOptions> }): Promise<FexiosFinalContext<MwApiResponse<T>>>- Performs a POST request with a token.
tokenType: The type of token to use.body: The body of the request (MwApiParams,URLSearchParams, orFormData).options: The options for the request.tokenName: The name of the token to use.retry: Maximum total attempts including the initial request (defaultconfig.retry ?? 3, matchinguseRetry's existing behavior where3means 1 initial attempt + up to 2 retries). Automatically retriesbadtoken; transport or other errors are only retried whenshouldRetry(error, retryCount)returnstrue, and otherwise propagate untouched.retryDelay: Delay in milliseconds (or backoff callback, e.g.createRetryDelay(...)) between retry attempts. In browsers,Retry-Afteris readable on same-origin requests and on cross-origin MediaWiki responses (which sendAccess-Control-Expose-Headers: Retry-After); if a reverse proxy / WAF omitsAccess-Control-Expose-Headers: Retry-Afteron a CORS 429/503,createRetryDelayfalls back to exponential backoff automatically.onRetry: Callback invoked before each scheduled retry attempt.shouldRetry: Optional predicate(error, retryCount) => booleanto opt in to retrying transport/network or custom errors. Warning: passingisRetryableTransportErrorat client level or on write requests (post/postWithToken) will also retry non-idempotent writes on ambiguous transport failures, which may cause duplicate edits if the server already processed the request.signal:AbortSignalto cancel both in-flight requests and retry backoff sleeps.noCache: Whether to bypass the cached token.
- This method will manage the token cache and retry logic automatically.
Authentication
Node.js only:
login(lgname: string, lgpassword: string, params?: MwApiParams, postOptions?: MediaWikiLoginOptions): Promise<MediaWikiLoginResult>login(options: MediaWikiLoginInput): Promise<MediaWikiLoginResult>- Login with bot password, cached cookies, or both (cookie-first with automatic fallback to bot password). Throws
WikiSaikouError(LOGIN_FAILED)if login fails. cookies: Accepts aCookieJar, a serialized JSON string/array fromapi.cookieJar.toJSON(), or a raw HTTPCookieheader string (e.g."session=abc; user=123").assertuser: Optional expected MediaWiki account name (only valid withcookies; matches MediaWiki'sassertusersemantics, not theUser@Botlgname). Checked againstuserinfo.namewhenverify: true(and enforced on fallback/relogin), or attached directly asassertuserwhenverify: false.verify: Defaults totrue(only valid withcookies). Callsaction=query&meta=userinfoto confirm the session is still logged in. Set tofalseto skip verification (0 startup requests); subsequent requests will still attachassertuser(when specified) orassert=user.autoRelogin: Defaults totrueand attachesassertuser(orassert=user) to future requests. Whenlgnameandlgpasswordare provided and the session drops, the SDK auto re-logins and retries the request.autoReloginRetries: Defaults to3and controls how many re-login attempts are made perassertuserfailed/assertnameduserfailedincident.onCookiesChange?: (cookieJar: CookieJar) => void(onnew MediaWikiApi({ baseURL, onCookiesChange })orapi.onCookiesChange): Invoked whenever server responses sendSet-Cookieheaders orlogout()clears cookies, making it easy to persistJSON.stringify(cookieJar)to disk/cache.
- Login with bot password, cached cookies, or both (cookie-first with automatic fallback to bot password). Throws
import { readFileSync, writeFileSync } from 'node:fs'
import { MediaWikiApi } from 'wiki-saikou/node'
const api = new MediaWikiApi({
baseURL: 'https://zh.moegirl.org.cn/api.php',
onCookiesChange(jar) {
writeFileSync('cookies.json', JSON.stringify(jar))
},
})
// Reuse cached cookies; fall back to bot password automatically if expired
await api.login({
cookies: readFileSync('cookies.json', 'utf-8'),
lgname: 'Bot@name',
lgpassword: 'bot-password',
})
Browser only:
clientLogin(username: string, password: string, params?: ClientLoginOptions): Promise<{ status: "PASS"; username: string; }>;- Login with regular username & password. Throws
WikiSaikouError(LOGIN_FAILED)if status is notPASS.
- Login with regular username & password. Throws
实用工具 Useful helpers
FexiosSaikou
A pre-configured Fexios instance with MediaWiki-friendly defaults:
- MediaWiki-specific request/response params normalization
- built-in token management
- error handling
MwParamNormalizer
MwParamNormalizer is a utility class that helps normalize MediaWiki API parameters.
import { MwParamNormalizer } from 'wiki-saikou'
MwParamNormalizer.normalizeBody({
string: 'foo',
number: 123,
boolean: true,
falsy: false,
undefined: undefined,
null: null,
array: ['foo', 'bar'],
file: new Blob(['file contents'], { type: 'text/plain' }),
})
// Result:
/**
* FormData
* string=foo
* number=123
* boolean=1
* array=foo|bar
* file=[Blob]
*/
错误处理 Errors and types
WikiSaikou will NOT throw errors for these situations by default:
- non-2xx HTTP status codes
- MediaWiki API responses containing
errororerrorsfieldYou should handle these situations manually by checking the response context.
WikiSaikouError- SDK behavioral errors such as exhausted token retries (
TOKEN_RETRY_LIMIT_EXCEEDED), login failures (LOGIN_FAILED), or invalid REST configurations (INVALID_REST_PATH/INVALID_REST_ENDPOINT) - Note: Transport/network failures (e.g.
fetch failed, timeouts, non-2xx HTTP responses) propagate as the underlyingFexiosError/FexiosResponseError/TypeErrordirectly unless handled viashouldRetry
- SDK behavioral errors such as exhausted token retries (
WikiSaikouErrorCode- Enum of error codes used in
WikiSaikouError
- Enum of error codes used in
If you set
options.throwOnApiError = truewhen constructingMediaWikiApi, then WikiSaikou will handle MediaWiki API errors automatically by throwingMediaWikiApiErrorfor you.
MediaWikiApiError- fetch succeeded (or HTTP non-2xx with MediaWiki error JSON) and JSON includes
errororerrors.length > 0 - Special states (e.g., login NeedToken/WrongToken) are also considered API-side errors
- Note: transport/network failures belong to
FexiosError/FexiosResponseError, and SDK retry/login errors belong toWikiSaikouError
- fetch succeeded (or HTTP non-2xx with MediaWiki error JSON) and JSON includes
浏览器专属 Browser only
Besides MediaWikiApi, the browser bundle also provides MediaWikiForeignApi which presets CORS-friendly defaults for cross-origin API access.
new MediaWikiForeignApi(config: WikiSaikouInitConfig)- Defaults
credentials: 'include',mode: 'cors', and injectsoriginautomatically based onlocation.origin.
- Defaults
Example:
import { MediaWikiForeignApi } from 'wiki-saikou/browser'
const api = new MediaWikiForeignApi({
baseURL: 'https://commons.wikimedia.org/w/api.php',
})
MIT License
Copyright (c) 2022 萌娘百科 User:机智的小鱼君 (A.K.A. Dragon-Fish)