### Run TypeScript Examples Source: https://github.com/moderation-api/sdk-typescript/blob/main/CONTRIBUTING.md Adds executable permissions to a TypeScript example file and then runs it using pnpm and tsn, allowing you to test SDK functionality against your API. Ensure the example file is placed in the 'examples/' directory. ```typescript // add an example to examples/.ts #!/usr/bin/env -S npm run tsn -T … ``` ```shell $ chmod +x examples/.ts # run the example against your api $ pnpm tsn -T examples/.ts ``` -------------------------------- ### Install SDK from Git Repository Source: https://github.com/moderation-api/sdk-typescript/blob/main/CONTRIBUTING.md Installs the SDK directly from a Git repository using npm. This is useful for directly consuming the latest changes or specific versions from the source control. ```shell $ npm install git+ssh://git@github.com:moderation-api/sdk-typescript.git ``` -------------------------------- ### Set Up Mock Server for Testing Source: https://github.com/moderation-api/sdk-typescript/blob/main/CONTRIBUTING.md Starts a mock server using Prism against your OpenAPI specification. This is a prerequisite for running most of the repository's tests, as it simulates the API's behavior. ```shell $ npx prism mock path/to/your/openapi.yml ``` -------------------------------- ### Install Dependencies and Build Project with pnpm Source: https://github.com/moderation-api/sdk-typescript/blob/main/CONTRIBUTING.md Installs all project dependencies and compiles the TypeScript code into JavaScript output files located in the 'dist/' directory. This is a foundational step for setting up the development environment. ```shell $ pnpm install $ pnpm build ``` -------------------------------- ### Format and Fix Lint Issues with pnpm Source: https://github.com/moderation-api/sdk-typescript/blob/main/CONTRIBUTING.md Applies automatic code formatting using Prettier and fixes any linting issues detected by ESLint. This command ensures the codebase adheres to the project's style guide. ```shell $ pnpm fix ``` -------------------------------- ### Run Project Tests Source: https://github.com/moderation-api/sdk-typescript/blob/main/CONTRIBUTING.md Executes the test suite for the SDK. It is recommended to have a mock server running as described in the 'Running tests' section for most tests to pass. ```shell $ pnpm run test ``` -------------------------------- ### Install Moderation API SDK Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Installs the Moderation API SDK using npm or pnpm package managers. This is the first step to integrate the SDK into your project. ```sh npm install @moderation-api/sdk # or pnpm add @moderation-api/sdk ``` -------------------------------- ### Lint Code with pnpm Source: https://github.com/moderation-api/sdk-typescript/blob/main/CONTRIBUTING.md Runs the ESLint linter to check for code style issues and potential errors across the project. This command helps maintain code quality and consistency. ```shell $ pnpm lint ``` -------------------------------- ### Link Local SDK Copy with pnpm Source: https://github.com/moderation-api/sdk-typescript/blob/main/CONTRIBUTING.md Links a local clone of the SDK repository to your project using pnpm. Similar to Yarn, this facilitates local development by creating symlinks for the SDK package. ```shell # Clone $ git clone https://www.github.com/moderation-api/sdk-typescript $ cd sdk-typescript # With pnpm $ pnpm link --global $ cd ../my-package $ pnpm link -—global @moderation-api/sdk ``` -------------------------------- ### Link Local SDK Copy with Yarn Source: https://github.com/moderation-api/sdk-typescript/blob/main/CONTRIBUTING.md Links a local clone of the SDK repository to your project using Yarn. This allows for development and testing of the SDK without publishing it, by creating a global or local symlink. ```shell # Clone $ git clone https://www.github.com/moderation-api/sdk-typescript $ cd sdk-typescript # With yarn $ yarn link $ cd ../my-package $ yarn link @moderation-api/sdk ``` -------------------------------- ### Publish NPM Package Manually Source: https://github.com/moderation-api/sdk-typescript/blob/main/CONTRIBUTING.md Manually releases the package to npm by executing a script. This requires the NPM_TOKEN environment variable to be set with valid authentication credentials. ```shell bin/publish-npm ``` -------------------------------- ### Verify Webhook Signatures using TypeScript (Next.js example) Source: https://context7.com/moderation-api/sdk-typescript/llms.txt Securely process incoming webhook events by verifying their signatures using the provided secret. This example demonstrates a Next.js API route, requiring the 'micro' package for raw body buffering. The 'MODAPI_WEBHOOK_SECRET' environment variable must be set. ```typescript import { webhooks } from '@moderation-api/sdk'; import { buffer } from 'micro'; const handler = async (req, res) => { const webhookRawBody = await buffer(req); const webhookSignatureHeader = req.headers['modapi-signature']; try { const payload = await webhooks.constructEvent( webhookRawBody, webhookSignatureHeader ); console.log('Webhook event:', payload); res.status(200).json({ received: true }); } catch (err) { console.error('Webhook signature verification failed:', err.message); res.status(400).json({ error: 'Invalid signature' }); } }; export const config = { api: { bodyParser: false, }, }; export default handler; ``` -------------------------------- ### TypeScript: Accessing Raw Response Data Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Explains how to use `.asResponse()` to get the raw `Response` object for custom parsing or streaming, and `.withResponse()` to get both the parsed data and the raw `Response`. ```typescript const client = new ModerationAPI(); const response = await client.content.submit({ content: { text: 'x', type: 'text' } }).asResponse(); console.log(response.headers.get('X-My-Header')); console.log(response.statusText); const { data: response, response: raw } = await client.content .submit({ content: { text: 'x', type: 'text' } }) .withResponse(); console.log(raw.headers.get('X-My-Header')); console.log(response.recommendation); ``` -------------------------------- ### Configure Proxy for Moderation API SDK (Bun) Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Demonstrates setting up proxy configurations for the Moderation API SDK when using Bun. The `proxy` option is directly provided within the `fetchOptions` object. ```typescript import ModerationAPI from '@moderation-api/sdk'; const client = new ModerationAPI({ fetchOptions: { proxy: 'http://localhost:8888', }, }); ``` -------------------------------- ### List Accounts via SDK Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md This snippet shows how to list accounts using the SDK. The `list` method retrieves a list of accounts and returns an `AccountListResponse`. ```typescript import { ModerationAPIClient } from '@moderation/api-sdk-typescript'; const client = new ModerationAPIClient({ apiKey: 'YOUR_API_KEY' }); // List accounts client.account.list().then(response => { // Handle AccountListResponse }); ``` -------------------------------- ### Add Undocumented Parameters to Moderation API SDK Requests (TypeScript) Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Explains how to include undocumented parameters in requests made with the Moderation API SDK. This is achieved using `// @ts-expect-error` to bypass type checking. Extra parameters are sent in the query for GET requests and in the body for others, or explicitly via `query`, `body`, and `headers` options. ```typescript client.content.submit({ // ... // @ts-expect-error baz is not yet public baz: 'undocumented option', }); ``` -------------------------------- ### Configure Proxy with Deno for Moderation API SDK (Deno) Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Explains how to configure proxy settings for the Moderation API SDK within a Deno environment. It involves creating a `Deno.HttpClient` with proxy settings and passing it via `fetchOptions.client`. ```typescript import ModerationAPI from 'npm:@moderation-api/sdk'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const client = new ModerationAPI({ fetchOptions: { client: httpClient, }, }); ``` -------------------------------- ### Initialize Moderation API Client (TypeScript/JavaScript) Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Demonstrates how to instantiate the ModerationAPI client. It can be configured using the MODAPI_SECRET_KEY environment variable (recommended) or by explicitly passing the secret key during instantiation. The explicit key overrides the environment variable. ```javascript import ModerationAPI from '@moderation-api/sdk'; // Option 1: Use environment variable MODAPI_SECRET_KEY const moderationApi = new ModerationAPI(); // Option 2: Pass key explicitly (overrides environment variable) const moderationApi = new ModerationAPI({ secretKey: 'proj_...', }); ``` -------------------------------- ### Configure Custom Fetch and Debug Logging in TypeScript Source: https://context7.com/moderation-api/sdk-typescript/llms.txt This snippet demonstrates how to initialize the Moderation API client with custom fetch options and enable debug logging using Pino. It shows how to access both the parsed response data and the raw HTTP response, including headers and status. ```typescript import ModerationAPI from '@moderation-api/sdk'; import pino from 'pino'; const logger = pino(); const client = new ModerationAPI({ secretKey: 'proj_...', logLevel: 'debug', // 'debug' | 'info' | 'warn' | 'error' | 'off' logger: logger.child({ name: 'ModerationAPI' }), fetchOptions: { // Custom fetch options headers: { 'X-Custom-Header': 'value', }, }, }); // Access raw response const response = await client.content .submit({ content: { type: 'text', text: 'Test' } }) .asResponse(); console.log('Status:', response.status); console.log('Headers:', response.headers.get('X-My-Header')); // Get both parsed data and raw response const { data, response: raw } = await client.content .submit({ content: { type: 'text', text: 'Test' } }) .withResponse(); console.log('Data:', data.recommendation.action); console.log('Raw status:', raw.status); ``` -------------------------------- ### Execute Actions via SDK Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md This snippet shows how to execute actions using the SDK. It supports executing actions with parameters and executing a specific action by its ID. Each execution method returns a distinct response type. ```typescript import { ModerationAPIClient } from '@moderation/api-sdk-typescript'; const client = new ModerationAPIClient({ apiKey: 'YOUR_API_KEY' }); // Execute an action with parameters client.actions.execute.execute({ ...params }).then(response => { // Handle ExecuteExecuteResponse }); // Execute a specific action by ID client.actions.execute.executeByID('actionId', { ...params }).then(response => { // Handle ExecuteExecuteByIDResponse }); ``` -------------------------------- ### Configure Proxy with Undici for Moderation API SDK (Node.js) Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Shows how to configure proxy settings for the Moderation API SDK when using Node.js with the `undici` library. A `ProxyAgent` is instantiated and passed via the `fetchOptions.dispatcher` property. ```typescript import ModerationAPI from '@moderation-api/sdk'; import * as undici from 'undici'; const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const client = new ModerationAPI({ fetchOptions: { dispatcher: proxyAgent, }, }); ``` -------------------------------- ### Submit Content via SDK Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md This snippet demonstrates submitting content for moderation using the SDK. The `submit` method takes parameters and returns a `ContentSubmitResponse` upon successful submission. ```typescript import { ModerationAPIClient } from '@moderation/api-sdk-typescript'; const client = new ModerationAPIClient({ apiKey: 'YOUR_API_KEY' }); // Submit content for moderation client.content.submit({ ...params }).then(response => { // Handle ContentSubmitResponse }); ``` -------------------------------- ### Integrate Custom Logger with Moderation API SDK (TypeScript) Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Demonstrates how to integrate a custom logger, such as pino, with the Moderation API SDK. The SDK defaults to `globalThis.console` but supports various logging libraries. The `logLevel` option controls which messages are sent to the custom logger. ```typescript import ModerationAPI from '@moderation-api/sdk'; import pino from 'pino'; const logger = pino(); const client = new ModerationAPI({ logger: logger.child({ name: 'ModerationAPI' }), logLevel: 'debug', // Send all messages to pino, allowing it to filter }); ``` -------------------------------- ### Manage Queue Items via SDK Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md This snippet demonstrates how to manage items within a queue. It supports listing items, resolving them, and unresolving them. Each operation returns a specific response type. ```typescript import { ModerationAPIClient } from '@moderation/api-sdk-typescript'; const client = new ModerationAPIClient({ apiKey: 'YOUR_API_KEY' }); // List items in a queue client.queue.items.list('queueId', { ...params }).then(response => { // Handle ItemListResponse }); // Resolve an item client.queue.items.resolve('queueId', 'itemId', { ...params }).then(response => { // Handle ItemResolveResponse }); // Unresolve an item client.queue.items.unresolve('queueId', 'itemId', { ...params }).then(response => { // Handle ItemUnresolveResponse }); ``` -------------------------------- ### TypeScript: Configuring Request Timeouts Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Demonstrates how to set a default timeout for all API requests and how to override it for individual requests. The `timeout` option is specified in milliseconds. ```typescript // Configure the default for all requests: const client = new ModerationAPI({ timeout: 20 * 1000, // 20 seconds (default is 1 minute) }); // Override per-request: await client.content.submit({ content: { text: 'x', type: 'text' } }, { timeout: 5 * 1000, }); ``` -------------------------------- ### Manage Authors via SDK Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md This snippet demonstrates how to interact with the authors' resource using the SDK. It supports creating, retrieving, updating, listing, and deleting authors. The methods return specific response types for each operation. ```typescript import { ModerationAPIClient } from '@moderation/api-sdk-typescript'; const client = new ModerationAPIClient({ apiKey: 'YOUR_API_KEY' }); // Create an author client.authors.create({ ...params }).then(response => { // Handle AuthorCreateResponse }); // Retrieve an author client.authors.retrieve('authorId').then(response => { // Handle AuthorRetrieveResponse }); // Update an author client.authors.update('authorId', { ...params }).then(response => { // Handle AuthorUpdateResponse }); // List authors client.authors.list({ ...params }).then(response => { // Handle AuthorListResponse }); // Delete an author client.authors.delete('authorId').then(response => { // Handle AuthorDeleteResponse }); ``` -------------------------------- ### TypeScript: Submit Content and Handle Response Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Demonstrates how to import the ModerationAPI client, instantiate it, define request parameters, submit content, and process the response using TypeScript type definitions. ```typescript import ModerationAPI from '@moderation-api/sdk'; const client = new ModerationAPI(); const params: ModerationAPI.ContentSubmitParams = { content: { text: 'x', type: 'text' } }; const response: ModerationAPI.ContentSubmitResponse = await client.content.submit(params); ``` -------------------------------- ### Manage Actions via SDK Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md This snippet illustrates actions management using the SDK. It provides functionality for creating, retrieving, updating, listing, and deleting actions. Each method returns a corresponding response type. ```typescript import { ModerationAPIClient } from '@moderation/api-sdk-typescript'; const client = new ModerationAPIClient({ apiKey: 'YOUR_API_KEY' }); // Create an action client.actions.create({ ...params }).then(response => { // Handle ActionCreateResponse }); // Retrieve an action client.actions.retrieve('actionId').then(response => { // Handle ActionRetrieveResponse }); // Update an action client.actions.update('actionId', { ...params }).then(response => { // Handle ActionUpdateResponse }); // List actions client.actions.list({ ...params }).then(response => { // Handle ActionListResponse }); // Delete an action client.actions.delete('actionId').then(response => { // Handle ActionDeleteResponse }); ``` -------------------------------- ### Manage Queue via SDK Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md This snippet covers queue management operations. It allows retrieving queue details and statistics. The methods return specific response types for each operation. ```typescript import { ModerationAPIClient } from '@moderation/api-sdk-typescript'; const client = new ModerationAPIClient({ apiKey: 'YOUR_API_KEY' }); // Retrieve queue details client.queue.retrieve('queueId').then(response => { // Handle QueueRetrieveResponse }); // Get queue statistics client.queue.getStats('queueId', { ...params }).then(response => { // Handle QueueGetStatsResponse }); ``` -------------------------------- ### Customize Fetch Client in Moderation API SDK (TypeScript) Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Provides methods to customize the `fetch` client used by the Moderation API SDK. You can either polyfill the global `fetch` function or pass a custom `fetch` implementation directly to the SDK client during instantiation. ```typescript import fetch from 'my-fetch'; globalThis.fetch = fetch; ``` ```typescript import ModerationAPI from '@moderation-api/sdk'; import fetch from 'my-fetch'; const client = new ModerationAPI({ fetch }); ``` -------------------------------- ### Moderate Images, Video, and Audio using Moderation API SDK Source: https://context7.com/moderation-api/sdk-typescript/llms.txt Analyzes multimedia content (images, videos, audio) by providing public URLs. This function requires the '@moderation-api/sdk' package and accepts content with a 'url' property. The results include evaluation flags and severity scores. ```typescript // Image moderation const imageResult = await moderationApi.content.submit({ content: { type: 'image', url: 'https://example.com/user-upload.jpg', }, contentId: 'img_789', authorId: 'user_123', metaType: 'profile', }); // Video moderation const videoResult = await moderationApi.content.submit({ content: { type: 'video', url: 'https://example.com/video-upload.mp4', }, metaType: 'post', }); // Audio moderation const audioResult = await moderationApi.content.submit({ content: { type: 'audio', url: 'https://example.com/audio-message.mp3', }, }); console.log(`Flagged: ${imageResult.evaluation.flagged}`); console.log(`Severity Score: ${imageResult.evaluation.severity_score}`); ``` -------------------------------- ### Account API Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md Endpoint for listing account information. ```APIDOC ## GET /account ### Description Retrieves a list of account information. ### Method GET ### Endpoint /account ### Response #### Success Response (200) - **AccountListResponse** (object) - The response object containing account information. ### Response Example ```json { "AccountListResponse": { ... } } ``` ``` -------------------------------- ### Submit Text for Moderation using Moderation API SDK Source: https://context7.com/moderation-api/sdk-typescript/llms.txt Analyzes text content for policy violations and provides moderation recommendations. It requires the '@moderation-api/sdk' package and accepts parameters like content, contentId, authorId, conversationId, metaType, and metadata. The result includes a recommendation action (reject, review, approve), detailed policy results, and insights like sentiment and language. ```typescript import ModerationAPI from '@moderation-api/sdk'; const moderationApi = new ModerationAPI({ secretKey: 'proj_...', // or use MODAPI_SECRET_KEY env variable }); // Text moderation with full context const result = await moderationApi.content.submit({ content: { type: 'text', text: 'This is some user-generated content to moderate', }, contentId: 'msg_12345', authorId: 'user_67890', conversationId: 'room_abc123', metaType: 'message', metadata: { platform: 'mobile', version: '2.1.0' }, }); // Handle the response using recommendation if (result.recommendation.action === 'reject') { console.log('Content blocked:', result.recommendation.reason_codes); // Block content from being published } else if (result.recommendation.action === 'review') { console.log('Content flagged for manual review'); // Send to moderation queue } else { console.log('Content approved'); // Publish content } // Access detailed policy results result.policies.forEach((policy) => { if (policy.flagged) { console.log(`Policy: ${policy.id}`); console.log(`Probability: ${policy.probability}`); if (policy.type === 'classifier' && policy.labels) { policy.labels.forEach(label => { console.log(` Label: ${label.id} - ${label.probability}`); }); } } }); // Check insights (sentiment, language) result.insights.forEach((insight) => { if (insight.id === 'sentiment') { console.log(`Sentiment: ${insight.value} (${insight.probability})`); } else if (insight.id === 'language') { console.log(`Language: ${insight.value}`); } }); ``` -------------------------------- ### Submit Content for Moderation Source: https://context7.com/moderation-api/sdk-typescript/llms.txt Analyze text, images, video, audio, or complex objects for policy violations and receive detailed recommendations. This endpoint can be used to moderate various content types including text, images, videos, audio, and complex objects. ```APIDOC ## POST /content/submit ### Description Analyze text, images, video, audio, or complex objects for policy violations and receive detailed recommendations. ### Method POST ### Endpoint /content/submit ### Parameters #### Request Body - **content** (object) - Required - The content to moderate. Can be text, image, video, audio, or object type. - **type** (string) - Required - The type of content ('text', 'image', 'video', 'audio', 'object'). - **text** (string) - Optional - The text content. - **url** (string) - Optional - The URL of the image, video, or audio content. - **data** (object) - Optional - For 'object' type, a map of field names to content objects. - **contentId** (string) - Optional - An identifier for the content. - **authorId** (string) - Optional - An identifier for the author of the content. - **conversationId** (string) - Optional - An identifier for the conversation the content belongs to. - **metaType** (string) - Optional - The type of metadata associated with the content (e.g., 'message', 'profile', 'post'). - **metadata** (object) - Optional - Additional metadata key-value pairs. ### Request Example ```json { "content": { "type": "text", "text": "This is some user-generated content to moderate" }, "contentId": "msg_12345", "authorId": "user_67890", "conversationId": "room_abc123", "metaType": "message", "metadata": { "platform": "mobile", "version": "2.1.0" } } ``` ### Response #### Success Response (200) - **recommendation** (object) - The overall recommendation for the content. - **action** (string) - The recommended action ('accept', 'reject', 'review'). - **reason_codes** (array of strings) - Codes indicating the reason for the action. - **policies** (array of objects) - Detailed results for each moderation policy. - **id** (string) - The ID of the policy. - **flagged** (boolean) - Whether the content was flagged by this policy. - **probability** (number) - The probability of the content violating the policy. - **type** (string) - The type of policy ('classifier', 'entity', 'profanity'). - **labels** (array of objects) - For 'classifier' type, detailed labels and their probabilities. - **flagged_fields** (array of strings) - For 'object' type, fields flagged by this policy. - **insights** (array of objects) - Analysis insights such as sentiment and language detection. - **id** (string) - The ID of the insight (e.g., 'sentiment', 'language'). - **value** (string) - The detected value. - **probability** (number) - The probability of the detected value. - **evaluation** (object) - General evaluation metrics for multimedia content. - **flagged** (boolean) - Whether the content was flagged. - **severity_score** (number) - A score indicating the severity of the flagged content. - **content** (object) - Information about the processed content, potentially modified. - **masked** (boolean) - Whether the content was masked or modified. - **modified** (object) - The modified content. #### Response Example ```json { "recommendation": { "action": "reject", "reason_codes": ["PROFANITY", "HATE_SPEECH"] }, "policies": [ { "id": "toxicity_v1", "flagged": true, "probability": 0.95, "type": "classifier", "labels": [ { "id": "toxic", "probability": 0.98 }, { "id": "insult", "probability": 0.75 } ] } ], "insights": [ { "id": "language", "value": "en", "probability": 1.0 }, { "id": "sentiment", "value": "negative", "probability": 0.88 } ] } ``` ``` -------------------------------- ### TypeScript: Handling API Errors Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Illustrates how to catch and handle various API errors thrown by the SDK. It shows how to check if an error is an instance of ModerationAPI.APIError and access properties like status, name, and headers. ```typescript const response = await client.content.submit({ content: { text: 'x', type: 'text' } }).catch(async (err) => { if (err instanceof ModerationAPI.APIError) { console.log(err.status); console.log(err.name); console.log(err.headers); } else { throw err; } }); ``` -------------------------------- ### Configure Fetch Options for Moderation API SDK (TypeScript) Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Details how to set custom `fetch` options for the Moderation API SDK, either globally during client instantiation or on a per-request basis. These options can override default behaviors and are useful for configuring aspects like proxies. ```typescript import ModerationAPI from '@moderation-api/sdk'; const client = new ModerationAPI({ fetchOptions: { // `RequestInit` options }, }); ``` -------------------------------- ### List and Query Authors with Pagination - TypeScript Source: https://context7.com/moderation-api/sdk-typescript/llms.txt Retrieves a paginated list of authors, allowing for sorting by trust level and filtering by the last active date. The output includes author names, trust levels, flagged content ratios, and pagination details like total count and next page availability. Dependencies include the initialized 'moderationApi' object. ```typescript const authorsList = await moderationApi.authors.list({ pageNumber: 1, pageSize: 20, sortBy: 'trustLevel', sortDirection: 'desc', lastActiveDate: '2024-01-01', }); authorsList.authors.forEach((author) => { console.log(`${author.name} - Trust: ${author.trust_level.level}`); console.log(` Flagged ratio: ${author.metrics.flagged_content}/${author.metrics.total_content}`); if (author.risk_evaluation?.risk_level) { console.log(` Risk level: ${author.risk_evaluation.risk_level}`); } if (author.block) { console.log(` Blocked: ${author.block.reason}`); } }); console.log(`Total: ${authorsList.pagination.total}`); console.log(`Has next page: ${authorsList.pagination.hasNextPage}`); ``` -------------------------------- ### List and Retrieve Wordlists - TypeScript Source: https://context7.com/moderation-api/sdk-typescript/llms.txt Fetches a list of all available custom wordlists, displaying their names, IDs, descriptions, and creation dates. It also shows how to retrieve a specific wordlist by its ID, including its name, the words it contains, and its strict mode setting. This functionality relies on the initialized 'moderationApi' object. ```typescript // List all wordlists const wordlists = await moderationApi.wordlist.list(); wordlists.forEach((list) => { console.log(`${list.name} (${list.id})`); console.log(` Description: ${list.description}`); console.log(` Created: ${list.createdAt}`); }); // Get a specific wordlist const wordlist = await moderationApi.wordlist.retrieve('wordlist_id'); console.log(`Name: ${wordlist.name}`); console.log(`Words: ${wordlist.words.join(', ')}`); console.log(`Strict mode: ${wordlist.strict}`); ``` -------------------------------- ### Queue Items API Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md Endpoints for managing items within a queue, including listing items and resolving/unresolving them. ```APIDOC ## GET /queue/{id}/items ### Description Retrieves a list of items within a specific queue. ### Method GET ### Endpoint /queue/{id}/items ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the queue whose items to list. #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination. ### Response #### Success Response (200) - **ItemListResponse** (object) - The response object containing a list of items. ### Response Example ```json { "ItemListResponse": { ... } } ``` ## POST /queue/{id}/items/{itemId}/resolve ### Description Resolves a specific item within a queue. ### Method POST ### Endpoint /queue/{id}/items/{itemId}/resolve ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the queue. - **itemId** (string) - Required - The ID of the item to resolve. #### Request Body - **params** (object) - Optional - Parameters for resolving the item. ### Request Example ```json { "params": { ... } } ``` ### Response #### Success Response (200) - **ItemResolveResponse** (object) - The response object for item resolution. ### Response Example ```json { "ItemResolveResponse": { ... } } ``` ## POST /queue/{id}/items/{itemId}/unresolve ### Description Unresolves a specific item within a queue. ### Method POST ### Endpoint /queue/{id}/items/{itemId}/unresolve ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the queue. - **itemId** (string) - Required - The ID of the item to unresolve. #### Request Body - **params** (object) - Optional - Parameters for unresolving the item. ### Request Example ```json { "params": { ... } } ``` ### Response #### Success Response (200) - **ItemUnresolveResponse** (object) - The response object for item unresolution. ### Response Example ```json { "ItemUnresolveResponse": { ... } } ``` ``` -------------------------------- ### Create Author with Metadata - TypeScript Source: https://context7.com/moderation-api/sdk-typescript/llms.txt Creates a new author in the system, including details like name, email, profile picture, and custom metadata. It outputs the author's ID, trust level, status, and content metrics. This function requires the 'moderationApi' object to be initialized. ```typescript const author = await moderationApi.authors.create({ external_id: 'user_abc123', name: 'John Doe', email: 'john@example.com', profile_picture: 'https://example.com/avatar.jpg', external_link: 'https://example.com/users/johndoe', metadata: { email_verified: true, phone_verified: true, is_paying_customer: true, identity_verified: false, }, }); console.log(`Author ID: ${author.id}`); console.log(`Trust Level: ${author.trust_level.level}`); console.log(`Status: ${author.status}`); console.log(`Metrics: ${author.metrics.total_content} content, ${author.metrics.flagged_content} flagged`); ``` -------------------------------- ### Execute Actions API Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md Endpoints for executing actions, either generally or by specific action ID. ```APIDOC ## POST /actions/execute ### Description Executes a general action. ### Method POST ### Endpoint /actions/execute ### Parameters #### Request Body - **params** (object) - Required - Parameters for executing the action. ### Request Example ```json { "params": { ... } } ``` ### Response #### Success Response (200) - **ExecuteExecuteResponse** (object) - The response object for general action execution. ### Response Example ```json { "ExecuteExecuteResponse": { ... } } ``` ## POST /actions/{actionId}/execute ### Description Executes a specific action by its ID. ### Method POST ### Endpoint /actions/{actionId}/execute ### Parameters #### Path Parameters - **actionId** (string) - Required - The ID of the action to execute. #### Request Body - **params** (object) - Required - Parameters for executing the action. ### Request Example ```json { "params": { ... } } ``` ### Response #### Success Response (200) - **ExecuteExecuteByIDResponse** (object) - The response object for executing a specific action. ### Response Example ```json { "ExecuteExecuteByIDResponse": { ... } } ``` ``` -------------------------------- ### TypeScript: Setting Log Level Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Shows how to configure the logging level for the Moderation API SDK using the `logLevel` client option. This overrides the `MODERATION_API_LOG` environment variable. ```typescript import ModerationAPI from '@moderation-api/sdk'; const client = new ModerationAPI({ logLevel: 'debug', // Show all log messages }); ``` -------------------------------- ### Queue API Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md Endpoints for managing the moderation queue, including retrieving queue details and statistics. ```APIDOC ## GET /queue/{id} ### Description Retrieves details of a specific queue by its ID. ### Method GET ### Endpoint /queue/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the queue to retrieve. ### Response #### Success Response (200) - **QueueRetrieveResponse** (object) - The response object for retrieving queue details. ### Response Example ```json { "QueueRetrieveResponse": { ... } } ``` ## GET /queue/{id}/stats ### Description Retrieves statistics for a specific queue by its ID. ### Method GET ### Endpoint /queue/{id}/stats ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the queue to get statistics for. #### Query Parameters - **params** (object) - Optional - Parameters for statistics retrieval. ### Response #### Success Response (200) - **QueueGetStatsResponse** (object) - The response object for queue statistics. ### Response Example ```json { "QueueGetStatsResponse": { ... } } ``` ``` -------------------------------- ### Monitor Moderation Queues using TypeScript Source: https://context7.com/moderation-api/sdk-typescript/llms.txt Retrieve queue statistics and review metrics, including total items, unresolved items, resolved items, and detailed statistics like average review time and top reviewers. This function requires a 'queue_id' as input. ```typescript const queue = await moderationApi.queue.retrieve('queue_id'); console.log(`Queue: ${queue.queue.name}`); console.log(`Description: ${queue.queue.description}`); console.log(`Total items: ${queue.queue.totalItemsCount}`); console.log(`Unresolved: ${queue.queue.unresolvedItemsCount}`); console.log(`Resolved: ${queue.queue.resolvedItemsCount}`); const stats = await moderationApi.queue.getStats('queue_id', { withinDays: '30', }); console.log(`Average review time: ${stats.reviewStats.averageTimeToReview}ms`); console.log(`Total pending: ${stats.reviewStats.totalPending}`); console.log(`Total reviewed: ${stats.reviewStats.totalReviewed}`); stats.actionStats.forEach((action) => { console.log(`${action.actionName}: ${action.count} (${action.percentageOfTotal}%)`); }); stats.topReviewers.forEach((reviewer) => { console.log(`${reviewer.name}: ${reviewer.reviewCount} reviews`); console.log(` Avg time: ${reviewer.averageTimePerReview}ms`); if (reviewer.accuracyScore) { console.log(` Accuracy: ${reviewer.accuracyScore}`); } }); ``` -------------------------------- ### JavaScript/TypeScript: Configuring Retries Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Shows how to configure the default number of retries for all requests or override it on a per-request basis. Setting `maxRetries` to 0 disables retries. ```javascript // Configure the default for all requests: const client = new ModerationAPI({ maxRetries: 0, // default is 2 }); // Or, configure per-request: await client.content.submit({ content: { text: 'x', type: 'text' } }, { maxRetries: 5, }); ``` -------------------------------- ### Actions API Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md Endpoints for managing actions, including creating, retrieving, updating, listing, and deleting actions. ```APIDOC ## POST /actions ### Description Creates a new action. ### Method POST ### Endpoint /actions ### Parameters #### Request Body - **params** (object) - Required - Action creation parameters. ### Request Example ```json { "params": { ... } } ``` ### Response #### Success Response (200) - **ActionCreateResponse** (object) - The response object for action creation. ### Response Example ```json { "ActionCreateResponse": { ... } } ``` ## GET /actions/{id} ### Description Retrieves a specific action by its ID. ### Method GET ### Endpoint /actions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the action to retrieve. ### Response #### Success Response (200) - **ActionRetrieveResponse** (object) - The response object for retrieving an action. ### Response Example ```json { "ActionRetrieveResponse": { ... } } ``` ## PUT /actions/{id} ### Description Updates an existing action by its ID. ### Method PUT ### Endpoint /actions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the action to update. #### Request Body - **params** (object) - Required - Action update parameters. ### Request Example ```json { "params": { ... } } ``` ### Response #### Success Response (200) - **ActionUpdateResponse** (object) - The response object for action update. ### Response Example ```json { "ActionUpdateResponse": { ... } } ``` ## GET /actions ### Description Retrieves a list of actions. ### Method GET ### Endpoint /actions ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination. ### Response #### Success Response (200) - **ActionListResponse** (object) - The response object containing a list of actions. ### Response Example ```json { "ActionListResponse": { ... } } ``` ## DELETE /actions/{id} ### Description Deletes a specific action by its ID. ### Method DELETE ### Endpoint /actions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the action to delete. ### Response #### Success Response (200) - **ActionDeleteResponse** (object) - The response object for action deletion. ### Response Example ```json { "ActionDeleteResponse": { ... } } ``` ``` -------------------------------- ### Wordlist API Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md Endpoints for managing wordlists, including retrieval, update, and listing. ```APIDOC ## GET /wordlist/{id} ### Description Retrieves a specific wordlist by its ID. ### Method GET ### Endpoint /wordlist/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the wordlist. ### Request Example ```json { "example": "No request body required." } ``` ### Response #### Success Response (200) - **WordlistRetrieveResponse** (object) - Contains the details of the retrieved wordlist. #### Response Example ```json { "example": "{\"id\": \"your_wordlist_id\", \"name\": \"example_list\"}" } ``` ``` ```APIDOC ## PUT /wordlist/{id} ### Description Updates an existing wordlist identified by its ID. ### Method PUT ### Endpoint /wordlist/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the wordlist to update. #### Request Body - **params** (object) - Required - An object containing the fields to update. ### Request Example ```json { "example": "{\"params\": { \"name\": \"updated_list_name\" }}" } ``` ### Response #### Success Response (200) - **WordlistUpdateResponse** (object) - Contains the result of the update operation. #### Response Example ```json { "example": "{\"success\": true}" } ``` ``` ```APIDOC ## GET /wordlist ### Description Retrieves a list of all available wordlists. ### Method GET ### Endpoint /wordlist ### Parameters None ### Request Example ```json { "example": "No request body required." } ``` ### Response #### Success Response (200) - **WordlistListResponse** (object) - Contains a list of wordlists. #### Response Example ```json { "example": "{\"wordlists\": [ { \"id\": \"list_id_1\", \"name\": \"list_name_1\" } ]}" } ``` ``` ```APIDOC ## GET /wordlist/{id}/embedding-status ### Description Retrieves the embedding status for a specific wordlist. ### Method GET ### Endpoint /wordlist/{id}/embedding-status ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the wordlist. ### Request Example ```json { "example": "No request body required." } ``` ### Response #### Success Response (200) - **WordlistGetEmbeddingStatusResponse** (object) - Contains the embedding status of the wordlist. #### Response Example ```json { "example": "{\"status\": \"completed\"}" } ``` ``` -------------------------------- ### Manage Moderation Queue Items using TypeScript Source: https://context7.com/moderation-api/sdk-typescript/llms.txt Perform operations on moderation queue items, including listing items with pagination, resolving items with optional actions, and unresolving items. Requires 'queue_id' and 'item_id' for most operations. The 'resolved' parameter filters list results. ```typescript const items = await moderationApi.queue.items.list('queue_id', { pageNumber: 1, pageSize: 50, resolved: false, }); items.items.forEach((item) => { console.log(`Item: ${item.id}`); console.log(` Created: ${new Date(item.createdAt * 1000)}`); console.log(` Resolved: ${item.resolved}`); }); console.log(`Total: ${items.pagination.total}`); const resolveResult = await moderationApi.queue.items.resolve('item_id', { queue_id: 'queue_id', action_id: 'action_id', // Optional action to apply }); console.log(`Resolved: ${resolveResult.success}`); const unresolveResult = await moderationApi.queue.items.unresolve('item_id', { queue_id: 'queue_id', }); console.log(`Unresolved: ${unresolveResult.success}`); ``` -------------------------------- ### Auth API Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md Endpoints for managing authentication with the Moderation API. ```APIDOC ## POST /auth ### Description Creates authentication credentials for the Moderation API. ### Method POST ### Endpoint /auth ### Parameters None ### Request Example ```json { "example": "No request body required." } ``` ### Response #### Success Response (200) - **AuthCreateResponse** (object) - Contains authentication details. #### Response Example ```json { "example": "{\"token\": \"your_auth_token\"}" } ``` ``` ```APIDOC ## GET /auth ### Description Retrieves authentication status or details. ### Method GET ### Endpoint /auth ### Parameters None ### Request Example ```json { "example": "No request body required." } ``` ### Response #### Success Response (200) - **AuthRetrieveResponse** (object) - Contains authentication retrieval details. #### Response Example ```json { "example": "{\"status\": \"authenticated\"}" } ``` ``` -------------------------------- ### Words API Source: https://github.com/moderation-api/sdk-typescript/blob/main/api.md Endpoints for managing individual words within a wordlist. ```APIDOC ## POST /wordlist/{id}/words ### Description Adds a new word to a specific wordlist. ### Method POST ### Endpoint /wordlist/{id}/words ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the wordlist to which the word will be added. #### Request Body - **params** (object) - Required - An object containing the word to add. ### Request Example ```json { "example": "{\"params\": { \"word\": \"new_word\" }}" } ``` ### Response #### Success Response (200) - **WordAddResponse** (object) - Contains the result of the word addition operation. #### Response Example ```json { "example": "{\"success\": true}" } ``` ``` ```APIDOC ## DELETE /wordlist/{id}/words ### Description Removes a word from a specific wordlist. ### Method DELETE ### Endpoint /wordlist/{id}/words ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the wordlist from which the word will be removed. #### Request Body - **params** (object) - Required - An object containing the word to remove. ### Request Example ```json { "example": "{\"params\": { \"word\": \"word_to_remove\" }}" } ``` ### Response #### Success Response (200) - **WordRemoveResponse** (object) - Contains the result of the word removal operation. #### Response Example ```json { "example": "{\"success\": true}" } ``` ``` -------------------------------- ### Make Undocumented POST Requests with Moderation API SDK (TypeScript) Source: https://github.com/moderation-api/sdk-typescript/blob/main/README.md Shows how to make requests to undocumented endpoints using HTTP verbs like `post`. The SDK respects client options such as retries for these requests. This method is useful for accessing features not yet exposed in the public API. ```typescript await client.post('/some/path', { body: { some_prop: 'foo' }, query: { some_query_arg: 'bar' }, }); ```