### Jira.js - Core Functionality Source: https://context7.com/context7/mrrefactoring_github_io-jira.js/llms.txt This section details the core functionality and setup for using the Jira.js library, including installation and client initialization with different authentication methods. ```APIDOC ## Installation ### Using npm ```bash npm install jira.js ``` ### Using yarn ```bash yarn add jira.js ``` ### Using pnpm ```bash pnpm add jira.js ``` ## Basic Setup with Basic Authentication (API Token) ### Description Initializes the Jira.js client using basic authentication with an email and an API token. This is a common method for server-to-server integrations. ### Method Instantiation ### Endpoint N/A (Client-side configuration) ### Parameters #### Client Configuration - **host** (string) - Required - The Jira Cloud instance URL (e.g., `https://your-domain.atlassian.net`). - **authentication** (object) - Required - Authentication configuration. - **basic** (object) - Required - Basic authentication details. - **email** (string) - Required - The email address associated with the Jira account. - **apiToken** (string) - Required - The API token generated from Atlassian account settings. - **noCheckAtlassianToken** (boolean) - Optional - Set to `true` to add the `X-Atlassian-Token: no-check` header. Defaults to `false`. - **strictGDPR** (boolean) - Optional - Enables GDPR compliance features. Defaults to `false`. ### Request Example ```typescript import { Version3Client } from 'jira.js'; const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'your@email.com', apiToken: 'YOUR_API_TOKEN' } }, noCheckAtlassianToken: false, strictGDPR: false }); ``` ### Response #### Success Response A configured `Version3Client` instance is returned, ready to make API calls. #### Response Example ```typescript // Client instance is ready for use const myself = await client.myself.getCurrentUser(); console.log(myself); ``` ## Setup with OAuth 2.0 Authentication ### Description Initializes the Jira.js client using OAuth 2.0 authentication. This requires a pre-existing OAuth access token obtained through a separate authorization flow. ### Method Instantiation ### Endpoint N/A (Client-side configuration) ### Parameters #### Client Configuration - **host** (string) - Required - The Jira Cloud instance URL (e.g., `https://your-domain.atlassian.net`). - **authentication** (object) - Required - Authentication configuration. - **oauth2** (object) - Required - OAuth 2.0 details. - **accessToken** (string) - Required - The OAuth 2.0 access token. ### Request Example ```typescript import { Version3Client } from 'jira.js'; const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { oauth2: { accessToken: 'YOUR_OAUTH_ACCESS_TOKEN' } } }); // Function to update the access token when it expires function updateAccessToken(newToken: string) { const updatedClient = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { oauth2: { accessToken: newToken } } }); return updatedClient; } ``` ### Response #### Success Response A configured `Version3Client` instance is returned, ready to make API calls. #### Response Example ```typescript // Client instance is ready for use const projects = await client.projects.getProjects(); console.log(projects); ``` ``` -------------------------------- ### Basic Setup and Initialization of Jira.js Client Source: https://context7.com/context7/mrrefactoring_github_io-jira.js/llms.txt Demonstrates how to initialize the Jira.js `Version3Client` using basic authentication with an API token. This setup is the first step to interacting with Jira Cloud APIs from your application. ```typescript import { Version3Client } from 'jira.js'; const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'your@email.com', apiToken: 'YOUR_API_TOKEN' } } }); // Now you can use client.projects, client.issues, client.boards, etc. ``` -------------------------------- ### Jira API Access Example Source: https://mrrefactoring.github.io/jira.js/index Demonstrates how to access Jira API endpoints using the client.. pattern. It shows examples for searching projects and creating sprints. This requires an initialized Jira client. ```javascript // Get all projects const projects = await client.projects.searchProjects(); // Create a sprint const sprint = await client.sprint.createSprint({ name: 'Q4 Sprint' }); ``` -------------------------------- ### Install Jira.js using npm, yarn, or pnpm Source: https://mrrefactoring.github.io/jira.js/index Instructions for installing the jira.js library using popular package managers like npm, yarn, and pnpm. Requires Node.js version 20.0.0 or newer. ```bash # Using npm npm install jira.js # Using yarn yarn add jira.js # Using pnpm pnpm add jira.js ``` -------------------------------- ### Create, Get, and Update Jira Projects with jira.js Source: https://context7.com/context7/mrrefactoring_github_io-jira.js/llms.txt This snippet provides examples for managing Jira projects using the jira.js client. It covers creating a new project, retrieving a list of all projects, fetching details for a specific project, and updating an existing project. Authentication requires Jira host, email, and API token. Functions accept project keys or details as input and return project data or void. ```typescript import { Version3Client } from 'jira.js'; const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'your@email.com', apiToken: 'YOUR_API_TOKEN' } } }); async function createProject() { const project = await client.projects.createProject({ key: 'NEWPROJ', name: 'New Project', projectTypeKey: 'software', projectTemplateKey: 'com.pyxis.greenhopper.jira:gh-simplified-agility-kanban', description: 'This is a new software project', leadAccountId: '5b10ac8d82e05b22cc7d4ef5' }); console.log(`Created project: ${project.key}`); return project; } async function getAllProjects() { const projects = await client.projects.searchProjects({ expand: ['description', 'lead', 'url'], maxResults: 100 }); projects.values?.forEach(project => { console.log(`${project.key}: ${project.name} (${project.projectTypeKey})`); }); return projects; } async function getProjectDetails(projectKey: string) { const project = await client.projects.getProject({ projectIdOrKey: projectKey, expand: ['description', 'issueTypes', 'lead', 'projectKeys'] }); console.log(`Project: ${project.name}`); console.log(`Lead: ${project.lead?.displayName}`); console.log(`Issue types: ${project.issueTypes?.map(t => t.name).join(', ')}`); return project; } async function updateProject(projectKey: string) { await client.projects.updateProject({ projectIdOrKey: projectKey, description: 'Updated project description', leadAccountId: '5b10ac8d82e05b22cc7d4ef5' }); console.log(`Updated project ${projectKey}`); } ``` -------------------------------- ### Install Jira.js with npm, yarn, or pnpm Source: https://context7.com/context7/mrrefactoring_github_io-jira.js/llms.txt Instructions for installing the jira.js library using popular package managers like npm, yarn, and pnpm. Ensures the library is available for use in your Node.js or browser project. ```bash # Using npm npm install jira.js # Using yarn yarn add jira.js # Using pnpm pnpm add jira.js ``` -------------------------------- ### API Structure and Usage Source: https://mrrefactoring.github.io/jira.js/index Demonstrates how to access Jira API endpoints using the `client..` pattern and provides an example of creating a sprint. ```APIDOC ## API Structure and Usage Access endpoints using the `client..` pattern. ### Example: ```javascript // Get all projects const projects = await client.projects.searchProjects(); // Create a sprint const sprint = await client.sprint.createSprint({ name: 'Q4 Sprint' }); ``` ### Available API Groups: * **Agile Cloud API:** backlog, board, builds, deployments, developmentInformation, devopsComponents, epic, featureFlags, issue, operations, remoteLinks, securityInformation, sprint * **Core REST API (v2/v3):** announcementBanner, appDataPolicy, applicationRoles, appMigration, auditRecords, avatars, classificationLevels, dashboards, filters, filterSharing, groupAndUserPicker, groups, instanceInformation, issues, issueAttachments, issueBulkOperations, issueComments, issueCustomFieldAssociations, issueCustomFieldConfigurationApps, issueCommentProperties, issueFields, issueFieldConfigurations, issueCustomFieldContexts, issueCustomFieldOptions, issueCustomFieldOptionsApps, issueCustomFieldValuesApps, issueLinks, issueLinkTypes, issueNavigatorSettings, issueNotificationSchemes, issuePriorities, issueProperties, issueRemoteLinks, issueResolutions, issueSearch, issueSecurityLevel, issueSecuritySchemes, issueTypes, issueTypeSchemes, issueTypeScreenSchemes, issueTypeProperties, issueVotes, issueWatchers, issueWorklogs, issueWorklogProperties, jiraExpressions, jiraSettings, jql, jqlFunctionsApps, labels, licenseMetrics, myself, permissions, permissionSchemes, plans, prioritySchemes, projects, projectTemplates, projectAvatars, projectCategories, projectClassificationLevels, projectComponents, projectEmail, projectFeatures, projectKeyAndNameValidation, projectPermissionSchemes, projectProperties, projectRoles, projectRoleActors, projectTypes, projectVersions, screens, screenTabs, screenTabFields, screenSchemes, serverInfo, serviceRegistry, status, tasks, teamsInPlan, timeTracking, uiModificationsApps, users, userNavProperties, userProperties, userSearch, webhooks, workflows, workflowTransitionRules, workflowSchemes, workflowSchemeProjectAssociations, workflowSchemeDrafts, workflowStatuses, workflowStatusCategories, workflowTransitionProperties, appProperties, dynamicModules * **Service Desk API:** customer, info, insight, knowledgeBase, organizations, request, requestType, serviceDesk See full group list in original documentation. ``` -------------------------------- ### Tree Shaking with Jira.js Source: https://mrrefactoring.github.io/jira.js/index Illustrates how to optimize bundle size by importing only necessary modules from Jira.js. This custom client example imports specific classes like Issues and Board for reduced footprint. It requires the jira.js library and defines a custom client extending BaseClient. ```typescript // custom-client.ts import { BaseClient } from 'jira.js'; import { Issues } from 'jira.js/version3'; import { Board } from 'jira.js/agile'; export class CustomClient extends BaseClient { issues = new Issues(this); board = new Board(this); } // Usage const client = new CustomClient({ /* config */ }); await client.issues.getIssue({ issueIdOrKey: 'KEY-1' }); ``` -------------------------------- ### Create a Jira Issue with Jira.js (JavaScript) Source: https://mrrefactoring.github.io/jira.js/index A quick example demonstrating how to create a Jira issue using the Jira.js library. It initializes a client with host and authentication details, fetches project information, and then creates a new issue. ```javascript import { Version3Client } from 'jira.js'; const client = new Version3Client({" ``` ```javascript host: 'https://your-domain.atlassian.net', authentication: {" ``` ```javascript basic: {" ``` ```javascript email: 'your@email.com', apiToken: 'YOUR_API_TOKEN', // Create one: https://id.atlassian.com/manage-profile/security/api-tokens }, }," ``` ```javascript }); async function createIssue() { const project = await client.projects.getProject({ projectIdOrKey: 'Your project id or key' }); const newIssue = await client.issues.createIssue({" ``` ```javascript fields: {" ``` ```javascript summary: 'Hello Jira.js!', issuetype: { name: 'Task' }, project: { key: project.key }, }, }); console.log(`Issue created: ${newIssue.id}`); } createIssue(); ``` -------------------------------- ### Search Jira Issues with JQL using jira.js Source: https://context7.com/context7/mrrefactoring_github_io-jira.js/llms.txt Provides TypeScript examples for searching Jira issues using JQL with the jira.js library. Covers basic searching, advanced queries, and paginated results. Requires 'jira.js' and a Jira API token. ```typescript import { Version3Client } from 'jira.js'; const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'your@email.com', apiToken: 'YOUR_API_TOKEN' } } }); async function searchIssues() { const result = await client.issueSearch.searchForIssuesUsingJql({ jql: 'project = PROJ AND status = "In Progress"', maxResults: 50, startAt: 0, fields: ['summary', 'status', 'assignee', 'created'] }); console.log(`Found ${result.total} issues`); result.issues?.forEach(issue => { console.log(`${issue.key}: ${issue.fields.summary}`); }); return result; } async function advancedSearch() { const result = await client.issueSearch.searchForIssuesUsingJql({ jql: 'project = PROJ AND assignee = currentUser() AND status != Done ORDER BY priority DESC, created ASC', maxResults: 100, fields: ['*all'], expand: ['changelog', 'renderedFields'], validateQuery: 'strict' }); return result; } async function paginatedSearch() { const allIssues = []; let startAt = 0; const maxResults = 50; let hasMore = true; while (hasMore) { const result = await client.issueSearch.searchForIssuesUsingJql({ jql: 'project = PROJ', startAt, maxResults, fields: ['summary', 'status'] }); allIssues.push(...(result.issues || [])); startAt += maxResults; hasMore = (result.total || 0) > startAt; console.log(`Fetched ${allIssues.length} of ${result.total} issues`); } return allIssues; } ``` -------------------------------- ### Configure Jira.js Client with Email and API Token (JavaScript) Source: https://mrrefactoring.github.io/jira.js/index Example of how to configure the Jira.js client for authentication using an email address and an API token. This is a common method for server-to-server interactions. ```javascript const client = new Version3Client({" ``` ```javascript host: 'https://your-domain.atlassian.net', authentication: {" ``` ```javascript basic: { email: 'YOUR@EMAIL.ORG', apiToken: 'YOUR_API_TOKEN' }, }," ``` ```javascript }); ``` -------------------------------- ### Jira.js Authentication using Basic API Token Source: https://context7.com/context7/mrrefactoring_github_io-jira.js/llms.txt Provides a detailed example of authenticating with Jira.js using a basic API token. It includes creating the `Version3Client` and a function to test the connection by fetching the current user's details. ```typescript import { Version3Client } from 'jira.js'; // Create API token at: https://id.atlassian.com/manage-profile/security/api-tokens const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'admin@company.com', apiToken: 'ATATT3xFfGF0...' } }, noCheckAtlassianToken: false, // Set to true to add X-Atlassian-Token header strictGDPR: false }); // Test the connection async function testConnection() { try { const myself = await client.myself.getCurrentUser(); console.log(`Connected as: ${myself.displayName}`); } catch (error) { console.error('Connection failed:', error); } } ``` -------------------------------- ### ScreenTabs - Get Bulk Screen Tabs Source: https://mrrefactoring.github.io/jira.js/classes/Version3 Returns the list of tabs for a bulk of screens. Requires Administer Jira global permission. ```APIDOC ## GET /rest/api/3/screens/tabs/bulk ### Description Returns the list of tabs for a bulk of screens. ### Method GET ### Endpoint /rest/api/3/screens/tabs/bulk ### Parameters #### Query Parameters - **screenIds** (string) - Required - Comma-separated list of screen IDs. ### Response #### Success Response (200) - **screenId** (string) - The ID of the screen. - **tabs** (array) - A list of screen tabs for the screen. - **id** (string) - The ID of the screen tab. - **name** (string) - The name of the screen tab. - **order** (integer) - The order of the screen tab. #### Response Example ```json { "screenId": "screen-id-abc", "tabs": [ { "id": "tab-id-123", "name": "Tab 1", "order": 0 } ] } ``` ### Permissions Required _Administer Jira_ global permission. ``` -------------------------------- ### Get User Source: https://mrrefactoring.github.io/jira.js/modules/Version2Parameters Retrieves details for a specific user. ```APIDOC ## GET /rest/api/2/user ### Description Retrieves details for a specific user. ### Method GET ### Endpoint /rest/api/2/user ### Parameters #### Query Parameters - **accountId** (string) - Required - The account ID of the user. - **expand** (string) - Optional - A comma-separated list of fields to expand. ### Request Example ``` GET /rest/api/2/user?accountId=5b10ac8d82e05b22cc7d43bb ``` ### Response #### Success Response (200) - **self** (string) - The self URL of the user. - **accountId** (string) - The account ID of the user. - **accountType** (string) - The account type of the user. - **emailAddress** (string) - The email address of the user. - **avatarUrls** (object) - URLs for the user's avatars. - **48x48** (string) - URL for the 48x48 avatar. - **24x24** (string) - URL for the 24x24 avatar. - **16x16** (string) - URL for the 16x16 avatar. - **32x32** (string) - URL for the 32x32 avatar. - **displayName** (string) - The display name of the user. - **active** (boolean) - Whether the user is active. - **timeZone** (string) - The user's time zone. - **locale** (string) - The user's locale. - **groups** (object) - Information about the user's groups. - **size** (integer) - The number of groups. - **items** (array[object]) - A list of groups. - **name** (string) - The name of the group. - **id** (string) - The ID of the group. - **parameters** (object) - Group parameters. - **applicationRoles** (object) - Information about the user's application roles. - **size** (integer) - The number of application roles. - **items** (array[object]) - A list of application roles. - **name** (string) - The name of the application role. - **id** (string) - The ID of the application role. - **description** (string) - The description of the application role. #### Response Example ```json { "self": "https://your-domain.atlassian.net/rest/api/2/user?accountId=5b10ac8d82e05b22cc7d43bb", "accountId": "5b10ac8d82e05b22cc7d43bb", "accountType": "atlassian", "emailAddress": "john.doe@example.com", "avatarUrls": { "48x48": "https://avatar-management-service.production.internal.atlassian.com/useravatar/5b10ac8d82e05b22cc7d43bb-1677791821331/48", "24x24": "https://avatar-management-service.production.internal.atlassian.com/useravatar/5b10ac8d82e05b22cc7d43bb-1677791821331/24", "16x16": "https://avatar-management-service.production.internal.atlassian.com/useravatar/5b10ac8d82e05b22cc7d43bb-1677791821331/16", "32x32": "https://avatar-management-service.production.internal.atlassian.com/useravatar/5b10ac8d82e05b22cc7d43bb-1677791821331/32" }, "displayName": "John Doe", "active": true, "timeZone": "Asia/Kolkata", "locale": "en_US", "groups": { "size": 2, "items": [ { "name": "jira-software-users", "id": "10009", "parameters": {} }, { "name": "jira-access", "id": "10001", "parameters": {} } ] }, "applicationRoles": { "size": 1, "items": [ { "name": "jira-software", "id": "10003", "description": "For users who need access to Jira Software." } ] } } ``` ``` -------------------------------- ### Create Jira Issues with jira.js Source: https://context7.com/context7/mrrefactoring_github_io-jira.js/llms.txt Demonstrates how to create single and multiple Jira issues using the jira.js client. Includes examples for basic issue creation, issues with custom fields, and bulk issue creation. Requires 'jira.js' and a valid Jira API token. ```typescript import { Version3Client } from 'jira.js'; const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'your@email.com', apiToken: 'YOUR_API_TOKEN' } } }); async function createBasicIssue() { const newIssue = await client.issues.createIssue({ fields: { project: { key: 'PROJ' }, summary: 'Fix login page bug', description: 'Users cannot login when using special characters', issuetype: { name: 'Bug' }, priority: { name: 'High' } } }); console.log(`Created issue: ${newIssue.key} (${newIssue.id})`); return newIssue; } async function createIssueWithCustomFields() { const newIssue = await client.issues.createIssue({ fields: { project: { key: 'PROJ' }, summary: 'Implement new feature', description: 'Add dark mode support to the application', issuetype: { name: 'Story' }, assignee: { accountId: '5b10ac8d82e05b22cc7d4ef5' }, labels: ['frontend', 'ui', 'enhancement'], components: [{ name: 'UI' }], customfield_10001: 'Custom value', // Text field customfield_10002: { value: 'Option1' }, // Select field customfield_10003: ['value1', 'value2'] // Multi-select field } }); return newIssue; } // Bulk create issues async function createMultipleIssues() { const result = await client.issues.createIssues({ issueUpdates: [ { fields: { project: { key: 'PROJ' }, summary: 'First issue', issuetype: { name: 'Task' } } }, { fields: { project: { key: 'PROJ' }, summary: 'Second issue', issuetype: { name: 'Task' } } } ] }); console.log(`Created ${result.issues?.length} issues`); return result; } ``` -------------------------------- ### GET /getProperty Source: https://mrrefactoring.github.io/jira.js/classes/Agile Retrieves the value of a specified property from a sprint. Requires permissions to view the sprint. ```APIDOC ## GET /getProperty ### Description Returns the value of the property with a given key from the sprint identified by the provided id. The user who retrieves the property is required to have permissions to view the sprint. ### Method GET ### Endpoint /getProperty ### Parameters #### Query Parameters - **parameters** (AgileParameters.GetProperty) - Required - The parameters object containing the property key and sprint ID. - **callback** (Callback) - Optional - A callback function to handle the response. ### Request Example ```json { "parameters": { "sprintId": "string", "propertyKey": "string" } } ``` ### Response #### Success Response (200) - **T** (any) - The value of the requested property. #### Response Example ```json { "propertyValue": "example" } ``` ``` -------------------------------- ### ScreenTabs - Get All Screen Tabs Source: https://mrrefactoring.github.io/jira.js/classes/Version3 Returns the list of tabs for a screen. Requires Administer Jira global permission and potentially Administer projects permission. ```APIDOC ## GET /rest/api/3/screens/{screenId}/tabs ### Description Returns the list of tabs for a screen. ### Method GET ### Endpoint /rest/api/3/screens/{screenId}/tabs ### Parameters #### Path Parameters - **screenId** (string) - Required - The ID of the screen. #### Query Parameters - **projectId** (string) - Optional - The project key to filter tabs by. ### Response #### Success Response (200) - **id** (string) - The ID of the screen tab. - **name** (string) - The name of the screen tab. - **order** (integer) - The order of the screen tab. #### Response Example ```json [ { "id": "tab-id-123", "name": "Tab 1", "order": 0 }, { "id": "tab-id-456", "name": "Tab 2", "order": 1 } ] ``` ### Permissions Required - _Administer Jira_ global permission. - _Administer projects_ project permission when the project key is specified, providing that the screen is associated with the project through a Screen Scheme and Issue Type Screen Scheme. ``` -------------------------------- ### Handle Jira API Errors with Jira.js (JavaScript) Source: https://mrrefactoring.github.io/jira.js/index Example of error handling for Jira API interactions using Jira.js. It shows how to catch `HttpException` for server errors and `AxiosError` for network issues, providing specific logging for each. ```javascript try { await client.issues.getIssue({ issueIdOrKey: 'INVALID-123' }); } catch (error) { if (error instanceof HttpException) { console.error('Server error:', error.message); console.debug('Response headers:', error.cause.response?.headers); } else if (error instanceof AxiosError) { console.error('Network error:', error.code); } else { console.error('Unexpected error:', error); } } ``` -------------------------------- ### Send Request for Full Axios Response Source: https://mrrefactoring.github.io/jira.js/classes/BaseClient Demonstrates how to use sendRequestFullResponse to get the complete Axios response object, which includes data, status, headers, and other details. ```typescript import { AxiosResponse } from "axios"; const client = new BaseClient({...}); async function fetchFullResponse() { const response: AxiosResponse = await client.sendRequestFullResponse(requestConfig); // Access response.data, response.status, etc. } ``` -------------------------------- ### Jira Agile Boards and Sprints Management with jira.js Source: https://context7.com/context7/mrrefactoring_github_io-jira.js/llms.txt This snippet demonstrates how to use the AgileClient from jira.js to interact with Jira Agile boards and sprints. It covers fetching all boards, creating new sprints, moving issues between sprints, starting and closing sprints, and retrieving issues for a specific sprint. Requires 'jira.js' library and valid Jira authentication credentials. ```typescript import { AgileClient } from 'jira.js/agile'; const client = new AgileClient({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'your@email.com', apiToken: 'YOUR_API_TOKEN' } } }); async function getAllBoards() { const boards = await client.board.getAllBoards({ type: 'scrum', maxResults: 50 }); boards.values?.forEach(board => { console.log(`Board: ${board.name} (ID: ${board.id})`); }); return boards; } async function createSprint(boardId: number) { const sprint = await client.sprint.createSprint({ name: 'Sprint 42', originBoardId: boardId, startDate: new Date('2025-11-01').toISOString(), endDate: new Date('2025-11-14').toISOString(), goal: 'Complete user authentication module' }); console.log(`Created sprint: ${sprint.name} (ID: ${sprint.id})`); return sprint; } async function moveIssuesToSprint(sprintId: number, issueKeys: string[]) { await client.sprint.moveIssuesToSprintAndRank({ sprintId, issues: issueKeys }); console.log(`Moved ${issueKeys.length} issues to sprint ${sprintId}`); } async function startSprint(sprintId: number) { const sprint = await client.sprint.partiallyUpdateSprint({ sprintId, state: 'active', startDate: new Date().toISOString(), endDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString() }); console.log(`Started sprint ${sprintId}`); return sprint; } async function getSprintIssues(sprintId: number) { const result = await client.sprint.getIssuesForSprint({ sprintId, maxResults: 100, fields: ['summary', 'status', 'assignee', 'priority'] }); console.log(`Sprint has ${result.total} issues`); return result; } async function closeSprint(sprintId: number) { const sprint = await client.sprint.partiallyUpdateSprint({ sprintId, state: 'closed' }); console.log(`Closed sprint ${sprintId}`); return sprint; } ``` -------------------------------- ### Advanced Jira.js Configuration with Custom Axios Settings (TypeScript) Source: https://context7.com/context7/mrrefactoring_github_io-jira.js/llms.txt Shows how to customize the underlying Axios HTTP client configuration for the Jira.js library. This allows for fine-grained control over request behavior, such as setting timeouts, custom headers, proxy configurations, redirect limits, and defining custom status validation logic. Ensure the 'jira.js' library is installed. ```typescript import { Version3Client } from 'jira.js'; const client = new Version3Client({ host: 'https://your-domain.atlassian.net', authentication: { basic: { email: 'your@email.com', apiToken: 'YOUR_API_TOKEN' } }, baseRequestConfig: { timeout: 30000, // 30 second timeout headers: { 'X-Custom-Header': 'custom-value' }, proxy: { host: 'proxy.company.com', port: 8080, auth: { username: 'proxyuser', password: 'proxypass' } }, maxRedirects: 5, validateStatus: (status) => { return status >= 200 && status < 300; } }, noCheckAtlassianToken: true, // Adds X-Atlassian-Token: no-check header strictGDPR: true // Ensures GDPR compliance }); // All requests will use these custom axios configurations ``` -------------------------------- ### Initialize ServiceDeskClient in Jira.js Source: https://mrrefactoring.github.io/jira.js/classes/ServiceDesk Demonstrates how to instantiate the ServiceDeskClient with various authentication methods (basic auth with API token or OAuth 2.0) and configuration options. It highlights the required 'host' parameter and optional settings like custom base request configurations and middleware for handling responses. ```javascript import ServiceDeskClient from "jira.js/out/service-desk" // Using Basic Authentication const clientWithBasicAuth = new ServiceDeskClient({ host: "your-domain.atlassian.net", authentication: { basic: { email: "user@example.com", apiToken: "your_api_token" } } }); // Using OAuth 2.0 Authentication const clientWithOAuth = new ServiceDeskClient({ host: "your-domain.atlassian.net", authentication: { oauth2: { accessToken: "your_access_token" } } }); // With custom middlewares const clientWithMiddlewares = new ServiceDeskClient({ host: "your-domain.atlassian.net", middlewares: { onResponse: (response) => { console.log("Response received:", response); return response; }, onError: (error) => { console.error("Request failed:", error); throw error; } } }); ``` -------------------------------- ### Version 2 Client Constructor Source: https://mrrefactoring.github.io/jira.js/classes/Version2 Initializes a new instance of the Version2Client with configuration details for connecting to the Jira Cloud API. ```APIDOC ## Constructors ### constructor * new Version2Client( config: { authentication?: | { basic: { apiToken: string; email: string } } | { oauth2: { accessToken: string } }; baseRequestConfig?: any; host: string; middlewares?: { onError?: (...args: [any, ...unknown[]]) => void; onResponse?: (...args: [any, ...unknown[]]) => void; }; noCheckAtlassianToken?: boolean; strictGDPR?: boolean; }): Version2.Version2Client #### Parameters * config: { authentication?: | { basic: { apiToken: string; email: string } } | { oauth2: { accessToken: string } }; baseRequestConfig?: any; host: string; middlewares?: { onError?: (...args: [any, ...unknown[]]) => void; onResponse?: (...args: [any, ...unknown[]]) => void; }; noCheckAtlassianToken?: boolean; strictGDPR?: boolean; } * ##### `Optional`authentication?: | { basic: { apiToken: string; email: string } } | { oauth2: { accessToken: string } } * ##### `Optional`baseRequestConfig?: any * ##### host: string * ##### `Optional`middlewares?: { onError?: (...args: [any, ...unknown[]]) => void; onResponse?: (...args: [any, ...unknown[]]) => void; } * ##### `Optional`noCheckAtlassianToken?: boolean Adds `'X-Atlassian-Token': 'no-check'` to each request header * ##### `Optional`strictGDPR?: boolean #### Returns Version2.Version2Client ``` -------------------------------- ### GET /getSprint Source: https://mrrefactoring.github.io/jira.js/classes/Agile Retrieves sprint details for a given sprint ID. Requires permissions to view the associated board or its issues. ```APIDOC ## GET /getSprint ### Description Returns the sprint for a given sprint ID. The sprint will only be returned if the user can view the board that the sprint was created on, or view at least one of the issues in the sprint. ### Method GET ### Endpoint /getSprint ### Parameters #### Query Parameters - **parameters** (GetSprint) - Required - The parameters object containing the sprint ID. - **callback** (Callback) - Optional - A callback function to handle the response. ### Request Example ```json { "parameters": { "sprintId": "string" } } ``` ### Response #### Success Response (200) - **AgileModels.Sprint** (object) - The sprint object containing sprint details. #### Response Example ```json { "id": "sprint-123", "name": "Sprint Name", "state": "active", "startDate": "2023-10-27T10:00:00Z", "endDate": "2023-11-10T10:00:00Z" } ``` ``` -------------------------------- ### BaseClient Constructor Source: https://mrrefactoring.github.io/jira.js/classes/BaseClient Initializes a new instance of the BaseClient class, which serves as the foundation for interacting with the Jira API. ```APIDOC ## Constructors ### constructor * `new BaseClient(config: BaseClientConfig): BaseClient` #### Parameters * `config` (BaseClientConfig) - Configuration object for the client. * ##### `Optional` `authentication` - Authentication method for the API. Can be basic (apiToken, email) or oauth2 (accessToken). * ##### `Optional` `baseRequestConfig` - Optional base configuration for Axios requests. * ##### `host` (string) - The Jira Cloud instance hostname. * ##### `Optional` `middlewares` - Middleware functions to intercept requests and responses. * ##### `onError` - Function to handle request errors. * ##### `onResponse` - Function to handle responses. * ##### `Optional` `noCheckAtlassianToken` - If true, adds `'X-Atlassian-Token': 'no-check'` to request headers. * ##### `Optional` `strictGDPR` - If true, enforces strict GDPR compliance. #### Returns * `BaseClient` - An instance of the BaseClient. ``` -------------------------------- ### Initialize Jira Version 2 Client Source: https://mrrefactoring.github.io/jira.js/classes/Version2 Instantiates the Version2Client with configuration options. Supports basic authentication with email and API token, or OAuth 2.0 with an access token. Optional configurations include base request settings, host, custom middlewares for request handling, and flags for Atlassian token checks and GDPR compliance. ```javascript import { Version2Client } from "jira.js/out/version2"; const jiraClient = new Version2Client({ authentication: { basic: { email: "your-email@example.com", apiToken: "your-api-token" } }, host: "your-jira-instance.atlassian.net" }); // Or with OAuth 2.0 // const jiraClient = new Version2Client({ // authentication: { // oauth2: { // accessToken: "your-access-token" // } // }, // host: "your-jira-instance.atlassian.net" // }); ``` -------------------------------- ### Initialize BaseClient with Authentication Source: https://mrrefactoring.github.io/jira.js/classes/BaseClient Demonstrates initializing the BaseClient with basic authentication using an API token and email, or with OAuth2 access token. This client is the foundation for interacting with Jira's API. ```typescript new BaseClient({ authentication: { basic: { apiToken: "YOUR_API_TOKEN", email: "YOUR_EMAIL" } }, host: "your-domain.atlassian.net" }); new BaseClient({ authentication: { oauth2: { accessToken: "YOUR_ACCESS_TOKEN" } }, host: "your-domain.atlassian.net" }); ``` -------------------------------- ### Tree Shaking for Bundle Optimization Source: https://mrrefactoring.github.io/jira.js/index Explains how to optimize bundle size by importing only the necessary modules for your project. ```APIDOC ## Tree Shaking Optimize bundle size by importing only needed modules: ### Example: ```typescript // custom-client.ts import { BaseClient } from 'jira.js'; import { Issues } from 'jira.js/version3'; import { Board } from 'jira.js/agile'; export class CustomClient extends BaseClient { issues = new Issues(this); board = new Board(this); } // Usage const client = new CustomClient({ /* config */ }); await client.issues.getIssue({ issueIdOrKey: 'KEY-1' }); ``` ``` -------------------------------- ### Update Sprint API Source: https://mrrefactoring.github.io/jira.js/classes/Agile Performs a full update on a sprint's details. This endpoint allows modification of various sprint attributes like name, goal, state, start date, and end date. Note that closed sprints have restricted update capabilities. ```APIDOC ## PUT /sprints/{sprintId} ### Description Performs a full update of a sprint. A full update means that the result will be exactly the same as the request body. Any fields not present in the request JSON will be set to null. **Notes:** * For closed sprints, only the name and goal can be updated; changes to other fields will be ignored. * A sprint can be started by updating the state to 'active'. This requires the sprint to be in the 'future' state and have a startDate and endDate set. * A sprint can be completed by updating the state to 'closed'. This action requires the sprint to be in the 'active' state. This sets the completeDate to the time of the request. * Other changes to state are not allowed. * The completeDate field cannot be updated manually. ### Method PUT ### Endpoint `/sprints/{sprintId}` ### Parameters #### Path Parameters - **sprintId** (string) - Required - The ID of the sprint to update. #### Request Body - **name** (string) - Optional - The updated name of the sprint. - **goal** (string) - Optional - The updated goal of the sprint. - **state** (string) - Optional - The updated state of the sprint ('future', 'active', 'closed'). - **startDate** (string) - Optional - The updated start date of the sprint (ISO 8601 format). - **endDate** (string) - Optional - The updated end date of the sprint (ISO 8601 format). ### Request Example ```json { "name": "Updated Sprint Name", "state": "active", "endDate": "2024-12-31T23:59:59Z" } ``` ### Response #### Success Response (200) - **sprint** (AgileModels.Sprint) - The updated sprint object. #### Response Example ```json { "id": "sp-789", "name": "Updated Sprint Name", "goal": "Achieve project milestones", "state": "active", "startDate": "2024-01-01T00:00:00Z", "endDate": "2024-12-31T23:59:59Z", "completeDate": null } ``` ```