bereach
v1.4.3
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage *bereach* API.
Readme
bereach
Developer-friendly & type-safe Typescript SDK specifically catered to leverage bereach API.
[!IMPORTANT] This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
Summary
BeReach API: BeReach | Unofficial Linkedin API
Table of Contents
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add bereachPNPM
pnpm add bereachBun
bun add bereachYarn
yarn add bereach[!NOTE] This package is published as an ES Module (ESM) only. For applications using CommonJS, use
await import("bereach")to import and use this package.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { Bereach } from "bereach";
const bereach = new Bereach({
token: "BEREACH_API_KEY",
});
async function run() {
const result = await bereach.scrapers.collectLikes({
postUrl:
"https://www.linkedin.com/feed/update/urn:li:activity:1234567890123456789/",
start: 0,
});
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
| ------- | ---- | ----------- | -------------------- |
| token | http | HTTP Bearer | BEREACH_TOKEN |
To authenticate with the API the token parameter must be set when initializing the SDK client instance. For example:
import { Bereach } from "bereach";
const bereach = new Bereach({
token: "BEREACH_API_KEY",
});
async function run() {
const result = await bereach.scrapers.collectLikes({
postUrl:
"https://www.linkedin.com/feed/update/urn:li:activity:1234567890123456789/",
start: 0,
});
console.log(result);
}
run();
Available Resources and Operations
Actions
- connectProfile - Send LinkedIn connection request
- listInvitations - List received LinkedIn connection invitations
- acceptInvitation - Accept a LinkedIn connection invitation
- sendMessage - Send LinkedIn message
- replyToComment - Reply to a LinkedIn comment
- likeComment - Like a LinkedIn comment
- publishPost - Publish or schedule a LinkedIn post
- createComment - Comment on a LinkedIn post
- likePost - Like a LinkedIn post
- declineInvitation - Decline a connection invitation
- listSentInvitations - List sent connection invitations
- withdrawInvitation - Withdraw a sent connection invitation
- followProfile - Follow a profile
- unfollowProfile - Unfollow a profile
- editPost - Edit a post
- editComment - Edit a comment
- repostPost - Repost / share a post
- unlikePost - Unlike a post
- unlikeComment - Unlike a comment
- savePost - Save a post
- unsavePost - Unsave a post
- followCompany - Follow a company
- unfollowCompany - Unfollow a company
Campaigns
- ~~filter~~ - Check if campaign actions are completed :warning: Deprecated
- getStatus - Query per-profile action status within a campaign
- sync - Mark actions as completed without performing them
- stats - Get aggregate campaign statistics
Chat
- listInbox - List LinkedIn inbox conversations
- searchConversations - Search LinkedIn conversations
- findConversation - Find a conversation with a specific person
- getMessages - Read messages from a conversation
- markSeen - Mark a conversation as read
- markAllRead - Mark all conversations as read
- star - Star a conversation
- unstar - Unstar a conversation
- listStarred - List starred conversations
- archive - Archive a conversation
- unarchive - Unarchive a conversation
- listArchived - List archived conversations
- react - React to a message with emoji
- unreact - Remove emoji reaction from a message
- sendTypingIndicator - Send typing indicator
- getUnreadCount - Get unread message count
CompanyPages
- list - List company pages the user administers
- posts - Get recent posts from a company page
- getPermissions - Get admin permissions for a company page
- getAnalytics - Get company page overview analytics
Contacts
- upsert - Create or upsert contacts (no campaign required)
- search - Search and filter contacts
- get - Get a single contact with activities and campaigns
- update - Update a contact
- listActivities - List activities for a contact
- addActivities - Log activities for a contact
- bulkUpdate - Bulk update contacts
- stats - Get contact funnel statistics
- listAgentStates - List all agent state entries
- getAgentState - Get agent state by key
- setAgentState - Set agent state by key
- deleteAgentState - Delete agent state by key
- patchAgentState - Merge-update agent state by key
- listCampaigns - List campaigns
- createCampaign - Create a lead-gen campaign
- getCampaign - Get a single campaign
- deleteCampaign - Delete a campaign
- updateCampaign - Update campaign settings
- campaignStatusTransition - Campaign state transition
- listByCampaign - List contacts in a campaign
- addToCampaign - Add contacts to a campaign
- getByUrl - Look up contact by LinkedIn URL
Context
- listEntries - List context entries
- set - Create or update a context entry
- delete - Delete a context entry
Cron
- listSchedules - List active cron schedules
- updateSchedule - Pause, resume, or delete a cron schedule
Profile
- get - Get authenticated user's LinkedIn profile
- listAccounts - List all LinkedIn accounts for the authenticated user
- updateAccount - Update a LinkedIn account (label, default)
- refresh - Refresh authenticated user's LinkedIn profile
- posts - Get authenticated user's LinkedIn posts
- getFollowers - Get authenticated user's LinkedIn followers
- getLimits - Get current LinkedIn rate limit status
- getCredits - Get current BeReach credit balance
- views - Get profile views
- getSearchAppearances - Get search appearances
- getPostAnalytics - Get post analytics
- getFollowerAnalytics - Get follower analytics
- switchAccount - Switch active LinkedIn account
- listConnections - List LinkedIn connections
SalesNav
- search - Sales Navigator Search — leads (people) & accounts (companies)
- people - Sales Navigator People/Lead Search
- companies - Sales Navigator Company/Account Search
ScheduledMessages
- list - List scheduled messages
- create - Create a draft DM
- batchSchedule - Batch-schedule drafts for auto-send
- cancel - Cancel scheduled or draft messages
Scrapers
- collectLikes - Scrape LinkedIn post likes
- collectComments - Scrape LinkedIn post comments
- collectCommentReplies - Scrape replies to a LinkedIn comment
- collectPosts - Scrape LinkedIn profile posts
- visitProfile - Visit LinkedIn profile and extract contact data
- bulkVisitProfile - Queue bulk LinkedIn profile visits (fire-and-forget)
- bulkVisitBatchStatus - Get bulk visit batch status
- visitCompany - Visit LinkedIn company page and extract profile data
- listSavedPosts - List saved posts
- getFeed - Get home feed
- collectHashtagPosts - Collect posts from a hashtag
Search
- search - Unified LinkedIn Search — posts, people, companies, jobs
- posts - Search LinkedIn Posts
- people - Search LinkedIn People
- companies - Search LinkedIn Companies
- jobs - Search LinkedIn Jobs
- byUrl - Search LinkedIn by URL
- resolveParameters - Resolve text to LinkedIn search parameter IDs (typeahead)
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
actionsAcceptInvitation- Accept a LinkedIn connection invitationactionsConnectProfile- Send LinkedIn connection requestactionsCreateComment- Comment on a LinkedIn postactionsDeclineInvitation- Decline a connection invitationactionsEditComment- Edit a commentactionsEditPost- Edit a postactionsFollowCompany- Follow a companyactionsFollowProfile- Follow a profileactionsLikeComment- Like a LinkedIn commentactionsLikePost- Like a LinkedIn postactionsListInvitations- List received LinkedIn connection invitationsactionsListSentInvitations- List sent connection invitationsactionsPublishPost- Publish or schedule a LinkedIn postactionsReplyToComment- Reply to a LinkedIn commentactionsRepostPost- Repost / share a postactionsSavePost- Save a postactionsSendMessage- Send LinkedIn messageactionsUnfollowCompany- Unfollow a companyactionsUnfollowProfile- Unfollow a profileactionsUnlikeComment- Unlike a commentactionsUnlikePost- Unlike a postactionsUnsavePost- Unsave a postactionsWithdrawInvitation- Withdraw a sent connection invitationcampaignsGetStatus- Query per-profile action status within a campaigncampaignsStats- Get aggregate campaign statisticscampaignsSync- Mark actions as completed without performing themchatArchive- Archive a conversationchatFindConversation- Find a conversation with a specific personchatGetMessages- Read messages from a conversationchatGetUnreadCount- Get unread message countchatListArchived- List archived conversationschatListInbox- List LinkedIn inbox conversationschatListStarred- List starred conversationschatMarkAllRead- Mark all conversations as readchatMarkSeen- Mark a conversation as readchatReact- React to a message with emojichatSearchConversations- Search LinkedIn conversationschatSendTypingIndicator- Send typing indicatorchatStar- Star a conversationchatUnarchive- Unarchive a conversationchatUnreact- Remove emoji reaction from a messagechatUnstar- Unstar a conversationcompanyPagesGetAnalytics- Get company page overview analyticscompanyPagesGetPermissions- Get admin permissions for a company pagecompanyPagesList- List company pages the user administerscompanyPagesPosts- Get recent posts from a company pagecontactsAddActivities- Log activities for a contactcontactsAddToCampaign- Add contacts to a campaigncontactsBulkUpdate- Bulk update contactscontactsCampaignStatusTransition- Campaign state transitioncontactsCreateCampaign- Create a lead-gen campaigncontactsDeleteAgentState- Delete agent state by keycontactsDeleteCampaign- Delete a campaigncontactsGet- Get a single contact with activities and campaignscontactsGetAgentState- Get agent state by keycontactsGetByUrl- Look up contact by LinkedIn URLcontactsGetCampaign- Get a single campaigncontactsListActivities- List activities for a contactcontactsListAgentStates- List all agent state entriescontactsListByCampaign- List contacts in a campaigncontactsListCampaigns- List campaignscontactsPatchAgentState- Merge-update agent state by keycontactsSearch- Search and filter contactscontactsSetAgentState- Set agent state by keycontactsStats- Get contact funnel statisticscontactsUpdate- Update a contactcontactsUpdateCampaign- Update campaign settingscontactsUpsert- Create or upsert contacts (no campaign required)contextDelete- Delete a context entrycontextListEntries- List context entriescontextSet- Create or update a context entrycronListSchedules- List active cron schedulescronUpdateSchedule- Pause, resume, or delete a cron scheduleprofileGet- Get authenticated user's LinkedIn profileprofileGetCredits- Get current BeReach credit balanceprofileGetFollowerAnalytics- Get follower analyticsprofileGetFollowers- Get authenticated user's LinkedIn followersprofileGetLimits- Get current LinkedIn rate limit statusprofileGetPostAnalytics- Get post analyticsprofileGetSearchAppearances- Get search appearancesprofileListAccounts- List all LinkedIn accounts for the authenticated userprofileListConnections- List LinkedIn connectionsprofilePosts- Get authenticated user's LinkedIn postsprofileRefresh- Refresh authenticated user's LinkedIn profileprofileSwitchAccount- Switch active LinkedIn accountprofileUpdateAccount- Update a LinkedIn account (label, default)profileViews- Get profile viewssalesNavCompanies- Sales Navigator Company/Account SearchsalesNavPeople- Sales Navigator People/Lead SearchsalesNavSearch- Sales Navigator Search — leads (people) & accounts (companies)scheduledMessagesBatchSchedule- Batch-schedule drafts for auto-sendscheduledMessagesCancel- Cancel scheduled or draft messagesscheduledMessagesCreate- Create a draft DMscheduledMessagesList- List scheduled messagesscrapersBulkVisitBatchStatus- Get bulk visit batch statusscrapersBulkVisitProfile- Queue bulk LinkedIn profile visits (fire-and-forget)scrapersCollectCommentReplies- Scrape replies to a LinkedIn commentscrapersCollectComments- Scrape LinkedIn post commentsscrapersCollectHashtagPosts- Collect posts from a hashtagscrapersCollectLikes- Scrape LinkedIn post likesscrapersCollectPosts- Scrape LinkedIn profile postsscrapersGetFeed- Get home feedscrapersListSavedPosts- List saved postsscrapersVisitCompany- Visit LinkedIn company page and extract profile datascrapersVisitProfile- Visit LinkedIn profile and extract contact datasearchByUrl- Search LinkedIn by URLsearchCompanies- Search LinkedIn CompaniessearchJobs- Search LinkedIn JobssearchPeople- Search LinkedIn PeoplesearchPosts- Search LinkedIn PostssearchResolveParameters- Resolve text to LinkedIn search parameter IDs (typeahead)searchSearch- Unified LinkedIn Search — posts, people, companies, jobs- ~~
campaignsFilter~~ - Check if campaign actions are completed :warning: Deprecated
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { Bereach } from "bereach";
const bereach = new Bereach({
token: "BEREACH_API_KEY",
});
async function run() {
const result = await bereach.scrapers.collectLikes({
postUrl:
"https://www.linkedin.com/feed/update/urn:li:activity:1234567890123456789/",
start: 0,
}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { Bereach } from "bereach";
const bereach = new Bereach({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
token: "BEREACH_API_KEY",
});
async function run() {
const result = await bereach.scrapers.collectLikes({
postUrl:
"https://www.linkedin.com/feed/update/urn:li:activity:1234567890123456789/",
start: 0,
});
console.log(result);
}
run();
Error Handling
BereachError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
| error.data$ | | Optional. Some errors may contain structured data. See Error Classes. |
Example
import { Bereach } from "bereach";
import * as errors from "bereach/models/errors";
const bereach = new Bereach({
token: "BEREACH_API_KEY",
});
async function run() {
try {
const result = await bereach.scrapers.collectLikes({
postUrl:
"https://www.linkedin.com/feed/update/urn:li:activity:1234567890123456789/",
start: 0,
});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.BereachError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.BadRequestError) {
console.log(error.data$.success); // boolean
console.log(error.data$.error); // operations.CollectLikesBadRequestError
}
}
}
}
run();
Error Classes
Primary errors:
BereachError: The base class for HTTP error responses.BadRequestError: The server cannot or will not process the request due to something that is perceived to be a client error. Status code400.UnauthorizedError: Although HTTP specifies "unauthorized", this response means "unauthenticated". Authenticate to continue. Status code401.ForbiddenError: The client does not have access rights to the content. Status code403.NotFoundError: The server cannot find the requested resource. Status code404.ConflictError: The request conflicts with the current state of the server. Status code409.GoneError: The requested content has been permanently deleted from the server. Status code410.UnprocessableEntityError: The request was well-formed but was unable to be followed due to semantic errors. Status code422.TooManyRequestsError: Rate limit exceeded. Read error.retryAfter for the wait time in seconds. Status code429.InternalServerError: The server encountered a situation it does not know how to handle. Status code500.BadGatewayError: LinkedIn returned a server error or the proxy connection failed. Retry after a few seconds. Status code502.ServiceUnavailableError: Proxy capacity temporarily exceeded. Retry after a few seconds. Status code503.
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from BereachError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
Server Selection
Select Server by Index
You can override the default server globally by passing a server index to the serverIdx: number optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:
| # | Server | Description |
| --- | ------------------------------ | -------------- |
| 0 | https://api.berea.ch | Production API |
| 1 | https://api-staging.berea.ch | Staging API |
Example
import { Bereach } from "bereach";
const bereach = new Bereach({
serverIdx: 0,
token: "BEREACH_API_KEY",
});
async function run() {
const result = await bereach.scrapers.collectLikes({
postUrl:
"https://www.linkedin.com/feed/update/urn:li:activity:1234567890123456789/",
start: 0,
});
console.log(result);
}
run();
Override Server URL Per-Client
The default server can also be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { Bereach } from "bereach";
const bereach = new Bereach({
serverURL: "https://api-staging.berea.ch",
token: "BEREACH_API_KEY",
});
async function run() {
const result = await bereach.scrapers.collectLikes({
postUrl:
"https://www.linkedin.com/feed/update/urn:li:activity:1234567890123456789/",
start: 0,
});
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to:
- route requests through a proxy server using undici's ProxyAgent
- use the
"beforeRequest"hook to add a custom header and a timeout to requests - use the
"requestError"hook to log errors
import { Bereach } from "bereach";
import { ProxyAgent } from "undici";
import { HTTPClient } from "bereach/lib/http";
const dispatcher = new ProxyAgent("http://proxy.example.com:8080");
const httpClient = new HTTPClient({
// 'fetcher' takes a function that has the same signature as native 'fetch'.
fetcher: (input, init) =>
// 'dispatcher' is specific to undici and not part of the standard Fetch API.
fetch(input, { ...init, dispatcher } as RequestInit),
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new Bereach({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { Bereach } from "bereach";
const sdk = new Bereach({ debugLogger: console });You can also enable a default debug logger by setting an environment variable BEREACH_DEBUG to true.
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
