vidnavigator 1.0.4 → 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.
@@ -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.4",
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
+ }