@gravitek/confluence-mirror-core 0.2.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/README.md +141 -0
- package/dist/client/auth-strategies.d.ts +49 -0
- package/dist/client/auth-strategies.js +69 -0
- package/dist/client/cloud-id-manager.d.ts +34 -0
- package/dist/client/cloud-id-manager.js +56 -0
- package/dist/client/confluence-client.d.ts +98 -0
- package/dist/client/confluence-client.js +222 -0
- package/dist/client/oauth2-token-manager.d.ts +40 -0
- package/dist/client/oauth2-token-manager.js +73 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +14 -0
- package/dist/processors/adf-processor.d.ts +4 -0
- package/dist/processors/adf-processor.js +37 -0
- package/dist/processors/link-processor.d.ts +35 -0
- package/dist/processors/link-processor.js +174 -0
- package/dist/processors/media-processor.d.ts +2 -0
- package/dist/processors/media-processor.js +160 -0
- package/dist/processors/toc-processor.d.ts +5 -0
- package/dist/processors/toc-processor.js +90 -0
- package/dist/types/index.d.ts +67 -0
- package/dist/types/index.js +7 -0
- package/dist/utils/url-transformer.d.ts +80 -0
- package/dist/utils/url-transformer.js +116 -0
- package/package.json +38 -0
package/README.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# confluence-mirror-core
|
|
2
|
+
|
|
3
|
+
Core logic for Confluence page rendering - framework agnostic.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install confluence-mirror-core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- ✅ **Confluence REST API Client** - Authenticate and fetch pages
|
|
14
|
+
- ✅ **ADF Processing** - Parse Atlas Document Format
|
|
15
|
+
- ✅ **Media Processing** - Extract and rewrite media URLs
|
|
16
|
+
- ✅ **TOC Extraction** - Generate table of contents from headings
|
|
17
|
+
- ✅ **TypeScript Support** - Full type definitions
|
|
18
|
+
- ✅ **Zero Dependencies** - Pure logic, no UI framework dependencies
|
|
19
|
+
|
|
20
|
+
## Quick Start
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import {
|
|
24
|
+
ConfluenceClient,
|
|
25
|
+
processADFWithMedia,
|
|
26
|
+
processADFWithTOC
|
|
27
|
+
} from 'confluence-mirror-core';
|
|
28
|
+
|
|
29
|
+
// Initialize client
|
|
30
|
+
const client = new ConfluenceClient(
|
|
31
|
+
"https://your-domain.atlassian.net",
|
|
32
|
+
"your-email@domain.com",
|
|
33
|
+
"your-api-key"
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
// Fetch a page
|
|
37
|
+
const page = await client.getPage("page-id");
|
|
38
|
+
|
|
39
|
+
// Process ADF with media URLs
|
|
40
|
+
const processedContent = await processADFWithMedia(
|
|
41
|
+
JSON.parse(page.body.atlas_doc_format.value),
|
|
42
|
+
page.body.storage?.value || "",
|
|
43
|
+
"page-id"
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
// Extract table of contents
|
|
47
|
+
const { enrichedDocument, tableOfContents } = processADFWithTOC(processedContent);
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## API Reference
|
|
51
|
+
|
|
52
|
+
### ConfluenceClient
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
class ConfluenceClient {
|
|
56
|
+
constructor(baseUrl: string, email: string, apiKey: string)
|
|
57
|
+
|
|
58
|
+
async getPage(pageId: string, includeChildren?: boolean): Promise<ConfluencePage>
|
|
59
|
+
async getChildPages(pageId: string): Promise<ConfluenceChildPage[]>
|
|
60
|
+
async getCurrentUser(): Promise<any>
|
|
61
|
+
|
|
62
|
+
static extractPageIdFromUrl(url: string): string | null
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Processing Functions
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
// Media processing
|
|
70
|
+
async function processADFWithMedia(
|
|
71
|
+
adfDocument: ADFDocument,
|
|
72
|
+
storageHtml: string,
|
|
73
|
+
pageId: string
|
|
74
|
+
): Promise<ADFDocument>
|
|
75
|
+
|
|
76
|
+
// TOC processing
|
|
77
|
+
function processADFWithTOC(adfDocument: ADFDocument): {
|
|
78
|
+
enrichedDocument: ADFDocument;
|
|
79
|
+
tableOfContents: TocItem[];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Utility functions
|
|
83
|
+
function extractTextFromADFNodes(nodes: ADFNode[]): string
|
|
84
|
+
function generateSlug(text: string, existingSlugs?: Set<string>): string
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Types
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
interface ConfluencePage {
|
|
91
|
+
id: string;
|
|
92
|
+
title: string;
|
|
93
|
+
body: {
|
|
94
|
+
atlas_doc_format?: { value: string };
|
|
95
|
+
storage?: { value: string; representation: string };
|
|
96
|
+
};
|
|
97
|
+
version: { number: number };
|
|
98
|
+
space: { key: string; name: string };
|
|
99
|
+
_links: { webui: string };
|
|
100
|
+
children?: { page?: { results: ConfluenceChildPage[]; size: number } };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
interface ADFDocument {
|
|
104
|
+
version: number;
|
|
105
|
+
type: "doc";
|
|
106
|
+
content: ADFNode[];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
interface TocItem {
|
|
110
|
+
id: string;
|
|
111
|
+
title: string;
|
|
112
|
+
level: number;
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Error Handling
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
import { ConfluenceApiError } from 'confluence-mirror-core';
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
const page = await client.getPage("invalid-id");
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (error instanceof ConfluenceApiError) {
|
|
125
|
+
console.log(`API Error ${error.statusCode}: ${error.message}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Contributing
|
|
131
|
+
|
|
132
|
+
This package contains pure logic with no UI dependencies. When contributing:
|
|
133
|
+
|
|
134
|
+
1. Keep functions pure and testable
|
|
135
|
+
2. Maintain TypeScript strict mode compliance
|
|
136
|
+
3. Add tests for new functionality
|
|
137
|
+
4. Update type definitions as needed
|
|
138
|
+
|
|
139
|
+
## License
|
|
140
|
+
|
|
141
|
+
Apache-2.0
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base interface for authentication strategies
|
|
3
|
+
* Supports both Basic Authentication and OAuth2
|
|
4
|
+
*/
|
|
5
|
+
export interface AuthStrategy {
|
|
6
|
+
/**
|
|
7
|
+
* Get authentication headers for API requests
|
|
8
|
+
* @returns Headers object with Authorization header
|
|
9
|
+
*/
|
|
10
|
+
getAuthHeaders(): Promise<Record<string, string>>;
|
|
11
|
+
/**
|
|
12
|
+
* Optional method to force authentication refresh
|
|
13
|
+
* Used for token expiration handling
|
|
14
|
+
*/
|
|
15
|
+
refreshAuth?(): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Basic Authentication strategy using email and API key
|
|
19
|
+
* Uses HTTP Basic Auth with Base64 encoding
|
|
20
|
+
*/
|
|
21
|
+
export declare class BasicAuthStrategy implements AuthStrategy {
|
|
22
|
+
private email;
|
|
23
|
+
private apiKey;
|
|
24
|
+
constructor(email: string, apiKey: string);
|
|
25
|
+
getAuthHeaders(): Promise<Record<string, string>>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* OAuth2 authentication strategy for Atlassian service accounts
|
|
29
|
+
* Implements Client Credentials Flow (2LO) with automatic token refresh
|
|
30
|
+
* and Cloud ID detection
|
|
31
|
+
*
|
|
32
|
+
* IMPORTANT: Uses singleton pattern to share tokens across all instances
|
|
33
|
+
* with the same clientId. This prevents 401 loops in Next.js Server Components.
|
|
34
|
+
*/
|
|
35
|
+
export declare class OAuth2Strategy implements AuthStrategy {
|
|
36
|
+
private tokenManager;
|
|
37
|
+
private cloudIdManager;
|
|
38
|
+
constructor(clientId: string, clientSecret: string);
|
|
39
|
+
getAuthHeaders(): Promise<Record<string, string>>;
|
|
40
|
+
/**
|
|
41
|
+
* Get the Cloud ID for constructing OAuth2 API URLs
|
|
42
|
+
* @returns Confluence Cloud ID
|
|
43
|
+
*/
|
|
44
|
+
getCloudId(): Promise<string>;
|
|
45
|
+
/**
|
|
46
|
+
* Force token refresh (called on 401 errors)
|
|
47
|
+
*/
|
|
48
|
+
refreshAuth(): Promise<void>;
|
|
49
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { OAuth2TokenManager } from "./oauth2-token-manager";
|
|
2
|
+
import { CloudIdManager } from "./cloud-id-manager";
|
|
3
|
+
/**
|
|
4
|
+
* Basic Authentication strategy using email and API key
|
|
5
|
+
* Uses HTTP Basic Auth with Base64 encoding
|
|
6
|
+
*/
|
|
7
|
+
export class BasicAuthStrategy {
|
|
8
|
+
constructor(email, apiKey) {
|
|
9
|
+
this.email = email;
|
|
10
|
+
this.apiKey = apiKey;
|
|
11
|
+
}
|
|
12
|
+
async getAuthHeaders() {
|
|
13
|
+
const credentials = Buffer.from(`${this.email}:${this.apiKey}`).toString("base64");
|
|
14
|
+
return {
|
|
15
|
+
Authorization: `Basic ${credentials}`,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Global cache for OAuth2 token managers
|
|
21
|
+
* Keyed by clientId to ensure tokens are shared across instances
|
|
22
|
+
*/
|
|
23
|
+
const tokenManagerCache = new Map();
|
|
24
|
+
/**
|
|
25
|
+
* Global cache for Cloud ID managers
|
|
26
|
+
* Keyed by clientId to ensure Cloud IDs are shared across instances
|
|
27
|
+
*/
|
|
28
|
+
const cloudIdManagerCache = new Map();
|
|
29
|
+
/**
|
|
30
|
+
* OAuth2 authentication strategy for Atlassian service accounts
|
|
31
|
+
* Implements Client Credentials Flow (2LO) with automatic token refresh
|
|
32
|
+
* and Cloud ID detection
|
|
33
|
+
*
|
|
34
|
+
* IMPORTANT: Uses singleton pattern to share tokens across all instances
|
|
35
|
+
* with the same clientId. This prevents 401 loops in Next.js Server Components.
|
|
36
|
+
*/
|
|
37
|
+
export class OAuth2Strategy {
|
|
38
|
+
constructor(clientId, clientSecret) {
|
|
39
|
+
// Reuse existing token manager for this clientId if available
|
|
40
|
+
if (!tokenManagerCache.has(clientId)) {
|
|
41
|
+
tokenManagerCache.set(clientId, new OAuth2TokenManager(clientId, clientSecret));
|
|
42
|
+
}
|
|
43
|
+
this.tokenManager = tokenManagerCache.get(clientId);
|
|
44
|
+
// Reuse existing Cloud ID manager for this clientId if available
|
|
45
|
+
if (!cloudIdManagerCache.has(clientId)) {
|
|
46
|
+
cloudIdManagerCache.set(clientId, new CloudIdManager(this.tokenManager));
|
|
47
|
+
}
|
|
48
|
+
this.cloudIdManager = cloudIdManagerCache.get(clientId);
|
|
49
|
+
}
|
|
50
|
+
async getAuthHeaders() {
|
|
51
|
+
const accessToken = await this.tokenManager.getAccessToken();
|
|
52
|
+
return {
|
|
53
|
+
Authorization: `Bearer ${accessToken}`,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Get the Cloud ID for constructing OAuth2 API URLs
|
|
58
|
+
* @returns Confluence Cloud ID
|
|
59
|
+
*/
|
|
60
|
+
async getCloudId() {
|
|
61
|
+
return this.cloudIdManager.getCloudId();
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Force token refresh (called on 401 errors)
|
|
65
|
+
*/
|
|
66
|
+
async refreshAuth() {
|
|
67
|
+
await this.tokenManager.refreshToken();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { OAuth2TokenManager } from "./oauth2-token-manager";
|
|
2
|
+
/**
|
|
3
|
+
* Represents an accessible Atlassian Cloud resource
|
|
4
|
+
* Returned by the accessible-resources endpoint
|
|
5
|
+
*/
|
|
6
|
+
export interface AccessibleResource {
|
|
7
|
+
id: string;
|
|
8
|
+
url: string;
|
|
9
|
+
name: string;
|
|
10
|
+
scopes: string[];
|
|
11
|
+
avatarUrl: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Manages automatic Cloud ID detection for Atlassian instances
|
|
15
|
+
* The Cloud ID is required to construct API URLs for OAuth2 authentication
|
|
16
|
+
*/
|
|
17
|
+
export declare class CloudIdManager {
|
|
18
|
+
private tokenManager;
|
|
19
|
+
private cloudId;
|
|
20
|
+
private readonly resourcesEndpoint;
|
|
21
|
+
constructor(tokenManager: OAuth2TokenManager);
|
|
22
|
+
/**
|
|
23
|
+
* Get the Cloud ID for the Confluence instance
|
|
24
|
+
* Automatically detects and caches the Cloud ID on first call
|
|
25
|
+
* @returns Confluence Cloud ID (UUID format)
|
|
26
|
+
*/
|
|
27
|
+
getCloudId(): Promise<string>;
|
|
28
|
+
/**
|
|
29
|
+
* Fetch the Cloud ID from Atlassian's accessible-resources endpoint
|
|
30
|
+
* Uses the first accessible resource (standard for service accounts)
|
|
31
|
+
* @throws Error if no accessible resources are found
|
|
32
|
+
*/
|
|
33
|
+
private fetchCloudId;
|
|
34
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Manages automatic Cloud ID detection for Atlassian instances
|
|
3
|
+
* The Cloud ID is required to construct API URLs for OAuth2 authentication
|
|
4
|
+
*/
|
|
5
|
+
export class CloudIdManager {
|
|
6
|
+
constructor(tokenManager) {
|
|
7
|
+
this.tokenManager = tokenManager;
|
|
8
|
+
this.cloudId = null;
|
|
9
|
+
this.resourcesEndpoint = "https://api.atlassian.com/oauth/token/accessible-resources";
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Get the Cloud ID for the Confluence instance
|
|
13
|
+
* Automatically detects and caches the Cloud ID on first call
|
|
14
|
+
* @returns Confluence Cloud ID (UUID format)
|
|
15
|
+
*/
|
|
16
|
+
async getCloudId() {
|
|
17
|
+
if (!this.cloudId) {
|
|
18
|
+
await this.fetchCloudId();
|
|
19
|
+
}
|
|
20
|
+
return this.cloudId;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Fetch the Cloud ID from Atlassian's accessible-resources endpoint
|
|
24
|
+
* Uses the first accessible resource (standard for service accounts)
|
|
25
|
+
* @throws Error if no accessible resources are found
|
|
26
|
+
*/
|
|
27
|
+
async fetchCloudId() {
|
|
28
|
+
console.log("[CloudID] Fetching accessible resources...");
|
|
29
|
+
const startTime = Date.now();
|
|
30
|
+
const accessToken = await this.tokenManager.getAccessToken();
|
|
31
|
+
const response = await fetch(this.resourcesEndpoint, {
|
|
32
|
+
headers: {
|
|
33
|
+
Authorization: `Bearer ${accessToken}`,
|
|
34
|
+
Accept: "application/json",
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
const elapsed = Date.now() - startTime;
|
|
38
|
+
if (!response.ok) {
|
|
39
|
+
const errorBody = await response.text();
|
|
40
|
+
console.error(`[CloudID] Failed to fetch resources after ${elapsed}ms:`, response.status);
|
|
41
|
+
throw new Error(`Failed to fetch accessible resources: ${response.status} - ${errorBody}`);
|
|
42
|
+
}
|
|
43
|
+
const resources = await response.json();
|
|
44
|
+
console.log(`[CloudID] Resources received in ${elapsed}ms, count: ${resources.length}`);
|
|
45
|
+
if (resources.length === 0) {
|
|
46
|
+
console.error("[CloudID] No accessible resources found!");
|
|
47
|
+
throw new Error("No accessible Confluence sites found for this service account. " +
|
|
48
|
+
"Please verify that the service account has proper permissions.");
|
|
49
|
+
}
|
|
50
|
+
// Use the first accessible resource (typically there's only one for service accounts)
|
|
51
|
+
this.cloudId = resources[0].id;
|
|
52
|
+
console.log(`[CloudID] Using Cloud ID: ${this.cloudId}`);
|
|
53
|
+
console.log(`[CloudID] Site: ${resources[0].name} (${resources[0].url})`);
|
|
54
|
+
console.log(`[CloudID] Scopes: ${resources[0].scopes.join(", ")}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { AuthStrategy } from "./auth-strategies";
|
|
2
|
+
export interface ConfluencePage {
|
|
3
|
+
id: string;
|
|
4
|
+
title: string;
|
|
5
|
+
body: {
|
|
6
|
+
atlas_doc_format?: {
|
|
7
|
+
value: string;
|
|
8
|
+
};
|
|
9
|
+
storage?: {
|
|
10
|
+
value: string;
|
|
11
|
+
representation: string;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
version: {
|
|
15
|
+
number: number;
|
|
16
|
+
when?: string;
|
|
17
|
+
by?: {
|
|
18
|
+
displayName: string;
|
|
19
|
+
email?: string;
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
space: {
|
|
23
|
+
key: string;
|
|
24
|
+
name: string;
|
|
25
|
+
};
|
|
26
|
+
_links: {
|
|
27
|
+
webui: string;
|
|
28
|
+
};
|
|
29
|
+
children?: {
|
|
30
|
+
page?: {
|
|
31
|
+
results: ConfluenceChildPage[];
|
|
32
|
+
size: number;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
export interface ConfluenceChildPage {
|
|
37
|
+
id: string;
|
|
38
|
+
title: string;
|
|
39
|
+
type: string;
|
|
40
|
+
status: string;
|
|
41
|
+
_links: {
|
|
42
|
+
webui: string;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export declare class ConfluenceApiError extends Error {
|
|
46
|
+
statusCode?: number;
|
|
47
|
+
constructor(message: string, statusCode?: number);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Confluence API client supporting both Basic Auth and OAuth2 authentication
|
|
51
|
+
*/
|
|
52
|
+
export declare class ConfluenceClient {
|
|
53
|
+
private readonly baseUrl;
|
|
54
|
+
private readonly authStrategy;
|
|
55
|
+
/**
|
|
56
|
+
* Create a ConfluenceClient with a specific authentication strategy
|
|
57
|
+
* @param authStrategy - Authentication strategy (BasicAuthStrategy or OAuth2Strategy)
|
|
58
|
+
* @param baseUrl - Base URL for Confluence instance (required only for Basic Auth)
|
|
59
|
+
*/
|
|
60
|
+
constructor(authStrategy: AuthStrategy, baseUrl?: string);
|
|
61
|
+
/**
|
|
62
|
+
* Factory method for Basic Authentication (backward compatibility)
|
|
63
|
+
* @param baseUrl - Confluence instance URL (e.g., https://your-domain.atlassian.net)
|
|
64
|
+
* @param email - User email
|
|
65
|
+
* @param apiKey - API key
|
|
66
|
+
* @returns ConfluenceClient instance
|
|
67
|
+
*/
|
|
68
|
+
static createWithBasicAuth(baseUrl: string, email: string, apiKey: string): ConfluenceClient;
|
|
69
|
+
/**
|
|
70
|
+
* Factory method for OAuth2 authentication with service accounts
|
|
71
|
+
* @param clientId - OAuth2 Client ID
|
|
72
|
+
* @param clientSecret - OAuth2 Client Secret
|
|
73
|
+
* @returns ConfluenceClient instance
|
|
74
|
+
*/
|
|
75
|
+
static createWithOAuth2(clientId: string, clientSecret: string): ConfluenceClient;
|
|
76
|
+
/**
|
|
77
|
+
* Construct the full API URL based on authentication strategy
|
|
78
|
+
* - Basic Auth: https://{domain}.atlassian.net/wiki/rest/api/{endpoint} (API v1)
|
|
79
|
+
* - OAuth2: https://api.atlassian.com/ex/confluence/{cloudId}/wiki/api/v2/{endpoint} (API v2)
|
|
80
|
+
*/
|
|
81
|
+
private getApiUrl;
|
|
82
|
+
/**
|
|
83
|
+
* Make an authenticated request to the Confluence API
|
|
84
|
+
* Handles token refresh on 401 errors for OAuth2
|
|
85
|
+
*/
|
|
86
|
+
private makeRequest;
|
|
87
|
+
getPage(pageId: string, includeChildren?: boolean): Promise<ConfluencePage>;
|
|
88
|
+
getChildPages(pageId: string): Promise<ConfluenceChildPage[]>;
|
|
89
|
+
getCurrentUser(): Promise<any>;
|
|
90
|
+
/**
|
|
91
|
+
* Extract page ID from Confluence URL
|
|
92
|
+
* Supports formats like:
|
|
93
|
+
* - https://your-domain.atlassian.net/wiki/spaces/SPACE/pages/123456/Page+Title
|
|
94
|
+
* - https://your-domain.atlassian.net/wiki/pages/viewpage.action?pageId=123456
|
|
95
|
+
* - https://your-domain.atlassian.net/wiki/spaces/SPACE/overview?homepageId=123456
|
|
96
|
+
*/
|
|
97
|
+
static extractPageIdFromUrl(url: string): string | null;
|
|
98
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { BasicAuthStrategy, OAuth2Strategy } from "./auth-strategies";
|
|
2
|
+
export class ConfluenceApiError extends Error {
|
|
3
|
+
constructor(message, statusCode) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "ConfluenceApiError";
|
|
6
|
+
this.statusCode = statusCode;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Confluence API client supporting both Basic Auth and OAuth2 authentication
|
|
11
|
+
*/
|
|
12
|
+
export class ConfluenceClient {
|
|
13
|
+
/**
|
|
14
|
+
* Create a ConfluenceClient with a specific authentication strategy
|
|
15
|
+
* @param authStrategy - Authentication strategy (BasicAuthStrategy or OAuth2Strategy)
|
|
16
|
+
* @param baseUrl - Base URL for Confluence instance (required only for Basic Auth)
|
|
17
|
+
*/
|
|
18
|
+
constructor(authStrategy, baseUrl) {
|
|
19
|
+
this.authStrategy = authStrategy;
|
|
20
|
+
this.baseUrl = baseUrl ? baseUrl.replace(/\/$/, "") : null;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Factory method for Basic Authentication (backward compatibility)
|
|
24
|
+
* @param baseUrl - Confluence instance URL (e.g., https://your-domain.atlassian.net)
|
|
25
|
+
* @param email - User email
|
|
26
|
+
* @param apiKey - API key
|
|
27
|
+
* @returns ConfluenceClient instance
|
|
28
|
+
*/
|
|
29
|
+
static createWithBasicAuth(baseUrl, email, apiKey) {
|
|
30
|
+
return new ConfluenceClient(new BasicAuthStrategy(email, apiKey), baseUrl);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Factory method for OAuth2 authentication with service accounts
|
|
34
|
+
* @param clientId - OAuth2 Client ID
|
|
35
|
+
* @param clientSecret - OAuth2 Client Secret
|
|
36
|
+
* @returns ConfluenceClient instance
|
|
37
|
+
*/
|
|
38
|
+
static createWithOAuth2(clientId, clientSecret) {
|
|
39
|
+
return new ConfluenceClient(new OAuth2Strategy(clientId, clientSecret));
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Construct the full API URL based on authentication strategy
|
|
43
|
+
* - Basic Auth: https://{domain}.atlassian.net/wiki/rest/api/{endpoint} (API v1)
|
|
44
|
+
* - OAuth2: https://api.atlassian.com/ex/confluence/{cloudId}/wiki/api/v2/{endpoint} (API v2)
|
|
45
|
+
*/
|
|
46
|
+
async getApiUrl(endpoint) {
|
|
47
|
+
// OAuth2: Use api.atlassian.com with cloudId and API v2
|
|
48
|
+
if (this.authStrategy instanceof OAuth2Strategy) {
|
|
49
|
+
const cloudId = await this.authStrategy.getCloudId();
|
|
50
|
+
return `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/${endpoint}`;
|
|
51
|
+
}
|
|
52
|
+
// Basic Auth: Use direct instance URL with API v1
|
|
53
|
+
if (!this.baseUrl) {
|
|
54
|
+
throw new Error("Base URL is required for Basic Authentication");
|
|
55
|
+
}
|
|
56
|
+
return `${this.baseUrl}/wiki/rest/api/${endpoint}`;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Make an authenticated request to the Confluence API
|
|
60
|
+
* Handles token refresh on 401 errors for OAuth2
|
|
61
|
+
*/
|
|
62
|
+
async makeRequest(endpoint, retryCount = 0) {
|
|
63
|
+
const url = await this.getApiUrl(endpoint);
|
|
64
|
+
const authHeaders = await this.authStrategy.getAuthHeaders();
|
|
65
|
+
const response = await fetch(url, {
|
|
66
|
+
headers: {
|
|
67
|
+
...authHeaders,
|
|
68
|
+
Accept: "application/json",
|
|
69
|
+
"Content-Type": "application/json",
|
|
70
|
+
},
|
|
71
|
+
cache: "no-store", // Always fetch fresh data for confluence pages
|
|
72
|
+
});
|
|
73
|
+
// Handle 401 errors with token refresh for OAuth2 (max 1 retry to avoid infinite loops)
|
|
74
|
+
if (response.status === 401 && this.authStrategy.refreshAuth && retryCount === 0) {
|
|
75
|
+
await this.authStrategy.refreshAuth();
|
|
76
|
+
// Retry request with new token (only once)
|
|
77
|
+
return this.makeRequest(endpoint, retryCount + 1);
|
|
78
|
+
}
|
|
79
|
+
if (!response.ok) {
|
|
80
|
+
const errorBody = await response.text();
|
|
81
|
+
throw new ConfluenceApiError(`Confluence API Error: ${response.status} - ${errorBody}`, response.status);
|
|
82
|
+
}
|
|
83
|
+
const data = await response.json();
|
|
84
|
+
return data;
|
|
85
|
+
}
|
|
86
|
+
async getPage(pageId, includeChildren = false) {
|
|
87
|
+
// OAuth2 uses API v2, Basic Auth uses API v1
|
|
88
|
+
if (this.authStrategy instanceof OAuth2Strategy) {
|
|
89
|
+
// API v2 endpoint: /pages/{id}
|
|
90
|
+
// Note: v2 only accepts ONE body-format at a time
|
|
91
|
+
// We need BOTH formats: atlas_doc_format for rendering AND storage for media URLs
|
|
92
|
+
// Fetch BOTH formats in parallel (v2 API limitation: only one format per request)
|
|
93
|
+
// We need atlas_doc_format for rendering AND storage for media URLs extraction
|
|
94
|
+
const adfParams = new URLSearchParams({
|
|
95
|
+
"body-format": "atlas_doc_format",
|
|
96
|
+
});
|
|
97
|
+
if (includeChildren) {
|
|
98
|
+
adfParams.append("include-children", "true");
|
|
99
|
+
}
|
|
100
|
+
const storageParams = new URLSearchParams({
|
|
101
|
+
"body-format": "storage",
|
|
102
|
+
});
|
|
103
|
+
// Fetch both formats in parallel for better performance
|
|
104
|
+
const [pageData, storagePage] = await Promise.all([
|
|
105
|
+
this.makeRequest(`pages/${pageId}?${adfParams.toString()}`),
|
|
106
|
+
this.makeRequest(`pages/${pageId}?${storageParams.toString()}`),
|
|
107
|
+
]);
|
|
108
|
+
// Merge storage body into the page data
|
|
109
|
+
if (storagePage.body?.storage) {
|
|
110
|
+
pageData.body = pageData.body || {};
|
|
111
|
+
pageData.body.storage = storagePage.body.storage;
|
|
112
|
+
}
|
|
113
|
+
// API v2 doesn't return space object, only spaceId
|
|
114
|
+
// Fetch space details if spaceId is available
|
|
115
|
+
if (pageData.spaceId && !pageData.space) {
|
|
116
|
+
try {
|
|
117
|
+
const spaceData = await this.makeRequest(`spaces/${pageData.spaceId}`);
|
|
118
|
+
pageData.space = {
|
|
119
|
+
key: spaceData.key,
|
|
120
|
+
name: spaceData.name,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
// Fallback: create minimal space object
|
|
125
|
+
pageData.space = {
|
|
126
|
+
key: pageData.spaceId,
|
|
127
|
+
name: pageData.spaceId,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// Map v2 response to v1 structure expected by the app
|
|
132
|
+
const page = {
|
|
133
|
+
id: pageData.id,
|
|
134
|
+
title: pageData.title,
|
|
135
|
+
body: pageData.body,
|
|
136
|
+
version: pageData.version || { number: 1 },
|
|
137
|
+
space: pageData.space || { key: '', name: '' },
|
|
138
|
+
_links: pageData._links || { webui: '' },
|
|
139
|
+
children: pageData.children,
|
|
140
|
+
};
|
|
141
|
+
return page;
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
// API v1 endpoint: /content/{id}
|
|
145
|
+
const expandParams = [
|
|
146
|
+
"body.storage",
|
|
147
|
+
"body.atlas_doc_format",
|
|
148
|
+
"version",
|
|
149
|
+
"space",
|
|
150
|
+
"history.lastUpdated",
|
|
151
|
+
];
|
|
152
|
+
if (includeChildren) {
|
|
153
|
+
expandParams.push("children.page");
|
|
154
|
+
}
|
|
155
|
+
return this.makeRequest(`content/${pageId}?expand=${expandParams.join(",")}`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async getChildPages(pageId) {
|
|
159
|
+
// OAuth2 uses API v2, Basic Auth uses API v1
|
|
160
|
+
if (this.authStrategy instanceof OAuth2Strategy) {
|
|
161
|
+
// API v2 endpoint: /pages/{id}/children
|
|
162
|
+
const response = await this.makeRequest(`pages/${pageId}/children`);
|
|
163
|
+
// Map v2 response format to match v1 format expected by the app
|
|
164
|
+
// Note: v2 child pages don't have _links, we need to construct webui URL manually
|
|
165
|
+
const baseUrl = response._links?.base || 'https://confluence.atlassian.net/wiki';
|
|
166
|
+
return response.results.map((page) => ({
|
|
167
|
+
id: page.id,
|
|
168
|
+
title: page.title,
|
|
169
|
+
type: page.type || "page",
|
|
170
|
+
status: page.status || "current",
|
|
171
|
+
_links: {
|
|
172
|
+
// Construct webui URL from base URL and page ID
|
|
173
|
+
// Format: /wiki/spaces/{spaceKey}/pages/{pageId}/{pageTitle}
|
|
174
|
+
// Since we don't have spaceKey, use simpler format: /wiki/pages/{pageId}
|
|
175
|
+
webui: `${baseUrl}/pages/${page.id}`,
|
|
176
|
+
},
|
|
177
|
+
}));
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
// API v1 endpoint: /content/{id}/child/page
|
|
181
|
+
const response = await this.makeRequest(`content/${pageId}/child/page?expand=version,space`);
|
|
182
|
+
return response.results;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
async getCurrentUser() {
|
|
186
|
+
// OAuth2 uses API v2, Basic Auth uses API v1
|
|
187
|
+
if (this.authStrategy instanceof OAuth2Strategy) {
|
|
188
|
+
// API v2 doesn't have a direct "current user" endpoint
|
|
189
|
+
// We'll need to use the user endpoint with proper auth context
|
|
190
|
+
return this.makeRequest("user");
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
// API v1 endpoint
|
|
194
|
+
return this.makeRequest("user/current");
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Extract page ID from Confluence URL
|
|
199
|
+
* Supports formats like:
|
|
200
|
+
* - https://your-domain.atlassian.net/wiki/spaces/SPACE/pages/123456/Page+Title
|
|
201
|
+
* - https://your-domain.atlassian.net/wiki/pages/viewpage.action?pageId=123456
|
|
202
|
+
* - https://your-domain.atlassian.net/wiki/spaces/SPACE/overview?homepageId=123456
|
|
203
|
+
*/
|
|
204
|
+
static extractPageIdFromUrl(url) {
|
|
205
|
+
// Pattern 1: /pages/123456/title format
|
|
206
|
+
const match1 = url.match(/\/pages\/(\d+)(?:\/|$)/);
|
|
207
|
+
if (match1) {
|
|
208
|
+
return match1[1];
|
|
209
|
+
}
|
|
210
|
+
// Pattern 2: pageId=123456 query parameter
|
|
211
|
+
const match2 = url.match(/[?&]pageId=(\d+)/);
|
|
212
|
+
if (match2) {
|
|
213
|
+
return match2[1];
|
|
214
|
+
}
|
|
215
|
+
// Pattern 3: homepageId=123456 query parameter (space overview pages)
|
|
216
|
+
const match3 = url.match(/[?&]homepageId=(\d+)/);
|
|
217
|
+
if (match3) {
|
|
218
|
+
return match3[1];
|
|
219
|
+
}
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
}
|