@codybrom/denim 1.3.6 → 2.0.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/.github/workflows/publish.yml +17 -7
- package/.vscode/settings.json +34 -9
- package/CHANGELOG.md +128 -0
- package/deno.json +22 -8
- package/deno.lock +17 -59
- package/examples/edge-function.ts +171 -177
- package/mod.ts +138 -635
- package/mod_test.ts +1287 -431
- package/package.json +22 -22
- package/readme.md +155 -191
- package/src/api/createCarouselItem.ts +86 -0
- package/src/api/createThreadsContainer.ts +122 -0
- package/src/api/debugToken.ts +35 -0
- package/src/api/deleteThread.ts +36 -0
- package/src/api/exchangeCodeForToken.ts +50 -0
- package/src/api/exchangeToken.ts +36 -0
- package/src/api/getAppAccessToken.ts +35 -0
- package/src/api/getConversation.ts +51 -0
- package/src/api/getGhostPosts.ts +50 -0
- package/src/api/getLocation.ts +38 -0
- package/src/api/getMediaInsights.ts +39 -0
- package/src/api/getMentions.ts +57 -0
- package/src/api/getOEmbed.ts +41 -0
- package/src/api/getProfile.ts +46 -0
- package/src/api/getProfilePosts.ts +53 -0
- package/src/api/getPublishingLimit.ts +59 -0
- package/src/api/getReplies.ts +51 -0
- package/src/api/getSingleThread.ts +37 -0
- package/src/api/getThreadsList.ts +49 -0
- package/src/api/getUserInsights.ts +54 -0
- package/src/api/getUserReplies.ts +54 -0
- package/src/api/lookupProfile.ts +53 -0
- package/src/api/manageReply.ts +41 -0
- package/src/api/publishThreadsContainer.ts +107 -0
- package/src/api/refreshToken.ts +33 -0
- package/src/api/repost.ts +38 -0
- package/src/api/searchKeyword.ts +86 -0
- package/src/api/searchLocations.ts +46 -0
- package/src/constants.ts +80 -0
- package/src/types.ts +925 -0
- package/src/utils/checkContainerStatus.ts +39 -0
- package/src/utils/getAPI.ts +13 -0
- package/src/utils/mock_threads_api.ts +582 -0
- package/src/utils/validateRequest.ts +166 -0
- package/mock_threads_api.ts +0 -174
- package/types.ts +0 -235
package/mod.ts
CHANGED
|
@@ -1,642 +1,145 @@
|
|
|
1
|
-
// mod.ts
|
|
2
|
-
import type {
|
|
3
|
-
ThreadsPostRequest,
|
|
4
|
-
PublishingLimit,
|
|
5
|
-
ThreadsPost,
|
|
6
|
-
ThreadsListResponse,
|
|
7
|
-
MockThreadsAPI,
|
|
8
|
-
} from "./types.ts";
|
|
9
|
-
export type {
|
|
10
|
-
ThreadsPostRequest,
|
|
11
|
-
PublishingLimit,
|
|
12
|
-
ThreadsPost,
|
|
13
|
-
ThreadsListResponse,
|
|
14
|
-
};
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Retrieves the mock API instance if available.
|
|
18
|
-
*
|
|
19
|
-
* @returns The mock API instance or null if not available
|
|
20
|
-
*/
|
|
21
|
-
function getAPI(): MockThreadsAPI | null {
|
|
22
|
-
return (globalThis as { threadsAPI?: MockThreadsAPI }).threadsAPI || null;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
1
|
/**
|
|
26
2
|
* @module
|
|
27
3
|
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
/** The base URL for the Threads API */
|
|
33
|
-
export const THREADS_API_BASE_URL = "https://graph.threads.net/v1.0";
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Creates a Threads media container.
|
|
37
|
-
*
|
|
38
|
-
* @param request - The ThreadsPostRequest object containing post details
|
|
39
|
-
* @returns A Promise that resolves to the container ID
|
|
40
|
-
* @throws Will throw an error if the API request fails
|
|
41
|
-
*
|
|
42
|
-
* @example
|
|
43
|
-
* ```typescript
|
|
44
|
-
* const request: ThreadsPostRequest = {
|
|
45
|
-
* userId: "123456",
|
|
46
|
-
* accessToken: "your_access_token",
|
|
47
|
-
* mediaType: "VIDEO",
|
|
48
|
-
* text: "Check out this video!",
|
|
49
|
-
* videoUrl: "https://example.com/video.mp4",
|
|
50
|
-
* altText: "A cool video"
|
|
51
|
-
* };
|
|
52
|
-
* const containerId = await createThreadsContainer(request);
|
|
53
|
-
* ```
|
|
54
|
-
*/
|
|
55
|
-
export async function createThreadsContainer(
|
|
56
|
-
request: ThreadsPostRequest
|
|
57
|
-
): Promise<string | { id: string; permalink: string }> {
|
|
58
|
-
const api = getAPI();
|
|
59
|
-
if (api) {
|
|
60
|
-
// Use mock API
|
|
61
|
-
return api.createThreadsContainer(request);
|
|
62
|
-
}
|
|
63
|
-
try {
|
|
64
|
-
// Input validation
|
|
65
|
-
validateRequest(request);
|
|
66
|
-
|
|
67
|
-
const url = `${THREADS_API_BASE_URL}/${request.userId}/threads`;
|
|
68
|
-
const body = new URLSearchParams({
|
|
69
|
-
access_token: request.accessToken,
|
|
70
|
-
media_type: request.mediaType,
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
// Add common optional parameters
|
|
74
|
-
if (request.text) body.append("text", request.text);
|
|
75
|
-
if (request.altText) body.append("alt_text", request.altText);
|
|
76
|
-
if (request.replyControl)
|
|
77
|
-
body.append("reply_control", request.replyControl);
|
|
78
|
-
if (request.allowlistedCountryCodes) {
|
|
79
|
-
body.append(
|
|
80
|
-
"allowlisted_country_codes",
|
|
81
|
-
request.allowlistedCountryCodes.join(",")
|
|
82
|
-
);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
// Handle media type specific parameters
|
|
86
|
-
if (request.mediaType === "VIDEO" && request.videoUrl) {
|
|
87
|
-
const videoItemId = await createVideoItemContainer(request);
|
|
88
|
-
body.set("media_type", "CAROUSEL");
|
|
89
|
-
body.append("children", videoItemId);
|
|
90
|
-
} else if (request.mediaType === "IMAGE" && request.imageUrl) {
|
|
91
|
-
body.append("image_url", request.imageUrl);
|
|
92
|
-
} else if (request.mediaType === "TEXT" && request.linkAttachment) {
|
|
93
|
-
body.append("link_attachment", request.linkAttachment);
|
|
94
|
-
} else if (request.mediaType === "CAROUSEL" && request.children) {
|
|
95
|
-
body.append("children", request.children.join(","));
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
console.log(`Sending request to: ${url}`);
|
|
99
|
-
console.log(`Request body: ${body.toString()}`);
|
|
100
|
-
|
|
101
|
-
const response = await fetch(url, {
|
|
102
|
-
method: "POST",
|
|
103
|
-
body: body,
|
|
104
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
const responseText = await response.text();
|
|
108
|
-
|
|
109
|
-
console.log(`Response status: ${response.status} ${response.statusText}`);
|
|
110
|
-
console.log(`Response body: ${responseText}`);
|
|
111
|
-
|
|
112
|
-
if (!response.ok) {
|
|
113
|
-
throw new Error(`Internal Server Error. Details: ${responseText}`);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
const data = JSON.parse(responseText);
|
|
117
|
-
console.log(`Created container: ${data}`);
|
|
118
|
-
|
|
119
|
-
return data.id;
|
|
120
|
-
} catch (error) {
|
|
121
|
-
// Access error message safely
|
|
122
|
-
const errorMessage =
|
|
123
|
-
error instanceof Error ? error.message : "Unknown Error";
|
|
124
|
-
throw new Error(`Failed to create Threads container: ${errorMessage}`);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* Validates the ThreadsPostRequest object to ensure correct usage of media-specific properties.
|
|
130
|
-
*
|
|
131
|
-
* @param request - The ThreadsPostRequest object to validate
|
|
132
|
-
* @throws Will throw an error if the request contains invalid combinations of media type and properties
|
|
133
|
-
*
|
|
134
|
-
* @example
|
|
135
|
-
* ```typescript
|
|
136
|
-
* const request: ThreadsPostRequest = {
|
|
137
|
-
* userId: "123456",
|
|
138
|
-
* accessToken: "your_access_token",
|
|
139
|
-
* mediaType: "IMAGE",
|
|
140
|
-
* imageUrl: "https://example.com/image.jpg"
|
|
141
|
-
* };
|
|
142
|
-
* validateRequest(request); // This will not throw an error
|
|
143
|
-
*
|
|
144
|
-
* const invalidRequest: ThreadsPostRequest = {
|
|
145
|
-
* userId: "123456",
|
|
146
|
-
* accessToken: "your_access_token",
|
|
147
|
-
* mediaType: "TEXT",
|
|
148
|
-
* imageUrl: "https://example.com/image.jpg"
|
|
149
|
-
* };
|
|
150
|
-
* validateRequest(invalidRequest); // This will throw an error
|
|
151
|
-
* ```
|
|
152
|
-
*/
|
|
153
|
-
function validateRequest(request: ThreadsPostRequest): void {
|
|
154
|
-
if (request.mediaType !== "IMAGE" && request.imageUrl) {
|
|
155
|
-
throw new Error("imageUrl can only be used with IMAGE media type");
|
|
156
|
-
}
|
|
157
|
-
if (request.mediaType !== "VIDEO" && request.videoUrl) {
|
|
158
|
-
throw new Error("videoUrl can only be used with VIDEO media type");
|
|
159
|
-
}
|
|
160
|
-
if (request.mediaType !== "TEXT" && request.linkAttachment) {
|
|
161
|
-
throw new Error("linkAttachment can only be used with TEXT media type");
|
|
162
|
-
}
|
|
163
|
-
if (request.mediaType !== "CAROUSEL" && request.children) {
|
|
164
|
-
throw new Error("children can only be used with CAROUSEL media type");
|
|
165
|
-
}
|
|
166
|
-
if (
|
|
167
|
-
request.mediaType === "CAROUSEL" &&
|
|
168
|
-
(!request.children || request.children.length < 2)
|
|
169
|
-
) {
|
|
170
|
-
throw new Error("CAROUSEL media type requires at least 2 children");
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* Creates a video item container for Threads.
|
|
176
|
-
*
|
|
177
|
-
* @param request - The ThreadsPostRequest object containing video post details
|
|
178
|
-
* @returns A Promise that resolves to the video item container ID
|
|
179
|
-
* @throws Will throw an error if the API request fails
|
|
180
|
-
*/
|
|
181
|
-
async function createVideoItemContainer(
|
|
182
|
-
request: ThreadsPostRequest
|
|
183
|
-
): Promise<string> {
|
|
184
|
-
const url = `${THREADS_API_BASE_URL}/${request.userId}/threads`;
|
|
185
|
-
const body = new URLSearchParams({
|
|
186
|
-
access_token: request.accessToken,
|
|
187
|
-
is_carousel_item: "true",
|
|
188
|
-
media_type: "VIDEO",
|
|
189
|
-
video_url: request.videoUrl!,
|
|
190
|
-
...(request.altText && { alt_text: request.altText }),
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
const response = await fetch(url, {
|
|
194
|
-
method: "POST",
|
|
195
|
-
body: body,
|
|
196
|
-
headers: {
|
|
197
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
198
|
-
},
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
const responseText = await response.text();
|
|
202
|
-
|
|
203
|
-
if (!response.ok) {
|
|
204
|
-
throw new Error(
|
|
205
|
-
`Failed to create video item container: ${response.statusText}. Details: ${responseText}`
|
|
206
|
-
);
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
try {
|
|
210
|
-
const data = JSON.parse(responseText);
|
|
211
|
-
return data.id;
|
|
212
|
-
} catch (error) {
|
|
213
|
-
console.error(`Failed to parse response JSON: ${error}`);
|
|
214
|
-
throw new Error(`Invalid response from Threads API: ${responseText}`);
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
/**
|
|
219
|
-
* Creates a carousel item for a Threads carousel post.
|
|
220
|
-
*
|
|
221
|
-
* This function sends a request to the Threads API to create a single item
|
|
222
|
-
* that will be part of a carousel post. It can be used for both image and
|
|
223
|
-
* video items.
|
|
224
|
-
*
|
|
225
|
-
* @param request - The request object containing carousel item details
|
|
226
|
-
* @param request.userId - The user ID of the Threads account
|
|
227
|
-
* @param request.accessToken - The access token for authentication
|
|
228
|
-
* @param request.mediaType - The type of media for this carousel item ('IMAGE' or 'VIDEO')
|
|
229
|
-
* @param request.imageUrl - The URL of the image (required if mediaType is 'IMAGE')
|
|
230
|
-
* @param request.videoUrl - The URL of the video (required if mediaType is 'VIDEO')
|
|
231
|
-
* @param request.altText - Optional accessibility text for the image or video
|
|
232
|
-
* @returns A Promise that resolves to the carousel item ID
|
|
233
|
-
* @throws Will throw an error if the API request fails or returns an invalid response
|
|
234
|
-
*
|
|
235
|
-
* @example
|
|
236
|
-
* ```typescript
|
|
237
|
-
* const itemRequest = {
|
|
238
|
-
* userId: "123456",
|
|
239
|
-
* accessToken: "your_access_token",
|
|
240
|
-
* mediaType: "IMAGE" as const,
|
|
241
|
-
* imageUrl: "https://example.com/image.jpg",
|
|
242
|
-
* altText: "A beautiful landscape"
|
|
243
|
-
* };
|
|
244
|
-
* const itemId = await createCarouselItem(itemRequest);
|
|
245
|
-
* ```
|
|
4
|
+
* Denim - A Deno/TypeScript library for the Threads API.
|
|
5
|
+
* Provides complete coverage of all Threads API endpoints including
|
|
6
|
+
* posting, retrieval, replies, insights, search, locations, and more.
|
|
246
7
|
*/
|
|
247
|
-
export async function createCarouselItem(
|
|
248
|
-
request: Omit<ThreadsPostRequest, "mediaType"> & {
|
|
249
|
-
mediaType: "IMAGE" | "VIDEO";
|
|
250
|
-
}
|
|
251
|
-
): Promise<string | { id: string }> {
|
|
252
|
-
const api = getAPI();
|
|
253
|
-
if (api) {
|
|
254
|
-
// Use mock API
|
|
255
|
-
return api.createCarouselItem(request);
|
|
256
|
-
}
|
|
257
|
-
if (request.mediaType !== "IMAGE" && request.mediaType !== "VIDEO") {
|
|
258
|
-
throw new Error("Carousel items must be either IMAGE or VIDEO type");
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
if (request.mediaType === "IMAGE" && !request.imageUrl) {
|
|
262
|
-
throw new Error("imageUrl is required for IMAGE type carousel items");
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
if (request.mediaType === "VIDEO" && !request.videoUrl) {
|
|
266
|
-
throw new Error("videoUrl is required for VIDEO type carousel items");
|
|
267
|
-
}
|
|
268
8
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
* @throws Will throw an error if the API request fails
|
|
311
|
-
*/
|
|
312
|
-
async function checkContainerStatus(
|
|
313
|
-
containerId: string,
|
|
314
|
-
accessToken: string
|
|
315
|
-
): Promise<string> {
|
|
316
|
-
const url = `${THREADS_API_BASE_URL}/${containerId}?fields=status,error_message&access_token=${accessToken}`;
|
|
317
|
-
|
|
318
|
-
const response = await fetch(url);
|
|
319
|
-
if (!response.ok) {
|
|
320
|
-
throw new Error(`Failed to check container status: ${response.statusText}`);
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
const data = await response.json();
|
|
324
|
-
return data.status;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
/**
|
|
328
|
-
* Publishes a Threads media container.
|
|
329
|
-
*
|
|
330
|
-
* @param userId - The user ID of the Threads account
|
|
331
|
-
* @param accessToken - The access token for authentication
|
|
332
|
-
* @param containerId - The ID of the container to publish
|
|
333
|
-
* @returns A Promise that resolves to the published container ID
|
|
334
|
-
* @throws Will throw an error if the API request fails or if publishing times out
|
|
335
|
-
*
|
|
336
|
-
* @example
|
|
337
|
-
* ```typescript
|
|
338
|
-
* const publishedId = await publishThreadsContainer("123456", "your_access_token", "container_id");
|
|
339
|
-
* ```
|
|
340
|
-
*/
|
|
341
|
-
export async function publishThreadsContainer(
|
|
342
|
-
userId: string,
|
|
343
|
-
accessToken: string,
|
|
344
|
-
containerId: string,
|
|
345
|
-
getPermalink: boolean = false
|
|
346
|
-
): Promise<string | { id: string; permalink: string }> {
|
|
347
|
-
const api = getAPI();
|
|
348
|
-
if (api) {
|
|
349
|
-
// Use mock API
|
|
350
|
-
return api.publishThreadsContainer(
|
|
351
|
-
userId,
|
|
352
|
-
accessToken,
|
|
353
|
-
containerId,
|
|
354
|
-
getPermalink
|
|
355
|
-
);
|
|
356
|
-
}
|
|
357
|
-
try {
|
|
358
|
-
const publishUrl = `${THREADS_API_BASE_URL}/${userId}/threads_publish`;
|
|
359
|
-
const publishBody = new URLSearchParams({
|
|
360
|
-
access_token: accessToken,
|
|
361
|
-
creation_id: containerId,
|
|
362
|
-
});
|
|
363
|
-
|
|
364
|
-
const publishResponse = await fetch(publishUrl, {
|
|
365
|
-
method: "POST",
|
|
366
|
-
body: publishBody,
|
|
367
|
-
headers: {
|
|
368
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
369
|
-
},
|
|
370
|
-
});
|
|
371
|
-
|
|
372
|
-
if (!publishResponse.ok) {
|
|
373
|
-
throw new Error(
|
|
374
|
-
`Failed to publish Threads container: ${publishResponse.statusText}`
|
|
375
|
-
);
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
const publishData = await publishResponse.json();
|
|
379
|
-
|
|
380
|
-
// Check container status
|
|
381
|
-
let status = await checkContainerStatus(containerId, accessToken);
|
|
382
|
-
let attempts = 0;
|
|
383
|
-
const maxAttempts = 5;
|
|
384
|
-
|
|
385
|
-
while (
|
|
386
|
-
status !== "PUBLISHED" &&
|
|
387
|
-
status !== "FINISHED" &&
|
|
388
|
-
attempts < maxAttempts
|
|
389
|
-
) {
|
|
390
|
-
await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait for 1 second
|
|
391
|
-
status = await checkContainerStatus(containerId, accessToken);
|
|
392
|
-
attempts++;
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
if (status === "ERROR") {
|
|
396
|
-
throw new Error(`Failed to publish container. Error: ${status}`);
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
if (status !== "PUBLISHED" && status !== "FINISHED") {
|
|
400
|
-
throw new Error(
|
|
401
|
-
`Container not published after ${maxAttempts} attempts. Current status: ${status}`
|
|
402
|
-
);
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
if (getPermalink) {
|
|
406
|
-
const threadData = await getSingleThread(publishData.id, accessToken);
|
|
407
|
-
return {
|
|
408
|
-
id: publishData.id,
|
|
409
|
-
permalink: threadData.permalink || "",
|
|
410
|
-
};
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
return publishData.id;
|
|
414
|
-
} catch (error) {
|
|
415
|
-
if (error instanceof Error) {
|
|
416
|
-
throw new Error(`Failed to publish Threads container: ${error.message}`);
|
|
417
|
-
}
|
|
418
|
-
throw error;
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
/**
|
|
423
|
-
* Serves HTTP requests to create and publish Threads posts.
|
|
424
|
-
*
|
|
425
|
-
* This function sets up a server that listens for POST requests
|
|
426
|
-
* containing ThreadsPostRequest data. It creates a container and
|
|
427
|
-
* immediately publishes it.
|
|
428
|
-
*
|
|
429
|
-
* @throws Will throw an error if the request is invalid or if there's an error during processing
|
|
430
|
-
*
|
|
431
|
-
* @example
|
|
432
|
-
* ```typescript
|
|
433
|
-
* // Start the server
|
|
434
|
-
* serveRequests();
|
|
435
|
-
* ```
|
|
436
|
-
*/
|
|
437
|
-
export function serveRequests() {
|
|
438
|
-
const api = getAPI();
|
|
439
|
-
|
|
440
|
-
Deno.serve(async (req) => {
|
|
441
|
-
if (req.method !== "POST") {
|
|
442
|
-
return new Response("Method Not Allowed", { status: 405 });
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
try {
|
|
446
|
-
const requestData: ThreadsPostRequest = await req.json();
|
|
447
|
-
console.log(`Received request data: ${JSON.stringify(requestData)}`);
|
|
448
|
-
|
|
449
|
-
if (
|
|
450
|
-
!requestData.userId ||
|
|
451
|
-
!requestData.accessToken ||
|
|
452
|
-
!requestData.mediaType
|
|
453
|
-
) {
|
|
454
|
-
return new Response(
|
|
455
|
-
JSON.stringify({ success: false, error: "Missing required fields" }),
|
|
456
|
-
{
|
|
457
|
-
status: 400,
|
|
458
|
-
headers: { "Content-Type": "application/json" },
|
|
459
|
-
}
|
|
460
|
-
);
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
let containerResult;
|
|
464
|
-
let publishResult;
|
|
465
|
-
|
|
466
|
-
if (api) {
|
|
467
|
-
// Use mock API
|
|
468
|
-
containerResult = await api.createThreadsContainer(requestData);
|
|
469
|
-
publishResult = await api.publishThreadsContainer(
|
|
470
|
-
requestData.userId,
|
|
471
|
-
requestData.accessToken,
|
|
472
|
-
typeof containerResult === "string"
|
|
473
|
-
? containerResult
|
|
474
|
-
: containerResult.id,
|
|
475
|
-
requestData.getPermalink
|
|
476
|
-
);
|
|
477
|
-
} else {
|
|
478
|
-
// Use real API calls
|
|
479
|
-
containerResult = await createThreadsContainer(requestData);
|
|
480
|
-
if (typeof containerResult === "string") {
|
|
481
|
-
publishResult = await publishThreadsContainer(
|
|
482
|
-
requestData.userId,
|
|
483
|
-
requestData.accessToken,
|
|
484
|
-
containerResult,
|
|
485
|
-
requestData.getPermalink
|
|
486
|
-
);
|
|
487
|
-
} else {
|
|
488
|
-
publishResult = containerResult;
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
let responseData;
|
|
493
|
-
if (typeof publishResult === "string") {
|
|
494
|
-
responseData = { success: true, publishedId: publishResult };
|
|
495
|
-
} else {
|
|
496
|
-
responseData = {
|
|
497
|
-
success: true,
|
|
498
|
-
publishedId: publishResult.id,
|
|
499
|
-
permalink: publishResult.permalink,
|
|
500
|
-
};
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
return new Response(JSON.stringify(responseData), {
|
|
504
|
-
headers: { "Content-Type": "application/json" },
|
|
505
|
-
});
|
|
506
|
-
} catch (error) {
|
|
507
|
-
console.error("Error posting to Threads:", error);
|
|
508
|
-
return new Response(
|
|
509
|
-
JSON.stringify({
|
|
510
|
-
success: false,
|
|
511
|
-
error: error.message,
|
|
512
|
-
stack: error.stack,
|
|
513
|
-
}),
|
|
514
|
-
{
|
|
515
|
-
status: 500,
|
|
516
|
-
headers: { "Content-Type": "application/json" },
|
|
517
|
-
}
|
|
518
|
-
);
|
|
519
|
-
}
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
/**
|
|
524
|
-
* Retrieves the current publishing rate limit usage for a user.
|
|
525
|
-
*
|
|
526
|
-
* @param userId - The user ID of the Threads account
|
|
527
|
-
* @param accessToken - The access token for authentication
|
|
528
|
-
* @returns A Promise that resolves to the rate limit usage information
|
|
529
|
-
* @throws Will throw an error if the API request fails
|
|
530
|
-
* @example
|
|
531
|
-
* ```typescript
|
|
532
|
-
* const rateLimit = await getPublishingLimit("123456", "your_access_token");
|
|
533
|
-
* console.log(`Current usage: ${rateLimit.quota_usage}`);
|
|
534
|
-
* ```
|
|
535
|
-
*/
|
|
536
|
-
export async function getPublishingLimit(
|
|
537
|
-
userId: string,
|
|
538
|
-
accessToken: string
|
|
539
|
-
): Promise<PublishingLimit> {
|
|
540
|
-
const api = getAPI();
|
|
541
|
-
if (api) {
|
|
542
|
-
// Use mock API
|
|
543
|
-
return api.getPublishingLimit(userId, accessToken);
|
|
544
|
-
}
|
|
545
|
-
const url = `${THREADS_API_BASE_URL}/${userId}/threads_publishing_limit`;
|
|
546
|
-
const params = new URLSearchParams({
|
|
547
|
-
access_token: accessToken,
|
|
548
|
-
fields: "quota_usage,config",
|
|
549
|
-
});
|
|
550
|
-
|
|
551
|
-
const response = await fetch(`${url}?${params}`);
|
|
552
|
-
if (!response.ok) {
|
|
553
|
-
throw new Error(`Failed to get publishing limit: ${response.statusText}`);
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
const data = await response.json();
|
|
557
|
-
return data.data[0];
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
/**
|
|
561
|
-
* Retrieves a list of all threads created by a user.
|
|
562
|
-
*
|
|
563
|
-
* @param userId - The user ID of the Threads account
|
|
564
|
-
* @param accessToken - The access token for authentication
|
|
565
|
-
* @param options - Optional parameters for the request
|
|
566
|
-
* @param options.since - Start date for fetching threads (ISO 8601 format)
|
|
567
|
-
* @param options.until - End date for fetching threads (ISO 8601 format)
|
|
568
|
-
* @param options.limit - Maximum number of threads to return
|
|
569
|
-
* @param options.after - Cursor for pagination (next page)
|
|
570
|
-
* @param options.before - Cursor for pagination (previous page)
|
|
571
|
-
* @returns A Promise that resolves to the ThreadsListResponse
|
|
572
|
-
* @throws Will throw an error if the API request fails
|
|
573
|
-
*/
|
|
574
|
-
export async function getThreadsList(
|
|
575
|
-
userId: string,
|
|
576
|
-
accessToken: string,
|
|
577
|
-
options?: {
|
|
578
|
-
since?: string;
|
|
579
|
-
until?: string;
|
|
580
|
-
limit?: number;
|
|
581
|
-
after?: string;
|
|
582
|
-
before?: string;
|
|
583
|
-
}
|
|
584
|
-
): Promise<ThreadsListResponse> {
|
|
585
|
-
const api = getAPI();
|
|
586
|
-
if (api) {
|
|
587
|
-
// Use mock API
|
|
588
|
-
return api.getThreadsList(userId, accessToken, options);
|
|
589
|
-
}
|
|
590
|
-
const fields =
|
|
591
|
-
"id,media_product_type,media_type,media_url,permalink,owner,username,text,timestamp,shortcode,thumbnail_url,children,is_quote_post";
|
|
592
|
-
const url = new URL(`${THREADS_API_BASE_URL}/${userId}/threads`);
|
|
593
|
-
url.searchParams.append("fields", fields);
|
|
594
|
-
url.searchParams.append("access_token", accessToken);
|
|
595
|
-
|
|
596
|
-
if (options) {
|
|
597
|
-
if (options.since) url.searchParams.append("since", options.since);
|
|
598
|
-
if (options.until) url.searchParams.append("until", options.until);
|
|
599
|
-
if (options.limit)
|
|
600
|
-
url.searchParams.append("limit", options.limit.toString());
|
|
601
|
-
if (options.after) url.searchParams.append("after", options.after);
|
|
602
|
-
if (options.before) url.searchParams.append("before", options.before);
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
const response = await fetch(url.toString());
|
|
606
|
-
if (!response.ok) {
|
|
607
|
-
throw new Error(`Failed to retrieve threads list: ${response.statusText}`);
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
return await response.json();
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
/**
|
|
614
|
-
* Retrieves a single Threads media object.
|
|
615
|
-
*
|
|
616
|
-
* @param mediaId - The ID of the Threads media object
|
|
617
|
-
* @param accessToken - The access token for authentication
|
|
618
|
-
* @returns A Promise that resolves to the ThreadsPost object
|
|
619
|
-
* @throws Will throw an error if the API request fails
|
|
620
|
-
*/
|
|
621
|
-
export async function getSingleThread(
|
|
622
|
-
mediaId: string,
|
|
623
|
-
accessToken: string
|
|
624
|
-
): Promise<ThreadsPost> {
|
|
625
|
-
const api = getAPI();
|
|
626
|
-
if (api) {
|
|
627
|
-
// Use mock API
|
|
628
|
-
return api.getSingleThread(mediaId, accessToken);
|
|
629
|
-
}
|
|
630
|
-
const fields =
|
|
631
|
-
"id,media_product_type,media_type,media_url,permalink,owner,username,text,timestamp,shortcode,thumbnail_url,children,is_quote_post";
|
|
632
|
-
const url = new URL(`${THREADS_API_BASE_URL}/${mediaId}`);
|
|
633
|
-
url.searchParams.append("fields", fields);
|
|
634
|
-
url.searchParams.append("access_token", accessToken);
|
|
9
|
+
// ─── Types ───────────────────────────────────────────────────────────────────
|
|
10
|
+
import type {
|
|
11
|
+
AuthCodeResponse,
|
|
12
|
+
CursorPaginationOptions,
|
|
13
|
+
DebugTokenInfo,
|
|
14
|
+
GifAttachment,
|
|
15
|
+
InsightValue,
|
|
16
|
+
KeywordSearchOptions,
|
|
17
|
+
LocationSearchOptions,
|
|
18
|
+
MediaInsight,
|
|
19
|
+
MediaInsightsResponse,
|
|
20
|
+
MediaType,
|
|
21
|
+
MockThreadsAPI,
|
|
22
|
+
OEmbedResponse,
|
|
23
|
+
PaginationOptions,
|
|
24
|
+
PollAttachment,
|
|
25
|
+
PollAttachmentInput,
|
|
26
|
+
PublicProfile,
|
|
27
|
+
PublishingLimit,
|
|
28
|
+
QuotaConfig,
|
|
29
|
+
ReplyControl,
|
|
30
|
+
ResponseMediaType,
|
|
31
|
+
TextAttachment,
|
|
32
|
+
TextAttachmentInput,
|
|
33
|
+
TextEntity,
|
|
34
|
+
ThreadsContainer,
|
|
35
|
+
ThreadsListResponse,
|
|
36
|
+
ThreadsLocation,
|
|
37
|
+
ThreadsPost,
|
|
38
|
+
ThreadsPostRequest,
|
|
39
|
+
ThreadsProfile,
|
|
40
|
+
TokenResponse,
|
|
41
|
+
UserInsight,
|
|
42
|
+
UserInsightsOptions,
|
|
43
|
+
UserInsightsResponse,
|
|
44
|
+
WebhookDeleteValue,
|
|
45
|
+
WebhookMentionValue,
|
|
46
|
+
WebhookPayload,
|
|
47
|
+
WebhookPublishValue,
|
|
48
|
+
WebhookReplyValue,
|
|
49
|
+
} from "./src/types.ts";
|
|
635
50
|
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
51
|
+
export type {
|
|
52
|
+
AuthCodeResponse,
|
|
53
|
+
CursorPaginationOptions,
|
|
54
|
+
DebugTokenInfo,
|
|
55
|
+
GifAttachment,
|
|
56
|
+
InsightValue,
|
|
57
|
+
KeywordSearchOptions,
|
|
58
|
+
LocationSearchOptions,
|
|
59
|
+
MediaInsight,
|
|
60
|
+
MediaInsightsResponse,
|
|
61
|
+
MediaType,
|
|
62
|
+
MockThreadsAPI,
|
|
63
|
+
OEmbedResponse,
|
|
64
|
+
PaginationOptions,
|
|
65
|
+
PollAttachment,
|
|
66
|
+
PollAttachmentInput,
|
|
67
|
+
PublicProfile,
|
|
68
|
+
PublishingLimit,
|
|
69
|
+
QuotaConfig,
|
|
70
|
+
ReplyControl,
|
|
71
|
+
ResponseMediaType,
|
|
72
|
+
TextAttachment,
|
|
73
|
+
TextAttachmentInput,
|
|
74
|
+
TextEntity,
|
|
75
|
+
ThreadsContainer,
|
|
76
|
+
ThreadsListResponse,
|
|
77
|
+
ThreadsLocation,
|
|
78
|
+
ThreadsPost,
|
|
79
|
+
ThreadsPostRequest,
|
|
80
|
+
ThreadsProfile,
|
|
81
|
+
TokenResponse,
|
|
82
|
+
UserInsight,
|
|
83
|
+
UserInsightsOptions,
|
|
84
|
+
UserInsightsResponse,
|
|
85
|
+
WebhookDeleteValue,
|
|
86
|
+
WebhookMentionValue,
|
|
87
|
+
WebhookPayload,
|
|
88
|
+
WebhookPublishValue,
|
|
89
|
+
WebhookReplyValue,
|
|
90
|
+
};
|
|
640
91
|
|
|
641
|
-
|
|
642
|
-
}
|
|
92
|
+
// ─── Publishing ──────────────────────────────────────────────────────────────
|
|
93
|
+
export { createCarouselItem } from "./src/api/createCarouselItem.ts";
|
|
94
|
+
export { createThreadsContainer } from "./src/api/createThreadsContainer.ts";
|
|
95
|
+
export { deleteThread } from "./src/api/deleteThread.ts";
|
|
96
|
+
export { publishThreadsContainer } from "./src/api/publishThreadsContainer.ts";
|
|
97
|
+
export { repost } from "./src/api/repost.ts";
|
|
98
|
+
|
|
99
|
+
// ─── Retrieval ───────────────────────────────────────────────────────────────
|
|
100
|
+
export { getGhostPosts } from "./src/api/getGhostPosts.ts";
|
|
101
|
+
export { getSingleThread } from "./src/api/getSingleThread.ts";
|
|
102
|
+
export { getThreadsList } from "./src/api/getThreadsList.ts";
|
|
103
|
+
|
|
104
|
+
// ─── Profiles ────────────────────────────────────────────────────────────────
|
|
105
|
+
export { getProfile } from "./src/api/getProfile.ts";
|
|
106
|
+
export { getProfilePosts } from "./src/api/getProfilePosts.ts";
|
|
107
|
+
export { lookupProfile } from "./src/api/lookupProfile.ts";
|
|
108
|
+
|
|
109
|
+
// ─── Replies ─────────────────────────────────────────────────────────────────
|
|
110
|
+
export { getConversation } from "./src/api/getConversation.ts";
|
|
111
|
+
export { getReplies } from "./src/api/getReplies.ts";
|
|
112
|
+
export { getUserReplies } from "./src/api/getUserReplies.ts";
|
|
113
|
+
export { manageReply } from "./src/api/manageReply.ts";
|
|
114
|
+
|
|
115
|
+
// ─── Mentions ────────────────────────────────────────────────────────────────
|
|
116
|
+
export { getMentions } from "./src/api/getMentions.ts";
|
|
117
|
+
|
|
118
|
+
// ─── Insights ────────────────────────────────────────────────────────────────
|
|
119
|
+
export { getMediaInsights } from "./src/api/getMediaInsights.ts";
|
|
120
|
+
export { getUserInsights } from "./src/api/getUserInsights.ts";
|
|
121
|
+
|
|
122
|
+
// ─── Search ──────────────────────────────────────────────────────────────────
|
|
123
|
+
export { getLocation } from "./src/api/getLocation.ts";
|
|
124
|
+
export { searchKeyword } from "./src/api/searchKeyword.ts";
|
|
125
|
+
export { searchLocations } from "./src/api/searchLocations.ts";
|
|
126
|
+
|
|
127
|
+
// ─── Tokens ──────────────────────────────────────────────────────────────────
|
|
128
|
+
export { debugToken } from "./src/api/debugToken.ts";
|
|
129
|
+
export { exchangeCodeForToken } from "./src/api/exchangeCodeForToken.ts";
|
|
130
|
+
export { exchangeToken } from "./src/api/exchangeToken.ts";
|
|
131
|
+
export { getAppAccessToken } from "./src/api/getAppAccessToken.ts";
|
|
132
|
+
export { refreshToken } from "./src/api/refreshToken.ts";
|
|
133
|
+
|
|
134
|
+
// ─── oEmbed ──────────────────────────────────────────────────────────────────
|
|
135
|
+
export { getOEmbed } from "./src/api/getOEmbed.ts";
|
|
136
|
+
|
|
137
|
+
// ─── Rate Limits ─────────────────────────────────────────────────────────────
|
|
138
|
+
export { getPublishingLimit } from "./src/api/getPublishingLimit.ts";
|
|
139
|
+
|
|
140
|
+
// ─── Utilities ───────────────────────────────────────────────────────────────
|
|
141
|
+
export { checkContainerStatus } from "./src/utils/checkContainerStatus.ts";
|
|
142
|
+
export { validateRequest } from "./src/utils/validateRequest.ts";
|
|
143
|
+
|
|
144
|
+
// ─── Testing ─────────────────────────────────────────────────────────────────
|
|
145
|
+
export { MockThreadsAPIImpl } from "./src/utils/mock_threads_api.ts";
|