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.
package/dist/jobs.js ADDED
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Job = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_POLL_INTERVAL_MS = void 0;
4
+ exports.isTerminal = isTerminal;
5
+ exports.pollUntilDone = pollUntilDone;
6
+ exports.errorFromFailedTask = errorFromFailedTask;
7
+ const errors_1 = require("./errors");
8
+ const http_1 = require("./http");
9
+ exports.DEFAULT_POLL_INTERVAL_MS = 3000;
10
+ exports.DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
11
+ const FAST_START_WINDOW_MS = 10000;
12
+ const FAST_START_INTERVAL_MS = 1000;
13
+ function isTerminal(status) {
14
+ return status === 'completed' || status === 'failed';
15
+ }
16
+ function abortError(task_id) {
17
+ const err = new errors_1.VidNavigatorError(`Stopped waiting for task ${task_id} (aborted); the job keeps running server-side`);
18
+ err.task_id = task_id;
19
+ return err;
20
+ }
21
+ function sleep(ms, task_id, signal) {
22
+ return new Promise((resolve, reject) => {
23
+ if (signal?.aborted)
24
+ return reject(abortError(task_id));
25
+ const onAbort = () => {
26
+ clearTimeout(timer);
27
+ reject(abortError(task_id));
28
+ };
29
+ const timer = setTimeout(() => {
30
+ signal?.removeEventListener('abort', onAbort);
31
+ resolve();
32
+ }, ms);
33
+ signal?.addEventListener('abort', onAbort, { once: true });
34
+ });
35
+ }
36
+ /** Poll `fetchTask` until `task_status` is `completed` or `failed`, and return that final snapshot. */
37
+ async function pollUntilDone(task_id, fetchTask, options = {}) {
38
+ const intervalMs = options.intervalMs ?? exports.DEFAULT_POLL_INTERVAL_MS;
39
+ const fastStart = options.fastStart ?? true;
40
+ const timeoutMs = options.timeoutMs ?? exports.DEFAULT_TIMEOUT_MS;
41
+ const started = Date.now();
42
+ let task = await withTaskId(task_id, fetchTask);
43
+ options.onPoll?.(task);
44
+ while (!isTerminal(task.task_status)) {
45
+ const elapsed = Date.now() - started;
46
+ const delay = fastStart && elapsed < FAST_START_WINDOW_MS ? Math.min(FAST_START_INTERVAL_MS, intervalMs) : intervalMs;
47
+ if (timeoutMs > 0 && elapsed + delay > timeoutMs) {
48
+ throw new errors_1.TaskTimeoutError(`Task ${task_id} still ${task.task_status} after ${Math.round(elapsed / 1000)}s. ` +
49
+ `It keeps running server-side; resume it with this task_id (results are kept 1 hour after it finishes).`, task_id);
50
+ }
51
+ await sleep(delay, task_id, options.signal);
52
+ task = await withTaskId(task_id, fetchTask);
53
+ options.onPoll?.(task);
54
+ }
55
+ return task;
56
+ }
57
+ /** Run `fn`, tagging any SDK error it throws with `task_id` so the job can always be resumed. */
58
+ async function withTaskId(task_id, fn) {
59
+ try {
60
+ return await fn();
61
+ }
62
+ catch (error) {
63
+ if (error instanceof errors_1.VidNavigatorError && !error.task_id)
64
+ error.task_id = task_id;
65
+ throw error;
66
+ }
67
+ }
68
+ /**
69
+ * Build the error for a `failed` task from its `error` object (`error`, `message`, `http_status`),
70
+ * using the same class the API would have used for that status. Carries `task_id`.
71
+ */
72
+ function errorFromFailedTask(task) {
73
+ const info = task.error;
74
+ let err;
75
+ if (info?.http_status) {
76
+ err = (0, http_1.buildApiError)(info.http_status, {
77
+ error: info.error,
78
+ message: info.message ?? `Task ${task.task_id} failed`,
79
+ task_id: task.task_id,
80
+ });
81
+ }
82
+ else {
83
+ const message = info?.message ?? 'no error details returned';
84
+ err = new errors_1.VidNavigatorError(`Task ${task.task_id} failed: ${message}`, undefined, info?.error, info?.message, task);
85
+ }
86
+ err.task_id = task.task_id;
87
+ return err;
88
+ }
89
+ /**
90
+ * Handle to a submitted async job. Use it to run many jobs at once: submit them all, then
91
+ * `await job.result()` on each (or check `await job.status()` yourself).
92
+ *
93
+ * Polling always works, whether or not a webhook is configured.
94
+ */
95
+ class Job {
96
+ constructor(info, fetchTask, toResult) {
97
+ this.task_id = info.task_id;
98
+ this.job_type = info.job_type;
99
+ this.check_status_url = info.check_status_url;
100
+ this.webhook_url = info.webhook_url;
101
+ this.expires_at = info.expires_at;
102
+ this.fetchTask = async () => {
103
+ const task = await fetchTask();
104
+ this.task = task;
105
+ return task;
106
+ };
107
+ this.toResult = toResult;
108
+ }
109
+ /** Poll once and return the full task snapshot. */
110
+ async refresh() {
111
+ return withTaskId(this.task_id, this.fetchTask);
112
+ }
113
+ /** Poll once and return the current `task_status`. */
114
+ async status() {
115
+ return (await this.refresh()).task_status;
116
+ }
117
+ /** Poll until the task is `completed` or `failed` and return the final snapshot. Does not throw on `failed`. */
118
+ async wait(options) {
119
+ return pollUntilDone(this.task_id, this.fetchTask, options);
120
+ }
121
+ /**
122
+ * Wait for the job and return its result. Throws the error from the task's `error` object when it
123
+ * failed, or {@link TaskTimeoutError} on timeout. Every error carries `task_id`.
124
+ */
125
+ async result(options) {
126
+ const task = await this.wait(options);
127
+ if (task.task_status === 'failed')
128
+ throw errorFromFailedTask(task);
129
+ return withTaskId(this.task_id, () => this.toResult(task));
130
+ }
131
+ }
132
+ exports.Job = Job;
@@ -0,0 +1,92 @@
1
+ import { UsageBlock } from './Usage';
2
+ /** Async job kinds returned by the `/transcribe/async`, `/extract/video/async` and `/tweet/statement/async` endpoints. */
3
+ export type AsyncJobType = 'transcribe' | 'extract_video' | 'tweet_statement';
4
+ /** `processing` = accepted and being worked on. `completed` and `failed` are terminal. */
5
+ export type AsyncTaskStatus = 'processing' | 'completed' | 'failed';
6
+ /**
7
+ * Present when `task_status === 'failed'`. Carries the same `error` code and HTTP status
8
+ * the synchronous endpoint would have returned (e.g. `video_too_long` / 400).
9
+ */
10
+ export interface AsyncJobError {
11
+ error?: string;
12
+ message?: string;
13
+ http_status?: number;
14
+ }
15
+ /**
16
+ * Delivery state of a job's webhook. `null` when no webhook was configured.
17
+ * The webhook URL itself is never echoed back.
18
+ */
19
+ export interface AsyncJobWebhookStatus {
20
+ status?: 'pending' | 'delivered' | 'failed';
21
+ /** Delivery attempts made (max 5). */
22
+ attempts?: number;
23
+ /** HTTP status your endpoint returned on the last attempt. */
24
+ response_status?: number | null;
25
+ last_error?: string | null;
26
+ delivered_at?: string | null;
27
+ }
28
+ export interface AsyncJobAcceptedJSON {
29
+ task_id: string;
30
+ task_status: 'processing';
31
+ job_type?: AsyncJobType;
32
+ expires_at?: string;
33
+ check_status_url?: string;
34
+ webhook_url?: string | null;
35
+ message?: string;
36
+ docs_url?: string;
37
+ }
38
+ /** 202 response from an async submit endpoint. Poll with the matching `get...AsyncJob(task_id)` method. */
39
+ export declare class AsyncJobAccepted {
40
+ task_id: string;
41
+ task_status: 'processing';
42
+ job_type?: AsyncJobType;
43
+ /** Provisional submit-time bound; pushed out to finish time + 1 hour once the job completes. */
44
+ expires_at?: string;
45
+ /** Relative URL to poll for status and the result. */
46
+ check_status_url?: string;
47
+ /** The URL this job's result will be POSTed to, or `null` if no webhook applies. */
48
+ webhook_url?: string | null;
49
+ message?: string;
50
+ docs_url?: string;
51
+ constructor(data: AsyncJobAcceptedJSON);
52
+ static fromJSON(json: AsyncJobAcceptedJSON): AsyncJobAccepted;
53
+ }
54
+ export interface AsyncJobJSON {
55
+ task_id: string;
56
+ task_status: AsyncTaskStatus;
57
+ job_type?: string;
58
+ request?: Record<string, unknown>;
59
+ created_at?: string;
60
+ started_at?: string | null;
61
+ completed_at?: string | null;
62
+ expires_at?: string;
63
+ check_status_url?: string;
64
+ webhook?: AsyncJobWebhookStatus | null;
65
+ result?: any;
66
+ error?: AsyncJobError | null;
67
+ }
68
+ /**
69
+ * State of an async job, returned by the `get...AsyncJob(task_id)` pollers.
70
+ * `result` is populated only when `task_status === 'completed'` and is parsed into the same
71
+ * shape the synchronous endpoint returns; `error` is populated only when `task_status === 'failed'`.
72
+ */
73
+ export declare class AsyncJob<TResult> {
74
+ task_id: string;
75
+ task_status: AsyncTaskStatus;
76
+ job_type?: string;
77
+ /** Echo of the submitted parameters (`webhook_url` is never echoed). */
78
+ request?: Record<string, unknown>;
79
+ created_at?: string;
80
+ started_at?: string | null;
81
+ completed_at?: string | null;
82
+ /** Results are deleted after this time (1 hour after the job finishes). */
83
+ expires_at?: string;
84
+ check_status_url?: string;
85
+ webhook?: AsyncJobWebhookStatus | null;
86
+ result: TResult | null;
87
+ error: AsyncJobError | null;
88
+ /** Per-call usage, populated only when polled with `include_usage: true` and `task_status === 'completed'`. */
89
+ usage?: UsageBlock;
90
+ constructor(data: AsyncJobJSON, parseResult: (raw: any) => TResult);
91
+ static fromJSON<T>(json: AsyncJobJSON, parseResult: (raw: any) => T): AsyncJob<T>;
92
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AsyncJob = exports.AsyncJobAccepted = void 0;
4
+ /** 202 response from an async submit endpoint. Poll with the matching `get...AsyncJob(task_id)` method. */
5
+ class AsyncJobAccepted {
6
+ constructor(data) {
7
+ this.task_id = data.task_id;
8
+ this.task_status = data.task_status;
9
+ this.job_type = data.job_type;
10
+ this.expires_at = data.expires_at;
11
+ this.check_status_url = data.check_status_url;
12
+ this.webhook_url = data.webhook_url;
13
+ this.message = data.message;
14
+ this.docs_url = data.docs_url;
15
+ }
16
+ static fromJSON(json) {
17
+ return new AsyncJobAccepted(json);
18
+ }
19
+ }
20
+ exports.AsyncJobAccepted = AsyncJobAccepted;
21
+ /**
22
+ * State of an async job, returned by the `get...AsyncJob(task_id)` pollers.
23
+ * `result` is populated only when `task_status === 'completed'` and is parsed into the same
24
+ * shape the synchronous endpoint returns; `error` is populated only when `task_status === 'failed'`.
25
+ */
26
+ class AsyncJob {
27
+ constructor(data, parseResult) {
28
+ this.task_id = data.task_id;
29
+ this.task_status = data.task_status;
30
+ this.job_type = data.job_type;
31
+ this.request = data.request;
32
+ this.created_at = data.created_at;
33
+ this.started_at = data.started_at;
34
+ this.completed_at = data.completed_at;
35
+ this.expires_at = data.expires_at;
36
+ this.check_status_url = data.check_status_url;
37
+ this.webhook = data.webhook;
38
+ this.result = data.result !== undefined && data.result !== null ? parseResult(data.result) : null;
39
+ this.error = data.error ?? null;
40
+ }
41
+ static fromJSON(json, parseResult) {
42
+ return new AsyncJob(json, parseResult);
43
+ }
44
+ }
45
+ exports.AsyncJob = AsyncJob;
@@ -1,3 +1,9 @@
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';
1
7
  export interface TikTokProfileScrapeRequest {
2
8
  profile_url: string;
3
9
  max_posts?: number;
@@ -7,11 +13,22 @@ export interface TikTokProfileScrapeRequest {
7
13
  before_datetime?: string;
8
14
  min_likes?: number;
9
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;
10
23
  }
11
24
  export interface TikTokSearchRequest {
12
25
  query: string;
13
26
  max_results?: number;
14
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;
15
32
  /** Format: YYYY-MM-DD or ISO datetime with timezone */
16
33
  after_datetime?: string;
17
34
  /** Format: YYYY-MM-DD or ISO datetime with timezone */
@@ -20,6 +37,13 @@ export interface TikTokSearchRequest {
20
37
  max_likes?: number;
21
38
  min_views?: number;
22
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;
23
47
  }
24
48
  export interface TikTokProfileScrapeSubmissionJSON {
25
49
  task_id: string;
@@ -28,6 +52,7 @@ export interface TikTokProfileScrapeSubmissionJSON {
28
52
  expires_at?: string;
29
53
  check_status_url?: string;
30
54
  message?: string;
55
+ webhook_url?: string | null;
31
56
  }
32
57
  export declare class TikTokProfileScrapeSubmission {
33
58
  task_id: string;
@@ -36,6 +61,8 @@ export declare class TikTokProfileScrapeSubmission {
36
61
  expires_at?: string;
37
62
  check_status_url?: string;
38
63
  message?: string;
64
+ /** The URL this task's result notification will be POSTed to, or `null`. */
65
+ webhook_url?: string | null;
39
66
  constructor(data: TikTokProfileScrapeSubmissionJSON);
40
67
  static fromJSON(json: TikTokProfileScrapeSubmissionJSON): TikTokProfileScrapeSubmission;
41
68
  }
@@ -49,6 +76,7 @@ export interface TikTokSearchSubmissionJSON {
49
76
  expires_at?: string;
50
77
  check_status_url?: string;
51
78
  message?: string;
79
+ webhook_url?: string | null;
52
80
  }
53
81
  export declare class TikTokSearchSubmission {
54
82
  task_id: string;
@@ -60,6 +88,8 @@ export declare class TikTokSearchSubmission {
60
88
  expires_at?: string;
61
89
  check_status_url?: string;
62
90
  message?: string;
91
+ /** The URL this task's result notification will be POSTed to, or `null`. */
92
+ webhook_url?: string | null;
63
93
  constructor(data: TikTokSearchSubmissionJSON);
64
94
  static fromJSON(json: TikTokSearchSubmissionJSON): TikTokSearchSubmission;
65
95
  }
@@ -166,6 +196,8 @@ export declare class TikTokSearchResult {
166
196
  static fromJSON(json: TikTokSearchResultJSON): TikTokSearchResult;
167
197
  }
168
198
  export interface TikTokSearchFilters {
199
+ sort_by?: TikTokSearchSortBy | null;
200
+ published_within?: TikTokPublishedWithin | null;
169
201
  after_datetime?: string | null;
170
202
  before_datetime?: string | null;
171
203
  min_likes?: number | null;
@@ -177,6 +209,10 @@ export interface TikTokSearchStats {
177
209
  pages_fetched?: number;
178
210
  results_count?: number;
179
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;
180
216
  }
181
217
  export interface TikTokProfileTaskJSON {
182
218
  task_id: string;
@@ -192,6 +228,8 @@ export interface TikTokProfileTaskJSON {
192
228
  created_at?: string | null;
193
229
  completed_at?: string | null;
194
230
  expires_at?: string | null;
231
+ error?: AsyncJobError | null;
232
+ webhook?: AsyncJobWebhookStatus | null;
195
233
  }
196
234
  export declare class TikTokProfileTask {
197
235
  task_id: string;
@@ -203,10 +241,17 @@ export declare class TikTokProfileTask {
203
241
  videos: TikTokVideo[];
204
242
  pagination?: TikTokProfilePagination;
205
243
  download_url?: string | null;
244
+ /** @deprecated Use `error`, which carries a machine-readable code. */
206
245
  error_message?: string | null;
207
246
  created_at?: string | null;
208
247
  completed_at?: string | null;
209
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;
253
+ /** Per-call usage, populated only when polled with `include_usage=true` and `task_status=completed`. */
254
+ usage?: UsageBlock;
210
255
  constructor(data: TikTokProfileTaskJSON);
211
256
  static fromJSON(json: TikTokProfileTaskJSON): TikTokProfileTask;
212
257
  }
@@ -224,6 +269,8 @@ export interface TikTokSearchTaskJSON {
224
269
  created_at?: string | null;
225
270
  completed_at?: string | null;
226
271
  expires_at?: string | null;
272
+ error?: AsyncJobError | null;
273
+ webhook?: AsyncJobWebhookStatus | null;
227
274
  }
228
275
  export declare class TikTokSearchTask {
229
276
  task_id: string;
@@ -235,10 +282,17 @@ export declare class TikTokSearchTask {
235
282
  results: TikTokSearchResult[];
236
283
  pagination?: TikTokProfilePagination;
237
284
  download_url?: string | null;
285
+ /** @deprecated Use `error`, which carries a machine-readable code. */
238
286
  error_message?: string | null;
239
287
  created_at?: string | null;
240
288
  completed_at?: string | null;
241
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;
294
+ /** Per-call usage, populated only when polled with `include_usage=true` and `task_status=completed`. */
295
+ usage?: UsageBlock;
242
296
  constructor(data: TikTokSearchTaskJSON);
243
297
  static fromJSON(json: TikTokSearchTaskJSON): TikTokSearchTask;
244
298
  }
@@ -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,75 @@
1
1
  export type UnlimitedOrNumber = number | 'unlimited';
2
+ /** Meters that can appear in a per-call {@link UsageBlock}. */
3
+ export type UsageServiceType = 'standard_request' | 'residential_request' | 'transcription_hour' | 'analysis_request' | 'search_request' | 'scene_analysis_hour';
4
+ export interface UsageTokens {
5
+ prompt_tokens?: number;
6
+ completion_tokens?: number;
7
+ total_tokens?: number;
8
+ }
9
+ export interface UsageChargeJSON {
10
+ service_type: UsageServiceType;
11
+ quantity: number;
12
+ credits: number;
13
+ waived?: boolean;
14
+ credits_saved?: number;
15
+ tokens?: UsageTokens;
16
+ }
17
+ /** A single consolidated meter charge within a per-call usage block. */
18
+ export declare class UsageCharge {
19
+ service_type: UsageServiceType;
20
+ quantity: number;
21
+ credits: number;
22
+ waived?: boolean;
23
+ credits_saved?: number;
24
+ tokens?: UsageTokens;
25
+ constructor(data: UsageChargeJSON);
26
+ static fromJSON(json: UsageChargeJSON): UsageCharge;
27
+ }
28
+ export interface UsageBlockJSON {
29
+ charges?: UsageChargeJSON[];
30
+ total_credits?: number;
31
+ credits_remaining_after?: number;
32
+ waived?: {
33
+ credits_saved: number;
34
+ };
35
+ /** Legacy flat token fields. Some /extract/* responses may still echo these. */
36
+ prompt_tokens?: number;
37
+ completion_tokens?: number;
38
+ total_tokens?: number;
39
+ }
40
+ /**
41
+ * Per-call usage disclosure returned when a request is made with `include_usage=true`.
42
+ * Lists every meter charged during the request plus the credits actually deducted.
43
+ *
44
+ * LLM token counts live nested inside the `analysis_request` charge; use the
45
+ * {@link UsageBlock.analysis_tokens} accessor to read them (it falls back to the
46
+ * legacy flat token fields when present).
47
+ */
48
+ export declare class UsageBlock {
49
+ charges: UsageCharge[];
50
+ total_credits?: number;
51
+ credits_remaining_after?: number;
52
+ waived?: {
53
+ credits_saved: number;
54
+ };
55
+ /** Legacy flat token fields, only present on some /extract/* responses. */
56
+ prompt_tokens?: number;
57
+ completion_tokens?: number;
58
+ total_tokens?: number;
59
+ constructor(data: UsageBlockJSON);
60
+ /** Return the consolidated charge entry for a given meter, if present. */
61
+ charge_for(service_type: UsageServiceType): UsageCharge | undefined;
62
+ /** camelCase alias for {@link UsageBlock.charge_for}. */
63
+ chargeFor(service_type: UsageServiceType): UsageCharge | undefined;
64
+ /**
65
+ * LLM token tally for this request. Reads the `tokens` object from the
66
+ * `analysis_request` charge, falling back to legacy flat token fields.
67
+ */
68
+ get analysis_tokens(): UsageTokens | undefined;
69
+ /** camelCase alias for {@link UsageBlock.analysis_tokens}. */
70
+ get analysisTokens(): UsageTokens | undefined;
71
+ static fromJSON(json: UsageBlockJSON): UsageBlock;
72
+ }
2
73
  export interface CreditsInfoJSON {
3
74
  monthly_total: UnlimitedOrNumber;
4
75
  monthly_remaining: UnlimitedOrNumber;
@@ -1,6 +1,75 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UsageData = exports.StorageUsage = exports.CapacityMetric = exports.ActivityCount = exports.CreditsInfo = void 0;
3
+ exports.UsageData = exports.StorageUsage = exports.CapacityMetric = exports.ActivityCount = exports.CreditsInfo = exports.UsageBlock = exports.UsageCharge = void 0;
4
+ /** A single consolidated meter charge within a per-call usage block. */
5
+ class UsageCharge {
6
+ constructor(data) {
7
+ this.service_type = data.service_type;
8
+ this.quantity = data.quantity;
9
+ this.credits = data.credits;
10
+ this.waived = data.waived;
11
+ this.credits_saved = data.credits_saved;
12
+ this.tokens = data.tokens;
13
+ }
14
+ static fromJSON(json) {
15
+ return new UsageCharge(json);
16
+ }
17
+ }
18
+ exports.UsageCharge = UsageCharge;
19
+ /**
20
+ * Per-call usage disclosure returned when a request is made with `include_usage=true`.
21
+ * Lists every meter charged during the request plus the credits actually deducted.
22
+ *
23
+ * LLM token counts live nested inside the `analysis_request` charge; use the
24
+ * {@link UsageBlock.analysis_tokens} accessor to read them (it falls back to the
25
+ * legacy flat token fields when present).
26
+ */
27
+ class UsageBlock {
28
+ constructor(data) {
29
+ this.charges = (data.charges ?? []).map(UsageCharge.fromJSON);
30
+ this.total_credits = data.total_credits;
31
+ this.credits_remaining_after = data.credits_remaining_after;
32
+ this.waived = data.waived;
33
+ this.prompt_tokens = data.prompt_tokens;
34
+ this.completion_tokens = data.completion_tokens;
35
+ this.total_tokens = data.total_tokens;
36
+ }
37
+ /** Return the consolidated charge entry for a given meter, if present. */
38
+ charge_for(service_type) {
39
+ return this.charges.find((c) => c.service_type === service_type);
40
+ }
41
+ /** camelCase alias for {@link UsageBlock.charge_for}. */
42
+ chargeFor(service_type) {
43
+ return this.charge_for(service_type);
44
+ }
45
+ /**
46
+ * LLM token tally for this request. Reads the `tokens` object from the
47
+ * `analysis_request` charge, falling back to legacy flat token fields.
48
+ */
49
+ get analysis_tokens() {
50
+ const analysis = this.charge_for('analysis_request');
51
+ if (analysis?.tokens)
52
+ return analysis.tokens;
53
+ if (this.prompt_tokens !== undefined ||
54
+ this.completion_tokens !== undefined ||
55
+ this.total_tokens !== undefined) {
56
+ return {
57
+ prompt_tokens: this.prompt_tokens,
58
+ completion_tokens: this.completion_tokens,
59
+ total_tokens: this.total_tokens,
60
+ };
61
+ }
62
+ return undefined;
63
+ }
64
+ /** camelCase alias for {@link UsageBlock.analysis_tokens}. */
65
+ get analysisTokens() {
66
+ return this.analysis_tokens;
67
+ }
68
+ static fromJSON(json) {
69
+ return new UsageBlock(json);
70
+ }
71
+ }
72
+ exports.UsageBlock = UsageBlock;
4
73
  class CreditsInfo {
5
74
  constructor(data) {
6
75
  this.monthly_total = data.monthly_total;
@@ -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);