@felixgeelhaar/jira-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Felix Geelhaar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,535 @@
1
+ # @felixgeelhaar/jira-sdk
2
+
3
+ Type-safe TypeScript SDK for the Atlassian Jira REST API with Zod validation and built-in resilience.
4
+
5
+ ## Features
6
+
7
+ - **Type-Safe**: Full TypeScript support with strict mode
8
+ - **Runtime Validation**: Zod schemas for request/response validation
9
+ - **Resilience Built-In**: Circuit breaker, retry, rate limiting
10
+ - **Multiple Auth Methods**: API Token, PAT, Basic Auth, OAuth 2.0
11
+ - **Middleware Architecture**: Extensible request/response pipeline
12
+ - **Tree-Shakeable**: ESM and CJS builds with proper exports
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @felixgeelhaar/jira-sdk
18
+ # or
19
+ pnpm add @felixgeelhaar/jira-sdk
20
+ # or
21
+ yarn add @felixgeelhaar/jira-sdk
22
+ ```
23
+
24
+ ## Quick Start
25
+
26
+ ```typescript
27
+ import { createJiraClient, createApiTokenAuth } from '@felixgeelhaar/jira-sdk';
28
+
29
+ // Create auth provider
30
+ const auth = createApiTokenAuth({
31
+ email: 'your-email@example.com',
32
+ apiToken: 'your-api-token', // From https://id.atlassian.com/manage-profile/security/api-tokens
33
+ });
34
+
35
+ // Create client
36
+ const client = createJiraClient({
37
+ host: 'https://your-domain.atlassian.net',
38
+ auth,
39
+ });
40
+
41
+ // Fetch an issue
42
+ const issue = await client.issues.get('PROJ-123');
43
+ console.log(issue.fields.summary);
44
+
45
+ // Search with JQL
46
+ const results = await client.search.jql('project = PROJ AND status = Open');
47
+ for (const issue of results.issues) {
48
+ console.log(issue.key, issue.fields.summary);
49
+ }
50
+ ```
51
+
52
+ ## Authentication
53
+
54
+ ### API Token (Atlassian Cloud)
55
+
56
+ Recommended for Atlassian Cloud instances:
57
+
58
+ ```typescript
59
+ import { createApiTokenAuth } from '@felixgeelhaar/jira-sdk';
60
+
61
+ const auth = createApiTokenAuth({
62
+ email: 'your-email@example.com',
63
+ apiToken: 'your-api-token',
64
+ });
65
+ ```
66
+
67
+ Get your API token from [Atlassian Account Settings](https://id.atlassian.com/manage-profile/security/api-tokens).
68
+
69
+ ### Personal Access Token (Server/Data Center)
70
+
71
+ For Jira Server or Data Center:
72
+
73
+ ```typescript
74
+ import { createPatAuth } from '@felixgeelhaar/jira-sdk';
75
+
76
+ const auth = createPatAuth({
77
+ token: 'your-personal-access-token',
78
+ });
79
+ ```
80
+
81
+ ### Basic Auth
82
+
83
+ ```typescript
84
+ import { createBasicAuth } from '@felixgeelhaar/jira-sdk';
85
+
86
+ const auth = createBasicAuth({
87
+ username: 'your-username',
88
+ password: 'your-password',
89
+ });
90
+ ```
91
+
92
+ ### OAuth 2.0
93
+
94
+ For OAuth 2.0 3LO (three-legged OAuth):
95
+
96
+ ```typescript
97
+ import { createOAuth2Auth } from '@felixgeelhaar/jira-sdk';
98
+
99
+ const auth = createOAuth2Auth({
100
+ clientId: 'your-client-id',
101
+ clientSecret: 'your-client-secret',
102
+ accessToken: 'current-access-token',
103
+ refreshToken: 'refresh-token',
104
+ expiresAt: Date.now() + 3600000,
105
+ });
106
+
107
+ // Automatic token refresh with persistence
108
+ auth.onTokenRefresh = async (tokens) => {
109
+ await saveTokensToDatabase(tokens);
110
+ };
111
+ ```
112
+
113
+ ## Services
114
+
115
+ ### Issues
116
+
117
+ ```typescript
118
+ // Get an issue
119
+ const issue = await client.issues.get('PROJ-123');
120
+ const issue = await client.issues.get('PROJ-123', {
121
+ fields: ['summary', 'status', 'assignee'],
122
+ expand: ['changelog', 'renderedFields'],
123
+ });
124
+
125
+ // Create an issue
126
+ const newIssue = await client.issues.create({
127
+ fields: {
128
+ project: { key: 'PROJ' },
129
+ summary: 'New issue from SDK',
130
+ description: 'Detailed description here',
131
+ issuetype: { name: 'Task' },
132
+ priority: { name: 'High' },
133
+ assignee: { accountId: 'user-account-id' },
134
+ },
135
+ });
136
+
137
+ // Update an issue
138
+ await client.issues.update('PROJ-123', {
139
+ fields: {
140
+ summary: 'Updated summary',
141
+ description: 'New description',
142
+ },
143
+ });
144
+
145
+ // Delete an issue
146
+ await client.issues.delete('PROJ-123');
147
+
148
+ // Transition an issue
149
+ await client.issues.transition('PROJ-123', {
150
+ transition: { id: '31' }, // Transition ID
151
+ });
152
+
153
+ // Get available transitions
154
+ const transitions = await client.issues.getTransitions('PROJ-123');
155
+ ```
156
+
157
+ ### Comments
158
+
159
+ ```typescript
160
+ // Get comments
161
+ const comments = await client.issues.getComments('PROJ-123');
162
+
163
+ // Add a comment
164
+ await client.issues.addComment('PROJ-123', {
165
+ body: 'This is a comment from the SDK',
166
+ });
167
+
168
+ // Update a comment
169
+ await client.issues.updateComment('PROJ-123', 'comment-id', {
170
+ body: 'Updated comment text',
171
+ });
172
+
173
+ // Delete a comment
174
+ await client.issues.deleteComment('PROJ-123', 'comment-id');
175
+ ```
176
+
177
+ ### Search (JQL)
178
+
179
+ ```typescript
180
+ // Simple JQL search
181
+ const results = await client.search.jql('project = PROJ');
182
+
183
+ // Advanced search with options
184
+ const results = await client.search.jql(
185
+ 'project = PROJ AND status = "In Progress" ORDER BY created DESC',
186
+ {
187
+ startAt: 0,
188
+ maxResults: 50,
189
+ fields: ['summary', 'status', 'assignee'],
190
+ expand: ['changelog'],
191
+ }
192
+ );
193
+
194
+ // Iterate through all results
195
+ for (const issue of results.issues) {
196
+ console.log(`${issue.key}: ${issue.fields.summary}`);
197
+ }
198
+
199
+ // Pagination info
200
+ console.log(`Showing ${results.startAt + 1} to ${results.startAt + results.issues.length} of ${results.total}`);
201
+ ```
202
+
203
+ ### Projects
204
+
205
+ ```typescript
206
+ // List all projects
207
+ const projects = await client.projects.list();
208
+
209
+ // Get a project
210
+ const project = await client.projects.get('PROJ');
211
+ const project = await client.projects.get('PROJ', {
212
+ expand: ['description', 'lead', 'issueTypes'],
213
+ });
214
+ ```
215
+
216
+ ### Users
217
+
218
+ ```typescript
219
+ // Get current user
220
+ const myself = await client.users.getCurrentUser();
221
+
222
+ // Get user by account ID
223
+ const user = await client.users.get('account-id');
224
+
225
+ // Search users
226
+ const users = await client.users.search({
227
+ query: 'john',
228
+ maxResults: 10,
229
+ });
230
+
231
+ // Find users assignable to a project
232
+ const assignable = await client.users.findAssignable({
233
+ project: 'PROJ',
234
+ query: 'jane',
235
+ });
236
+ ```
237
+
238
+ ## Resilience
239
+
240
+ ### Built-in Resilience Middleware
241
+
242
+ Add retry, rate limiting, and circuit breaker with one call:
243
+
244
+ ```typescript
245
+ import { createJiraClient, createResilienceMiddleware } from '@felixgeelhaar/jira-sdk';
246
+
247
+ const { middleware, circuitBreaker } = createResilienceMiddleware({
248
+ retry: {
249
+ maxRetries: 3,
250
+ initialDelayMs: 1000,
251
+ maxDelayMs: 30000,
252
+ multiplier: 2,
253
+ jitter: true,
254
+ },
255
+ rateLimit: {
256
+ maxRequests: 90, // Jira Cloud limit is ~100/min
257
+ windowMs: 60000,
258
+ waitForSlot: true,
259
+ },
260
+ circuitBreaker: {
261
+ failureThreshold: 5,
262
+ resetTimeoutMs: 30000,
263
+ failureWindowMs: 60000,
264
+ },
265
+ });
266
+
267
+ const client = createJiraClient({
268
+ host: 'https://your-domain.atlassian.net',
269
+ auth,
270
+ middleware: [middleware],
271
+ });
272
+
273
+ // Monitor circuit breaker
274
+ setInterval(() => {
275
+ const stats = circuitBreaker?.getStats();
276
+ console.log('Circuit state:', stats?.state);
277
+ }, 10000);
278
+ ```
279
+
280
+ ### Using Default Configuration
281
+
282
+ ```typescript
283
+ import { createJiraClient, withResilience } from '@felixgeelhaar/jira-sdk';
284
+
285
+ // Apply default resilience configuration
286
+ const options = withResilience();
287
+
288
+ const client = createJiraClient({
289
+ host: 'https://your-domain.atlassian.net',
290
+ auth,
291
+ ...options,
292
+ });
293
+ ```
294
+
295
+ ### Disable Specific Features
296
+
297
+ ```typescript
298
+ const { middleware } = createResilienceMiddleware({
299
+ retry: {
300
+ maxRetries: 5,
301
+ initialDelayMs: 500,
302
+ },
303
+ rateLimit: false, // Disable rate limiting
304
+ circuitBreaker: false, // Disable circuit breaker
305
+ });
306
+ ```
307
+
308
+ ## Error Handling
309
+
310
+ ```typescript
311
+ import {
312
+ ApiError,
313
+ UnauthorizedError,
314
+ ForbiddenError,
315
+ NotFoundError,
316
+ RateLimitError,
317
+ ServerError,
318
+ NetworkError,
319
+ TimeoutError,
320
+ ValidationError,
321
+ CircuitBreakerOpenError,
322
+ } from '@felixgeelhaar/jira-sdk';
323
+
324
+ try {
325
+ const issue = await client.issues.get('PROJ-999');
326
+ } catch (error) {
327
+ if (error instanceof NotFoundError) {
328
+ console.log('Issue not found');
329
+ } else if (error instanceof UnauthorizedError) {
330
+ console.log('Invalid credentials - check your API token');
331
+ } else if (error instanceof ForbiddenError) {
332
+ console.log('You do not have permission to access this issue');
333
+ } else if (error instanceof RateLimitError) {
334
+ console.log(`Rate limited. Retry after ${error.retryAfter}ms`);
335
+ } else if (error instanceof ServerError) {
336
+ console.log('Jira server error - try again later');
337
+ } else if (error instanceof NetworkError) {
338
+ console.log('Network error:', error.message);
339
+ } else if (error instanceof TimeoutError) {
340
+ console.log('Request timed out');
341
+ } else if (error instanceof CircuitBreakerOpenError) {
342
+ console.log('Circuit breaker open - Jira may be unavailable');
343
+ } else if (error instanceof ValidationError) {
344
+ console.log('Invalid data:', error.errors);
345
+ } else if (error instanceof ApiError) {
346
+ console.log(`API error ${error.statusCode}:`, error.responseBody);
347
+ }
348
+ }
349
+ ```
350
+
351
+ ## Configuration Options
352
+
353
+ ```typescript
354
+ const client = createJiraClient({
355
+ // Required
356
+ host: 'https://your-domain.atlassian.net',
357
+ auth,
358
+
359
+ // Optional
360
+ apiVersion: '3', // Jira API version (default: '3')
361
+ timeout: 30000, // Request timeout in ms (default: 30000)
362
+ middleware: [], // Custom middleware
363
+ allowInsecureHttp: false, // Allow HTTP (not recommended)
364
+ });
365
+ ```
366
+
367
+ ## Request Cancellation
368
+
369
+ ```typescript
370
+ const controller = new AbortController();
371
+
372
+ // Start request
373
+ const promise = client.search.jql('project = PROJ', {
374
+ signal: controller.signal,
375
+ });
376
+
377
+ // Cancel after 5 seconds
378
+ setTimeout(() => controller.abort(), 5000);
379
+
380
+ try {
381
+ const results = await promise;
382
+ } catch (error) {
383
+ if (error instanceof AbortError) {
384
+ console.log('Request was cancelled');
385
+ }
386
+ }
387
+ ```
388
+
389
+ ## Custom Middleware
390
+
391
+ ```typescript
392
+ import type { Middleware } from '@felixgeelhaar/jira-sdk';
393
+
394
+ // Timing middleware
395
+ const timingMiddleware: Middleware = async (context, next) => {
396
+ const start = Date.now();
397
+ const response = await next(context);
398
+ console.log(`${context.request.method} ${context.request.url} - ${Date.now() - start}ms`);
399
+ return response;
400
+ };
401
+
402
+ // Add custom headers
403
+ const headerMiddleware: Middleware = async (context, next) => {
404
+ context.request.headers = {
405
+ ...context.request.headers,
406
+ 'X-Custom-Header': 'value',
407
+ };
408
+ return next(context);
409
+ };
410
+
411
+ const client = createJiraClient({
412
+ host: 'https://your-domain.atlassian.net',
413
+ auth,
414
+ middleware: [timingMiddleware, headerMiddleware],
415
+ });
416
+ ```
417
+
418
+ ## Logging
419
+
420
+ ```typescript
421
+ import { createJiraClient, createLoggingMiddleware, ConsoleLogger } from '@felixgeelhaar/jira-sdk';
422
+
423
+ const logger = new ConsoleLogger('debug');
424
+
425
+ const client = createJiraClient({
426
+ host: 'https://your-domain.atlassian.net',
427
+ auth,
428
+ middleware: [createLoggingMiddleware(logger)],
429
+ });
430
+ ```
431
+
432
+ ## Subpath Exports
433
+
434
+ Import specific modules for better tree-shaking:
435
+
436
+ ```typescript
437
+ // Schemas only
438
+ import { IssueSchema, ProjectSchema } from '@felixgeelhaar/jira-sdk/schemas';
439
+
440
+ // Services only
441
+ import { IssueService, SearchService } from '@felixgeelhaar/jira-sdk/services';
442
+ ```
443
+
444
+ ## TypeScript Support
445
+
446
+ Full TypeScript support with strict mode:
447
+
448
+ ```typescript
449
+ import type {
450
+ Issue,
451
+ Project,
452
+ User,
453
+ SearchResults,
454
+ JiraClientConfig,
455
+ ResilienceConfig,
456
+ } from '@felixgeelhaar/jira-sdk';
457
+
458
+ // Type-safe issue fields
459
+ const issue: Issue = await client.issues.get('PROJ-123');
460
+ console.log(issue.fields.summary); // Type-safe access
461
+ ```
462
+
463
+ ## Examples
464
+
465
+ ### Bulk Operations
466
+
467
+ ```typescript
468
+ // Create multiple issues
469
+ const issues = await Promise.all([
470
+ client.issues.create({
471
+ fields: {
472
+ project: { key: 'PROJ' },
473
+ summary: 'Task 1',
474
+ issuetype: { name: 'Task' },
475
+ },
476
+ }),
477
+ client.issues.create({
478
+ fields: {
479
+ project: { key: 'PROJ' },
480
+ summary: 'Task 2',
481
+ issuetype: { name: 'Task' },
482
+ },
483
+ }),
484
+ ]);
485
+ ```
486
+
487
+ ### Iterate All Issues
488
+
489
+ ```typescript
490
+ async function* getAllIssues(client: JiraClient, jql: string) {
491
+ let startAt = 0;
492
+ const maxResults = 100;
493
+
494
+ while (true) {
495
+ const results = await client.search.jql(jql, { startAt, maxResults });
496
+
497
+ for (const issue of results.issues) {
498
+ yield issue;
499
+ }
500
+
501
+ startAt += results.issues.length;
502
+ if (startAt >= results.total) break;
503
+ }
504
+ }
505
+
506
+ // Usage
507
+ for await (const issue of getAllIssues(client, 'project = PROJ')) {
508
+ console.log(issue.key);
509
+ }
510
+ ```
511
+
512
+ ### Webhook Handler
513
+
514
+ ```typescript
515
+ import express from 'express';
516
+ import { IssueSchema } from '@felixgeelhaar/jira-sdk/schemas';
517
+
518
+ const app = express();
519
+
520
+ app.post('/webhook/jira', express.json(), (req, res) => {
521
+ const result = IssueSchema.safeParse(req.body.issue);
522
+
523
+ if (result.success) {
524
+ console.log('Issue updated:', result.data.key);
525
+ res.sendStatus(200);
526
+ } else {
527
+ console.error('Invalid webhook payload:', result.error);
528
+ res.sendStatus(400);
529
+ }
530
+ });
531
+ ```
532
+
533
+ ## License
534
+
535
+ MIT