-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathwordpress.ts
More file actions
273 lines (229 loc) · 7.76 KB
/
Copy pathwordpress.ts
File metadata and controls
273 lines (229 loc) · 7.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import { createLogger } from '@sim/logger'
import { getErrorMessage, toError } from '@sim/utils/errors'
import { fetchWithRetry, VALIDATE_RETRY_OPTIONS } from '@/lib/knowledge/documents/utils'
import type { ConnectorConfig, ExternalDocument, ExternalDocumentList } from '@/connectors/types'
import { htmlToPlainText, joinTagArray, parseTagDate } from '@/connectors/utils'
import { DEFAULT_MAX_POSTS, wordpressConnectorMeta } from '@/connectors/wordpress/meta'
const logger = createLogger('WordPressConnector')
const WP_API_BASE = 'https://public-api.wordpress.com/rest/v1.1/sites'
/**
* Strips protocol prefix and trailing slashes from a site URL so the
* WordPress.com API receives a bare domain (e.g. "mysite.wordpress.com").
*/
function normalizeSiteUrl(raw: string): string {
return raw.replace(/^https?:\/\//, '').replace(/\/+$/, '')
}
const POSTS_PER_PAGE = 20
interface WordPressPost {
ID: number
title: string
content: string
URL: string
modified: string
type: string
author: {
name: string
}
categories: Record<string, { name: string }>
tags: Record<string, { name: string }>
}
interface WordPressPostsResponse {
found: number
posts: WordPressPost[]
}
interface ListCursor {
offset: number
}
/**
* Extracts category names from a WordPress categories object.
*/
function extractCategoryNames(categories: Record<string, { name: string }>): string[] {
return Object.values(categories).map((c) => c.name)
}
/**
* Extracts tag names from a WordPress tags object.
*/
function extractTagNames(tags: Record<string, { name: string }>): string[] {
return Object.values(tags).map((t) => t.name)
}
/**
* Converts a WordPress post to an ExternalDocument.
*/
function postToDocument(post: WordPressPost): ExternalDocument {
const plainText = htmlToPlainText(post.content)
const fullContent = `# ${post.title}\n\n${plainText}`
const contentHash = `wordpress:${post.ID}:${post.modified || ''}`
const categories = extractCategoryNames(post.categories)
const tags = extractTagNames(post.tags)
return {
externalId: String(post.ID),
title: post.title || 'Untitled',
content: fullContent,
mimeType: 'text/plain',
sourceUrl: post.URL,
contentHash,
metadata: {
author: post.author?.name,
lastModified: post.modified,
postType: post.type,
categories,
tags,
},
}
}
/**
* Resolves the postType config value to the WordPress API type parameter.
*/
function resolvePostType(postType?: string): string {
switch (postType) {
case 'Posts':
return 'post'
case 'Pages':
return 'page'
default:
return 'any'
}
}
export const wordpressConnector: ConnectorConfig = {
...wordpressConnectorMeta,
listDocuments: async (
accessToken: string,
sourceConfig: Record<string, unknown>,
cursor?: string,
syncContext?: Record<string, unknown>
): Promise<ExternalDocumentList> => {
const rawSiteUrl = (sourceConfig.siteUrl as string)?.trim()
if (!rawSiteUrl) {
throw new Error('Site URL is required')
}
const siteUrl = normalizeSiteUrl(rawSiteUrl)
const maxPosts = sourceConfig.maxPosts ? Number(sourceConfig.maxPosts) : DEFAULT_MAX_POSTS
const type = resolvePostType(sourceConfig.postType as string | undefined)
const parsed: ListCursor = cursor ? JSON.parse(cursor) : { offset: 0 }
const totalDocsFetched = (syncContext?.totalDocsFetched as number) ?? 0
const remaining = maxPosts > 0 ? maxPosts - totalDocsFetched : POSTS_PER_PAGE
if (remaining <= 0) {
return { documents: [], hasMore: false }
}
const pageSize = Math.min(POSTS_PER_PAGE, remaining)
const url = `${WP_API_BASE}/${encodeURIComponent(siteUrl)}/posts?number=${pageSize}&offset=${parsed.offset}&type=${type}`
logger.info('Fetching WordPress posts', { siteUrl, offset: parsed.offset, type, pageSize })
const response = await fetchWithRetry(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: 'application/json',
},
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
throw new Error(`WordPress API error: ${response.status} ${errorText}`)
}
const data = (await response.json()) as WordPressPostsResponse
const posts = data.posts || []
const documents = posts.map(postToDocument)
const totalFetched = totalDocsFetched + documents.length
if (syncContext) syncContext.totalDocsFetched = totalFetched
const hitLimit = maxPosts > 0 && totalFetched >= maxPosts
const newOffset = parsed.offset + posts.length
const hasMore = !hitLimit && newOffset < data.found
return {
documents,
hasMore,
nextCursor: hasMore ? JSON.stringify({ offset: newOffset }) : undefined,
}
},
getDocument: async (
accessToken: string,
sourceConfig: Record<string, unknown>,
externalId: string
): Promise<ExternalDocument | null> => {
const rawSiteUrl = (sourceConfig.siteUrl as string)?.trim()
if (!rawSiteUrl) {
throw new Error('Site URL is required')
}
const siteUrl = normalizeSiteUrl(rawSiteUrl)
const url = `${WP_API_BASE}/${encodeURIComponent(siteUrl)}/posts/${externalId}`
try {
const response = await fetchWithRetry(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: 'application/json',
},
})
if (!response.ok) {
if (response.status === 404) return null
throw new Error(`WordPress API error: ${response.status}`)
}
const post = (await response.json()) as WordPressPost
return postToDocument(post)
} catch (error) {
logger.warn('Failed to get WordPress document', {
externalId,
error: toError(error).message,
})
return null
}
},
validateConfig: async (
accessToken: string,
sourceConfig: Record<string, unknown>
): Promise<{ valid: boolean; error?: string }> => {
const rawSiteUrl = (sourceConfig.siteUrl as string)?.trim()
const maxPosts = sourceConfig.maxPosts as string | undefined
if (!rawSiteUrl) {
return { valid: false, error: 'Site URL is required' }
}
const siteUrl = normalizeSiteUrl(rawSiteUrl)
if (maxPosts && (Number.isNaN(Number(maxPosts)) || Number(maxPosts) <= 0)) {
return { valid: false, error: 'Max posts must be a positive number' }
}
try {
const url = `${WP_API_BASE}/${encodeURIComponent(siteUrl)}`
const response = await fetchWithRetry(
url,
{
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: 'application/json',
},
},
VALIDATE_RETRY_OPTIONS
)
if (!response.ok) {
if (response.status === 404) {
return { valid: false, error: `Site not found: ${siteUrl}` }
}
return { valid: false, error: `WordPress API error: ${response.status}` }
}
return { valid: true }
} catch (error) {
const message = getErrorMessage(error, 'Failed to validate configuration')
return { valid: false, error: message }
}
},
mapTags: (metadata: Record<string, unknown>): Record<string, unknown> => {
const result: Record<string, unknown> = {}
if (typeof metadata.author === 'string') {
result.author = metadata.author
}
const lastModified = parseTagDate(metadata.lastModified)
if (lastModified) {
result.lastModified = lastModified
}
if (typeof metadata.postType === 'string') {
result.postType = metadata.postType
}
const categories = joinTagArray(metadata.categories)
if (categories) {
result.categories = categories
}
const tags = joinTagArray(metadata.tags)
if (tags) {
result.tags = tags
}
return result
},
}