/**
*
* mwn: a MediaWiki bot framework for Node.js
*
* Copyright (C) 2020 Siddharth VP
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see .
*
*/
import { AxiosResponse, AxiosInstance } from 'axios';
import * as tough from 'tough-cookie';
import * as OAuth from 'oauth-1.0a';
import { MwnDateStatic } from './date';
import { MwnTitle, MwnTitleStatic } from './title';
import { MwnPageStatic } from './page';
import { MwnWikitextStatic } from './wikitext';
import { MwnUserStatic } from './user';
import { MwnCategoryStatic } from './category';
import { MwnFileStatic } from './file';
import { RawRequestParams } from './core';
import { log, updateLoggingConfig } from './log';
import { MwnError, MwnMissingPageError } from './error';
import { link, Table, template } from './static_utils';
import { sleep } from './utils';
import type { ApiDeleteParams, ApiEditPageParams, ApiMoveParams, ApiParseParams, ApiPurgeParams, ApiQueryAllMessagesParams, ApiQueryAllPagesParams, ApiQueryCategoryMembersParams, ApiQuerySearchParams, ApiQueryUserInfoParams, ApiRollbackParams, ApiUndeleteParams, ApiUploadParams } from 'types-mediawiki-api';
import type { ApiDeleteResponse, ApiEditResponse, ApiMoveResponse, ApiPage, ApiQueryResponse, ApiResponse, ApiRollbackResponse, ApiSearchResult, ApiUndeleteResponse, ApiUploadResponse } from './api_response_types';
export interface MwnOptions {
/** Suppress messages, except for error messages and warnings */
silent?: boolean;
/** Site API url, example https://en.wikipedia.org/w/api.php */
apiUrl?: string;
/** User agent string. Required for WMF wikis, see https://foundation.wikimedia.org/wiki/Policy:User-Agent_policy */
userAgent?: string;
/** Bot login username and password, setup using Special:BotPasswords */
username?: string;
password?: string;
/** OAuth 1.0a credentials */
OAuthCredentials?: {
consumerToken: string;
consumerSecret: string;
accessToken: string;
accessSecret: string;
};
/** OAuth 2 access token */
OAuth2AccessToken?: string;
/**
* Max number of times to retry the same request on errors due to
* maxlag, wiki being in readonly mode, and other transient errors
*/
maxRetries?: number;
/** Milliseconds to pause before retrying after a transient error */
retryPause?: number;
/** Bot emergency shutoff options */
shutoff?: {
/** Interval every which to check for shutoff, in milliseconds */
intervalDuration?: number;
/** Page to which to check for shutoff */
page?: string;
/** Condition satisfied by the page text for the bot to shut off */
condition?: RegExp | ((text: string) => boolean);
/** Function to run for the bot to shut off, eg. you can call process.exit(1) here, or shut down more gracefully */
onShutoff?: (text: string) => void;
};
/** Default parameters included in every API request */
defaultParams?: ApiParams;
/** Suppress logging of warnings received from the API */
suppressAPIWarnings?: boolean;
/** Options for the edit() function */
editConfig?: EditConfig;
/** Suppress warning about construction of invalid bot.Date objects */
suppressInvalidDateWarning?: boolean;
}
export type EditTransform = (rev: {
content: string;
timestamp: string;
}) => string | ApiEditPageParams | Promise;
export type EditConfig = {
/** Max number of retries on edit conflicts, default: 2 */
conflictRetries?: number;
/** Suppress warning on an edit resulting in no change to the page, default: false */
suppressNochangeWarning?: boolean;
/** Abort edit if exclusionRegex matches on the page content */
exclusionRegex?: RegExp;
};
export type ApiParams = {
[param: string]: string | string[] | boolean | number | number[] | Date | File | {
stream: NodeJS.ReadableStream;
name: string;
};
};
export declare class Mwn {
/**
* Bot instance Login State
* Is received from the MW Login API and contains token, userid, etc.
*/
state: any;
/**
* Bot instance is logged in or not
*/
loggedIn: boolean;
/**
* Bot instance's edit token. Initially set as an invalid token string
* so that the badtoken handling logic is invoked if the token is
* not set before a query is sent.
* @type {string}
*/
csrfToken: string;
/**
* Default options.
* Should be immutable
*/
readonly defaultOptions: MwnOptions;
/**
* Actual, current options of the bot instance
* Mix of the default options, the custom options and later changes
* @type {Object}
*/
options: MwnOptions;
/**
* Cookie jar for the bot instance - holds session and login cookies
* @type {tough.CookieJar}
*/
cookieJar: tough.CookieJar;
/** Axios instance for the bot instance. */
axiosInstance: AxiosInstance;
static requestDefaults: RawRequestParams;
/**
* Request options for the axios library.
* Change the defaults using setRequestOptions()
* @type {Object}
*/
requestOptions: RawRequestParams;
/**
* Emergency shutoff config
* @type {{hook: NodeJS.Timeout, state: boolean}}
*/
shutoff: {
state: boolean;
hook: NodeJS.Timeout;
};
hasApiHighLimit: boolean;
oauth: OAuth;
usingOAuth: boolean;
usingOAuth2: boolean;
static Error: typeof MwnError;
static MissingPageError: typeof MwnMissingPageError;
static log: typeof log;
static setLoggingConfig: typeof updateLoggingConfig;
static link: typeof link;
static template: typeof template;
static Table: typeof Table;
static util: {
escapeRegExp: (str: string) => string;
escapeHtml: (s: string) => string;
rawurlencode: (str: string) => string;
wikiUrlencode: (str: string) => string;
isIPv4Address: (address: string, allowBlock?: boolean) => boolean;
isIPv6Address: (address: string, allowBlock?: boolean) => boolean;
isIPAddress: (address: string, allowBlock?: boolean) => boolean;
};
/**
* Title class associated with the bot instance.
* See {@link MwnTitle} interface for methods on title objects.
*/
Title: MwnTitleStatic;
/**
* Page class associated with the bot instance.
* See {@link MwnPage} interface for methods on page objects.
*/
Page: MwnPageStatic;
/**
* Category class associated with the bot instance.
* See {@link MwnCategory} interface for methods on category objects.
*/
Category: MwnCategoryStatic;
/**
* File class associated with the bot instance.
* See {@link MwnFile} interface for methods on file objects.
*/
File: MwnFileStatic;
/**
* User class associated with the bot instance.
* See {@link MwnUser} interface for methods on user objects.
*/
User: MwnUserStatic;
/**
* Wikitext class associated with the bot instance.
* See {@link MwnWikitext} interface for methods on wikitext objects.
*/
Wikitext: MwnWikitextStatic;
/**
* Date class associated with the bot instance.
* See {@link MwnDate} interface for methods on date objects.
*/
Date: MwnDateStatic;
/**
* Constructs a new bot instance. Recommended usage is one bot instance for every wiki and user.
* A bot instance has its own state (e.g. tokens) that is necessary for some operations.
*
* @param [customOptions] - Custom options
*/
constructor(customOptions?: MwnOptions | string);
/**
* Initialize a bot object. Login to the wiki and fetch editing tokens. If OAuth
* credentials are provided, they will be used over BotPassword credentials.
* Also fetches the site data needed for parsing and constructing title objects.
* @param {Object} config - Bot configurations, including apiUrl, and either the
* username and password or the OAuth credentials
* @returns {Promise} bot object
*/
static init(config: MwnOptions): Promise;
/**
* Set and overwrite mwn options
* @param {Object} customOptions
*/
setOptions(customOptions: MwnOptions): void;
/**
* Sets the API URL for MediaWiki requests
* This can be uses instead of a login, if no actions are used that require login.
* @param {string} apiUrl - API url to MediaWiki, e.g. https://en.wikipedia.org/w/api.php
*/
setApiUrl(apiUrl: string): void;
/**
* Sets and overwrites the raw request options, used by the axios library
* See https://www.npmjs.com/package/axios
*/
setRequestOptions(customRequestOptions: RawRequestParams): void;
/**
* Set the default parameters to be sent in API calls.
* @param {Object} params - default parameters
*/
setDefaultParams(params: ApiParams): void;
/**
* Set your API user agent. See https://meta.wikimedia.org/wiki/User-Agent_policy
* Required for WMF wikis.
* @param {string} userAgent
*/
setUserAgent(userAgent: string): void;
/**
* @private
* Determine if we're going to use OAuth for authentication
*/
private _usingOAuth;
/**
* Initialize OAuth instance
*/
initOAuth(): void;
/************ CORE REQUESTS ***************/
/**
* Executes a raw request
* Uses the axios library
* @param {Object} requestOptions
* @returns {Promise}
*/
rawRequest(requestOptions: RawRequestParams): Promise;
/**
* Executes a request with the ability to use custom parameters and custom
* request options
* @param {Object} params
* @param {Object} [customRequestOptions={}]
* @returns {Promise}
*/
request(params: ApiParams, customRequestOptions?: RawRequestParams): Promise;
query(params: ApiParams, customRequestOptions?: RawRequestParams): Promise;
/************** CORE FUNCTIONS *******************/
private loginInProgress;
/**
* Executes a Login
* @see https://www.mediawiki.org/wiki/API:Login
* @returns {Promise}
*/
login(loginOptions?: {
username?: string;
password?: string;
apiUrl?: string;
}): Promise;
private loginInternal;
/**
* Log out of the account. Flushes the cookie jar and clears the saved tokens.
* Should not be used if authenticating via OAuth.
* @returns {Promise}
*/
logout(): Promise;
/**
* Create an account. Only works on wikis without extensions like
* ConfirmEdit enabled (hence doesn't work on WMF wikis).
* @param username
* @param password
*/
createAccount(username: string, password: string): Promise;
/**
* Get basic info about the logged-in user
* @param [options]
* @returns {Promise}
*/
userinfo(options?: ApiQueryUserInfoParams): Promise;
/**
* Gets namespace-related information for use in title nested class.
* This need not be used if login() is being used. This is for cases
* where mwn needs to be used without logging in.
* @returns {Promise}
*/
getSiteInfo(): Promise;
/**
* Get tokens and saves them in this.state
* @returns {Promise}
*/
getTokens(): Promise;
/**
* Gets an edit token (also used for most other actions
* such as moving and deleting)
* This is only compatible with MW >= 1.24
* @returns {Promise}
*/
getCsrfToken(): Promise;
/**
* Get tokens and siteinfo (using a single API request) and save them in the bot state.
* @returns {Promise}
*/
getTokensAndSiteInfo(): Promise;
/**
* Get type of token to be used with an API action
* @param {string} action - API action parameter
* @returns {Promise}
*/
getTokenType(action: string): Promise;
/**
* Get the wiki's server time
* @returns {Promise}
*/
getServerTime(): Promise;
/**
* Fetch and parse a JSON wikipage
* @param {string} title - page title
* @returns {Promise