vidnavigator 2.0.0 → 2.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/src/index.ts CHANGED
@@ -1,1082 +1,1081 @@
1
- import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
2
- import FormData from 'form-data';
3
- import fs from 'fs';
4
- import {
5
- VideoInfo,
6
- VideoInfoJSON,
7
- TranscriptSegmentJSON,
8
- TranscriptOutput,
9
- transcriptFromJSON,
10
- FileInfo,
11
- FileInfoJSON,
12
- AnalysisResult,
13
- AnalysisResultJSON,
14
- VideoSearchResult,
15
- VideoSearchResultJSON,
16
- FileSearchResult,
17
- FileSearchResultJSON,
18
- UsageData,
19
- UsageDataJSON,
20
- Namespace,
21
- NamespaceJSON,
22
- NamespaceRef,
23
- NamespaceRefJSON,
24
- ExtractionSchema,
25
- UsageBlock,
26
- UsageBlockJSON,
27
- CarouselInfo,
28
- CarouselInfoJSON,
29
- CarouselVideoResult,
30
- CarouselVideoResultJSON,
31
- TikTokProfileScrapeRequest,
32
- TikTokProfileScrapeSubmission,
33
- TikTokProfileScrapeSubmissionJSON,
34
- TikTokProfileTask,
35
- TikTokProfileTaskJSON,
36
- TikTokSearchRequest,
37
- TikTokSearchSubmission,
38
- TikTokSearchSubmissionJSON,
39
- TikTokSearchTask,
40
- TikTokSearchTaskJSON,
41
- TweetStatement,
42
- AsyncJob,
43
- AsyncJobJSON,
44
- AsyncJobAccepted,
45
- AsyncJobAcceptedJSON,
46
- TikTokProfilePagination,
47
- } from './models';
48
- import { VidNavigatorError, PaymentRequiredError } from './errors';
49
- import { buildApiError } from './http';
50
- import { Job, JobInfo, JobOperation, PollableTask, PollOptions, RunOptions, SubmitOptions } from './jobs';
51
-
52
- export * from './models';
53
- export * from './errors';
54
- export * from './webhooks';
55
- export { Job } from './jobs';
56
- export type { TaskStatus, PollableTask, PollOptions, JobOperation, SubmitOptions, RunOptions, JobInfo } from './jobs';
57
-
58
- /** SDK version (keep in sync with package.json) */
59
- export const SDK_VERSION = '2.0.0';
60
-
61
- //region --- Interfaces ---
62
- export interface SDKConfig {
63
- apiKey: string;
64
- baseURL?: string;
65
- axiosConfig?: AxiosRequestConfig;
66
- }
67
-
68
- interface ApiSuccessResponse<T> {
69
- status: 'success';
70
- data: T;
71
- usage?: UsageBlockJSON;
72
- }
73
-
74
- export type TranscriptRequestPayload = {
75
- video_url: string;
76
- language?: string;
77
- metadata_only?: boolean;
78
- fallback_to_metadata?: boolean;
79
- transcript_text?: boolean;
80
- include_usage?: boolean;
81
- };
82
-
83
- export type TranscribeVideoPayload = {
84
- video_url: string;
85
- transcript_text?: boolean;
86
- all_videos?: boolean;
87
- include_usage?: boolean;
88
- } & WebhookOption;
89
-
90
- /**
91
- * Where to POST a notification when an async job finishes. Overrides the account-level default
92
- * configured in Studio → API; pass an empty string to opt this job out of that default.
93
- * Must be a publicly reachable https URL. This is a pass-through: polling always works either way.
94
- */
95
- export type WebhookOption = { webhook_url?: string };
96
-
97
- /** Input for {@link VidNavigatorClient.transcribe}. A plain string is treated as `video_url`. */
98
- export type TranscribeInput = {
99
- video_url: string;
100
- transcript_text?: boolean;
101
- /** Instagram carousel posts only: transcribe every video in the post. */
102
- all_videos?: boolean;
103
- } & WebhookOption;
104
-
105
- /** Input for {@link VidNavigatorClient.extractVideo}: a JSON `schema`, or a JSON/YAML `schemaFilePath`. */
106
- export type ExtractVideoInput =
107
- | ({
108
- video_url: string;
109
- schema: ExtractionSchema;
110
- what_to_extract?: string;
111
- /** Speech-to-text the audio when no platform transcript exists. Default true. */
112
- transcribe?: boolean;
113
- } & WebhookOption)
114
- | ({
115
- video_url: string;
116
- /** Path to a JSON or YAML schema file (sent as multipart form-data). */
117
- schemaFilePath: string;
118
- what_to_extract?: string;
119
- transcribe?: boolean;
120
- } & WebhookOption);
121
-
122
- /** Input for {@link VidNavigatorClient.tweetStatement}. A plain string is treated as `tweet_id`. */
123
- export type TweetStatementInput = { tweet_id: string } & WebhookOption;
124
-
125
- export type TranscriptResult = {
126
- video_info: VideoInfo;
127
- transcript: TranscriptOutput;
128
- usage?: UsageBlock;
129
- };
130
-
131
- export type TranscribeVideoSingleResult = {
132
- video_info: VideoInfo;
133
- transcript: TranscriptOutput;
134
- usage?: UsageBlock;
135
- };
136
-
137
- export type TranscribeVideoCarouselResult = {
138
- carousel_info: CarouselInfo;
139
- videos: CarouselVideoResult[];
140
- usage?: UsageBlock;
141
- };
142
-
143
- export type TranscribeVideoResult = TranscribeVideoSingleResult | TranscribeVideoCarouselResult;
144
-
145
- /** Snapshot of a transcription task. `result` has the same shape as {@link VidNavigatorClient.transcribe}'s return value. */
146
- export type TranscribeAsyncJob = AsyncJob<TranscribeVideoResult>;
147
-
148
- /** Snapshot of an extraction task. `result` is the extracted object, shaped like your schema. */
149
- export type ExtractVideoAsyncJob = AsyncJob<Record<string, unknown>>;
150
-
151
- /** Snapshot of a tweet claim analysis task. `result` is a {@link TweetStatement}. */
152
- export type TweetStatementAsyncJob = AsyncJob<TweetStatement>;
153
-
154
- export type TranscribeJob = Job<TranscribeAsyncJob, TranscribeVideoResult>;
155
-
156
- /** Input that always yields a single-video result (the carousel shape needs `all_videos: true`). */
157
- type SingleTranscribeInput = string | (TranscribeInput & { all_videos?: false });
158
-
159
- /**
160
- * {@link JobOperation} for transcription, typed so that a plain URL (or `all_videos` left off)
161
- * resolves to {@link TranscribeVideoSingleResult}.
162
- */
163
- export interface TranscribeOperation extends JobOperation<string | TranscribeInput, TranscribeAsyncJob, TranscribeVideoResult> {
164
- (input: SingleTranscribeInput, options?: RunOptions<TranscribeAsyncJob>): Promise<TranscribeVideoSingleResult>;
165
- (input: string | TranscribeInput, options?: RunOptions<TranscribeAsyncJob>): Promise<TranscribeVideoResult>;
166
- submit(input: SingleTranscribeInput, options?: SubmitOptions): Promise<Job<TranscribeAsyncJob, TranscribeVideoSingleResult>>;
167
- submit(input: string | TranscribeInput, options?: SubmitOptions): Promise<Job<TranscribeAsyncJob, TranscribeVideoResult>>;
168
- }
169
- export type ExtractVideoJob = Job<ExtractVideoAsyncJob, ExtractDataResult>;
170
- export type TweetStatementJob = Job<TweetStatementAsyncJob, TweetStatement>;
171
- /** `result()` resolves to the completed task with **all** pages of `videos` collected. */
172
- export type TikTokProfileJob = Job<TikTokProfileTask, TikTokProfileTask>;
173
- /** `result()` resolves to the completed task with **all** pages of `results` collected. */
174
- export type TikTokSearchJob = Job<TikTokSearchTask, TikTokSearchTask>;
175
-
176
- export type UploadFileSuccessResult = {
177
- status: 'success';
178
- file_id: string;
179
- file_name: string;
180
- file_status: 'processing' | 'completed';
181
- message: string;
182
- file_info: FileInfo;
183
- };
184
-
185
- export type UploadFileAcceptedResult = {
186
- status: 'accepted';
187
- file_id: string;
188
- file_name: string;
189
- file_status: 'processing';
190
- message: string;
191
- note?: string;
192
- file_info?: FileInfo;
193
- };
194
-
195
- export type UploadFileResult = UploadFileSuccessResult | UploadFileAcceptedResult;
196
-
197
- export interface ExtractDataResult {
198
- data: Record<string, unknown>;
199
- video_info?: VideoInfo;
200
- file_info?: FileInfo;
201
- usage?: UsageBlock;
202
- }
203
-
204
- export type YouTubeSearchFocus = 'relevance' | 'popularity' | 'brevity';
205
-
206
- export type SearchYouTubePayload = {
207
- query: string;
208
- use_enhanced_search?: boolean;
209
- start_year?: number;
210
- end_year?: number;
211
- focus?: YouTubeSearchFocus;
212
- duration?: number;
213
- max_results?: number;
214
- include_usage?: boolean;
215
- };
216
-
217
- export type SearchYouTubeResult = {
218
- results: VideoSearchResult[];
219
- query: string;
220
- total_found: number;
221
- explanation?: string;
222
- usage?: UsageBlock;
223
- /** Present when a 402 partial-results response is returned. */
224
- status?: 'success' | 'partial';
225
- /** Present on partial results (e.g. `insufficient_credits_video_search`). */
226
- error_code?: string;
227
- };
228
-
229
- export type SearchFilesPayload = {
230
- query: string;
231
- namespace_ids?: string[];
232
- include_usage?: boolean;
233
- };
234
-
235
- export type SearchFilesResult = {
236
- results: FileSearchResult[];
237
- query: string;
238
- total_found: number;
239
- explanation?: string;
240
- usage?: UsageBlock;
241
- };
242
-
243
- export type AnalyzeVideoPayload = {
244
- video_url: string;
245
- query?: string;
246
- transcript_text?: boolean;
247
- include_usage?: boolean;
248
- };
249
-
250
- export type AnalyzeFilePayload = {
251
- file_id: string;
252
- query?: string;
253
- transcript_text?: boolean;
254
- include_usage?: boolean;
255
- };
256
-
257
- export type AnalyzeVideoResult = {
258
- video_info: VideoInfo;
259
- transcript: TranscriptOutput;
260
- transcript_analysis: AnalysisResult;
261
- usage?: UsageBlock;
262
- };
263
-
264
- export type AnalyzeFileResult = {
265
- file_info: FileInfo;
266
- transcript: TranscriptOutput;
267
- transcript_analysis: AnalysisResult;
268
- usage?: UsageBlock;
269
- };
270
-
271
- export type ExtractVideoDataPayload = {
272
- video_url: string;
273
- schema: ExtractionSchema;
274
- what_to_extract?: string;
275
- transcribe?: boolean;
276
- include_usage?: boolean;
277
- } & WebhookOption;
278
-
279
- export type ExtractVideoDataMultipartPayload = {
280
- video_url: string;
281
- /** Path to a JSON or YAML schema file. The API accepts either a raw schema or a full extraction request object. */
282
- schemaFilePath: string;
283
- what_to_extract?: string;
284
- transcribe?: boolean;
285
- include_usage?: boolean;
286
- } & WebhookOption;
287
-
288
- export type TweetStatementPayload = { tweet_id: string } & WebhookOption;
289
-
290
- export type ExtractFileDataPayload = {
291
- file_id: string;
292
- schema: ExtractionSchema;
293
- what_to_extract?: string;
294
- include_usage?: boolean;
295
- };
296
-
297
- export type ExtractFileDataMultipartPayload = {
298
- file_id: string;
299
- /** Path to a JSON or YAML schema file. The API accepts either a raw schema or a full extraction request object. */
300
- schemaFilePath: string;
301
- what_to_extract?: string;
302
- include_usage?: boolean;
303
- };
304
- //endregion
305
-
306
- function parseTranscribeData(
307
- inner:
308
- | { video_info: VideoInfoJSON; transcript: TranscriptSegmentJSON[] | string }
309
- | { carousel_info: CarouselInfoJSON; videos: CarouselVideoResultJSON[] },
310
- usage?: UsageBlock
311
- ): TranscribeVideoResult {
312
- if ('videos' in inner && 'carousel_info' in inner) {
313
- return {
314
- carousel_info: CarouselInfo.fromJSON(inner.carousel_info),
315
- videos: inner.videos.map((v) => CarouselVideoResult.fromJSON(v)),
316
- usage,
317
- };
318
- }
319
- const single = inner as { video_info: VideoInfoJSON; transcript: TranscriptSegmentJSON[] | string };
320
- return {
321
- video_info: VideoInfo.fromJSON(single.video_info),
322
- transcript: transcriptFromJSON(single.transcript)!,
323
- usage,
324
- };
325
- }
326
-
327
- function buildAsyncJobParams(options?: SubmitOptions): Record<string, string> | undefined {
328
- // Like the TikTok pollers, the async job pollers take include_usage as a query string value.
329
- return options?.include_usage ? { include_usage: 'true' } : undefined;
330
- }
331
-
332
- function requireResult<T>(task: AsyncJob<T>): T {
333
- if (task.result === null) {
334
- const err = new VidNavigatorError(`Task ${task.task_id} completed without a result`);
335
- err.task_id = task.task_id;
336
- throw err;
337
- }
338
- return task.result;
339
- }
340
-
341
- /** TikTok results are paginated; fetch every page of a completed task and merge the items. */
342
- async function collectAllPages<TTask extends { pagination?: TikTokProfilePagination }, TItem>(
343
- fetchPage: (query: { cursor?: string; limit: number; include_usage?: boolean }) => Promise<TTask>,
344
- items: (task: TTask) => TItem[],
345
- setItems: (task: TTask, all: TItem[]) => void,
346
- include_usage?: boolean
347
- ): Promise<TTask> {
348
- const first = await fetchPage({ limit: TIKTOK_PAGE_SIZE, include_usage });
349
- const all = [...items(first)];
350
- let cursor = first.pagination?.next_cursor ?? undefined;
351
- while (cursor) {
352
- const page = await fetchPage({ limit: TIKTOK_PAGE_SIZE, cursor });
353
- all.push(...items(page));
354
- cursor = page.pagination?.next_cursor ?? undefined;
355
- }
356
- setItems(first, all);
357
- if (first.pagination) {
358
- first.pagination = { ...first.pagination, limit: all.length, has_next: false, next_cursor: null };
359
- }
360
- return first;
361
- }
362
-
363
- const TIKTOK_PAGE_SIZE = 500;
364
-
365
- interface OperationSpec<TInput, TTask extends PollableTask, TResult> {
366
- jobType: string;
367
- submit: (input: TInput) => Promise<JobInfo>;
368
- fetchTask: (task_id: string, options: SubmitOptions) => Promise<TTask>;
369
- toResult: (task: TTask, options: SubmitOptions) => Promise<TResult>;
370
- }
371
-
372
- function appendOptionalFormField(form: FormData, name: string, value: string | number | boolean | undefined): void {
373
- if (value !== undefined) {
374
- form.append(name, String(value));
375
- }
376
- }
377
-
378
- function buildTikTokPollParams(query?: {
379
- cursor?: string;
380
- limit?: number;
381
- include_usage?: boolean;
382
- }): Record<string, string | number> | undefined {
383
- if (!query) return undefined;
384
- const params: Record<string, string | number> = {};
385
- if (query.cursor !== undefined) params.cursor = query.cursor;
386
- if (query.limit !== undefined) params.limit = query.limit;
387
- // The TikTok pollers expect include_usage as a query string value.
388
- if (query.include_usage) params.include_usage = 'true';
389
- return params;
390
- }
391
-
392
- const _deprecationWarned = new Set<string>();
393
-
394
- function warnDeprecated(oldName: string, newName: string): void {
395
- if (_deprecationWarned.has(oldName)) return;
396
- _deprecationWarned.add(oldName);
397
- if (typeof console !== 'undefined' && typeof console.warn === 'function') {
398
- console.warn(
399
- `[vidnavigator] ${oldName}() is deprecated and will be removed in a future release; use ${newName}() instead.`
400
- );
401
- }
402
- }
403
-
404
- export class VidNavigatorClient {
405
- private client: AxiosInstance;
406
-
407
- /**
408
- * Speech-to-text transcription of any length (Instagram, TikTok, X, Facebook, Vimeo, ...),
409
- * built on `POST /transcribe/async`.
410
- *
411
- * - `await vn.transcribe(url)` submits, polls, and returns the result.
412
- * - `await vn.transcribe.submit(url)` returns a {@link Job} handle right away.
413
- * - `vn.transcribe.resume(task_id)` reattaches to a job you already submitted.
414
- */
415
- readonly transcribe: TranscribeOperation;
416
-
417
- /**
418
- * Structured-data extraction from a video of any length, built on `POST /extract/video/async`.
419
- * The schema is validated when you submit. Same shapes as {@link VidNavigatorClient.transcribe}.
420
- */
421
- readonly extractVideo: JobOperation<ExtractVideoInput, ExtractVideoAsyncJob, ExtractDataResult>;
422
-
423
- /**
424
- * Structured claim analysis of an X/Twitter tweet (attached media of any length), built on
425
- * `POST /tweet/statement/async`. Same shapes as {@link VidNavigatorClient.transcribe}.
426
- */
427
- readonly tweetStatement: JobOperation<string | TweetStatementInput, TweetStatementAsyncJob, TweetStatement>;
428
-
429
- /**
430
- * TikTok profile scrape, built on `POST /tiktok/profile`. The result is the completed task with
431
- * every page of `videos` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
432
- */
433
- readonly tiktokProfile: JobOperation<string | TikTokProfileScrapeRequest, TikTokProfileTask, TikTokProfileTask>;
434
-
435
- /**
436
- * TikTok keyword search, built on `POST /tiktok/search`. The result is the completed task with
437
- * every page of `results` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
438
- */
439
- readonly tiktokSearch: JobOperation<string | TikTokSearchRequest, TikTokSearchTask, TikTokSearchTask>;
440
-
441
- constructor(config: SDKConfig) {
442
- if (!config?.apiKey) {
443
- throw new Error('An API key is required to use the VidNavigator SDK.');
444
- }
445
-
446
- this.client = axios.create({
447
- baseURL: config.baseURL ?? 'https://api.vidnavigator.com/v1',
448
- headers: {
449
- 'X-API-Key': config.apiKey,
450
- 'User-Agent': `vidnavigator-js/${SDK_VERSION}`,
451
- },
452
- ...config.axiosConfig,
453
- });
454
-
455
- this.transcribe = this.defineOperation({
456
- jobType: 'transcribe',
457
- submit: (input: string | TranscribeInput) =>
458
- this.submitAsyncJob('/transcribe/async', typeof input === 'string' ? { video_url: input } : input),
459
- fetchTask: (task_id, options) =>
460
- this.getAsyncJob(`/transcribe/${encodeURIComponent(task_id)}`, options, (raw) => parseTranscribeData(raw)),
461
- toResult: async (task) => ({ ...requireResult(task), usage: task.usage }),
462
- }) as TranscribeOperation;
463
-
464
- this.extractVideo = this.defineOperation({
465
- jobType: 'extract_video',
466
- submit: (input: ExtractVideoInput) => this.submitExtractVideo(input),
467
- fetchTask: (task_id, options) =>
468
- this.getAsyncJob(
469
- `/extract/video/${encodeURIComponent(task_id)}`,
470
- options,
471
- (raw) => raw as Record<string, unknown>
472
- ),
473
- toResult: async (task) => ({ data: requireResult(task), usage: task.usage }),
474
- });
475
-
476
- this.tweetStatement = this.defineOperation({
477
- jobType: 'tweet_statement',
478
- submit: (input: string | TweetStatementInput) =>
479
- this.submitAsyncJob('/tweet/statement/async', typeof input === 'string' ? { tweet_id: input } : input),
480
- fetchTask: (task_id, options) =>
481
- this.getAsyncJob(`/tweet/statement/${encodeURIComponent(task_id)}`, options, (raw) =>
482
- TweetStatement.fromJSON(raw)
483
- ),
484
- toResult: async (task) => {
485
- const statement = requireResult(task);
486
- statement.usage = task.usage;
487
- return statement;
488
- },
489
- });
490
-
491
- this.tiktokProfile = this.defineOperation({
492
- jobType: 'tiktok_profile',
493
- submit: async (input: string | TikTokProfileScrapeRequest) => {
494
- const sub = await this.submitTikTokProfileScrape(typeof input === 'string' ? { profile_url: input } : input);
495
- return { ...sub, job_type: 'tiktok_profile' };
496
- },
497
- // Status polls ask for one video only; the full result is paged in once the task completes.
498
- fetchTask: (task_id) => this.getTikTokProfileScrape(task_id, { limit: 1 }),
499
- toResult: (task, options) =>
500
- collectAllPages(
501
- (query) => this.getTikTokProfileScrape(task.task_id, query),
502
- (page) => page.videos,
503
- (page, all) => { page.videos = all; },
504
- options.include_usage
505
- ),
506
- });
507
-
508
- this.tiktokSearch = this.defineOperation({
509
- jobType: 'tiktok_search',
510
- submit: async (input: string | TikTokSearchRequest) => {
511
- const sub = await this.submitTikTokSearch(typeof input === 'string' ? { query: input } : input);
512
- return { ...sub, job_type: 'tiktok_search' };
513
- },
514
- fetchTask: (task_id) => this.getTikTokSearch(task_id, { limit: 1 }),
515
- toResult: (task, options) =>
516
- collectAllPages(
517
- (query) => this.getTikTokSearch(task.task_id, query),
518
- (page) => page.results,
519
- (page, all) => { page.results = all; },
520
- options.include_usage
521
- ),
522
- });
523
- }
524
-
525
- private defineOperation<TInput, TTask extends PollableTask, TResult>(
526
- spec: OperationSpec<TInput, TTask, TResult>
527
- ): JobOperation<TInput, TTask, TResult> {
528
- const makeJob = (info: JobInfo, options: SubmitOptions = {}) =>
529
- new Job<TTask, TResult>(
530
- info,
531
- () => spec.fetchTask(info.task_id, options),
532
- (task) => spec.toResult(task, options)
533
- );
534
- const submit = async (input: TInput, options?: SubmitOptions) => makeJob(await spec.submit(input), options);
535
- const run = async (input: TInput, options: RunOptions<TTask> = {}) => {
536
- const { include_usage, ...pollOptions } = options;
537
- const job = await submit(input, { include_usage });
538
- return job.result(pollOptions);
539
- };
540
- return Object.assign(run, {
541
- submit,
542
- resume: (task_id: string, options?: SubmitOptions) =>
543
- makeJob({ task_id, job_type: spec.jobType }, options),
544
- });
545
- }
546
-
547
- private async submitAsyncJob(url: string, body: unknown, headers?: Record<string, string>): Promise<JobInfo> {
548
- const response = await this.request<ApiSuccessResponse<AsyncJobAcceptedJSON>>('POST', url, body, undefined, headers);
549
- const accepted = AsyncJobAccepted.fromJSON(response.data);
550
- return { ...accepted, job_type: accepted.job_type ?? url.split('/')[1] };
551
- }
552
-
553
- private submitExtractVideo(input: ExtractVideoInput): Promise<JobInfo> {
554
- if ('schemaFilePath' in input) {
555
- const form = new FormData();
556
- form.append('video_url', input.video_url);
557
- form.append('schema', fs.createReadStream(input.schemaFilePath));
558
- appendOptionalFormField(form, 'what_to_extract', input.what_to_extract);
559
- appendOptionalFormField(form, 'transcribe', input.transcribe);
560
- appendOptionalFormField(form, 'webhook_url', input.webhook_url);
561
- return this.submitAsyncJob('/extract/video/async', form, form.getHeaders());
562
- }
563
- return this.submitAsyncJob('/extract/video/async', input);
564
- }
565
-
566
- private async getAsyncJob<T>(
567
- url: string,
568
- options: SubmitOptions | undefined,
569
- parseResult: (raw: any) => T
570
- ): Promise<AsyncJob<T>> {
571
- const response = await this.request<ApiSuccessResponse<AsyncJobJSON>>(
572
- 'GET',
573
- url,
574
- undefined,
575
- buildAsyncJobParams(options)
576
- );
577
- const job = AsyncJob.fromJSON(response.data, parseResult);
578
- if (response.usage) job.usage = UsageBlock.fromJSON(response.usage);
579
- return job;
580
- }
581
-
582
- private async request<T>(
583
- method: 'GET' | 'POST' | 'DELETE' | 'PUT',
584
- url: string,
585
- data?: any,
586
- params?: any,
587
- extraHeaders?: any
588
- ): Promise<T> {
589
- try {
590
- const response = await this.client.request<T>({
591
- method,
592
- url,
593
- data,
594
- params,
595
- headers: extraHeaders,
596
- });
597
- return response.data;
598
- } catch (error: any) {
599
- if (axios.isAxiosError(error) && error.response) {
600
- throw buildApiError(error.response.status, error.response.data, error.message);
601
- }
602
- throw new VidNavigatorError(error.message);
603
- }
604
- }
605
-
606
- //region --- Transcripts ---
607
- /**
608
- * Get a transcript for any supported video. The endpoint auto-detects the
609
- * platform (YouTube, Vimeo, X/Twitter, TikTok, Facebook, Dailymotion, Loom, etc.)
610
- * from `video_url`. For Instagram, use {@link VidNavigatorClient.transcribeVideo}.
611
- */
612
- async getTranscript(payload: TranscriptRequestPayload): Promise<TranscriptResult> {
613
- const response = await this.request<
614
- ApiSuccessResponse<{
615
- video_info: VideoInfoJSON;
616
- transcript: TranscriptSegmentJSON[] | string;
617
- }>
618
- >('POST', '/transcript', payload);
619
-
620
- return {
621
- video_info: VideoInfo.fromJSON(response.data.video_info),
622
- transcript: transcriptFromJSON(response.data.transcript)!,
623
- usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
624
- };
625
- }
626
-
627
- /**
628
- * @deprecated There is now a single `/transcript` endpoint that auto-detects the
629
- * platform. Use {@link VidNavigatorClient.getTranscript} instead. This alias
630
- * forwards to `getTranscript` and will be removed in a future release.
631
- */
632
- async getYouTubeTranscript(payload: TranscriptRequestPayload): Promise<TranscriptResult> {
633
- warnDeprecated('getYouTubeTranscript', 'getTranscript');
634
- return this.getTranscript(payload);
635
- }
636
-
637
- /**
638
- * Speech-to-text transcription. Blocking convenience wrapper around {@link VidNavigatorClient.transcribe}:
639
- * submits to `POST /transcribe/async` and polls until the job finishes, so media of any length works.
640
- */
641
- async transcribeVideo(
642
- payload: TranscribeVideoPayload,
643
- options?: PollOptions<TranscribeAsyncJob>
644
- ): Promise<TranscribeVideoResult> {
645
- const { include_usage, ...input } = payload;
646
- return this.transcribe(input, { ...options, include_usage });
647
- }
648
- //endregion
649
-
650
- //region --- TikTok ---
651
- async submitTikTokProfileScrape(
652
- payload: TikTokProfileScrapeRequest
653
- ): Promise<TikTokProfileScrapeSubmission> {
654
- const response = await this.request<ApiSuccessResponse<TikTokProfileScrapeSubmissionJSON>>(
655
- 'POST',
656
- '/tiktok/profile',
657
- payload
658
- );
659
- return TikTokProfileScrapeSubmission.fromJSON(response.data);
660
- }
661
-
662
- async getTikTokProfileScrape(
663
- task_id: string,
664
- query?: { cursor?: string; limit?: number; include_usage?: boolean }
665
- ): Promise<TikTokProfileTask> {
666
- const response = await this.request<ApiSuccessResponse<TikTokProfileTaskJSON>>(
667
- 'GET',
668
- `/tiktok/profile/${task_id}`,
669
- undefined,
670
- buildTikTokPollParams(query)
671
- );
672
- const task = TikTokProfileTask.fromJSON(response.data);
673
- if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
674
- return task;
675
- }
676
-
677
- async submitTikTokSearch(payload: TikTokSearchRequest): Promise<TikTokSearchSubmission> {
678
- const response = await this.request<ApiSuccessResponse<TikTokSearchSubmissionJSON>>(
679
- 'POST',
680
- '/tiktok/search',
681
- payload
682
- );
683
- return TikTokSearchSubmission.fromJSON(response.data);
684
- }
685
-
686
- async getTikTokSearch(
687
- task_id: string,
688
- query?: { cursor?: string; limit?: number; include_usage?: boolean }
689
- ): Promise<TikTokSearchTask> {
690
- const response = await this.request<ApiSuccessResponse<TikTokSearchTaskJSON>>(
691
- 'GET',
692
- `/tiktok/search/${task_id}`,
693
- undefined,
694
- buildTikTokPollParams(query)
695
- );
696
- const task = TikTokSearchTask.fromJSON(response.data);
697
- if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
698
- return task;
699
- }
700
- //endregion
701
-
702
- //region --- Files ---
703
- async getFiles(query?: {
704
- limit?: number;
705
- offset?: number;
706
- status?: 'processing' | 'completed' | 'failed' | 'cancelled';
707
- namespace_id?: string;
708
- }): Promise<{
709
- files: FileInfo[];
710
- total_count: number;
711
- limit: number;
712
- offset: number;
713
- has_more: boolean;
714
- }> {
715
- const response = await this.request<
716
- ApiSuccessResponse<{
717
- files: FileInfoJSON[];
718
- total_count: number;
719
- limit: number;
720
- offset: number;
721
- has_more: boolean;
722
- }>
723
- >('GET', '/files', undefined, query);
724
-
725
- return {
726
- files: response.data.files.map(FileInfo.fromJSON),
727
- total_count: response.data.total_count,
728
- limit: response.data.limit,
729
- offset: response.data.offset,
730
- has_more: response.data.has_more,
731
- };
732
- }
733
-
734
- async getFile(
735
- file_id: string,
736
- query?: { transcript_text?: boolean }
737
- ): Promise<{ file_info: FileInfo; transcript?: TranscriptOutput }> {
738
- const response = await this.request<
739
- ApiSuccessResponse<{
740
- file_info: FileInfoJSON;
741
- transcript?: TranscriptSegmentJSON[] | string;
742
- }>
743
- >('GET', `/file/${file_id}`, undefined, query);
744
-
745
- return {
746
- file_info: FileInfo.fromJSON(response.data.file_info),
747
- transcript: transcriptFromJSON(response.data.transcript),
748
- };
749
- }
750
-
751
- async uploadFile(options: {
752
- filePath: string;
753
- wait_for_completion?: boolean;
754
- namespace_ids?: string[];
755
- }): Promise<UploadFileResult> {
756
- const form = new FormData();
757
- form.append('file', fs.createReadStream(options.filePath));
758
- if (options.wait_for_completion) {
759
- form.append('wait_for_completion', 'true');
760
- }
761
- if (options.namespace_ids?.length) {
762
- form.append('namespace_ids', JSON.stringify(options.namespace_ids));
763
- }
764
-
765
- try {
766
- const response = await this.client.post<{
767
- status: 'success' | 'accepted';
768
- file_id: string;
769
- file_name: string;
770
- file_status: 'processing' | 'completed';
771
- message: string;
772
- note?: string;
773
- data?: { file_info: FileInfoJSON };
774
- }>('/upload/file', form, { headers: form.getHeaders() });
775
-
776
- const body = response.data;
777
- const fileInfo = body.data?.file_info ? FileInfo.fromJSON(body.data.file_info) : undefined;
778
- if (body.status === 'accepted') {
779
- return {
780
- status: 'accepted',
781
- file_id: body.file_id,
782
- file_name: body.file_name,
783
- file_status: body.file_status as 'processing',
784
- message: body.message,
785
- note: body.note,
786
- file_info: fileInfo,
787
- };
788
- }
789
- return {
790
- status: 'success',
791
- file_id: body.file_id,
792
- file_name: body.file_name,
793
- file_status: body.file_status,
794
- message: body.message,
795
- file_info: fileInfo!,
796
- };
797
- } catch (error: any) {
798
- if (axios.isAxiosError(error) && error.response) {
799
- throw buildApiError(error.response.status, error.response.data, error.message);
800
- }
801
- throw new VidNavigatorError(error.message);
802
- }
803
- }
804
-
805
- async deleteFile(file_id: string): Promise<{ file_id: string; file_name: string; message: string }> {
806
- const response = await this.request<
807
- ApiSuccessResponse<{ file_id: string; file_name: string; message: string }>
808
- >('DELETE', `/file/${file_id}/delete`);
809
- return response.data;
810
- }
811
-
812
- async getFileUrl(file_id: string): Promise<{ file_id: string; file_url: string }> {
813
- const response = await this.request<
814
- ApiSuccessResponse<{ file_id: string; file_url: string }>
815
- >('GET', `/file/${file_id}/url`);
816
- return response.data;
817
- }
818
-
819
- async retryFileProcessing(
820
- file_id: string
821
- ): Promise<{ file_id: string; file_name: string; file_status: string; message: string }> {
822
- const response = await this.request<
823
- ApiSuccessResponse<{
824
- file_id: string;
825
- file_name: string;
826
- file_status: string;
827
- message: string;
828
- }>
829
- >('POST', `/file/${file_id}/retry`);
830
- return response.data;
831
- }
832
-
833
- async cancelFileUpload(
834
- file_id: string
835
- ): Promise<{ file_id: string; file_name: string; message: string }> {
836
- const response = await this.request<
837
- ApiSuccessResponse<{ file_id: string; file_name: string; message: string }>
838
- >('POST', `/file/${file_id}/cancel`);
839
- return response.data;
840
- }
841
- //endregion
842
-
843
- //region --- Namespaces ---
844
- async getNamespaces(): Promise<Namespace[]> {
845
- const response = await this.request<ApiSuccessResponse<NamespaceJSON[]>>('GET', '/namespaces');
846
- return response.data.map((n) => Namespace.fromJSON(n));
847
- }
848
-
849
- async createNamespace(payload: { name: string }): Promise<Namespace> {
850
- const response = await this.request<ApiSuccessResponse<NamespaceJSON>>('POST', '/namespaces', payload);
851
- return Namespace.fromJSON(response.data);
852
- }
853
-
854
- async updateNamespace(namespace_id: string, payload: { name: string }): Promise<{ message: string }> {
855
- const body = await this.request<{ status: string; message: string }>(
856
- 'PUT',
857
- `/namespaces/${namespace_id}`,
858
- payload
859
- );
860
- return { message: body.message };
861
- }
862
-
863
- async deleteNamespace(namespace_id: string): Promise<{ message: string }> {
864
- const body = await this.request<{ status: string; message: string }>(
865
- 'DELETE',
866
- `/namespaces/${namespace_id}`
867
- );
868
- return { message: body.message };
869
- }
870
-
871
- async updateFileNamespaces(
872
- file_id: string,
873
- payload: { namespace_ids: string[] }
874
- ): Promise<{ message: string; namespace_ids: string[]; namespaces: NamespaceRef[] }> {
875
- const body = await this.request<{
876
- status: string;
877
- message: string;
878
- data: { namespace_ids: string[]; namespaces: NamespaceRefJSON[] };
879
- }>('PUT', `/file/${file_id}/namespaces`, payload);
880
- return {
881
- message: body.message,
882
- namespace_ids: body.data.namespace_ids,
883
- namespaces: body.data.namespaces.map(NamespaceRef.fromJSON),
884
- };
885
- }
886
- //endregion
887
-
888
- //region --- Analysis ---
889
- async analyzeVideo(payload: AnalyzeVideoPayload): Promise<AnalyzeVideoResult> {
890
- const response = await this.request<
891
- ApiSuccessResponse<{
892
- video_info: VideoInfoJSON;
893
- transcript: TranscriptSegmentJSON[] | string;
894
- transcript_analysis: AnalysisResultJSON;
895
- }>
896
- >('POST', '/analyze/video', payload);
897
-
898
- return {
899
- video_info: VideoInfo.fromJSON(response.data.video_info),
900
- transcript: transcriptFromJSON(response.data.transcript)!,
901
- transcript_analysis: AnalysisResult.fromJSON(response.data.transcript_analysis),
902
- usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
903
- };
904
- }
905
-
906
- async analyzeFile(payload: AnalyzeFilePayload): Promise<AnalyzeFileResult> {
907
- const response = await this.request<
908
- ApiSuccessResponse<{
909
- file_info: FileInfoJSON;
910
- transcript: TranscriptSegmentJSON[] | string;
911
- transcript_analysis: AnalysisResultJSON;
912
- }>
913
- >('POST', '/analyze/file', payload);
914
-
915
- return {
916
- file_info: FileInfo.fromJSON(response.data.file_info),
917
- transcript: transcriptFromJSON(response.data.transcript)!,
918
- transcript_analysis: AnalysisResult.fromJSON(response.data.transcript_analysis),
919
- usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
920
- };
921
- }
922
-
923
- /**
924
- * Structured claim analysis of an X/Twitter tweet. Blocking convenience wrapper around
925
- * {@link VidNavigatorClient.tweetStatement}: submits to `POST /tweet/statement/async` and polls.
926
- */
927
- async getTweetStatement(
928
- payload: TweetStatementPayload,
929
- options?: RunOptions<TweetStatementAsyncJob>
930
- ): Promise<TweetStatement> {
931
- return this.tweetStatement(payload, options);
932
- }
933
- //endregion
934
-
935
- //region --- Extraction ---
936
- /**
937
- * Structured-data extraction from an online video. Blocking convenience wrapper around
938
- * {@link VidNavigatorClient.extractVideo}: submits to `POST /extract/video/async` and polls, so
939
- * media of any length works. The async API does not return `video_info`; use
940
- * {@link VidNavigatorClient.getTranscript} with `metadata_only: true` if you need it.
941
- */
942
- async extractVideoData(
943
- payload: ExtractVideoDataPayload | ExtractVideoDataMultipartPayload,
944
- options?: PollOptions<ExtractVideoAsyncJob>
945
- ): Promise<ExtractDataResult> {
946
- const { include_usage, ...input } = payload;
947
- return this.extractVideo(input as ExtractVideoInput, { ...options, include_usage });
948
- }
949
-
950
- async extractFileData(
951
- payload: ExtractFileDataPayload | ExtractFileDataMultipartPayload
952
- ): Promise<ExtractDataResult> {
953
- if ('schemaFilePath' in payload) {
954
- const form = new FormData();
955
- form.append('file_id', payload.file_id);
956
- form.append('schema', fs.createReadStream(payload.schemaFilePath));
957
- appendOptionalFormField(form, 'what_to_extract', payload.what_to_extract);
958
- appendOptionalFormField(form, 'include_usage', payload.include_usage);
959
-
960
- const body = await this.request<{
961
- status: 'success';
962
- data: Record<string, unknown>;
963
- file_info?: FileInfoJSON;
964
- usage?: UsageBlockJSON;
965
- }>('POST', '/extract/file', form, undefined, form.getHeaders());
966
- return {
967
- data: body.data,
968
- file_info: body.file_info ? FileInfo.fromJSON(body.file_info) : undefined,
969
- usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
970
- };
971
- }
972
-
973
- const body = await this.request<{
974
- status: 'success';
975
- data: Record<string, unknown>;
976
- file_info?: FileInfoJSON;
977
- usage?: UsageBlockJSON;
978
- }>('POST', '/extract/file', payload);
979
- return {
980
- data: body.data,
981
- file_info: body.file_info ? FileInfo.fromJSON(body.file_info) : undefined,
982
- usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
983
- };
984
- }
985
- //endregion
986
-
987
- //region --- Search ---
988
- /**
989
- * Search YouTube for videos with AI analysis and ranking.
990
- *
991
- * If the account runs out of `residential_request` credits mid-search, the API
992
- * returns HTTP 402 with `status: "partial"` and the videos analysed so far. The
993
- * SDK surfaces that partial payload (results, `status: "partial"`, `error_code`,
994
- * and `usage` when requested) instead of throwing.
995
- */
996
- async searchYouTube(payload: SearchYouTubePayload): Promise<SearchYouTubeResult> {
997
- let response: {
998
- status?: 'success' | 'partial';
999
- error_code?: string;
1000
- data: {
1001
- results: VideoSearchResultJSON[];
1002
- query: string;
1003
- total_found: number;
1004
- explanation?: string;
1005
- };
1006
- usage?: UsageBlockJSON;
1007
- };
1008
-
1009
- try {
1010
- response = await this.request('POST', '/youtube/search', payload);
1011
- } catch (error: any) {
1012
- const body = error?.details;
1013
- if (error instanceof PaymentRequiredError && body?.status === 'partial' && body?.data) {
1014
- response = body;
1015
- } else {
1016
- throw error;
1017
- }
1018
- }
1019
-
1020
- return {
1021
- results: (response.data.results ?? []).map(VideoSearchResult.fromJSON),
1022
- query: response.data.query,
1023
- total_found: response.data.total_found,
1024
- explanation: response.data.explanation,
1025
- usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1026
- status: response.status,
1027
- error_code: response.error_code,
1028
- };
1029
- }
1030
-
1031
- /**
1032
- * @deprecated `/search/video` moved to `/youtube/search`. Use
1033
- * {@link VidNavigatorClient.searchYouTube} instead. This alias forwards to
1034
- * `searchYouTube` and will be removed in a future release.
1035
- */
1036
- async searchVideos(payload: SearchYouTubePayload): Promise<SearchYouTubeResult> {
1037
- warnDeprecated('searchVideos', 'searchYouTube');
1038
- return this.searchYouTube(payload);
1039
- }
1040
-
1041
- async searchFiles(payload: SearchFilesPayload): Promise<SearchFilesResult> {
1042
- const response = await this.request<
1043
- ApiSuccessResponse<{
1044
- results: FileSearchResultJSON[];
1045
- query: string;
1046
- total_found: number;
1047
- explanation?: string;
1048
- }>
1049
- >('POST', '/search/file', payload);
1050
-
1051
- return {
1052
- results: response.data.results.map(FileSearchResult.fromJSON),
1053
- query: response.data.query,
1054
- total_found: response.data.total_found,
1055
- explanation: response.data.explanation,
1056
- usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1057
- };
1058
- }
1059
- //endregion
1060
-
1061
- //region --- System ---
1062
- async getUsage(): Promise<UsageData> {
1063
- const response = await this.request<ApiSuccessResponse<UsageDataJSON>>('GET', '/usage');
1064
- return UsageData.fromJSON(response.data);
1065
- }
1066
-
1067
- async healthCheck(): Promise<{
1068
- status?: string;
1069
- message?: string;
1070
- version?: string;
1071
- endpoints?: Array<{
1072
- path?: string;
1073
- method?: string;
1074
- description?: string;
1075
- auth_required?: boolean;
1076
- }>;
1077
- }> {
1078
- const response = await this.client.get('/health');
1079
- return response.data;
1080
- }
1081
- //endregion
1082
- }
1
+ import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
2
+ import FormData from 'form-data';
3
+ import fs from 'fs';
4
+ import {
5
+ VideoInfo,
6
+ VideoInfoJSON,
7
+ TranscriptSegmentJSON,
8
+ TranscriptOutput,
9
+ transcriptFromJSON,
10
+ FileInfo,
11
+ FileInfoJSON,
12
+ AnalysisResult,
13
+ AnalysisResultJSON,
14
+ VideoSearchResult,
15
+ VideoSearchResultJSON,
16
+ FileSearchResult,
17
+ FileSearchResultJSON,
18
+ UsageData,
19
+ UsageDataJSON,
20
+ Namespace,
21
+ NamespaceJSON,
22
+ NamespaceRef,
23
+ NamespaceRefJSON,
24
+ ExtractionSchema,
25
+ UsageBlock,
26
+ UsageBlockJSON,
27
+ CarouselInfo,
28
+ CarouselInfoJSON,
29
+ CarouselVideoResult,
30
+ CarouselVideoResultJSON,
31
+ TikTokProfileScrapeRequest,
32
+ TikTokProfileScrapeSubmission,
33
+ TikTokProfileScrapeSubmissionJSON,
34
+ TikTokProfileTask,
35
+ TikTokProfileTaskJSON,
36
+ TikTokSearchRequest,
37
+ TikTokSearchSubmission,
38
+ TikTokSearchSubmissionJSON,
39
+ TikTokSearchTask,
40
+ TikTokSearchTaskJSON,
41
+ TweetStatement,
42
+ AsyncJob,
43
+ AsyncJobJSON,
44
+ AsyncJobAccepted,
45
+ AsyncJobAcceptedJSON,
46
+ TikTokProfilePagination,
47
+ } from './models';
48
+ import { VidNavigatorError, PaymentRequiredError } from './errors';
49
+ import { buildApiError } from './http';
50
+ import { Job, JobInfo, JobOperation, PollableTask, PollOptions, RunOptions, SubmitOptions } from './jobs';
51
+
52
+ export * from './models';
53
+ export * from './errors';
54
+ export * from './webhooks';
55
+ export { Job } from './jobs';
56
+ export type { TaskStatus, PollableTask, PollOptions, JobOperation, SubmitOptions, RunOptions, JobInfo } from './jobs';
57
+
58
+ /** SDK version (keep in sync with package.json) */
59
+ export const SDK_VERSION = '2.1.0';
60
+
61
+ //region --- Interfaces ---
62
+ export interface SDKConfig {
63
+ apiKey: string;
64
+ baseURL?: string;
65
+ axiosConfig?: AxiosRequestConfig;
66
+ }
67
+
68
+ interface ApiSuccessResponse<T> {
69
+ status: 'success';
70
+ data: T;
71
+ usage?: UsageBlockJSON;
72
+ }
73
+
74
+ export type TranscriptRequestPayload = {
75
+ video_url: string;
76
+ language?: string;
77
+ metadata_only?: boolean;
78
+ fallback_to_metadata?: boolean;
79
+ transcript_text?: boolean;
80
+ include_usage?: boolean;
81
+ };
82
+
83
+ export type TranscribeVideoPayload = {
84
+ video_url: string;
85
+ transcript_text?: boolean;
86
+ all_videos?: boolean;
87
+ include_usage?: boolean;
88
+ } & WebhookOption;
89
+
90
+ /**
91
+ * Where to POST a notification when an async job finishes. Overrides the account-level default
92
+ * configured in Studio → API; pass an empty string to opt this job out of that default.
93
+ * Must be a publicly reachable https URL. This is a pass-through: polling always works either way.
94
+ */
95
+ export type WebhookOption = { webhook_url?: string };
96
+
97
+ /** Input for {@link VidNavigatorClient.transcribe}. A plain string is treated as `video_url`. */
98
+ export type TranscribeInput = {
99
+ video_url: string;
100
+ transcript_text?: boolean;
101
+ /** Instagram carousel posts only: transcribe every video in the post. */
102
+ all_videos?: boolean;
103
+ } & WebhookOption;
104
+
105
+ /** Input for {@link VidNavigatorClient.extractVideo}: a JSON `schema`, or a JSON/YAML `schemaFilePath`. */
106
+ export type ExtractVideoInput =
107
+ | ({
108
+ video_url: string;
109
+ schema: ExtractionSchema;
110
+ what_to_extract?: string;
111
+ /** Speech-to-text the audio when no platform transcript exists. Default true. */
112
+ transcribe?: boolean;
113
+ } & WebhookOption)
114
+ | ({
115
+ video_url: string;
116
+ /** Path to a JSON or YAML schema file (sent as multipart form-data). */
117
+ schemaFilePath: string;
118
+ what_to_extract?: string;
119
+ transcribe?: boolean;
120
+ } & WebhookOption);
121
+
122
+ /** Input for {@link VidNavigatorClient.tweetStatement}. A plain string is treated as `tweet_id`. */
123
+ export type TweetStatementInput = { tweet_id: string } & WebhookOption;
124
+
125
+ export type TranscriptResult = {
126
+ video_info: VideoInfo;
127
+ transcript: TranscriptOutput;
128
+ usage?: UsageBlock;
129
+ };
130
+
131
+ export type TranscribeVideoSingleResult = {
132
+ video_info: VideoInfo;
133
+ transcript: TranscriptOutput;
134
+ usage?: UsageBlock;
135
+ };
136
+
137
+ export type TranscribeVideoCarouselResult = {
138
+ carousel_info: CarouselInfo;
139
+ videos: CarouselVideoResult[];
140
+ usage?: UsageBlock;
141
+ };
142
+
143
+ export type TranscribeVideoResult = TranscribeVideoSingleResult | TranscribeVideoCarouselResult;
144
+
145
+ /** Snapshot of a transcription task. `result` has the same shape as {@link VidNavigatorClient.transcribe}'s return value. */
146
+ export type TranscribeAsyncJob = AsyncJob<TranscribeVideoResult>;
147
+
148
+ /** Snapshot of an extraction task. `result` is the extracted object, shaped like your schema. */
149
+ export type ExtractVideoAsyncJob = AsyncJob<Record<string, unknown>>;
150
+
151
+ /** Snapshot of a tweet claim analysis task. `result` is a {@link TweetStatement}. */
152
+ export type TweetStatementAsyncJob = AsyncJob<TweetStatement>;
153
+
154
+ export type TranscribeJob = Job<TranscribeAsyncJob, TranscribeVideoResult>;
155
+
156
+ /** Input that always yields a single-video result (the carousel shape needs `all_videos: true`). */
157
+ type SingleTranscribeInput = string | (TranscribeInput & { all_videos?: false });
158
+
159
+ /**
160
+ * {@link JobOperation} for transcription, typed so that a plain URL (or `all_videos` left off)
161
+ * resolves to {@link TranscribeVideoSingleResult}.
162
+ */
163
+ export interface TranscribeOperation extends JobOperation<string | TranscribeInput, TranscribeAsyncJob, TranscribeVideoResult> {
164
+ (input: SingleTranscribeInput, options?: RunOptions<TranscribeAsyncJob>): Promise<TranscribeVideoSingleResult>;
165
+ (input: string | TranscribeInput, options?: RunOptions<TranscribeAsyncJob>): Promise<TranscribeVideoResult>;
166
+ submit(input: SingleTranscribeInput, options?: SubmitOptions): Promise<Job<TranscribeAsyncJob, TranscribeVideoSingleResult>>;
167
+ submit(input: string | TranscribeInput, options?: SubmitOptions): Promise<Job<TranscribeAsyncJob, TranscribeVideoResult>>;
168
+ }
169
+ export type ExtractVideoJob = Job<ExtractVideoAsyncJob, ExtractDataResult>;
170
+ export type TweetStatementJob = Job<TweetStatementAsyncJob, TweetStatement>;
171
+ /** `result()` resolves to the completed task with **all** pages of `videos` collected. */
172
+ export type TikTokProfileJob = Job<TikTokProfileTask, TikTokProfileTask>;
173
+ /** `result()` resolves to the completed task with **all** pages of `results` collected. */
174
+ export type TikTokSearchJob = Job<TikTokSearchTask, TikTokSearchTask>;
175
+
176
+ export type UploadFileSuccessResult = {
177
+ status: 'success';
178
+ file_id: string;
179
+ file_name: string;
180
+ file_status: 'processing' | 'completed';
181
+ message: string;
182
+ file_info: FileInfo;
183
+ };
184
+
185
+ export type UploadFileAcceptedResult = {
186
+ status: 'accepted';
187
+ file_id: string;
188
+ file_name: string;
189
+ file_status: 'processing';
190
+ message: string;
191
+ note?: string;
192
+ file_info?: FileInfo;
193
+ };
194
+
195
+ export type UploadFileResult = UploadFileSuccessResult | UploadFileAcceptedResult;
196
+
197
+ export interface ExtractDataResult {
198
+ data: Record<string, unknown>;
199
+ video_info?: VideoInfo;
200
+ file_info?: FileInfo;
201
+ usage?: UsageBlock;
202
+ }
203
+
204
+ export type YouTubeSearchFocus = 'relevance' | 'popularity' | 'brevity';
205
+
206
+ export type SearchYouTubePayload = {
207
+ query: string;
208
+ use_enhanced_search?: boolean;
209
+ start_year?: number;
210
+ end_year?: number;
211
+ focus?: YouTubeSearchFocus;
212
+ duration?: number;
213
+ max_results?: number;
214
+ include_usage?: boolean;
215
+ };
216
+
217
+ export type SearchYouTubeResult = {
218
+ results: VideoSearchResult[];
219
+ query: string;
220
+ total_found: number;
221
+ explanation?: string;
222
+ usage?: UsageBlock;
223
+ /** Present when a 402 partial-results response is returned. */
224
+ status?: 'success' | 'partial';
225
+ /** Present on partial results (e.g. `insufficient_credits_video_search`). */
226
+ error_code?: string;
227
+ };
228
+
229
+ export type SearchFilesPayload = {
230
+ query: string;
231
+ namespace_ids?: string[];
232
+ include_usage?: boolean;
233
+ };
234
+
235
+ export type SearchFilesResult = {
236
+ results: FileSearchResult[];
237
+ query: string;
238
+ total_found: number;
239
+ explanation?: string;
240
+ usage?: UsageBlock;
241
+ };
242
+
243
+ export type AnalyzeVideoPayload = {
244
+ video_url: string;
245
+ query?: string;
246
+ transcript_text?: boolean;
247
+ include_usage?: boolean;
248
+ };
249
+
250
+ export type AnalyzeFilePayload = {
251
+ file_id: string;
252
+ query?: string;
253
+ transcript_text?: boolean;
254
+ include_usage?: boolean;
255
+ };
256
+
257
+ export type AnalyzeVideoResult = {
258
+ video_info: VideoInfo;
259
+ transcript: TranscriptOutput;
260
+ transcript_analysis: AnalysisResult;
261
+ usage?: UsageBlock;
262
+ };
263
+
264
+ export type AnalyzeFileResult = {
265
+ file_info: FileInfo;
266
+ transcript: TranscriptOutput;
267
+ transcript_analysis: AnalysisResult;
268
+ usage?: UsageBlock;
269
+ };
270
+
271
+ export type ExtractVideoDataPayload = {
272
+ video_url: string;
273
+ schema: ExtractionSchema;
274
+ what_to_extract?: string;
275
+ transcribe?: boolean;
276
+ include_usage?: boolean;
277
+ } & WebhookOption;
278
+
279
+ export type ExtractVideoDataMultipartPayload = {
280
+ video_url: string;
281
+ /** Path to a JSON or YAML schema file. The API accepts either a raw schema or a full extraction request object. */
282
+ schemaFilePath: string;
283
+ what_to_extract?: string;
284
+ transcribe?: boolean;
285
+ include_usage?: boolean;
286
+ } & WebhookOption;
287
+
288
+ export type TweetStatementPayload = { tweet_id: string } & WebhookOption;
289
+
290
+ export type ExtractFileDataPayload = {
291
+ file_id: string;
292
+ schema: ExtractionSchema;
293
+ what_to_extract?: string;
294
+ include_usage?: boolean;
295
+ };
296
+
297
+ export type ExtractFileDataMultipartPayload = {
298
+ file_id: string;
299
+ /** Path to a JSON or YAML schema file. The API accepts either a raw schema or a full extraction request object. */
300
+ schemaFilePath: string;
301
+ what_to_extract?: string;
302
+ include_usage?: boolean;
303
+ };
304
+ //endregion
305
+
306
+ function parseTranscribeData(
307
+ inner:
308
+ | { video_info: VideoInfoJSON; transcript: TranscriptSegmentJSON[] | string }
309
+ | { carousel_info: CarouselInfoJSON; videos: CarouselVideoResultJSON[] },
310
+ usage?: UsageBlock
311
+ ): TranscribeVideoResult {
312
+ if ('videos' in inner && 'carousel_info' in inner) {
313
+ return {
314
+ carousel_info: CarouselInfo.fromJSON(inner.carousel_info),
315
+ videos: inner.videos.map((v) => CarouselVideoResult.fromJSON(v)),
316
+ usage,
317
+ };
318
+ }
319
+ const single = inner as { video_info: VideoInfoJSON; transcript: TranscriptSegmentJSON[] | string };
320
+ return {
321
+ video_info: VideoInfo.fromJSON(single.video_info),
322
+ transcript: transcriptFromJSON(single.transcript)!,
323
+ usage,
324
+ };
325
+ }
326
+
327
+ function buildAsyncJobParams(options?: SubmitOptions): Record<string, string> | undefined {
328
+ // Like the TikTok pollers, the async job pollers take include_usage as a query string value.
329
+ return options?.include_usage ? { include_usage: 'true' } : undefined;
330
+ }
331
+
332
+ function requireResult<T>(task: AsyncJob<T>): T {
333
+ if (task.result === null) {
334
+ const err = new VidNavigatorError(`Task ${task.task_id} completed without a result`);
335
+ err.task_id = task.task_id;
336
+ throw err;
337
+ }
338
+ return task.result;
339
+ }
340
+
341
+ /** TikTok results are paginated; fetch every page of a completed task and merge the items. */
342
+ async function collectAllPages<TTask extends { pagination?: TikTokProfilePagination }, TItem>(
343
+ fetchPage: (query: { cursor?: string; limit: number; include_usage?: boolean }) => Promise<TTask>,
344
+ items: (task: TTask) => TItem[],
345
+ setItems: (task: TTask, all: TItem[]) => void,
346
+ include_usage?: boolean
347
+ ): Promise<TTask> {
348
+ const first = await fetchPage({ limit: TIKTOK_PAGE_SIZE, include_usage });
349
+ const all = [...items(first)];
350
+ let cursor = first.pagination?.next_cursor ?? undefined;
351
+ while (cursor) {
352
+ const page = await fetchPage({ limit: TIKTOK_PAGE_SIZE, cursor });
353
+ all.push(...items(page));
354
+ cursor = page.pagination?.next_cursor ?? undefined;
355
+ }
356
+ setItems(first, all);
357
+ if (first.pagination) {
358
+ first.pagination = { ...first.pagination, limit: all.length, has_next: false, next_cursor: null };
359
+ }
360
+ return first;
361
+ }
362
+
363
+ const TIKTOK_PAGE_SIZE = 500;
364
+
365
+ interface OperationSpec<TInput, TTask extends PollableTask, TResult> {
366
+ jobType: string;
367
+ submit: (input: TInput) => Promise<JobInfo>;
368
+ fetchTask: (task_id: string, options: SubmitOptions) => Promise<TTask>;
369
+ toResult: (task: TTask, options: SubmitOptions) => Promise<TResult>;
370
+ }
371
+
372
+ function appendOptionalFormField(form: FormData, name: string, value: string | number | boolean | undefined): void {
373
+ if (value !== undefined) {
374
+ form.append(name, String(value));
375
+ }
376
+ }
377
+
378
+ function buildTikTokPollParams(query?: {
379
+ cursor?: string;
380
+ limit?: number;
381
+ include_usage?: boolean;
382
+ }): Record<string, string | number> | undefined {
383
+ if (!query) return undefined;
384
+ const params: Record<string, string | number> = {};
385
+ if (query.cursor !== undefined) params.cursor = query.cursor;
386
+ if (query.limit !== undefined) params.limit = query.limit;
387
+ // The TikTok pollers expect include_usage as a query string value.
388
+ if (query.include_usage) params.include_usage = 'true';
389
+ return params;
390
+ }
391
+
392
+ const _deprecationWarned = new Set<string>();
393
+
394
+ function warnDeprecated(oldName: string, newName: string): void {
395
+ if (_deprecationWarned.has(oldName)) return;
396
+ _deprecationWarned.add(oldName);
397
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
398
+ console.warn(
399
+ `[vidnavigator] ${oldName}() is deprecated and will be removed in a future release; use ${newName}() instead.`
400
+ );
401
+ }
402
+ }
403
+
404
+ export class VidNavigatorClient {
405
+ private client: AxiosInstance;
406
+
407
+ /**
408
+ * Speech-to-text transcription of any length (Instagram, TikTok, X, Facebook, Vimeo, ...),
409
+ * built on `POST /transcribe/async`.
410
+ *
411
+ * - `await vn.transcribe(url)` submits, polls, and returns the result.
412
+ * - `await vn.transcribe.submit(url)` returns a {@link Job} handle right away.
413
+ * - `vn.transcribe.resume(task_id)` reattaches to a job you already submitted.
414
+ */
415
+ readonly transcribe: TranscribeOperation;
416
+
417
+ /**
418
+ * Structured-data extraction from a video of any length, built on `POST /extract/video/async`.
419
+ * The schema is validated when you submit. Same shapes as {@link VidNavigatorClient.transcribe}.
420
+ */
421
+ readonly extractVideo: JobOperation<ExtractVideoInput, ExtractVideoAsyncJob, ExtractDataResult>;
422
+
423
+ /**
424
+ * Structured claim analysis of an X/Twitter tweet (attached media of any length), built on
425
+ * `POST /tweet/statement/async`. Same shapes as {@link VidNavigatorClient.transcribe}.
426
+ */
427
+ readonly tweetStatement: JobOperation<string | TweetStatementInput, TweetStatementAsyncJob, TweetStatement>;
428
+
429
+ /**
430
+ * TikTok profile scrape, built on `POST /tiktok/profile`. The result is the completed task with
431
+ * every page of `videos` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
432
+ */
433
+ readonly tiktokProfile: JobOperation<string | TikTokProfileScrapeRequest, TikTokProfileTask, TikTokProfileTask>;
434
+
435
+ /**
436
+ * TikTok keyword search, built on `POST /tiktok/search`. The result is the completed task with
437
+ * every page of `results` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
438
+ */
439
+ readonly tiktokSearch: JobOperation<string | TikTokSearchRequest, TikTokSearchTask, TikTokSearchTask>;
440
+
441
+ constructor(config: SDKConfig) {
442
+ if (!config?.apiKey) {
443
+ throw new Error('An API key is required to use the VidNavigator SDK.');
444
+ }
445
+
446
+ this.client = axios.create({
447
+ baseURL: config.baseURL ?? 'https://api.vidnavigator.com/v1',
448
+ headers: {
449
+ 'X-API-Key': config.apiKey,
450
+ 'User-Agent': `vidnavigator-js/${SDK_VERSION}`,
451
+ },
452
+ ...config.axiosConfig,
453
+ });
454
+
455
+ this.transcribe = this.defineOperation({
456
+ jobType: 'transcribe',
457
+ submit: (input: string | TranscribeInput) =>
458
+ this.submitAsyncJob('/transcribe/async', typeof input === 'string' ? { video_url: input } : input),
459
+ fetchTask: (task_id, options) =>
460
+ this.getAsyncJob(`/transcribe/${encodeURIComponent(task_id)}`, options, (raw) => parseTranscribeData(raw)),
461
+ toResult: async (task) => ({ ...requireResult(task), usage: task.usage }),
462
+ }) as TranscribeOperation;
463
+
464
+ this.extractVideo = this.defineOperation({
465
+ jobType: 'extract_video',
466
+ submit: (input: ExtractVideoInput) => this.submitExtractVideo(input),
467
+ fetchTask: (task_id, options) =>
468
+ this.getAsyncJob(
469
+ `/extract/video/${encodeURIComponent(task_id)}`,
470
+ options,
471
+ (raw) => raw as Record<string, unknown>
472
+ ),
473
+ toResult: async (task) => ({ data: requireResult(task), video_info: task.video_info, usage: task.usage }),
474
+ });
475
+
476
+ this.tweetStatement = this.defineOperation({
477
+ jobType: 'tweet_statement',
478
+ submit: (input: string | TweetStatementInput) =>
479
+ this.submitAsyncJob('/tweet/statement/async', typeof input === 'string' ? { tweet_id: input } : input),
480
+ fetchTask: (task_id, options) =>
481
+ this.getAsyncJob(`/tweet/statement/${encodeURIComponent(task_id)}`, options, (raw) =>
482
+ TweetStatement.fromJSON(raw)
483
+ ),
484
+ toResult: async (task) => {
485
+ const statement = requireResult(task);
486
+ statement.usage = task.usage;
487
+ return statement;
488
+ },
489
+ });
490
+
491
+ this.tiktokProfile = this.defineOperation({
492
+ jobType: 'tiktok_profile',
493
+ submit: async (input: string | TikTokProfileScrapeRequest) => {
494
+ const sub = await this.submitTikTokProfileScrape(typeof input === 'string' ? { profile_url: input } : input);
495
+ return { ...sub, job_type: 'tiktok_profile' };
496
+ },
497
+ // Status polls ask for one video only; the full result is paged in once the task completes.
498
+ fetchTask: (task_id) => this.getTikTokProfileScrape(task_id, { limit: 1 }),
499
+ toResult: (task, options) =>
500
+ collectAllPages(
501
+ (query) => this.getTikTokProfileScrape(task.task_id, query),
502
+ (page) => page.videos,
503
+ (page, all) => { page.videos = all; },
504
+ options.include_usage
505
+ ),
506
+ });
507
+
508
+ this.tiktokSearch = this.defineOperation({
509
+ jobType: 'tiktok_search',
510
+ submit: async (input: string | TikTokSearchRequest) => {
511
+ const sub = await this.submitTikTokSearch(typeof input === 'string' ? { query: input } : input);
512
+ return { ...sub, job_type: 'tiktok_search' };
513
+ },
514
+ fetchTask: (task_id) => this.getTikTokSearch(task_id, { limit: 1 }),
515
+ toResult: (task, options) =>
516
+ collectAllPages(
517
+ (query) => this.getTikTokSearch(task.task_id, query),
518
+ (page) => page.results,
519
+ (page, all) => { page.results = all; },
520
+ options.include_usage
521
+ ),
522
+ });
523
+ }
524
+
525
+ private defineOperation<TInput, TTask extends PollableTask, TResult>(
526
+ spec: OperationSpec<TInput, TTask, TResult>
527
+ ): JobOperation<TInput, TTask, TResult> {
528
+ const makeJob = (info: JobInfo, options: SubmitOptions = {}) =>
529
+ new Job<TTask, TResult>(
530
+ info,
531
+ () => spec.fetchTask(info.task_id, options),
532
+ (task) => spec.toResult(task, options)
533
+ );
534
+ const submit = async (input: TInput, options?: SubmitOptions) => makeJob(await spec.submit(input), options);
535
+ const run = async (input: TInput, options: RunOptions<TTask> = {}) => {
536
+ const { include_usage, ...pollOptions } = options;
537
+ const job = await submit(input, { include_usage });
538
+ return job.result(pollOptions);
539
+ };
540
+ return Object.assign(run, {
541
+ submit,
542
+ resume: (task_id: string, options?: SubmitOptions) =>
543
+ makeJob({ task_id, job_type: spec.jobType }, options),
544
+ });
545
+ }
546
+
547
+ private async submitAsyncJob(url: string, body: unknown, headers?: Record<string, string>): Promise<JobInfo> {
548
+ const response = await this.request<ApiSuccessResponse<AsyncJobAcceptedJSON>>('POST', url, body, undefined, headers);
549
+ const accepted = AsyncJobAccepted.fromJSON(response.data);
550
+ return { ...accepted, job_type: accepted.job_type ?? url.split('/')[1] };
551
+ }
552
+
553
+ private submitExtractVideo(input: ExtractVideoInput): Promise<JobInfo> {
554
+ if ('schemaFilePath' in input) {
555
+ const form = new FormData();
556
+ form.append('video_url', input.video_url);
557
+ form.append('schema', fs.createReadStream(input.schemaFilePath));
558
+ appendOptionalFormField(form, 'what_to_extract', input.what_to_extract);
559
+ appendOptionalFormField(form, 'transcribe', input.transcribe);
560
+ appendOptionalFormField(form, 'webhook_url', input.webhook_url);
561
+ return this.submitAsyncJob('/extract/video/async', form, form.getHeaders());
562
+ }
563
+ return this.submitAsyncJob('/extract/video/async', input);
564
+ }
565
+
566
+ private async getAsyncJob<T>(
567
+ url: string,
568
+ options: SubmitOptions | undefined,
569
+ parseResult: (raw: any) => T
570
+ ): Promise<AsyncJob<T>> {
571
+ const response = await this.request<ApiSuccessResponse<AsyncJobJSON>>(
572
+ 'GET',
573
+ url,
574
+ undefined,
575
+ buildAsyncJobParams(options)
576
+ );
577
+ const job = AsyncJob.fromJSON(response.data, parseResult);
578
+ if (response.usage) job.usage = UsageBlock.fromJSON(response.usage);
579
+ return job;
580
+ }
581
+
582
+ private async request<T>(
583
+ method: 'GET' | 'POST' | 'DELETE' | 'PUT',
584
+ url: string,
585
+ data?: any,
586
+ params?: any,
587
+ extraHeaders?: any
588
+ ): Promise<T> {
589
+ try {
590
+ const response = await this.client.request<T>({
591
+ method,
592
+ url,
593
+ data,
594
+ params,
595
+ headers: extraHeaders,
596
+ });
597
+ return response.data;
598
+ } catch (error: any) {
599
+ if (axios.isAxiosError(error) && error.response) {
600
+ throw buildApiError(error.response.status, error.response.data, error.message);
601
+ }
602
+ throw new VidNavigatorError(error.message);
603
+ }
604
+ }
605
+
606
+ //region --- Transcripts ---
607
+ /**
608
+ * Get a transcript for any supported video. The endpoint auto-detects the
609
+ * platform (YouTube, Vimeo, X/Twitter, TikTok, Facebook, Dailymotion, Loom, etc.)
610
+ * from `video_url`. For Instagram, use {@link VidNavigatorClient.transcribeVideo}.
611
+ */
612
+ async getTranscript(payload: TranscriptRequestPayload): Promise<TranscriptResult> {
613
+ const response = await this.request<
614
+ ApiSuccessResponse<{
615
+ video_info: VideoInfoJSON;
616
+ transcript: TranscriptSegmentJSON[] | string;
617
+ }>
618
+ >('POST', '/transcript', payload);
619
+
620
+ return {
621
+ video_info: VideoInfo.fromJSON(response.data.video_info),
622
+ transcript: transcriptFromJSON(response.data.transcript)!,
623
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
624
+ };
625
+ }
626
+
627
+ /**
628
+ * @deprecated There is now a single `/transcript` endpoint that auto-detects the
629
+ * platform. Use {@link VidNavigatorClient.getTranscript} instead. This alias
630
+ * forwards to `getTranscript` and will be removed in a future release.
631
+ */
632
+ async getYouTubeTranscript(payload: TranscriptRequestPayload): Promise<TranscriptResult> {
633
+ warnDeprecated('getYouTubeTranscript', 'getTranscript');
634
+ return this.getTranscript(payload);
635
+ }
636
+
637
+ /**
638
+ * Speech-to-text transcription. Blocking convenience wrapper around {@link VidNavigatorClient.transcribe}:
639
+ * submits to `POST /transcribe/async` and polls until the job finishes, so media of any length works.
640
+ */
641
+ async transcribeVideo(
642
+ payload: TranscribeVideoPayload,
643
+ options?: PollOptions<TranscribeAsyncJob>
644
+ ): Promise<TranscribeVideoResult> {
645
+ const { include_usage, ...input } = payload;
646
+ return this.transcribe(input, { ...options, include_usage });
647
+ }
648
+ //endregion
649
+
650
+ //region --- TikTok ---
651
+ async submitTikTokProfileScrape(
652
+ payload: TikTokProfileScrapeRequest
653
+ ): Promise<TikTokProfileScrapeSubmission> {
654
+ const response = await this.request<ApiSuccessResponse<TikTokProfileScrapeSubmissionJSON>>(
655
+ 'POST',
656
+ '/tiktok/profile',
657
+ payload
658
+ );
659
+ return TikTokProfileScrapeSubmission.fromJSON(response.data);
660
+ }
661
+
662
+ async getTikTokProfileScrape(
663
+ task_id: string,
664
+ query?: { cursor?: string; limit?: number; include_usage?: boolean }
665
+ ): Promise<TikTokProfileTask> {
666
+ const response = await this.request<ApiSuccessResponse<TikTokProfileTaskJSON>>(
667
+ 'GET',
668
+ `/tiktok/profile/${task_id}`,
669
+ undefined,
670
+ buildTikTokPollParams(query)
671
+ );
672
+ const task = TikTokProfileTask.fromJSON(response.data);
673
+ if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
674
+ return task;
675
+ }
676
+
677
+ async submitTikTokSearch(payload: TikTokSearchRequest): Promise<TikTokSearchSubmission> {
678
+ const response = await this.request<ApiSuccessResponse<TikTokSearchSubmissionJSON>>(
679
+ 'POST',
680
+ '/tiktok/search',
681
+ payload
682
+ );
683
+ return TikTokSearchSubmission.fromJSON(response.data);
684
+ }
685
+
686
+ async getTikTokSearch(
687
+ task_id: string,
688
+ query?: { cursor?: string; limit?: number; include_usage?: boolean }
689
+ ): Promise<TikTokSearchTask> {
690
+ const response = await this.request<ApiSuccessResponse<TikTokSearchTaskJSON>>(
691
+ 'GET',
692
+ `/tiktok/search/${task_id}`,
693
+ undefined,
694
+ buildTikTokPollParams(query)
695
+ );
696
+ const task = TikTokSearchTask.fromJSON(response.data);
697
+ if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
698
+ return task;
699
+ }
700
+ //endregion
701
+
702
+ //region --- Files ---
703
+ async getFiles(query?: {
704
+ limit?: number;
705
+ offset?: number;
706
+ status?: 'processing' | 'completed' | 'failed' | 'cancelled';
707
+ namespace_id?: string;
708
+ }): Promise<{
709
+ files: FileInfo[];
710
+ total_count: number;
711
+ limit: number;
712
+ offset: number;
713
+ has_more: boolean;
714
+ }> {
715
+ const response = await this.request<
716
+ ApiSuccessResponse<{
717
+ files: FileInfoJSON[];
718
+ total_count: number;
719
+ limit: number;
720
+ offset: number;
721
+ has_more: boolean;
722
+ }>
723
+ >('GET', '/files', undefined, query);
724
+
725
+ return {
726
+ files: response.data.files.map(FileInfo.fromJSON),
727
+ total_count: response.data.total_count,
728
+ limit: response.data.limit,
729
+ offset: response.data.offset,
730
+ has_more: response.data.has_more,
731
+ };
732
+ }
733
+
734
+ async getFile(
735
+ file_id: string,
736
+ query?: { transcript_text?: boolean }
737
+ ): Promise<{ file_info: FileInfo; transcript?: TranscriptOutput }> {
738
+ const response = await this.request<
739
+ ApiSuccessResponse<{
740
+ file_info: FileInfoJSON;
741
+ transcript?: TranscriptSegmentJSON[] | string;
742
+ }>
743
+ >('GET', `/file/${file_id}`, undefined, query);
744
+
745
+ return {
746
+ file_info: FileInfo.fromJSON(response.data.file_info),
747
+ transcript: transcriptFromJSON(response.data.transcript),
748
+ };
749
+ }
750
+
751
+ async uploadFile(options: {
752
+ filePath: string;
753
+ wait_for_completion?: boolean;
754
+ namespace_ids?: string[];
755
+ }): Promise<UploadFileResult> {
756
+ const form = new FormData();
757
+ form.append('file', fs.createReadStream(options.filePath));
758
+ if (options.wait_for_completion) {
759
+ form.append('wait_for_completion', 'true');
760
+ }
761
+ if (options.namespace_ids?.length) {
762
+ form.append('namespace_ids', JSON.stringify(options.namespace_ids));
763
+ }
764
+
765
+ try {
766
+ const response = await this.client.post<{
767
+ status: 'success' | 'accepted';
768
+ file_id: string;
769
+ file_name: string;
770
+ file_status: 'processing' | 'completed';
771
+ message: string;
772
+ note?: string;
773
+ data?: { file_info: FileInfoJSON };
774
+ }>('/upload/file', form, { headers: form.getHeaders() });
775
+
776
+ const body = response.data;
777
+ const fileInfo = body.data?.file_info ? FileInfo.fromJSON(body.data.file_info) : undefined;
778
+ if (body.status === 'accepted') {
779
+ return {
780
+ status: 'accepted',
781
+ file_id: body.file_id,
782
+ file_name: body.file_name,
783
+ file_status: body.file_status as 'processing',
784
+ message: body.message,
785
+ note: body.note,
786
+ file_info: fileInfo,
787
+ };
788
+ }
789
+ return {
790
+ status: 'success',
791
+ file_id: body.file_id,
792
+ file_name: body.file_name,
793
+ file_status: body.file_status,
794
+ message: body.message,
795
+ file_info: fileInfo!,
796
+ };
797
+ } catch (error: any) {
798
+ if (axios.isAxiosError(error) && error.response) {
799
+ throw buildApiError(error.response.status, error.response.data, error.message);
800
+ }
801
+ throw new VidNavigatorError(error.message);
802
+ }
803
+ }
804
+
805
+ async deleteFile(file_id: string): Promise<{ file_id: string; file_name: string; message: string }> {
806
+ const response = await this.request<
807
+ ApiSuccessResponse<{ file_id: string; file_name: string; message: string }>
808
+ >('DELETE', `/file/${file_id}/delete`);
809
+ return response.data;
810
+ }
811
+
812
+ async getFileUrl(file_id: string): Promise<{ file_id: string; file_url: string }> {
813
+ const response = await this.request<
814
+ ApiSuccessResponse<{ file_id: string; file_url: string }>
815
+ >('GET', `/file/${file_id}/url`);
816
+ return response.data;
817
+ }
818
+
819
+ async retryFileProcessing(
820
+ file_id: string
821
+ ): Promise<{ file_id: string; file_name: string; file_status: string; message: string }> {
822
+ const response = await this.request<
823
+ ApiSuccessResponse<{
824
+ file_id: string;
825
+ file_name: string;
826
+ file_status: string;
827
+ message: string;
828
+ }>
829
+ >('POST', `/file/${file_id}/retry`);
830
+ return response.data;
831
+ }
832
+
833
+ async cancelFileUpload(
834
+ file_id: string
835
+ ): Promise<{ file_id: string; file_name: string; message: string }> {
836
+ const response = await this.request<
837
+ ApiSuccessResponse<{ file_id: string; file_name: string; message: string }>
838
+ >('POST', `/file/${file_id}/cancel`);
839
+ return response.data;
840
+ }
841
+ //endregion
842
+
843
+ //region --- Namespaces ---
844
+ async getNamespaces(): Promise<Namespace[]> {
845
+ const response = await this.request<ApiSuccessResponse<NamespaceJSON[]>>('GET', '/namespaces');
846
+ return response.data.map((n) => Namespace.fromJSON(n));
847
+ }
848
+
849
+ async createNamespace(payload: { name: string }): Promise<Namespace> {
850
+ const response = await this.request<ApiSuccessResponse<NamespaceJSON>>('POST', '/namespaces', payload);
851
+ return Namespace.fromJSON(response.data);
852
+ }
853
+
854
+ async updateNamespace(namespace_id: string, payload: { name: string }): Promise<{ message: string }> {
855
+ const body = await this.request<{ status: string; message: string }>(
856
+ 'PUT',
857
+ `/namespaces/${namespace_id}`,
858
+ payload
859
+ );
860
+ return { message: body.message };
861
+ }
862
+
863
+ async deleteNamespace(namespace_id: string): Promise<{ message: string }> {
864
+ const body = await this.request<{ status: string; message: string }>(
865
+ 'DELETE',
866
+ `/namespaces/${namespace_id}`
867
+ );
868
+ return { message: body.message };
869
+ }
870
+
871
+ async updateFileNamespaces(
872
+ file_id: string,
873
+ payload: { namespace_ids: string[] }
874
+ ): Promise<{ message: string; namespace_ids: string[]; namespaces: NamespaceRef[] }> {
875
+ const body = await this.request<{
876
+ status: string;
877
+ message: string;
878
+ data: { namespace_ids: string[]; namespaces: NamespaceRefJSON[] };
879
+ }>('PUT', `/file/${file_id}/namespaces`, payload);
880
+ return {
881
+ message: body.message,
882
+ namespace_ids: body.data.namespace_ids,
883
+ namespaces: body.data.namespaces.map(NamespaceRef.fromJSON),
884
+ };
885
+ }
886
+ //endregion
887
+
888
+ //region --- Analysis ---
889
+ async analyzeVideo(payload: AnalyzeVideoPayload): Promise<AnalyzeVideoResult> {
890
+ const response = await this.request<
891
+ ApiSuccessResponse<{
892
+ video_info: VideoInfoJSON;
893
+ transcript: TranscriptSegmentJSON[] | string;
894
+ transcript_analysis: AnalysisResultJSON;
895
+ }>
896
+ >('POST', '/analyze/video', payload);
897
+
898
+ return {
899
+ video_info: VideoInfo.fromJSON(response.data.video_info),
900
+ transcript: transcriptFromJSON(response.data.transcript)!,
901
+ transcript_analysis: AnalysisResult.fromJSON(response.data.transcript_analysis),
902
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
903
+ };
904
+ }
905
+
906
+ async analyzeFile(payload: AnalyzeFilePayload): Promise<AnalyzeFileResult> {
907
+ const response = await this.request<
908
+ ApiSuccessResponse<{
909
+ file_info: FileInfoJSON;
910
+ transcript: TranscriptSegmentJSON[] | string;
911
+ transcript_analysis: AnalysisResultJSON;
912
+ }>
913
+ >('POST', '/analyze/file', payload);
914
+
915
+ return {
916
+ file_info: FileInfo.fromJSON(response.data.file_info),
917
+ transcript: transcriptFromJSON(response.data.transcript)!,
918
+ transcript_analysis: AnalysisResult.fromJSON(response.data.transcript_analysis),
919
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
920
+ };
921
+ }
922
+
923
+ /**
924
+ * Structured claim analysis of an X/Twitter tweet. Blocking convenience wrapper around
925
+ * {@link VidNavigatorClient.tweetStatement}: submits to `POST /tweet/statement/async` and polls.
926
+ */
927
+ async getTweetStatement(
928
+ payload: TweetStatementPayload,
929
+ options?: RunOptions<TweetStatementAsyncJob>
930
+ ): Promise<TweetStatement> {
931
+ return this.tweetStatement(payload, options);
932
+ }
933
+ //endregion
934
+
935
+ //region --- Extraction ---
936
+ /**
937
+ * Structured-data extraction from an online video. Blocking convenience wrapper around
938
+ * {@link VidNavigatorClient.extractVideo}: submits to `POST /extract/video/async` and polls, so
939
+ * media of any length works. The result carries the extracted `data` and the video's `video_info`.
940
+ */
941
+ async extractVideoData(
942
+ payload: ExtractVideoDataPayload | ExtractVideoDataMultipartPayload,
943
+ options?: PollOptions<ExtractVideoAsyncJob>
944
+ ): Promise<ExtractDataResult> {
945
+ const { include_usage, ...input } = payload;
946
+ return this.extractVideo(input as ExtractVideoInput, { ...options, include_usage });
947
+ }
948
+
949
+ async extractFileData(
950
+ payload: ExtractFileDataPayload | ExtractFileDataMultipartPayload
951
+ ): Promise<ExtractDataResult> {
952
+ if ('schemaFilePath' in payload) {
953
+ const form = new FormData();
954
+ form.append('file_id', payload.file_id);
955
+ form.append('schema', fs.createReadStream(payload.schemaFilePath));
956
+ appendOptionalFormField(form, 'what_to_extract', payload.what_to_extract);
957
+ appendOptionalFormField(form, 'include_usage', payload.include_usage);
958
+
959
+ const body = await this.request<{
960
+ status: 'success';
961
+ data: Record<string, unknown>;
962
+ file_info?: FileInfoJSON;
963
+ usage?: UsageBlockJSON;
964
+ }>('POST', '/extract/file', form, undefined, form.getHeaders());
965
+ return {
966
+ data: body.data,
967
+ file_info: body.file_info ? FileInfo.fromJSON(body.file_info) : undefined,
968
+ usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
969
+ };
970
+ }
971
+
972
+ const body = await this.request<{
973
+ status: 'success';
974
+ data: Record<string, unknown>;
975
+ file_info?: FileInfoJSON;
976
+ usage?: UsageBlockJSON;
977
+ }>('POST', '/extract/file', payload);
978
+ return {
979
+ data: body.data,
980
+ file_info: body.file_info ? FileInfo.fromJSON(body.file_info) : undefined,
981
+ usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
982
+ };
983
+ }
984
+ //endregion
985
+
986
+ //region --- Search ---
987
+ /**
988
+ * Search YouTube for videos with AI analysis and ranking.
989
+ *
990
+ * If the account runs out of `residential_request` credits mid-search, the API
991
+ * returns HTTP 402 with `status: "partial"` and the videos analysed so far. The
992
+ * SDK surfaces that partial payload (results, `status: "partial"`, `error_code`,
993
+ * and `usage` when requested) instead of throwing.
994
+ */
995
+ async searchYouTube(payload: SearchYouTubePayload): Promise<SearchYouTubeResult> {
996
+ let response: {
997
+ status?: 'success' | 'partial';
998
+ error_code?: string;
999
+ data: {
1000
+ results: VideoSearchResultJSON[];
1001
+ query: string;
1002
+ total_found: number;
1003
+ explanation?: string;
1004
+ };
1005
+ usage?: UsageBlockJSON;
1006
+ };
1007
+
1008
+ try {
1009
+ response = await this.request('POST', '/youtube/search', payload);
1010
+ } catch (error: any) {
1011
+ const body = error?.details;
1012
+ if (error instanceof PaymentRequiredError && body?.status === 'partial' && body?.data) {
1013
+ response = body;
1014
+ } else {
1015
+ throw error;
1016
+ }
1017
+ }
1018
+
1019
+ return {
1020
+ results: (response.data.results ?? []).map(VideoSearchResult.fromJSON),
1021
+ query: response.data.query,
1022
+ total_found: response.data.total_found,
1023
+ explanation: response.data.explanation,
1024
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1025
+ status: response.status,
1026
+ error_code: response.error_code,
1027
+ };
1028
+ }
1029
+
1030
+ /**
1031
+ * @deprecated `/search/video` moved to `/youtube/search`. Use
1032
+ * {@link VidNavigatorClient.searchYouTube} instead. This alias forwards to
1033
+ * `searchYouTube` and will be removed in a future release.
1034
+ */
1035
+ async searchVideos(payload: SearchYouTubePayload): Promise<SearchYouTubeResult> {
1036
+ warnDeprecated('searchVideos', 'searchYouTube');
1037
+ return this.searchYouTube(payload);
1038
+ }
1039
+
1040
+ async searchFiles(payload: SearchFilesPayload): Promise<SearchFilesResult> {
1041
+ const response = await this.request<
1042
+ ApiSuccessResponse<{
1043
+ results: FileSearchResultJSON[];
1044
+ query: string;
1045
+ total_found: number;
1046
+ explanation?: string;
1047
+ }>
1048
+ >('POST', '/search/file', payload);
1049
+
1050
+ return {
1051
+ results: response.data.results.map(FileSearchResult.fromJSON),
1052
+ query: response.data.query,
1053
+ total_found: response.data.total_found,
1054
+ explanation: response.data.explanation,
1055
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1056
+ };
1057
+ }
1058
+ //endregion
1059
+
1060
+ //region --- System ---
1061
+ async getUsage(): Promise<UsageData> {
1062
+ const response = await this.request<ApiSuccessResponse<UsageDataJSON>>('GET', '/usage');
1063
+ return UsageData.fromJSON(response.data);
1064
+ }
1065
+
1066
+ async healthCheck(): Promise<{
1067
+ status?: string;
1068
+ message?: string;
1069
+ version?: string;
1070
+ endpoints?: Array<{
1071
+ path?: string;
1072
+ method?: string;
1073
+ description?: string;
1074
+ auth_required?: boolean;
1075
+ }>;
1076
+ }> {
1077
+ const response = await this.client.get('/health');
1078
+ return response.data;
1079
+ }
1080
+ //endregion
1081
+ }