vidnavigator 1.0.5 → 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/src/index.ts CHANGED
@@ -39,27 +39,24 @@ import {
39
39
  TikTokSearchTask,
40
40
  TikTokSearchTaskJSON,
41
41
  TweetStatement,
42
- TweetStatementJSON,
42
+ AsyncJob,
43
+ AsyncJobJSON,
44
+ AsyncJobAccepted,
45
+ AsyncJobAcceptedJSON,
46
+ TikTokProfilePagination,
43
47
  } from './models';
44
- import {
45
- VidNavigatorError,
46
- AuthenticationError,
47
- BadRequestError,
48
- AccessDeniedError,
49
- NotFoundError,
50
- RateLimitExceededError,
51
- PaymentRequiredError,
52
- ServerError,
53
- StorageQuotaExceededError,
54
- GeoRestrictedError,
55
- SystemOverloadError,
56
- } from './errors';
48
+ import { VidNavigatorError, PaymentRequiredError } from './errors';
49
+ import { buildApiError } from './http';
50
+ import { Job, JobInfo, JobOperation, PollableTask, PollOptions, RunOptions, SubmitOptions } from './jobs';
57
51
 
58
52
  export * from './models';
59
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';
60
57
 
61
58
  /** SDK version (keep in sync with package.json) */
62
- export const SDK_VERSION = '1.0.5';
59
+ export const SDK_VERSION = '2.0.0';
63
60
 
64
61
  //region --- Interfaces ---
65
62
  export interface SDKConfig {
@@ -88,7 +85,42 @@ export type TranscribeVideoPayload = {
88
85
  transcript_text?: boolean;
89
86
  all_videos?: boolean;
90
87
  include_usage?: boolean;
91
- };
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;
92
124
 
93
125
  export type TranscriptResult = {
94
126
  video_info: VideoInfo;
@@ -110,6 +142,37 @@ export type TranscribeVideoCarouselResult = {
110
142
 
111
143
  export type TranscribeVideoResult = TranscribeVideoSingleResult | TranscribeVideoCarouselResult;
112
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
+
113
176
  export type UploadFileSuccessResult = {
114
177
  status: 'success';
115
178
  file_id: string;
@@ -211,7 +274,7 @@ export type ExtractVideoDataPayload = {
211
274
  what_to_extract?: string;
212
275
  transcribe?: boolean;
213
276
  include_usage?: boolean;
214
- };
277
+ } & WebhookOption;
215
278
 
216
279
  export type ExtractVideoDataMultipartPayload = {
217
280
  video_url: string;
@@ -220,7 +283,9 @@ export type ExtractVideoDataMultipartPayload = {
220
283
  what_to_extract?: string;
221
284
  transcribe?: boolean;
222
285
  include_usage?: boolean;
223
- };
286
+ } & WebhookOption;
287
+
288
+ export type TweetStatementPayload = { tweet_id: string } & WebhookOption;
224
289
 
225
290
  export type ExtractFileDataPayload = {
226
291
  file_id: string;
@@ -238,18 +303,70 @@ export type ExtractFileDataMultipartPayload = {
238
303
  };
239
304
  //endregion
240
305
 
241
- function parseApiErrorPayload(data: any): {
242
- errorCode?: string;
243
- errorMessage?: string;
244
- details?: any;
245
- } {
246
- const errorField = data?.error;
247
- const errorCode =
248
- typeof errorField === 'string' ? errorField : errorField?.code;
249
- const errorMessage =
250
- data?.message ??
251
- (typeof errorField === 'object' ? errorField?.message : undefined);
252
- return { errorCode, errorMessage, details: data };
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>;
253
370
  }
254
371
 
255
372
  function appendOptionalFormField(form: FormData, name: string, value: string | number | boolean | undefined): void {
@@ -287,6 +404,40 @@ function warnDeprecated(oldName: string, newName: string): void {
287
404
  export class VidNavigatorClient {
288
405
  private client: AxiosInstance;
289
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
+
290
441
  constructor(config: SDKConfig) {
291
442
  if (!config?.apiKey) {
292
443
  throw new Error('An API key is required to use the VidNavigator SDK.');
@@ -300,6 +451,132 @@ export class VidNavigatorClient {
300
451
  },
301
452
  ...config.axiosConfig,
302
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;
303
580
  }
304
581
 
305
582
  private async request<T>(
@@ -320,42 +597,7 @@ export class VidNavigatorClient {
320
597
  return response.data;
321
598
  } catch (error: any) {
322
599
  if (axios.isAxiosError(error) && error.response) {
323
- const { status, data } = error.response;
324
- const { errorCode, errorMessage, details } = parseApiErrorPayload(data);
325
- const message = `API request failed with status ${status}: ${errorMessage || error.message}`;
326
-
327
- switch (status) {
328
- case 400:
329
- throw new BadRequestError(message, status, errorCode, errorMessage, details);
330
- case 401:
331
- throw new AuthenticationError(message, status, errorCode, errorMessage, details);
332
- case 402:
333
- throw new PaymentRequiredError(message, status, errorCode, errorMessage, details);
334
- case 403:
335
- throw new AccessDeniedError(message, status, errorCode, errorMessage, details);
336
- case 404:
337
- throw new NotFoundError(message, status, errorCode, errorMessage, details);
338
- case 413:
339
- throw new StorageQuotaExceededError(message, status, errorCode, errorMessage, details);
340
- case 429:
341
- throw new RateLimitExceededError(message, status, errorCode, errorMessage, details);
342
- case 451:
343
- throw new GeoRestrictedError(message, status, errorCode, errorMessage, details);
344
- case 503:
345
- throw new SystemOverloadError(
346
- message,
347
- status,
348
- errorCode,
349
- errorMessage,
350
- details,
351
- data?.retry_after_seconds
352
- );
353
- default:
354
- if (status >= 500) {
355
- throw new ServerError(message, status, errorCode, errorMessage, details);
356
- }
357
- throw new VidNavigatorError(message, status, errorCode, errorMessage, details);
358
- }
600
+ throw buildApiError(error.response.status, error.response.data, error.message);
359
601
  }
360
602
  throw new VidNavigatorError(error.message);
361
603
  }
@@ -392,36 +634,16 @@ export class VidNavigatorClient {
392
634
  return this.getTranscript(payload);
393
635
  }
394
636
 
395
- async transcribeVideo(payload: TranscribeVideoPayload): Promise<TranscribeVideoResult> {
396
- const response = await this.request<
397
- | ApiSuccessResponse<{
398
- video_info: VideoInfoJSON;
399
- transcript: TranscriptSegmentJSON[] | string;
400
- }>
401
- | ApiSuccessResponse<{
402
- carousel_info: CarouselInfoJSON;
403
- videos: CarouselVideoResultJSON[];
404
- }>
405
- >('POST', '/transcribe', payload);
406
-
407
- const inner = response.data;
408
- const usage = response.usage ? UsageBlock.fromJSON(response.usage) : undefined;
409
- if ('videos' in inner && 'carousel_info' in inner) {
410
- return {
411
- carousel_info: CarouselInfo.fromJSON(inner.carousel_info),
412
- videos: inner.videos.map((v) => CarouselVideoResult.fromJSON(v)),
413
- usage,
414
- };
415
- }
416
- const single = inner as {
417
- video_info: VideoInfoJSON;
418
- transcript: TranscriptSegmentJSON[] | string;
419
- };
420
- return {
421
- video_info: VideoInfo.fromJSON(single.video_info),
422
- transcript: transcriptFromJSON(single.transcript)!,
423
- usage,
424
- };
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 });
425
647
  }
426
648
  //endregion
427
649
 
@@ -574,33 +796,7 @@ export class VidNavigatorClient {
574
796
  };
575
797
  } catch (error: any) {
576
798
  if (axios.isAxiosError(error) && error.response) {
577
- const { status, data } = error.response;
578
- const { errorCode, errorMessage, details } = parseApiErrorPayload(data);
579
- const message = `API request failed with status ${status}: ${errorMessage || error.message}`;
580
- switch (status) {
581
- case 400:
582
- throw new BadRequestError(message, status, errorCode, errorMessage, details);
583
- case 401:
584
- throw new AuthenticationError(message, status, errorCode, errorMessage, details);
585
- case 402:
586
- throw new PaymentRequiredError(message, status, errorCode, errorMessage, details);
587
- case 413:
588
- throw new StorageQuotaExceededError(message, status, errorCode, errorMessage, details);
589
- case 503:
590
- throw new SystemOverloadError(
591
- message,
592
- status,
593
- errorCode,
594
- errorMessage,
595
- details,
596
- data?.retry_after_seconds
597
- );
598
- default:
599
- if (status >= 500) {
600
- throw new ServerError(message, status, errorCode, errorMessage, details);
601
- }
602
- throw new VidNavigatorError(message, status, errorCode, errorMessage, details);
603
- }
799
+ throw buildApiError(error.response.status, error.response.data, error.message);
604
800
  }
605
801
  throw new VidNavigatorError(error.message);
606
802
  }
@@ -724,52 +920,31 @@ export class VidNavigatorClient {
724
920
  };
725
921
  }
726
922
 
727
- async getTweetStatement(payload: { tweet_id: string }): Promise<TweetStatement> {
728
- const response = await this.request<ApiSuccessResponse<TweetStatementJSON>>(
729
- 'POST',
730
- '/tweet/statement',
731
- payload
732
- );
733
- return TweetStatement.fromJSON(response.data);
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);
734
932
  }
735
933
  //endregion
736
934
 
737
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
+ */
738
942
  async extractVideoData(
739
- payload: ExtractVideoDataPayload | ExtractVideoDataMultipartPayload
943
+ payload: ExtractVideoDataPayload | ExtractVideoDataMultipartPayload,
944
+ options?: PollOptions<ExtractVideoAsyncJob>
740
945
  ): Promise<ExtractDataResult> {
741
- if ('schemaFilePath' in payload) {
742
- const form = new FormData();
743
- form.append('video_url', payload.video_url);
744
- form.append('schema', fs.createReadStream(payload.schemaFilePath));
745
- appendOptionalFormField(form, 'what_to_extract', payload.what_to_extract);
746
- appendOptionalFormField(form, 'transcribe', payload.transcribe);
747
- appendOptionalFormField(form, 'include_usage', payload.include_usage);
748
-
749
- const body = await this.request<{
750
- status: 'success';
751
- data: Record<string, unknown>;
752
- video_info?: VideoInfoJSON;
753
- usage?: UsageBlockJSON;
754
- }>('POST', '/extract/video', form, undefined, form.getHeaders());
755
- return {
756
- data: body.data,
757
- video_info: body.video_info ? VideoInfo.fromJSON(body.video_info) : undefined,
758
- usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
759
- };
760
- }
761
-
762
- const body = await this.request<{
763
- status: 'success';
764
- data: Record<string, unknown>;
765
- video_info?: VideoInfoJSON;
766
- usage?: UsageBlockJSON;
767
- }>('POST', '/extract/video', payload);
768
- return {
769
- data: body.data,
770
- video_info: body.video_info ? VideoInfo.fromJSON(body.video_info) : undefined,
771
- usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
772
- };
946
+ const { include_usage, ...input } = payload;
947
+ return this.extractVideo(input as ExtractVideoInput, { ...options, include_usage });
773
948
  }
774
949
 
775
950
  async extractFileData(