### Install Envato.js Package Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Instructions to install the Envato.js library into your project using the npm package manager. ```shell npm install envato ``` -------------------------------- ### Handle Envato OAuth Callback with Express.js Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Provides an example Express.js route (`/authenticate`) to process the OAuth callback. It fetches the authentication code from the URL, uses it to get an authenticated Envato client, retrieves user details, and includes basic error handling. ```js // This is an example express route to handle the request app.get('/authenticate', async function(req, res) { try { // Fetch the code from the URL const code = req.query.code; // Authenticate the user via the API const client = await oauth.getClient(code); const username = await client.private.getUsername(); // You can also get their User ID for data storage const { userId } = await client.getIdentity(); res.send(`Hello, ${username}!`); } catch (error) { console.error('Authentication failed:', error); res.status(500).send('Something broke! Try again.'); } }); ``` -------------------------------- ### Envato.js Catalog: Get WordPress Theme/Plugin Version Source: https://github.com/baileyherbert/envato.js/blob/master/README.md This example shows how to use 'client.catalog.getItemVersion()' to retrieve the latest available version of a WordPress theme or plugin. This endpoint is recommended for authors building auto-upgrade systems and returns 'undefined' if the item is not found. ```javascript const version = await client.catalog.getItemVersion(123456); const themeVersion = version.wordpress_theme_latest_version; const pluginVersion = version.wordpress_plugin_latest_version; ``` -------------------------------- ### Basic Envato.js Client Usage with Personal Token Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Demonstrates how to initialize the Envato.js client with a personal token and perform basic operations like fetching user identity, username, and email. The example uses async/await for handling promises. ```javascript const Envato = require('envato'); async function start() { const client = new Envato.Client('personal token here'); const { userId } = await client.getIdentity(); const username = await client.private.getUsername(); const email = await client.private.getEmail(); console.log('Logged in:', userId, username, email); } start().catch(console.error); ``` -------------------------------- ### Get a user's newest Envato items Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves up to 1000 of the newest files uploaded by a user to a particular Envato site. ```js const items = await client.user.getNewItems('baileyherbert', 'codecanyon'); for (const item of items) { console.log(item.id, item.name); } ``` -------------------------------- ### Get similar Envato items Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Returns items similar to a given item ID from the Envato catalog. Useful for recommendations or related content. ```js const response = await client.catalog.getMoreLikeThis({ item_id: 123456, page_size: 100, page: 1 }); console.log('Similar items:', response.matches); ``` -------------------------------- ### Get new Envato items by site and category Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves recently uploaded files for a specific Envato site and category combination. ```js const items = await client.catalog.getNewFiles('codecanyon', 'php-scripts'); for (const item of items) { console.log(item.id, item.name); } ``` -------------------------------- ### Manual HTTP Request Methods in Envato.js Client Source: https://github.com/baileyherbert/envato.js/blob/master/README.md The envato.js client provides direct methods for sending HTTP requests (get, post, put, patch, delete) to any endpoint. This snippet demonstrates sending a POST request with parameters and shows how TypeScript generics can be used to specify the expected response format for type-safe development. ```javascript const params = { name: 'hello world', id: 24596 }; const response = await client.post('/v3/path/to/endpoint', params); ``` ```typescript interface Response { id: number; name: string; "private": boolean; }; const response = await client.get('/v3/endpoint'); const id = response.id; // Hinted as a number const "private" = response."private"; // Hinted as a boolean ``` -------------------------------- ### Search for comments on an Envato item Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Searches for comments on a specific item using the Envato API. This example demonstrates how to paginate and sort comments. ```js const response = await client.catalog.searchComments({ item_id: 123456, sort_by: 'newest', page_size: 100, page: 1 }); console.log('Search took %d milliseconds', response.took); console.log('Found %d comments', response.matches.length); ``` -------------------------------- ### Get a user's item count per Envato marketplace Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Displays the number of items an author has for sale on each specific Envato marketplace. ```js const counts = await client.user.getItemsBySite('baileyherbert'); for (const count of counts) { console.log('The user has %d items on %s', count.items, count.site); } ``` -------------------------------- ### Get a user's Envato profile details Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves detailed profile information for a specified Envato user, including username, sales, followers, and avatar. ```js const user = await client.user.getAccountDetails('baileyherbert'); console.log('Username:', user.username); console.log('Sales:', user.sales); console.log('Avatar URL:', user.image); ``` -------------------------------- ### Retrieving User ID and Scopes with Envato.js Source: https://github.com/baileyherbert/envato.js/blob/master/README.md This example shows how to use the 'client.getIdentity()' method to retrieve a user's unique ID and the permissions (scopes) associated with their personal token. This is useful for storing user-specific data in your database or verifying token capabilities. ```javascript const { userId, scopes } = await client.getIdentity(); console.log('Id:', userId); console.log('Scopes:', scopes); ``` -------------------------------- ### Get prices for an Envato item Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Returns available licenses and their corresponding prices for a given Envato item ID. This function will throw an error if the item is not found. ```js const prices = await client.catalog.getItemPrices(123456); for (const entry of prices) { console.log('%s ($%s)', entry.license, entry.price); } ``` -------------------------------- ### Get Authenticated User's Email Address (Private API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Returns the email address of the currently logged-in user as a string. ```js const email = await client.private.getEmail(); ``` -------------------------------- ### Get random new Envato items Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves a list of newly uploaded files from a specific Envato site, intended to be random but may be sorted by newest first. ```js const items = await client.catalog.getRandomNewFiles('codecanyon'); for (const item of items) { console.log(item.id, item.name); } ``` -------------------------------- ### Get Authenticated User's Username (Private API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Returns the Envato Account username of the currently logged-in user as a string. ```js const username = await client.private.getUsername(); ``` -------------------------------- ### Get User's Statement Transaction Data (Private API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Lists the financial transactions from the authenticated user's statement page. ```js const response = await client.private.getStatement(); ``` -------------------------------- ### Get Number of Items Per Category (Statistics API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves the total number of items available on Envato Market, broken down by category. ```js const categories = await client.stats.getFilesPerCategory(); ``` -------------------------------- ### Get Total Number of Envato Market Users (Statistics API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves the current total count of subscribed users across all Envato Marketplaces. ```js const users = await client.stats.getTotalUsers(); ``` -------------------------------- ### Get Total Number of Envato Market Items (Statistics API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves the current total count of all available items across all Envato Marketplaces. ```js const items = await client.stats.getTotalItems(); ``` -------------------------------- ### Get Author's Monthly Sales Data (Private API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves the monthly sales data for an author, mirroring the information displayed on their earnings page. The 'Earnings' reported are before any income tax deductions, such as US Royalty Withholding Tax. ```js const sales = await client.private.getMonthlySales(); ``` -------------------------------- ### Envato.js Catalog: Retrieve Public Collection Details Source: https://github.com/baileyherbert/envato.js/blob/master/README.md This example demonstrates how to use 'client.catalog.getCollection()' to fetch details and items contained within a public collection by its ID. The method returns 'undefined' if the collection is not found, and the response provides access to the collection's name and its items. ```javascript const response = await client.catalog.getCollection(25043); const name = response.collection.name; const items = response.items; ``` -------------------------------- ### Get Authenticated User's Account Details (Private API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves various account-related details for the currently logged-in user, including their first name, surname, available earnings for withdrawal, total deposits, current balance (deposits + earnings), and country. ```js const account = await client.private.getAccountDetails(); ``` -------------------------------- ### Initialize Envato OAuth Helper Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Shows how to create an OAuth helper instance by providing the client ID, client secret, and redirect URI, exactly as they were configured on build.envato.com. ```js const oauth = new Envato.OAuth({ client_id: '', client_secret: '', redirect_uri: '' }); ``` -------------------------------- ### Initialize Envato Client with Personal Token Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Demonstrates how to create an Envato client instance using a personal access token, either by passing the token string directly as an argument or within an options object. ```js const client = new Envato.Client('your personal token'); const client = new Envato.Client({ token: 'your personal token' }); ``` -------------------------------- ### Initialize Envato.js Client Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Describes the constructor for creating a new Envato.js client instance, which requires either a personal API token or an OAuth access token for authentication. ```APIDOC Envato.Client(token: string) token: Your personal Envato API token or OAuth access token. ``` -------------------------------- ### Configure Envato Client HTTP Request Options Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Illustrates how to customize the underlying `node-fetch` HTTP request settings, such as `timeout` and `compression`, by providing an `http` options object during client instantiation. ```js new Envato.Client({ token: 'personal token', http: { timeout: 30000, compression: false } }) ``` -------------------------------- ### Envato.js Client Endpoint Helpers Overview Source: https://github.com/baileyherbert/envato.js/blob/master/README.md The envato.js client provides four main endpoint helpers accessible as properties: 'catalog', 'user', 'private', and 'stats'. Each request made through these helpers returns a Promise instance, with 'await' syntax being the recommended approach for handling responses. ```APIDOC Endpoint Helpers: - client.catalog - client.user - client.private - client.stats Return Type: Promise instance ``` -------------------------------- ### Configure Envato.js Client for Public Sandbox Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Illustrates how to initialize the `Envato.Client` with the `sandbox` option set to `true` to use the unofficial public sandbox. This mode supports a limited set of endpoints and automatically removes sensitive information like personal tokens from requests. You can test by looking up a sale for the purchase code: `86781236-23d0-4b3c-7dfa-c1c147e0dece`. ```typescript new Envato.Client({ token: 'your personal token', sandbox: true }); ``` -------------------------------- ### Configure Envato Client with User Agent Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Demonstrates how to specify a custom user agent string via the `userAgent` option when instantiating the Envato client. This is recommended for high-volume users to help identify API usage. ```js new Envato.Client({ token: 'personal token', userAgent: 'License activation & forums for Avada at themefusion.com' }) ``` -------------------------------- ### Envato.js Catalog: Search Envato Market Items Source: https://github.com/baileyherbert/envato.js/blob/master/README.md This snippet demonstrates how to perform a search for items across Envato Marketplaces using 'client.catalog.searchItems()'. It shows how to pass search parameters like term, site, and pagination, then iterate through the matched items and log their details. ```javascript const response = await client.catalog.searchItems({ term: 'seo', site: 'codecanyon.net', page_size: 100, page: 3 }); console.log('Search took %d milliseconds', response.took); console.log('Found %d items', response.matches.length); for (const item of response.matches) { console.log('Item %d: %s', item.id, item.name); } ``` -------------------------------- ### Redirect User for Envato OAuth Authentication Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Illustrates how to obtain the authentication redirect URL from the OAuth helper instance and redirect the user's browser to initiate the OAuth flow. ```js res.redirect(oauth.getRedirectUrl()); ``` -------------------------------- ### Configure Envato.js Client with Custom Sandbox URL Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Shows how to specify a custom base URL for the sandbox environment by providing a string value to the `sandbox` option during `Envato.Client` initialization. This allows testing against a local or private sandbox instance. ```typescript new Envato.Client({ token: 'your personal token', sandbox: 'http://localhost:8080/' }); ``` -------------------------------- ### Envato.js API Endpoints Overview Source: https://github.com/baileyherbert/envato.js/blob/master/README.md A comprehensive list of the available API endpoints and methods exposed by the Envato.js library, categorized by their functional areas such as Catalog, User, Private User, and Statistics. ```APIDOC Catalog: - Look up a public collection - Look up a single item - Look up a WordPress theme or plugin's version - Search for items - Search for comments - Get more like this - Get popular items by site - Get categories by site - Get prices for an item - Get new items by site and category - Find featured items and authors - Get random new items User: - List a user's collections - Look up a user's private collection - Get a user's profile details - List a user's badges - Get a user's item count per marketplace - Get a user's newest items Private user: - List an author's sales - Look up a sale by code - List all purchases - List a buyer's purchases - Look up a purchase by code - Get a user's account details - Get a user's username - Get a user's email - Get an author's monthly sales - Get statement data - Download a purchase Statistics: - Get the total number of market users - Get the total number of market items - Get the number of items per category ``` -------------------------------- ### Handle API Errors with Try/Catch Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Demonstrates how to implement robust error handling using `try/catch` blocks when making API requests. It illustrates catching and differentiating between `Envato.HttpError`, `Envato.OAuthError`, and generic errors, providing specific handling for each type. ```js try { const email = await client.private.getEmail(); } catch (error) { if (error instanceof Envato.HttpError) { console.error('Status:', error.code); console.error('Message:', error.message); console.error('More details:', error.response); } else if (error instanceof Envato.OAuthError) { console.error('Failed to renew OAuth session.'); } else { console.error('Got an error from request.'); } } ``` ```json { "error": 400, "description": "An optional description of the error here" } ``` ```APIDOC Envato.HttpError: description: Represents an HTTP error returned by the Envato API. properties: code: number (HTTP status code) message: string (Error message) response: object (Optional, contains detailed error information) Envato.OAuthError: description: Represents an error specific to OAuth session failures. properties: http: Envato.HttpError (Optional, underlying HTTP error if applicable) Envato.FetchError: description: Represents a network connection error or timeout. ``` -------------------------------- ### Find featured Envato items and authors Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Shows the current featured items and authors for a given Envato site, including monthly free files. ```js const features = await client.catalog.getFeatures('codecanyon'); const featuredMonthlyFile = features.featured_file; const featuredAuthor = features.featured_author; const freeMonthlyFile = features.free_file; ``` -------------------------------- ### Download a Purchased Item (Private API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Generates a one-time download link for purchased items, identifiable by either the item ID or the purchase code. Each successful invocation of this endpoint contributes to the item's daily download limit. ```js const url = await client.private.getDownloadLink({ item_id: 123456 }); ``` -------------------------------- ### List All User Purchases (Private API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Fetches a comprehensive list of all items the authenticated user has purchased on their Envato account. ```js const purchases = await client.private.getPurchases(); ``` -------------------------------- ### Envato.js Sandboxing Feature Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Mentions the sandboxing capability provided by the Envato.js library, which can be useful for testing or isolated environments. ```APIDOC Sandboxing ``` -------------------------------- ### Reconstruct Envato Client with Token Renewal Options Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Explains how to reconstruct an Envato client instance from stored tokens. It shows how to enable automatic token renewal by providing an OAuth instance and all token properties, or how to create a client without renewal using only the access token. ```js // For automatic renewal of access tokens, you'll need an OAuth instance // It must have the same credentials as the instance that originally authenticated the user const oauth = new Envato.OAuth(...); // To construct a client with automatic renewal, pass all properties and an OAuth instance // Once the token expires, it will be automatically renewed const client = new Envato.Client({ token: fakeStorage.get('accessToken'), refreshToken: fakeStorage.get('refreshToken'), expiration: fakeStorage.get('expiration'), oauth }); // To construct a client WITHOUT automatic renewal, simply pass the token // Once the token expires, the client will stop working const client = new Envato.Client(fakeStorage.get('token')); ``` -------------------------------- ### Extract Access and Refresh Tokens from Envato Client Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Demonstrates how to destructure and extract the `token` (access token), `refreshToken`, and `expiration` properties from an authenticated Envato client instance for persistent storage. ```js const { token, refreshToken, expiration } = client; console.log('The current access token is %s', token); console.log('It expires at %d', expiration); ``` -------------------------------- ### Envato Client Option: handleRateLimits Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Documents the `handleRateLimits` option for the Envato client. This boolean setting controls the client's behavior when encountering API rate limits, allowing for silent handling or explicit error throwing. ```APIDOC Envato.Client Options: handleRateLimits: boolean (default: true) Description: Controls how the client responds to rate limiting. If true (default), the client will silently handle rate limit errors by pausing subsequent requests until the rate limit expires, as well as retrying the failed request automatically. This process is entirely behind-the-scenes and requires no extra implementation. If false, this option disables silent rate limit handling, and instead will throw Envato.TooManyRequests errors when rate limits are encountered, requiring manual throttling of requests. ``` -------------------------------- ### Monitor Envato.js Client Requests with Debug Event Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Illustrates how to subscribe to the 'debug' event to gain insights into client requests. This event fires for each request, providing a `response` object containing status, URL, response time, and body, useful for logging and troubleshooting. ```javascript client.on('debug', function(response) { console.log( '[Request] Got %d response back from %s (took %d ms):', response.status, response.request.url, response.took, response.body ); }); ``` -------------------------------- ### Handling Asynchronous Operations with Await and Promises Source: https://github.com/baileyherbert/envato.js/blob/master/README.md This snippet demonstrates two ways to handle asynchronous API calls using the envato.js client: the recommended 'await' operator for cleaner, synchronous-looking code, and the classic Promise '.then().catch()' syntax. Both methods include error handling for robust API interactions. ```javascript // With await operator (recommended) try { const username = await client.private.getUsername(); console.log(`Hello, ${username}!`); } catch (error) { console.error('Failed to get username:', error.message, error.response); } // With classic promises client.private.getUsername().then(function(username) { console.log(`Hello, ${username}!`); }).catch(function(error) { console.error('Failed to get username:', error.message, error.response); }); ``` -------------------------------- ### Retrieve popular Envato items by site Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Fetches popular files for a particular Envato site, categorized by popularity over different timeframes. ```js const popular = await client.catalog.getPopularItems(); const lastWeek = popular.items_last_week; const lastThreeMonths = popular.items_last_three_months; const authorsLastMonth = popular.authors_last_month; ``` -------------------------------- ### List Envato categories by site Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves a list of categories available for a specified Envato site, such as 'codecanyon'. ```js const categories = await client.catalog.getCategories('codecanyon'); for (const category of categories) { console.log('%s (%s)', category.name, category.path); } ``` -------------------------------- ### List an author's Envato sales Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Lists all unrefunded sales of the authenticated user's items on Envato Market. Sales amounts are reported before any tax deductions. ```js const sales = await client.private.getSales(); for (const sale of sales) { console.log('Sold %s for $%s', sale.item.name, sale.amount); } ``` -------------------------------- ### Handle Envato.js Client Rate Limit Event Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Shows how to listen for the 'ratelimit' event, which is emitted when the API imposes a rate limit, causing the client to pause requests. The event provides the `duration` in milliseconds for which requests will be held. This event is active only if `handleRateLimits` is enabled. ```javascript client.on('ratelimit', function(duration) { console.log('Rate limited for %d milliseconds.', duration); }); ``` -------------------------------- ### List a Buyer's Purchases from App Creator (Private API, OAuth Only) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves a list of purchases made by the authenticated user specifically for items listed by the app creator. This functionality is exclusively available when using OAuth tokens for authentication. ```js const { purchases } = await client.private.getPurchasesFromAppCreator(); for (const purchase of purchases) { console.log('Bought %s (purchase code: %s)', purchase.item.name, purchase.code); } ``` -------------------------------- ### Envato.js Client Events Source: https://github.com/baileyherbert/envato.js/blob/master/README.md A list of events that the Envato.js client can emit, providing hooks for various library operations such as token renewal, debugging information, rate limit notifications, and resumption of operations. ```APIDOC Events: - renew - debug - ratelimit - resume ``` -------------------------------- ### Detect Envato.js Client Rate Limit Resume Event Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Demonstrates how to use the 'resume' event, which is triggered once the client's rate limit period expires and it begins processing queued requests again. This event is only fired if the `handleRateLimits` option is set to `true`. ```javascript client.on('resume', function() { console.log('Rate limit has ended.'); }); ``` -------------------------------- ### Look up a User's Purchase by Code (Private API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Obtains the detailed information of a user's specific purchase by providing its purchase code. If the purchase is not found, the method returns `undefined`. ```js const purchase = await client.private.getPurchase('purchase-code'); ``` -------------------------------- ### Envato.js Error Handling Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Details on how the Envato.js library manages and reports errors, including general error codes and specific handling for 'not found' scenarios. ```APIDOC Error Handling: - Error codes - Not found errors ``` -------------------------------- ### List a user's Envato badges Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Shows a list of badges earned by the given Envato user. ```js const badges = await client.user.getBadges('baileyherbert'); for (const badge of badges) { console.log('Badge:', badge.name, badge.label, badge.image); } ``` -------------------------------- ### Listen for Envato Client Token Renewal Event Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Shows how to subscribe to the `renew` event on the client instance. This event fires when the access token is automatically regenerated, allowing you to update your stored `accessToken` and `expiration` values. ```js client.on('renew', renewal => { fakeStorage.set('accessToken', renewal.accessToken); fakeStorage.set('expiration', renewal.expiration); }); ``` -------------------------------- ### List a user's Envato collections Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves all private and public collections belonging to the authenticated user. ```js const collections = await client.user.getCollections(); for (const collection of collections) { console.log(collection.id, collection.name); } ``` -------------------------------- ### Envato.js Catalog: Retrieve Single Item Details Source: https://github.com/baileyherbert/envato.js/blob/master/README.md This snippet illustrates how to use 'client.catalog.getItem()' to retrieve comprehensive details for a specific item on Envato Market using its ID. The method returns 'undefined' if the item is not found, and the response allows access to properties like item ID, name, and author username. ```javascript const item = await client.catalog.getItem(123456); const itemId = item.id; const itemName = item.name; const itemAuthor = item.author_username; ``` -------------------------------- ### Envato.js Client Concurrency Control Source: https://github.com/baileyherbert/envato.js/blob/master/README.md This section describes the 'concurrency' option, which limits the number of active requests the client can handle simultaneously. The default is 3, and setting it to 0 disables throttling, also forcefully disabling rate limit handling for safety. ```APIDOC Concurrency Option: - Controls active requests (default: 3) - Setting to 0 disables throttling and 'handleRateLimits' ``` -------------------------------- ### Envato.js API Error Codes Reference Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Lists standard HTTP error codes returned by the Envato API, mapping them to specific `Envato` client error objects and their meanings. Includes notes on how `NotFoundError` is handled differently for built-in endpoint requests versus manual API calls. ```APIDOC Error Codes: 400: Envato.BadRequestError - A parameter or argument in the request was invalid or missing. 401: Envato.UnauthorizedError - The token is invalid or expired. 403: Envato.AccessDeniedError - The token does not have the required permissions. 404: Envato.NotFoundError - The requested resource was not found. 429: Envato.TooManyRequestsError - You're sending too many requests, slow down. 500: Envato.ServerError - API is down or under maintenance, try again later. Note on 404 (NotFoundError): For built-in endpoints that request a specific resource, this library will catch 404 errors and instead return `undefined` if the resource is not found. However, when sending requests manually, you will need to catch and handle any `Envato.NotFoundError` errors yourself. ``` -------------------------------- ### Handle Envato.js Client Token Renewal Event Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Demonstrates how to listen for the 'renew' event using `client.on()`. This event is triggered when the client obtains a new access token due to the previous one expiring, primarily for OAuth clients. The `data` object provides the `token` and `expiration` of the new access token. ```javascript client.on('renew', function(data) { const newAccessToken = data.token; const expiration = data.expiration; // Store the new data somewhere... // Note: The refresh token never changes }); ``` -------------------------------- ### Look up an Author's Sale by Purchase Code (Private API) Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Retrieves the detailed information of an author's sale using its unique purchase code. The 'Amount' reported is before any income tax deductions. This method returns `undefined` if no sale is found for the given code. ```js const sale = await client.private.getSale('purchase-code'); console.log('Buyer:', sale.buyer); console.log('Item:', sale.item.id, sale.item.name); ``` -------------------------------- ### Look up a user's private Envato collection Source: https://github.com/baileyherbert/envato.js/blob/master/README.md Returns details and items for a specific public or private collection of the user. Returns `undefined` if the collection is not found. ```js const { collection, items } = await client.user.getPrivateCollection(123456); console.log('Collection:', collection.id, collection.name); for (const item of items) { console.log('Item:', item.id, item.name); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.