拿掉 build files

This commit is contained in:
2022-07-18 16:33:23 +08:00
parent 41e2287bcb
commit 3707f158a3
31953 changed files with 0 additions and 4411796 deletions
-166
View File
@@ -1,166 +0,0 @@
/// <reference types="node" />
import { Readable } from "stream";
import * as Types from "./types";
import { AxiosRequestConfig } from "axios";
declare type RequestOption = {
retryKey: string;
};
export default class Client {
config: Types.ClientConfig;
private http;
private requestOption;
constructor(config: Types.ClientConfig);
setRequestOptionOnce(option: Partial<RequestOption>): void;
private generateRequestConfig;
private parseHTTPResponse;
pushMessage(to: string, messages: Types.Message | Types.Message[], notificationDisabled?: boolean): Promise<Types.MessageAPIResponseBase>;
replyMessage(replyToken: string, messages: Types.Message | Types.Message[], notificationDisabled?: boolean): Promise<Types.MessageAPIResponseBase>;
multicast(to: string[], messages: Types.Message | Types.Message[], notificationDisabled?: boolean): Promise<Types.MessageAPIResponseBase>;
narrowcast(messages: Types.Message | Types.Message[], recipient?: Types.ReceieptObject, filter?: {
demographic: Types.DemographicFilterObject;
}, limit?: {
max?: number;
upToRemainingQuota?: boolean;
}, notificationDisabled?: boolean): Promise<Types.MessageAPIResponseBase>;
broadcast(messages: Types.Message | Types.Message[], notificationDisabled?: boolean): Promise<Types.MessageAPIResponseBase>;
getProfile(userId: string): Promise<Types.Profile>;
private getChatMemberProfile;
getGroupMemberProfile(groupId: string, userId: string): Promise<Types.Profile>;
getRoomMemberProfile(roomId: string, userId: string): Promise<Types.Profile>;
private getChatMemberIds;
getGroupMemberIds(groupId: string): Promise<string[]>;
getRoomMemberIds(roomId: string): Promise<string[]>;
getBotFollowersIds(): Promise<string[]>;
getGroupMembersCount(groupId: string): Promise<Types.MembersCountResponse>;
getRoomMembersCount(roomId: string): Promise<Types.MembersCountResponse>;
getGroupSummary(groupId: string): Promise<Types.GroupSummaryResponse>;
getMessageContent(messageId: string): Promise<Readable>;
private leaveChat;
leaveGroup(groupId: string): Promise<any>;
leaveRoom(roomId: string): Promise<any>;
getRichMenu(richMenuId: string): Promise<Types.RichMenuResponse>;
createRichMenu(richMenu: Types.RichMenu): Promise<string>;
deleteRichMenu(richMenuId: string): Promise<any>;
getRichMenuAliasList(): Promise<Types.GetRichMenuAliasListResponse>;
getRichMenuAlias(richMenuAliasId: string): Promise<Types.GetRichMenuAliasResponse>;
createRichMenuAlias(richMenuId: string, richMenuAliasId: string): Promise<{}>;
deleteRichMenuAlias(richMenuAliasId: string): Promise<{}>;
updateRichMenuAlias(richMenuAliasId: string, richMenuId: string): Promise<{}>;
getRichMenuIdOfUser(userId: string): Promise<string>;
linkRichMenuToUser(userId: string, richMenuId: string): Promise<any>;
unlinkRichMenuFromUser(userId: string): Promise<any>;
linkRichMenuToMultipleUsers(richMenuId: string, userIds: string[]): Promise<any>;
unlinkRichMenusFromMultipleUsers(userIds: string[]): Promise<any>;
getRichMenuImage(richMenuId: string): Promise<Readable>;
setRichMenuImage(richMenuId: string, data: Buffer | Readable, contentType?: string): Promise<any>;
getRichMenuList(): Promise<Array<Types.RichMenuResponse>>;
setDefaultRichMenu(richMenuId: string): Promise<{}>;
getDefaultRichMenuId(): Promise<string>;
deleteDefaultRichMenu(): Promise<{}>;
getLinkToken(userId: string): Promise<string>;
getNumberOfSentReplyMessages(date: string): Promise<Types.NumberOfMessagesSentResponse>;
getNumberOfSentPushMessages(date: string): Promise<Types.NumberOfMessagesSentResponse>;
getNumberOfSentMulticastMessages(date: string): Promise<Types.NumberOfMessagesSentResponse>;
getNarrowcastProgress(requestId: string): Promise<Types.NarrowcastProgressResponse>;
getTargetLimitForAdditionalMessages(): Promise<Types.TargetLimitForAdditionalMessages>;
getNumberOfMessagesSentThisMonth(): Promise<Types.NumberOfMessagesSentThisMonth>;
getNumberOfSentBroadcastMessages(date: string): Promise<Types.NumberOfMessagesSentResponse>;
getNumberOfMessageDeliveries(date: string): Promise<Types.NumberOfMessageDeliveriesResponse>;
getNumberOfFollowers(date: string): Promise<Types.NumberOfFollowersResponse>;
getFriendDemographics(): Promise<Types.FriendDemographics>;
getUserInteractionStatistics(requestId: string): Promise<Types.UserInteractionStatistics>;
createUploadAudienceGroup(uploadAudienceGroup: {
description: string;
isIfaAudience?: boolean;
audiences?: {
id: string;
}[];
uploadDescription?: string;
}): Promise<{
audienceGroupId: number;
type: string;
description: string;
created: number;
}>;
createUploadAudienceGroupByFile(uploadAudienceGroup: {
description: string;
isIfaAudience?: boolean;
uploadDescription?: string;
file: Buffer | Readable;
}): Promise<{
audienceGroupId: number;
type: "UPLOAD";
description: string;
created: number;
}>;
updateUploadAudienceGroup(uploadAudienceGroup: {
audienceGroupId: number;
description?: string;
uploadDescription?: string;
audiences: {
id: string;
}[];
}, httpConfig?: Partial<AxiosRequestConfig>): Promise<{}>;
updateUploadAudienceGroupByFile(uploadAudienceGroup: {
audienceGroupId: number;
uploadDescription?: string;
file: Buffer | Readable;
}, httpConfig?: Partial<AxiosRequestConfig>): Promise<{}>;
createClickAudienceGroup(clickAudienceGroup: {
description: string;
requestId: string;
clickUrl?: string;
}): Promise<{
audienceGroupId: number;
type: string;
created: number;
} & {
description: string;
requestId: string;
clickUrl?: string;
}>;
createImpAudienceGroup(impAudienceGroup: {
requestId: string;
description: string;
}): Promise<{
audienceGroupId: number;
type: string;
created: number;
} & {
requestId: string;
description: string;
}>;
setDescriptionAudienceGroup(description: string, audienceGroupId: string): Promise<{}>;
deleteAudienceGroup(audienceGroupId: string): Promise<{}>;
getAudienceGroup(audienceGroupId: string): Promise<Types.AudienceGroup>;
getAudienceGroups(page: number, description?: string, status?: Types.AudienceGroupStatus, size?: number, createRoute?: Types.AudienceGroupCreateRoute, includesExternalPublicGroups?: boolean): Promise<{
audienceGroups: Types.AudienceGroups;
hasNextPage: boolean;
totalCount: number;
readWriteAudienceGroupTotalCount: number;
page: number;
size: number;
}>;
getAudienceGroupAuthorityLevel(): Promise<{
authorityLevel: Types.AudienceGroupAuthorityLevel;
}>;
changeAudienceGroupAuthorityLevel(authorityLevel: Types.AudienceGroupAuthorityLevel): Promise<{}>;
getBotInfo(): Promise<Types.BotInfoResponse>;
setWebhookEndpointUrl(endpoint: string): Promise<{}>;
getWebhookEndpointInfo(): Promise<Types.WebhookEndpointInfoResponse>;
testWebhookEndpoint(endpoint?: string): Promise<Types.TestWebhookEndpointResponse>;
}
export declare class OAuth {
private http;
constructor();
issueAccessToken(client_id: string, client_secret: string): Promise<Types.ChannelAccessToken>;
revokeAccessToken(access_token: string): Promise<{}>;
verifyAccessToken(access_token: string): Promise<Types.VerifyAccessToken>;
verifyIdToken(id_token: string, client_id: string, nonce?: string, user_id?: string): Promise<Types.VerifyIDToken>;
issueChannelAccessTokenV2_1(client_assertion: string): Promise<Types.ChannelAccessToken>;
getChannelAccessTokenKeyIdsV2_1(client_assertion: string): Promise<{
key_ids: string[];
}>;
revokeChannelAccessTokenV2_1(client_id: string, client_secret: string, access_token: string): Promise<{}>;
}
export {};
-397
View File
@@ -1,397 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OAuth = void 0;
const http_1 = require("./http");
const Types = require("./types");
const utils_1 = require("./utils");
const endpoints_1 = require("./endpoints");
class Client {
constructor(config) {
this.requestOption = {};
if (!config.channelAccessToken) {
throw new Error("no channel access token");
}
this.config = config;
this.http = new http_1.default(Object.assign({ defaultHeaders: {
Authorization: "Bearer " + this.config.channelAccessToken,
}, responseParser: this.parseHTTPResponse.bind(this) }, config.httpConfig));
}
setRequestOptionOnce(option) {
this.requestOption = option;
}
generateRequestConfig() {
const config = { headers: {} };
if (this.requestOption.retryKey) {
config.headers["X-Line-Retry-Key"] = this.requestOption.retryKey;
}
// clear requestOption
this.requestOption = {};
return config;
}
parseHTTPResponse(response) {
const { LINE_REQUEST_ID_HTTP_HEADER_NAME } = Types;
let resBody = Object.assign({}, response.data);
if (response.headers[LINE_REQUEST_ID_HTTP_HEADER_NAME]) {
resBody[LINE_REQUEST_ID_HTTP_HEADER_NAME] =
response.headers[LINE_REQUEST_ID_HTTP_HEADER_NAME];
}
return resBody;
}
pushMessage(to, messages, notificationDisabled = false) {
return this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/message/push`, {
messages: utils_1.toArray(messages),
to,
notificationDisabled,
}, this.generateRequestConfig());
}
replyMessage(replyToken, messages, notificationDisabled = false) {
return this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/message/reply`, {
messages: utils_1.toArray(messages),
replyToken,
notificationDisabled,
});
}
async multicast(to, messages, notificationDisabled = false) {
return this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/message/multicast`, {
messages: utils_1.toArray(messages),
to,
notificationDisabled,
}, this.generateRequestConfig());
}
async narrowcast(messages, recipient, filter, limit, notificationDisabled) {
return this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/message/narrowcast`, {
messages: utils_1.toArray(messages),
recipient,
filter,
limit,
notificationDisabled,
}, this.generateRequestConfig());
}
async broadcast(messages, notificationDisabled = false) {
return this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/message/broadcast`, {
messages: utils_1.toArray(messages),
notificationDisabled,
}, this.generateRequestConfig());
}
async getProfile(userId) {
const profile = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/profile/${userId}`);
return utils_1.ensureJSON(profile);
}
async getChatMemberProfile(chatType, chatId, userId) {
const profile = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/${chatType}/${chatId}/member/${userId}`);
return utils_1.ensureJSON(profile);
}
async getGroupMemberProfile(groupId, userId) {
return this.getChatMemberProfile("group", groupId, userId);
}
async getRoomMemberProfile(roomId, userId) {
return this.getChatMemberProfile("room", roomId, userId);
}
async getChatMemberIds(chatType, chatId) {
let memberIds = [];
let start;
do {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/${chatType}/${chatId}/members/ids`, start ? { start } : null);
utils_1.ensureJSON(res);
memberIds = memberIds.concat(res.memberIds);
start = res.next;
} while (start);
return memberIds;
}
async getGroupMemberIds(groupId) {
return this.getChatMemberIds("group", groupId);
}
async getRoomMemberIds(roomId) {
return this.getChatMemberIds("room", roomId);
}
async getBotFollowersIds() {
let userIds = [];
let start;
do {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/followers/ids`, start ? { start, limit: 1000 } : { limit: 1000 });
utils_1.ensureJSON(res);
userIds = userIds.concat(res.userIds);
start = res.next;
} while (start);
return userIds;
}
async getGroupMembersCount(groupId) {
const groupMemberCount = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/group/${groupId}/members/count`);
return utils_1.ensureJSON(groupMemberCount);
}
async getRoomMembersCount(roomId) {
const roomMemberCount = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/room/${roomId}/members/count`);
return utils_1.ensureJSON(roomMemberCount);
}
async getGroupSummary(groupId) {
const groupSummary = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/group/${groupId}/summary`);
return utils_1.ensureJSON(groupSummary);
}
async getMessageContent(messageId) {
return this.http.getStream(`${endpoints_1.DATA_API_PREFIX}/message/${messageId}/content`);
}
leaveChat(chatType, chatId) {
return this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/${chatType}/${chatId}/leave`);
}
async leaveGroup(groupId) {
return this.leaveChat("group", groupId);
}
async leaveRoom(roomId) {
return this.leaveChat("room", roomId);
}
async getRichMenu(richMenuId) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu/${richMenuId}`);
return utils_1.ensureJSON(res);
}
async createRichMenu(richMenu) {
const res = await this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu`, richMenu);
return utils_1.ensureJSON(res).richMenuId;
}
async deleteRichMenu(richMenuId) {
return this.http.delete(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu/${richMenuId}`);
}
async getRichMenuAliasList() {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu/alias/list`);
return utils_1.ensureJSON(res);
}
async getRichMenuAlias(richMenuAliasId) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu/alias/${richMenuAliasId}`);
return utils_1.ensureJSON(res);
}
async createRichMenuAlias(richMenuId, richMenuAliasId) {
const res = await this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu/alias`, {
richMenuId,
richMenuAliasId,
});
return utils_1.ensureJSON(res);
}
async deleteRichMenuAlias(richMenuAliasId) {
const res = this.http.delete(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu/alias/${richMenuAliasId}`);
return utils_1.ensureJSON(res);
}
async updateRichMenuAlias(richMenuAliasId, richMenuId) {
const res = await this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu/alias/${richMenuAliasId}`, {
richMenuId,
});
return utils_1.ensureJSON(res);
}
async getRichMenuIdOfUser(userId) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/user/${userId}/richmenu`);
return utils_1.ensureJSON(res).richMenuId;
}
async linkRichMenuToUser(userId, richMenuId) {
return this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/user/${userId}/richmenu/${richMenuId}`);
}
async unlinkRichMenuFromUser(userId) {
return this.http.delete(`${endpoints_1.MESSAGING_API_PREFIX}/user/${userId}/richmenu`);
}
async linkRichMenuToMultipleUsers(richMenuId, userIds) {
return this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu/bulk/link`, {
richMenuId,
userIds,
});
}
async unlinkRichMenusFromMultipleUsers(userIds) {
return this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu/bulk/unlink`, {
userIds,
});
}
async getRichMenuImage(richMenuId) {
return this.http.getStream(`${endpoints_1.DATA_API_PREFIX}/richmenu/${richMenuId}/content`);
}
async setRichMenuImage(richMenuId, data, contentType) {
return this.http.postBinary(`${endpoints_1.DATA_API_PREFIX}/richmenu/${richMenuId}/content`, data, contentType);
}
async getRichMenuList() {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/richmenu/list`);
return utils_1.ensureJSON(res).richmenus;
}
async setDefaultRichMenu(richMenuId) {
return this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/user/all/richmenu/${richMenuId}`);
}
async getDefaultRichMenuId() {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/user/all/richmenu`);
return utils_1.ensureJSON(res).richMenuId;
}
async deleteDefaultRichMenu() {
return this.http.delete(`${endpoints_1.MESSAGING_API_PREFIX}/user/all/richmenu`);
}
async getLinkToken(userId) {
const res = await this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/user/${userId}/linkToken`);
return utils_1.ensureJSON(res).linkToken;
}
async getNumberOfSentReplyMessages(date) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/message/delivery/reply?date=${date}`);
return utils_1.ensureJSON(res);
}
async getNumberOfSentPushMessages(date) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/message/delivery/push?date=${date}`);
return utils_1.ensureJSON(res);
}
async getNumberOfSentMulticastMessages(date) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/message/delivery/multicast?date=${date}`);
return utils_1.ensureJSON(res);
}
async getNarrowcastProgress(requestId) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/message/progress/narrowcast?requestId=${requestId}`);
return utils_1.ensureJSON(res);
}
async getTargetLimitForAdditionalMessages() {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/message/quota`);
return utils_1.ensureJSON(res);
}
async getNumberOfMessagesSentThisMonth() {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/message/quota/consumption`);
return utils_1.ensureJSON(res);
}
async getNumberOfSentBroadcastMessages(date) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/message/delivery/broadcast?date=${date}`);
return utils_1.ensureJSON(res);
}
async getNumberOfMessageDeliveries(date) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/insight/message/delivery?date=${date}`);
return utils_1.ensureJSON(res);
}
async getNumberOfFollowers(date) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/insight/followers?date=${date}`);
return utils_1.ensureJSON(res);
}
async getFriendDemographics() {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/insight/demographic`);
return utils_1.ensureJSON(res);
}
async getUserInteractionStatistics(requestId) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/insight/message/event?requestId=${requestId}`);
return utils_1.ensureJSON(res);
}
async createUploadAudienceGroup(uploadAudienceGroup) {
const res = await this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/audienceGroup/upload`, Object.assign({}, uploadAudienceGroup));
return utils_1.ensureJSON(res);
}
async createUploadAudienceGroupByFile(uploadAudienceGroup) {
const file = await this.http.toBuffer(uploadAudienceGroup.file);
const body = utils_1.createMultipartFormData(Object.assign(Object.assign({}, uploadAudienceGroup), { file }));
const res = await this.http.post(`${endpoints_1.DATA_API_PREFIX}/audienceGroup/upload/byFile`, body, {
headers: body.getHeaders(),
});
return utils_1.ensureJSON(res);
}
async updateUploadAudienceGroup(uploadAudienceGroup,
// for set request timeout
httpConfig) {
const res = await this.http.put(`${endpoints_1.MESSAGING_API_PREFIX}/audienceGroup/upload`, Object.assign({}, uploadAudienceGroup), httpConfig);
return utils_1.ensureJSON(res);
}
async updateUploadAudienceGroupByFile(uploadAudienceGroup,
// for set request timeout
httpConfig) {
const file = await this.http.toBuffer(uploadAudienceGroup.file);
const body = utils_1.createMultipartFormData(Object.assign(Object.assign({}, uploadAudienceGroup), { file }));
const res = await this.http.put(`${endpoints_1.DATA_API_PREFIX}/audienceGroup/upload/byFile`, body, Object.assign({ headers: body.getHeaders() }, httpConfig));
return utils_1.ensureJSON(res);
}
async createClickAudienceGroup(clickAudienceGroup) {
const res = await this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/audienceGroup/click`, Object.assign({}, clickAudienceGroup));
return utils_1.ensureJSON(res);
}
async createImpAudienceGroup(impAudienceGroup) {
const res = await this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/audienceGroup/imp`, Object.assign({}, impAudienceGroup));
return utils_1.ensureJSON(res);
}
async setDescriptionAudienceGroup(description, audienceGroupId) {
const res = await this.http.put(`${endpoints_1.MESSAGING_API_PREFIX}/audienceGroup/${audienceGroupId}/updateDescription`, {
description,
});
return utils_1.ensureJSON(res);
}
async deleteAudienceGroup(audienceGroupId) {
const res = await this.http.delete(`${endpoints_1.MESSAGING_API_PREFIX}/audienceGroup/${audienceGroupId}`);
return utils_1.ensureJSON(res);
}
async getAudienceGroup(audienceGroupId) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/audienceGroup/${audienceGroupId}`);
return utils_1.ensureJSON(res);
}
async getAudienceGroups(page, description, status, size, createRoute, includesExternalPublicGroups) {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/audienceGroup/list`, {
page,
description,
status,
size,
createRoute,
includesExternalPublicGroups,
});
return utils_1.ensureJSON(res);
}
async getAudienceGroupAuthorityLevel() {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/audienceGroup/authorityLevel`);
return utils_1.ensureJSON(res);
}
async changeAudienceGroupAuthorityLevel(authorityLevel) {
const res = await this.http.put(`${endpoints_1.MESSAGING_API_PREFIX}/audienceGroup/authorityLevel`, { authorityLevel });
return utils_1.ensureJSON(res);
}
async getBotInfo() {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/info`);
return utils_1.ensureJSON(res);
}
async setWebhookEndpointUrl(endpoint) {
return this.http.put(`${endpoints_1.MESSAGING_API_PREFIX}/channel/webhook/endpoint`, { endpoint });
}
async getWebhookEndpointInfo() {
const res = await this.http.get(`${endpoints_1.MESSAGING_API_PREFIX}/channel/webhook/endpoint`);
return utils_1.ensureJSON(res);
}
async testWebhookEndpoint(endpoint) {
const res = await this.http.post(`${endpoints_1.MESSAGING_API_PREFIX}/channel/webhook/test`, { endpoint });
return utils_1.ensureJSON(res);
}
}
exports.default = Client;
class OAuth {
constructor() {
this.http = new http_1.default();
}
issueAccessToken(client_id, client_secret) {
return this.http.postForm(`${endpoints_1.OAUTH_BASE_PREFIX}/accessToken`, {
grant_type: "client_credentials",
client_id,
client_secret,
});
}
revokeAccessToken(access_token) {
return this.http.postForm(`${endpoints_1.OAUTH_BASE_PREFIX}/revoke`, { access_token });
}
verifyAccessToken(access_token) {
return this.http.get(`${endpoints_1.OAUTH_BASE_PREFIX_V2_1}/verify`, { access_token });
}
verifyIdToken(id_token, client_id, nonce, user_id) {
return this.http.postForm(`${endpoints_1.OAUTH_BASE_PREFIX}/verify`, {
id_token,
client_id,
nonce,
user_id,
});
}
issueChannelAccessTokenV2_1(client_assertion) {
return this.http.postForm(`${endpoints_1.OAUTH_BASE_PREFIX_V2_1}/token`, {
grant_type: "client_credentials",
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
client_assertion,
});
}
getChannelAccessTokenKeyIdsV2_1(client_assertion) {
return this.http.get(`${endpoints_1.OAUTH_BASE_PREFIX_V2_1}/tokens/kid`, {
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
client_assertion,
});
}
revokeChannelAccessTokenV2_1(client_id, client_secret, access_token) {
return this.http.postForm(`${endpoints_1.OAUTH_BASE_PREFIX_V2_1}/revoke`, {
client_id,
client_secret,
access_token,
});
}
}
exports.OAuth = OAuth;
-4
View File
@@ -1,4 +0,0 @@
export declare const MESSAGING_API_PREFIX = "https://api.line.me/v2/bot";
export declare const DATA_API_PREFIX = "https://api-data.line.me/v2/bot";
export declare const OAUTH_BASE_PREFIX = "https://api.line.me/v2/oauth";
export declare const OAUTH_BASE_PREFIX_V2_1 = "https://api.line.me/oauth2/v2.1";
-7
View File
@@ -1,7 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OAUTH_BASE_PREFIX_V2_1 = exports.OAUTH_BASE_PREFIX = exports.DATA_API_PREFIX = exports.MESSAGING_API_PREFIX = void 0;
exports.MESSAGING_API_PREFIX = `https://api.line.me/v2/bot`;
exports.DATA_API_PREFIX = `https://api-data.line.me/v2/bot`;
exports.OAUTH_BASE_PREFIX = `https://api.line.me/v2/oauth`;
exports.OAUTH_BASE_PREFIX_V2_1 = `https://api.line.me/oauth2/v2.1`;
-23
View File
@@ -1,23 +0,0 @@
export declare class SignatureValidationFailed extends Error {
signature?: string;
constructor(message: string, signature?: string);
}
export declare class JSONParseError extends Error {
raw: any;
constructor(message: string, raw: any);
}
export declare class RequestError extends Error {
code: string;
private originalError;
constructor(message: string, code: string, originalError: Error);
}
export declare class ReadError extends Error {
private originalError;
constructor(originalError: Error);
}
export declare class HTTPError extends Error {
statusCode: number;
statusMessage: string;
originalError: any;
constructor(message: string, statusCode: number, statusMessage: string, originalError: any);
}
-41
View File
@@ -1,41 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HTTPError = exports.ReadError = exports.RequestError = exports.JSONParseError = exports.SignatureValidationFailed = void 0;
class SignatureValidationFailed extends Error {
constructor(message, signature) {
super(message);
this.signature = signature;
}
}
exports.SignatureValidationFailed = SignatureValidationFailed;
class JSONParseError extends Error {
constructor(message, raw) {
super(message);
this.raw = raw;
}
}
exports.JSONParseError = JSONParseError;
class RequestError extends Error {
constructor(message, code, originalError) {
super(message);
this.code = code;
this.originalError = originalError;
}
}
exports.RequestError = RequestError;
class ReadError extends Error {
constructor(originalError) {
super(originalError.message);
this.originalError = originalError;
}
}
exports.ReadError = ReadError;
class HTTPError extends Error {
constructor(message, statusCode, statusMessage, originalError) {
super(message);
this.statusCode = statusCode;
this.statusMessage = statusMessage;
this.originalError = originalError;
}
}
exports.HTTPError = HTTPError;
-24
View File
@@ -1,24 +0,0 @@
/// <reference types="node" />
import { AxiosResponse, AxiosRequestConfig } from "axios";
import { Readable } from "stream";
interface httpClientConfig extends Partial<AxiosRequestConfig> {
baseURL?: string;
defaultHeaders?: any;
responseParser?: <T>(res: AxiosResponse) => T;
}
export default class HTTPClient {
private instance;
private config;
constructor(config?: httpClientConfig);
get<T>(url: string, params?: any): Promise<T>;
getStream(url: string, params?: any): Promise<Readable>;
post<T>(url: string, body?: any, config?: Partial<AxiosRequestConfig>): Promise<T>;
private responseParse;
put<T>(url: string, body?: any, config?: Partial<AxiosRequestConfig>): Promise<T>;
postForm<T>(url: string, body?: any): Promise<T>;
toBuffer(data: Buffer | Readable): Promise<Buffer>;
postBinary<T>(url: string, data: Buffer | Readable, contentType?: string): Promise<T>;
delete<T>(url: string, params?: any): Promise<T>;
private wrapError;
}
export {};
-102
View File
@@ -1,102 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = require("axios");
const stream_1 = require("stream");
const exceptions_1 = require("./exceptions");
const fileType = require("file-type");
const qs = require("querystring");
const pkg = require("../package.json");
class HTTPClient {
constructor(config = {}) {
this.config = config;
const { baseURL, defaultHeaders } = config;
this.instance = axios_1.default.create({
baseURL,
headers: Object.assign({}, defaultHeaders, {
"User-Agent": `${pkg.name}/${pkg.version}`,
}),
});
this.instance.interceptors.response.use(res => res, err => Promise.reject(this.wrapError(err)));
}
async get(url, params) {
const res = await this.instance.get(url, { params });
return res.data;
}
async getStream(url, params) {
const res = await this.instance.get(url, {
params,
responseType: "stream",
});
return res.data;
}
async post(url, body, config) {
const res = await this.instance.post(url, body, Object.assign({ headers: Object.assign({ "Content-Type": "application/json" }, (config && config.headers)) }, config));
return this.responseParse(res);
}
responseParse(res) {
const { responseParser } = this.config;
if (responseParser)
return responseParser(res);
else
return res.data;
}
async put(url, body, config) {
const res = await this.instance.put(url, body, Object.assign({ headers: Object.assign({ "Content-Type": "application/json" }, (config && config.headers)) }, config));
return this.responseParse(res);
}
async postForm(url, body) {
const res = await this.instance.post(url, qs.stringify(body), {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
});
return res.data;
}
async toBuffer(data) {
if (Buffer.isBuffer(data)) {
return data;
}
else if (data instanceof stream_1.Readable) {
return await new Promise((resolve, reject) => {
const buffers = [];
let size = 0;
data.on("data", (chunk) => {
buffers.push(chunk);
size += chunk.length;
});
data.on("end", () => resolve(Buffer.concat(buffers, size)));
data.on("error", reject);
});
}
else {
throw new Error("invalid data type for binary data");
}
}
async postBinary(url, data, contentType) {
const buffer = await this.toBuffer(data);
const res = await this.instance.post(url, buffer, {
headers: {
"Content-Type": contentType || (await fileType.fromBuffer(buffer)).mime,
"Content-Length": buffer.length,
},
});
return res.data;
}
async delete(url, params) {
const res = await this.instance.delete(url, { params });
return res.data;
}
wrapError(err) {
if (err.response) {
return new exceptions_1.HTTPError(err.message, err.response.status, err.response.statusText, err);
}
else if (err.code) {
return new exceptions_1.RequestError(err.message, err.code, err);
}
else if (err.config) {
// unknown, but from axios
return new exceptions_1.ReadError(err);
}
// otherwise, just rethrow
return err;
}
}
exports.default = HTTPClient;
-6
View File
@@ -1,6 +0,0 @@
import Client, { OAuth } from "./client";
import middleware from "./middleware";
import validateSignature from "./validate-signature";
export { Client, middleware, validateSignature, OAuth };
export * from "./exceptions";
export * from "./types";
-23
View File
@@ -1,23 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OAuth = exports.validateSignature = exports.middleware = exports.Client = void 0;
const client_1 = require("./client");
exports.Client = client_1.default;
Object.defineProperty(exports, "OAuth", { enumerable: true, get: function () { return client_1.OAuth; } });
const middleware_1 = require("./middleware");
exports.middleware = middleware_1.default;
const validate_signature_1 = require("./validate-signature");
exports.validateSignature = validate_signature_1.default;
// re-export exceptions and types
__exportStar(require("./exceptions"), exports);
__exportStar(require("./types"), exports);
-10
View File
@@ -1,10 +0,0 @@
/// <reference types="node" />
import * as http from "http";
import * as Types from "./types";
export declare type Request = http.IncomingMessage & {
body: any;
};
export declare type Response = http.ServerResponse;
export declare type NextCallback = (err?: Error) => void;
export declare type Middleware = (req: Request, res: Response, next: NextCallback) => void | Promise<void>;
export default function middleware(config: Types.MiddlewareConfig): Middleware;
-53
View File
@@ -1,53 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const body_parser_1 = require("body-parser");
const exceptions_1 = require("./exceptions");
const Types = require("./types");
const validate_signature_1 = require("./validate-signature");
function isValidBody(body) {
return (body && typeof body === "string") || Buffer.isBuffer(body);
}
function middleware(config) {
if (!config.channelSecret) {
throw new Error("no channel secret");
}
const secret = config.channelSecret;
const _middleware = async (req, res, next) => {
// header names are lower-cased
// https://nodejs.org/api/http.html#http_message_headers
const signature = req.headers[Types.LINE_SIGNATURE_HTTP_HEADER_NAME];
if (!signature) {
next(new exceptions_1.SignatureValidationFailed("no signature"));
return;
}
const body = await (async () => {
if (isValidBody(req.rawBody)) {
// rawBody is provided in Google Cloud Functions and others
return req.rawBody;
}
else if (isValidBody(req.body)) {
return req.body;
}
else {
// body may not be parsed yet, parse it to a buffer
return new Promise((resolve, reject) => body_parser_1.raw({ type: "*/*" })(req, res, (error) => error ? reject(error) : resolve(req.body)));
}
})();
if (!validate_signature_1.default(body, secret, signature)) {
next(new exceptions_1.SignatureValidationFailed("signature validation failed", signature));
return;
}
const strBody = Buffer.isBuffer(body) ? body.toString() : body;
try {
req.body = JSON.parse(strBody);
next();
}
catch (err) {
next(new exceptions_1.JSONParseError(err.message, strBody));
}
};
return (req, res, next) => {
_middleware(req, res, next).catch(next);
};
}
exports.default = middleware;
-2460
View File
File diff suppressed because it is too large Load Diff
-5
View File
@@ -1,5 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LINE_SIGNATURE_HTTP_HEADER_NAME = exports.LINE_REQUEST_ID_HTTP_HEADER_NAME = void 0;
exports.LINE_REQUEST_ID_HTTP_HEADER_NAME = "x-line-request-id";
exports.LINE_SIGNATURE_HTTP_HEADER_NAME = "x-line-signature";
-4
View File
@@ -1,4 +0,0 @@
import * as FormData from "form-data";
export declare function toArray<T>(maybeArr: T | T[]): T[];
export declare function ensureJSON<T>(raw: T): T;
export declare function createMultipartFormData(this: FormData | void, formBody: Record<string, any>): FormData;
-31
View File
@@ -1,31 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMultipartFormData = exports.ensureJSON = exports.toArray = void 0;
const exceptions_1 = require("./exceptions");
const FormData = require("form-data");
function toArray(maybeArr) {
return Array.isArray(maybeArr) ? maybeArr : [maybeArr];
}
exports.toArray = toArray;
function ensureJSON(raw) {
if (typeof raw === "object") {
return raw;
}
else {
throw new exceptions_1.JSONParseError("Failed to parse response body as JSON", raw);
}
}
exports.ensureJSON = ensureJSON;
function createMultipartFormData(formBody) {
const formData = this instanceof FormData ? this : new FormData();
Object.entries(formBody).forEach(([key, value]) => {
if (Buffer.isBuffer(value) || value instanceof Uint8Array) {
formData.append(key, value);
}
else {
formData.append(key, String(value));
}
});
return formData;
}
exports.createMultipartFormData = createMultipartFormData;
-2
View File
@@ -1,2 +0,0 @@
/// <reference types="node" />
export default function validateSignature(body: string | Buffer, channelSecret: string, signature: string): boolean;
-16
View File
@@ -1,16 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
function s2b(str, encoding) {
return Buffer.from(str, encoding);
}
function safeCompare(a, b) {
if (a.length !== b.length) {
return false;
}
return crypto_1.timingSafeEqual(a, b);
}
function validateSignature(body, channelSecret, signature) {
return safeCompare(crypto_1.createHmac("SHA256", channelSecret).update(body).digest(), s2b(signature, "base64"));
}
exports.default = validateSignature;