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.
@@ -1,4 +1,9 @@
1
1
  import { UsageBlock } from './Usage';
2
+ import { AsyncJobError, AsyncJobWebhookStatus } from './AsyncJob';
3
+ /** Sort order applied by TikTok itself for keyword searches. */
4
+ export type TikTokSearchSortBy = 'relevance' | 'most_liked' | 'newest';
5
+ /** Rolling publication window applied by TikTok itself (`this_week` = the last 7 days). */
6
+ export type TikTokPublishedWithin = 'all' | 'past_24_hours' | 'this_week' | 'this_month' | 'last_3_months' | 'last_6_months';
2
7
  export interface TikTokProfileScrapeRequest {
3
8
  profile_url: string;
4
9
  max_posts?: number;
@@ -8,11 +13,22 @@ export interface TikTokProfileScrapeRequest {
8
13
  before_datetime?: string;
9
14
  min_likes?: number;
10
15
  max_likes?: number;
16
+ /**
17
+ * Where to POST a notification when the task finishes. Overrides the account-level default
18
+ * configured in Studio → API; pass an empty string to opt this task out of that default.
19
+ * Must be a publicly reachable https URL. The event's `data.result` is a summary (`stats`, `download_url_available`),
20
+ * not the videos (a scrape can hold thousands); read those with `vn.tiktokProfile.resume(task_id).result()`.
21
+ */
22
+ webhook_url?: string;
11
23
  }
12
24
  export interface TikTokSearchRequest {
13
25
  query: string;
14
26
  max_results?: number;
15
27
  parallel_search_slices?: number;
28
+ /** Sort order applied by TikTok. When omitted, results are returned newest first. */
29
+ sort_by?: TikTokSearchSortBy;
30
+ /** Publication window applied by TikTok. Auto-selected from `after_datetime` when omitted. */
31
+ published_within?: TikTokPublishedWithin;
16
32
  /** Format: YYYY-MM-DD or ISO datetime with timezone */
17
33
  after_datetime?: string;
18
34
  /** Format: YYYY-MM-DD or ISO datetime with timezone */
@@ -21,6 +37,13 @@ export interface TikTokSearchRequest {
21
37
  max_likes?: number;
22
38
  min_views?: number;
23
39
  max_views?: number;
40
+ /**
41
+ * Where to POST a notification when the task finishes. Overrides the account-level default
42
+ * configured in Studio → API; pass an empty string to opt this task out of that default.
43
+ * Must be a publicly reachable https URL. The event's `data.result` is a summary (`stats`, `download_url_available`);
44
+ * read the results with `vn.tiktokSearch.resume(task_id).result()`.
45
+ */
46
+ webhook_url?: string;
24
47
  }
25
48
  export interface TikTokProfileScrapeSubmissionJSON {
26
49
  task_id: string;
@@ -29,6 +52,7 @@ export interface TikTokProfileScrapeSubmissionJSON {
29
52
  expires_at?: string;
30
53
  check_status_url?: string;
31
54
  message?: string;
55
+ webhook_url?: string | null;
32
56
  }
33
57
  export declare class TikTokProfileScrapeSubmission {
34
58
  task_id: string;
@@ -37,6 +61,8 @@ export declare class TikTokProfileScrapeSubmission {
37
61
  expires_at?: string;
38
62
  check_status_url?: string;
39
63
  message?: string;
64
+ /** The URL this task's result notification will be POSTed to, or `null`. */
65
+ webhook_url?: string | null;
40
66
  constructor(data: TikTokProfileScrapeSubmissionJSON);
41
67
  static fromJSON(json: TikTokProfileScrapeSubmissionJSON): TikTokProfileScrapeSubmission;
42
68
  }
@@ -50,6 +76,7 @@ export interface TikTokSearchSubmissionJSON {
50
76
  expires_at?: string;
51
77
  check_status_url?: string;
52
78
  message?: string;
79
+ webhook_url?: string | null;
53
80
  }
54
81
  export declare class TikTokSearchSubmission {
55
82
  task_id: string;
@@ -61,6 +88,8 @@ export declare class TikTokSearchSubmission {
61
88
  expires_at?: string;
62
89
  check_status_url?: string;
63
90
  message?: string;
91
+ /** The URL this task's result notification will be POSTed to, or `null`. */
92
+ webhook_url?: string | null;
64
93
  constructor(data: TikTokSearchSubmissionJSON);
65
94
  static fromJSON(json: TikTokSearchSubmissionJSON): TikTokSearchSubmission;
66
95
  }
@@ -167,6 +196,8 @@ export declare class TikTokSearchResult {
167
196
  static fromJSON(json: TikTokSearchResultJSON): TikTokSearchResult;
168
197
  }
169
198
  export interface TikTokSearchFilters {
199
+ sort_by?: TikTokSearchSortBy | null;
200
+ published_within?: TikTokPublishedWithin | null;
170
201
  after_datetime?: string | null;
171
202
  before_datetime?: string | null;
172
203
  min_likes?: number | null;
@@ -178,6 +209,10 @@ export interface TikTokSearchStats {
178
209
  pages_fetched?: number;
179
210
  results_count?: number;
180
211
  next_search_cursor?: number | null;
212
+ /** Sort order the search ran with (`relevance` when `sort_by` was omitted). */
213
+ sort_by?: TikTokSearchSortBy;
214
+ /** Date window the search ran with; `all` means no window. */
215
+ published_within?: TikTokPublishedWithin;
181
216
  }
182
217
  export interface TikTokProfileTaskJSON {
183
218
  task_id: string;
@@ -193,6 +228,8 @@ export interface TikTokProfileTaskJSON {
193
228
  created_at?: string | null;
194
229
  completed_at?: string | null;
195
230
  expires_at?: string | null;
231
+ error?: AsyncJobError | null;
232
+ webhook?: AsyncJobWebhookStatus | null;
196
233
  }
197
234
  export declare class TikTokProfileTask {
198
235
  task_id: string;
@@ -204,10 +241,15 @@ export declare class TikTokProfileTask {
204
241
  videos: TikTokVideo[];
205
242
  pagination?: TikTokProfilePagination;
206
243
  download_url?: string | null;
244
+ /** @deprecated Use `error`, which carries a machine-readable code. */
207
245
  error_message?: string | null;
208
246
  created_at?: string | null;
209
247
  completed_at?: string | null;
210
248
  expires_at?: string | null;
249
+ /** Present when `task_status === 'failed'`: error code, message and HTTP status. */
250
+ error: AsyncJobError | null;
251
+ /** Webhook delivery state, or `null` when no webhook was configured. */
252
+ webhook?: AsyncJobWebhookStatus | null;
211
253
  /** Per-call usage, populated only when polled with `include_usage=true` and `task_status=completed`. */
212
254
  usage?: UsageBlock;
213
255
  constructor(data: TikTokProfileTaskJSON);
@@ -227,6 +269,8 @@ export interface TikTokSearchTaskJSON {
227
269
  created_at?: string | null;
228
270
  completed_at?: string | null;
229
271
  expires_at?: string | null;
272
+ error?: AsyncJobError | null;
273
+ webhook?: AsyncJobWebhookStatus | null;
230
274
  }
231
275
  export declare class TikTokSearchTask {
232
276
  task_id: string;
@@ -238,10 +282,15 @@ export declare class TikTokSearchTask {
238
282
  results: TikTokSearchResult[];
239
283
  pagination?: TikTokProfilePagination;
240
284
  download_url?: string | null;
285
+ /** @deprecated Use `error`, which carries a machine-readable code. */
241
286
  error_message?: string | null;
242
287
  created_at?: string | null;
243
288
  completed_at?: string | null;
244
289
  expires_at?: string | null;
290
+ /** Present when `task_status === 'failed'`: error code, message and HTTP status. */
291
+ error: AsyncJobError | null;
292
+ /** Webhook delivery state, or `null` when no webhook was configured. */
293
+ webhook?: AsyncJobWebhookStatus | null;
245
294
  /** Per-call usage, populated only when polled with `include_usage=true` and `task_status=completed`. */
246
295
  usage?: UsageBlock;
247
296
  constructor(data: TikTokSearchTaskJSON);
@@ -32,6 +32,8 @@ function normalizeSearchFilters(filters) {
32
32
  if (!filters)
33
33
  return undefined;
34
34
  return {
35
+ sort_by: filters.sort_by,
36
+ published_within: filters.published_within,
35
37
  after_datetime: filters.after_datetime,
36
38
  before_datetime: filters.before_datetime,
37
39
  min_likes: toInteger(filters.min_likes),
@@ -56,6 +58,8 @@ function normalizeSearchStats(stats) {
56
58
  pages_fetched: toOptionalInteger(stats.pages_fetched),
57
59
  results_count: toOptionalInteger(stats.results_count),
58
60
  next_search_cursor: toInteger(stats.next_search_cursor),
61
+ sort_by: stats.sort_by,
62
+ published_within: stats.published_within,
59
63
  };
60
64
  }
61
65
  function normalizePagination(pagination) {
@@ -79,6 +83,7 @@ class TikTokProfileScrapeSubmission {
79
83
  this.expires_at = data.expires_at;
80
84
  this.check_status_url = data.check_status_url;
81
85
  this.message = data.message;
86
+ this.webhook_url = data.webhook_url;
82
87
  }
83
88
  static fromJSON(json) {
84
89
  return new TikTokProfileScrapeSubmission(json);
@@ -96,6 +101,7 @@ class TikTokSearchSubmission {
96
101
  this.expires_at = data.expires_at;
97
102
  this.check_status_url = data.check_status_url;
98
103
  this.message = data.message;
104
+ this.webhook_url = data.webhook_url;
99
105
  }
100
106
  static fromJSON(json) {
101
107
  return new TikTokSearchSubmission(json);
@@ -171,6 +177,8 @@ class TikTokProfileTask {
171
177
  this.created_at = data.created_at;
172
178
  this.completed_at = data.completed_at;
173
179
  this.expires_at = data.expires_at;
180
+ this.error = data.error ?? null;
181
+ this.webhook = data.webhook;
174
182
  }
175
183
  static fromJSON(json) {
176
184
  return new TikTokProfileTask(json);
@@ -192,6 +200,8 @@ class TikTokSearchTask {
192
200
  this.created_at = data.created_at;
193
201
  this.completed_at = data.completed_at;
194
202
  this.expires_at = data.expires_at;
203
+ this.error = data.error ?? null;
204
+ this.webhook = data.webhook;
195
205
  }
196
206
  static fromJSON(json) {
197
207
  return new TikTokSearchTask(json);
@@ -1,3 +1,4 @@
1
+ import { UsageBlock } from './Usage';
1
2
  export type TweetClaimType = 'factual_claim' | 'opinion' | 'question' | 'call_to_action' | 'satire' | 'news_sharing' | 'personal_experience';
2
3
  export type TweetIntent = 'educate' | 'inform' | 'analyze' | 'persuade' | 'entertain' | 'inspire' | 'challenge';
3
4
  export type TweetTone = 'serious' | 'humorous' | 'provocative' | 'neutral' | 'warm' | 'skeptical' | 'inspirational';
@@ -21,6 +22,7 @@ export interface TweetStatementJSON {
21
22
  }
22
23
  export declare class TweetStatement {
23
24
  final_statement?: string;
25
+ /** @deprecated Not part of the API contract and not returned by the async endpoint; always undefined. */
24
26
  statement_query?: string;
25
27
  detailed_analysis?: string;
26
28
  topics?: string[];
@@ -34,6 +36,8 @@ export declare class TweetStatement {
34
36
  tweet_media_summary?: string | null;
35
37
  quoted_tweet_text?: string | null;
36
38
  quoted_media_summary?: string | null;
39
+ /** Per-call usage, populated when requested with include_usage. */
40
+ usage?: UsageBlock;
37
41
  constructor(data: TweetStatementJSON);
38
42
  static fromJSON(json: TweetStatementJSON): TweetStatement;
39
43
  }
@@ -1,4 +1,5 @@
1
1
  export * from './AnalysisResult';
2
+ export * from './AsyncJob';
2
3
  export * from './Carousel';
3
4
  export * from './CarouselVideoResult';
4
5
  export * from './Extraction';
@@ -15,6 +15,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./AnalysisResult"), exports);
18
+ __exportStar(require("./AsyncJob"), exports);
18
19
  __exportStar(require("./Carousel"), exports);
19
20
  __exportStar(require("./CarouselVideoResult"), exports);
20
21
  __exportStar(require("./Extraction"), exports);
@@ -0,0 +1,63 @@
1
+ import { AsyncJobError } from './models';
2
+ /** Event types delivered to a `webhook_url` when an async job reaches a terminal state. */
3
+ export type WebhookEventType = 'transcribe.completed' | 'transcribe.failed' | 'extract_video.completed' | 'extract_video.failed' | 'tweet_statement.completed' | 'tweet_statement.failed' | 'tiktok_profile.completed' | 'tiktok_profile.failed' | 'tiktok_search.completed' | 'tiktok_search.failed';
4
+ /** `data.result` of a `tiktok_profile.*` / `tiktok_search.*` event: a summary, not the videos. */
5
+ export interface TikTokWebhookResult {
6
+ /** Same fields as the task's `stats` (e.g. `videos_matched`, or `results_count` / `sort_by` for searches). */
7
+ stats?: Record<string, unknown>;
8
+ /** Whether the full result can be downloaded as one JSON file (`download_url` on the task). */
9
+ download_url_available?: boolean;
10
+ }
11
+ /** The JSON body POSTed to your `webhook_url`. */
12
+ export interface WebhookEvent {
13
+ /** Event id, e.g. `evt_9f2c...`. */
14
+ id: string;
15
+ type: WebhookEventType;
16
+ created_at: string;
17
+ api_version?: string;
18
+ data: {
19
+ task_id: string;
20
+ task_status: 'completed' | 'failed';
21
+ job_type?: string;
22
+ check_status_url?: string;
23
+ /**
24
+ * Raw (unparsed) result of the completed job. For transcription, extraction and tweet jobs it
25
+ * is the same data the job's `result()` parses. For TikTok tasks it is a summary only,
26
+ * {@link TikTokWebhookResult} (a scrape can hold thousands of videos); fetch the videos with
27
+ * `vn.tiktokProfile.resume(task_id).result()`. Omitted when `result_truncated` is true.
28
+ */
29
+ result?: Record<string, unknown> | TikTokWebhookResult | null;
30
+ /** True when the result exceeded 256 KB; fetch it with `resume(task_id).result()` instead. */
31
+ result_truncated?: boolean;
32
+ error?: AsyncJobError | null;
33
+ };
34
+ }
35
+ /** Header names sent with every webhook delivery. */
36
+ export declare const WEBHOOK_HEADERS: {
37
+ /** Same as the event `type`. */
38
+ readonly event: "x-vidnavigator-event";
39
+ /** Delivery id, stable across retries — dedupe on this. */
40
+ readonly delivery: "x-vidnavigator-delivery";
41
+ /** The job's `task_id`. */
42
+ readonly taskId: "x-vidnavigator-task-id";
43
+ /** `t=<unix_ts>,v1=<hmac_sha256 hex>` */
44
+ readonly signature: "x-vidnavigator-signature";
45
+ };
46
+ export interface VerifyWebhookOptions {
47
+ /** Reject deliveries whose timestamp is older (or further in the future) than this. Default 300 (5 minutes). Pass `0` to disable. */
48
+ toleranceSeconds?: number;
49
+ /** Override "now" as a unix timestamp in seconds (useful for tests). */
50
+ now?: number;
51
+ }
52
+ /**
53
+ * Verify the `X-VidNavigator-Signature` header of a webhook delivery.
54
+ *
55
+ * `payload` must be the **raw** request body exactly as received (not re-serialized JSON).
56
+ * Returns `true` when the HMAC-SHA256 signature matches and the timestamp is within tolerance.
57
+ */
58
+ export declare function verifyWebhookSignature(payload: string | Buffer, signatureHeader: string | string[] | undefined, secret: string, options?: VerifyWebhookOptions): boolean;
59
+ /**
60
+ * Verify a webhook delivery and parse its body into a {@link WebhookEvent}.
61
+ * Throws {@link WebhookSignatureError} when the signature is invalid or stale.
62
+ */
63
+ export declare function constructWebhookEvent(payload: string | Buffer, signatureHeader: string | string[] | undefined, secret: string, options?: VerifyWebhookOptions): WebhookEvent;
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.WEBHOOK_HEADERS = void 0;
7
+ exports.verifyWebhookSignature = verifyWebhookSignature;
8
+ exports.constructWebhookEvent = constructWebhookEvent;
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const errors_1 = require("./errors");
11
+ /** Header names sent with every webhook delivery. */
12
+ exports.WEBHOOK_HEADERS = {
13
+ /** Same as the event `type`. */
14
+ event: 'x-vidnavigator-event',
15
+ /** Delivery id, stable across retries — dedupe on this. */
16
+ delivery: 'x-vidnavigator-delivery',
17
+ /** The job's `task_id`. */
18
+ taskId: 'x-vidnavigator-task-id',
19
+ /** `t=<unix_ts>,v1=<hmac_sha256 hex>` */
20
+ signature: 'x-vidnavigator-signature',
21
+ };
22
+ function parseSignatureHeader(header) {
23
+ let timestamp;
24
+ const signatures = [];
25
+ for (const part of header.split(',')) {
26
+ const idx = part.indexOf('=');
27
+ if (idx === -1)
28
+ continue;
29
+ const key = part.slice(0, idx).trim();
30
+ const value = part.slice(idx + 1).trim();
31
+ if (key === 't')
32
+ timestamp = Number(value);
33
+ else if (key === 'v1' && value)
34
+ signatures.push(value);
35
+ }
36
+ if (timestamp === undefined || !Number.isFinite(timestamp) || signatures.length === 0)
37
+ return null;
38
+ return { timestamp, signatures };
39
+ }
40
+ function assertValidSignature(payload, signatureHeader, secret, options = {}) {
41
+ if (!secret)
42
+ throw new errors_1.WebhookSignatureError('A webhook signing secret is required.');
43
+ const header = Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader;
44
+ if (!header)
45
+ throw new errors_1.WebhookSignatureError('Missing X-VidNavigator-Signature header.');
46
+ const parsed = parseSignatureHeader(header);
47
+ if (!parsed)
48
+ throw new errors_1.WebhookSignatureError('Malformed X-VidNavigator-Signature header.');
49
+ const tolerance = options.toleranceSeconds ?? 300;
50
+ const now = options.now ?? Math.floor(Date.now() / 1000);
51
+ if (tolerance > 0 && Math.abs(now - parsed.timestamp) > tolerance) {
52
+ throw new errors_1.WebhookSignatureError('Webhook timestamp is outside the allowed tolerance.');
53
+ }
54
+ const body = typeof payload === 'string' ? payload : payload.toString('utf8');
55
+ const expected = crypto_1.default
56
+ .createHmac('sha256', secret)
57
+ .update(`${parsed.timestamp}.${body}`)
58
+ .digest();
59
+ const matches = parsed.signatures.some((sig) => {
60
+ if (!/^[0-9a-f]+$/i.test(sig))
61
+ return false;
62
+ const received = Buffer.from(sig, 'hex');
63
+ return received.length === expected.length && crypto_1.default.timingSafeEqual(received, expected);
64
+ });
65
+ if (!matches)
66
+ throw new errors_1.WebhookSignatureError('Webhook signature does not match.');
67
+ }
68
+ /**
69
+ * Verify the `X-VidNavigator-Signature` header of a webhook delivery.
70
+ *
71
+ * `payload` must be the **raw** request body exactly as received (not re-serialized JSON).
72
+ * Returns `true` when the HMAC-SHA256 signature matches and the timestamp is within tolerance.
73
+ */
74
+ function verifyWebhookSignature(payload, signatureHeader, secret, options) {
75
+ try {
76
+ assertValidSignature(payload, signatureHeader, secret, options);
77
+ return true;
78
+ }
79
+ catch (error) {
80
+ if (error instanceof errors_1.WebhookSignatureError)
81
+ return false;
82
+ throw error;
83
+ }
84
+ }
85
+ /**
86
+ * Verify a webhook delivery and parse its body into a {@link WebhookEvent}.
87
+ * Throws {@link WebhookSignatureError} when the signature is invalid or stale.
88
+ */
89
+ function constructWebhookEvent(payload, signatureHeader, secret, options) {
90
+ assertValidSignature(payload, signatureHeader, secret, options);
91
+ const body = typeof payload === 'string' ? payload : payload.toString('utf8');
92
+ try {
93
+ return JSON.parse(body);
94
+ }
95
+ catch {
96
+ throw new errors_1.VidNavigatorError('Webhook payload is not valid JSON.');
97
+ }
98
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vidnavigator",
3
- "version": "1.0.5",
3
+ "version": "2.0.0",
4
4
  "description": "Official JavaScript SDK for the VidNavigator Developer API",
5
5
  "author": "VidNavigator",
6
6
  "license": "Apache-2.0",
package/src/errors.ts CHANGED
@@ -11,6 +11,12 @@ export class VidNavigatorError extends Error {
11
11
  public readonly error_code?: string;
12
12
  public readonly error_message?: string;
13
13
  public readonly details?: any;
14
+ /**
15
+ * Set on every error raised while submitting, polling, or waiting for an async job once a
16
+ * `task_id` exists. The job keeps running server-side and its result stays readable for 1 hour
17
+ * after it finishes, so keep this id to resume with `vn.<operation>.resume(task_id)`.
18
+ */
19
+ public task_id?: string;
14
20
 
15
21
  constructor(
16
22
  message: string,
@@ -147,4 +153,56 @@ export class SystemOverloadError extends VidNavigatorError {
147
153
  this.retry_after_seconds = retry_after_seconds;
148
154
  Object.setPrototypeOf(this, SystemOverloadError.prototype);
149
155
  }
150
- }
156
+ }
157
+
158
+ /**
159
+ * Raised when an async job could not be submitted because the account is out of credits
160
+ * (HTTP 402, `limit_exceeded`), e.g. less than 60 seconds of transcription credit left.
161
+ * No task is created. Extends `PaymentRequiredError`.
162
+ */
163
+ export class InsufficientCreditsError extends PaymentRequiredError {
164
+ constructor(message: string, status_code?: number, error_code?: string, error_message?: string, details?: any) {
165
+ super(message, status_code, error_code, error_message, details);
166
+ this.name = 'InsufficientCreditsError';
167
+ Object.setPrototypeOf(this, InsufficientCreditsError.prototype);
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Raised when an async job could not be submitted because too many jobs are already running
173
+ * for this account (HTTP 429, `too_many_active_jobs`). No task is created; retry once some
174
+ * of your running jobs finish. Extends `RateLimitExceededError`.
175
+ */
176
+ export class TooManyActiveJobsError extends RateLimitExceededError {
177
+ constructor(message: string, status_code?: number, error_code?: string, error_message?: string, details?: any) {
178
+ super(message, status_code, error_code, error_message, details);
179
+ this.name = 'TooManyActiveJobsError';
180
+ Object.setPrototypeOf(this, TooManyActiveJobsError.prototype);
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Raised when waiting for a job exceeds `timeoutMs`. Always carries `task_id`: the job keeps
186
+ * running server-side and its result stays readable for 1 hour after it finishes, so resume it
187
+ * with `vn.<operation>.resume(err.task_id)`.
188
+ */
189
+ export class TaskTimeoutError extends VidNavigatorError {
190
+ constructor(message: string, task_id: string) {
191
+ super(message);
192
+ this.name = 'TaskTimeoutError';
193
+ this.task_id = task_id;
194
+ Object.setPrototypeOf(this, TaskTimeoutError.prototype);
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Raised by `constructWebhookEvent()` when a webhook delivery's signature is missing,
200
+ * malformed, does not match, or is older than the allowed tolerance.
201
+ */
202
+ export class WebhookSignatureError extends VidNavigatorError {
203
+ constructor(message: string) {
204
+ super(message);
205
+ this.name = 'WebhookSignatureError';
206
+ Object.setPrototypeOf(this, WebhookSignatureError.prototype);
207
+ }
208
+ }
package/src/http.ts ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Internal: maps API error responses to SDK error classes. Not re-exported from the package.
3
+ */
4
+ import {
5
+ VidNavigatorError,
6
+ AuthenticationError,
7
+ BadRequestError,
8
+ AccessDeniedError,
9
+ NotFoundError,
10
+ RateLimitExceededError,
11
+ PaymentRequiredError,
12
+ ServerError,
13
+ StorageQuotaExceededError,
14
+ GeoRestrictedError,
15
+ SystemOverloadError,
16
+ InsufficientCreditsError,
17
+ TooManyActiveJobsError,
18
+ } from './errors';
19
+
20
+ export function parseApiErrorPayload(data: any): {
21
+ errorCode?: string;
22
+ errorMessage?: string;
23
+ details?: any;
24
+ } {
25
+ const errorField = data?.error;
26
+ const errorCode =
27
+ (typeof errorField === 'string' ? errorField : errorField?.code) ?? data?.error_code;
28
+ const errorMessage =
29
+ data?.message ??
30
+ (typeof errorField === 'object' ? errorField?.message : undefined);
31
+ return { errorCode, errorMessage, details: data };
32
+ }
33
+
34
+ /** Map an HTTP error status + body to the matching SDK error class. */
35
+ export function buildApiError(status: number, data: any, fallbackMessage?: string): VidNavigatorError {
36
+ const { errorCode, errorMessage, details } = parseApiErrorPayload(data);
37
+ const message = `API request failed with status ${status}: ${errorMessage || fallbackMessage}`;
38
+
39
+ switch (status) {
40
+ case 400:
41
+ return new BadRequestError(message, status, errorCode, errorMessage, details);
42
+ case 401:
43
+ return new AuthenticationError(message, status, errorCode, errorMessage, details);
44
+ case 402:
45
+ if (errorCode === 'limit_exceeded') {
46
+ return new InsufficientCreditsError(message, status, errorCode, errorMessage, details);
47
+ }
48
+ return new PaymentRequiredError(message, status, errorCode, errorMessage, details);
49
+ case 403:
50
+ return new AccessDeniedError(message, status, errorCode, errorMessage, details);
51
+ case 404:
52
+ return new NotFoundError(message, status, errorCode, errorMessage, details);
53
+ case 413:
54
+ return new StorageQuotaExceededError(message, status, errorCode, errorMessage, details);
55
+ case 429:
56
+ if (errorCode === 'too_many_active_jobs') {
57
+ return new TooManyActiveJobsError(message, status, errorCode, errorMessage, details);
58
+ }
59
+ return new RateLimitExceededError(message, status, errorCode, errorMessage, details);
60
+ case 451:
61
+ return new GeoRestrictedError(message, status, errorCode, errorMessage, details);
62
+ case 503:
63
+ return new SystemOverloadError(
64
+ message,
65
+ status,
66
+ errorCode,
67
+ errorMessage,
68
+ details,
69
+ data?.retry_after_seconds
70
+ );
71
+ default:
72
+ if (status >= 500) {
73
+ return new ServerError(message, status, errorCode, errorMessage, details);
74
+ }
75
+ return new VidNavigatorError(message, status, errorCode, errorMessage, details);
76
+ }
77
+ }