@octavideo/node 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,33 @@
1
+ OctaVideo SDK License Agreement
2
+
3
+ Copyright (c) 2026 OctaVideo. All rights reserved.
4
+
5
+ This agreement covers the OctaVideo SDK (the "SDK"): the @octavideo/node package
6
+ on npm and the OctaVideo.Sdk package on NuGet, with their documentation. By
7
+ installing or using the SDK, you agree to it.
8
+
9
+ 1. Grant of License
10
+
11
+ OctaVideo grants you a non-exclusive, non-transferable, revocable license to
12
+ install, use, and integrate the SDK into your software applications solely
13
+ for interacting with OctaVideo services. You may redistribute the unmodified
14
+ SDK, as published by OctaVideo, as part of your application.
15
+
16
+ 2. Restrictions
17
+
18
+ You may not modify, adapt, translate, reverse engineer, decompile,
19
+ disassemble, or create derivative works based on the SDK. You may not sell,
20
+ sublicense, or distribute the SDK as a standalone product.
21
+
22
+ 3. Ownership
23
+
24
+ OctaVideo retains all title, ownership, and intellectual property rights in
25
+ and to the SDK. Nothing in this agreement transfers ownership of the SDK to
26
+ you.
27
+
28
+ 4. Disclaimer
29
+
30
+ THE SDK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
31
+ IMPLIED. IN NO EVENT SHALL OCTAVIDEO BE LIABLE FOR ANY CLAIM, DAMAGES OR
32
+ OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE SDK OR ITS
33
+ USE.
package/README.md ADDED
@@ -0,0 +1,110 @@
1
+ # @octavideo/node
2
+
3
+ Create playback OTPs for the videos in your OctaVideo library from your Node.js server, and get the embed URL that plays them.
4
+
5
+ ```sh
6
+ npm install @octavideo/node
7
+ ```
8
+
9
+ Node.js 22.12 or later, with no dependencies. The package is ESM, and CommonJS code can still require it on Node 22.12+. In TypeScript, set "module" to "nodenext" (or "moduleResolution" to "bundler") so the compiler reads the package's exports.
10
+
11
+ ## Quick start
12
+
13
+ ```ts
14
+ import { OctaVideo } from '@octavideo/node'
15
+
16
+ const octa = new OctaVideo({
17
+ libraryId: process.env.OCTAVIDEO_LIBRARY_ID!, // console → API & embeds
18
+ apiKey: process.env.OCTAVIDEO_API_KEY!, // ovk_…, from the same page
19
+ })
20
+
21
+ // Each time you serve the page, for the viewer who asked:
22
+ const otp = await octa.createOtp({ videoId, watermark: viewer.email })
23
+ const src = octa.embedUrl(otp)
24
+ ```
25
+
26
+ ```html
27
+ <iframe src="{src}" style="border:0;width:100%;aspect-ratio:16/9"
28
+ allow="encrypted-media; fullscreen" allowfullscreen></iframe>
29
+ ```
30
+
31
+ > **Before you ship**
32
+ >
33
+ > - **Check the viewer first.** Your app decides who may watch what. Create the OTP only after that check.
34
+ > - **A fresh OTP every time.** Create one each time you serve the page, and don't cache that page.
35
+ > - **The key stays on your server.** The package refuses to start in a browser page.
36
+
37
+ A complete Next.js page is in [Server SDKs](https://docs.octavideo.tech/developers/sdks#nextjs) on docs.octavideo.tech.
38
+
39
+ ## Creating an OTP
40
+
41
+ ```ts
42
+ const otp = await octa.createOtp(
43
+ {
44
+ videoId, // a READY video in this library
45
+ ttl: 600, // 30 to 3600 seconds (default 300); reusable until it expires
46
+ watermark: viewer.email, // text drawn over the video for this viewer, up to 255 characters
47
+ // ip binds playback to one viewer IP: not available yet (the API answers ip_binding_unavailable)
48
+ },
49
+ { signal }, // optional: an AbortSignal cancels the request
50
+ )
51
+
52
+ // otp.otp, otp.videoId, otp.expiresAt (a Date)
53
+
54
+ const src = octa.embedUrl(otp) // https://player.octavideo.tech/embed/{videoId}?otp={otp}
55
+ const same = octa.embedUrl(videoId, otp.otp) // the same URL, from the two strings
56
+ ```
57
+
58
+ The API checks the values, not the package. A ttl of 10, or an ip that isn't an IP address, comes back as a validation error that names the field.
59
+
60
+ ## Errors
61
+
62
+ Every error is an OctaVideoError. An answer from the API is an APIError, with:
63
+
64
+ - **status**: the HTTP status;
65
+ - **code**: the API's own code (check it rather than the message);
66
+ - **fields**: the refused fields, for validation_failed;
67
+ - **body**: the answer as sent.
68
+
69
+ ```ts
70
+ import { ConflictError } from '@octavideo/node'
71
+
72
+ try {
73
+ const otp = await octa.createOtp({ videoId })
74
+ } catch (error) {
75
+ if (error instanceof ConflictError && error.code === 'video_not_ready') {
76
+ // show "still being prepared"
77
+ } else throw error
78
+ }
79
+ ```
80
+
81
+ | Error | Status | Codes you'll see |
82
+ | --- | --- | --- |
83
+ | BadRequestError | 400 | validation_failed, bad_body, ip_binding_unavailable |
84
+ | AuthenticationError | 401 | invalid_api_key (a wrong key, or no such library), missing_token |
85
+ | NotFoundError | 404 | video_not_found |
86
+ | ConflictError | 409 | video_not_ready: still uploading or encoding |
87
+ | RateLimitError | 429 | after the retries |
88
+ | InternalServerError | 5xx | after the retries for 502, 503 and 504 |
89
+ | ConnectionError, TimeoutError | none | no answer, after the retries |
90
+
91
+ An answer that isn't the API's JSON (a proxy's error page, say) has the code unexpected_response.
92
+
93
+ ## Options
94
+
95
+ | Option | Default | |
96
+ | --- | --- | --- |
97
+ | libraryId | required | |
98
+ | apiKey | required | Kept in a private field: never shown by console.log, util.inspect or JSON.stringify, nor in the package's errors. |
99
+ | apiUrl | <https://api.octavideo.tech> | Plain http only for localhost, 127.0.0.1 or [::1] (a local stack); elsewhere the key would travel unencrypted. |
100
+ | playerUrl | <https://player.octavideo.tech> | Where embedUrl points. |
101
+ | timeout | 10000 | Per attempt, the answer included, in milliseconds. |
102
+ | maxRetries | 2 | Retries after a network failure, a timeout, or a 429, 502, 503 or 504. Waits 0.5 s, then 1 s, and so on, or the answer's Retry-After (at most 30 s). Other errors aren't retried. |
103
+ | fetch | the global fetch | For tests, proxies or instrumentation. |
104
+ | dangerouslyAllowBrowser | false | Lets it run in a browser. Don't: anyone could read the key there. |
105
+
106
+ A retried request can leave an extra unused OTP behind. It expires on its own.
107
+
108
+ ## License
109
+
110
+ Copyright © 2026 OctaVideo. All rights reserved. Use of this package is governed by the OctaVideo SDK License Agreement in its LICENSE file.
@@ -0,0 +1,70 @@
1
+ export declare const DEFAULT_API_URL = "https://api.octavideo.tech";
2
+ export declare const DEFAULT_PLAYER_URL = "https://player.octavideo.tech";
3
+ export interface OctaVideoOptions {
4
+ /** The library's ID, from the console's **API & embeds** page. */
5
+ libraryId: string;
6
+ /** The library's API key (`ovk_…`). It stays on your server: never send it to a browser. */
7
+ apiKey: string;
8
+ /** Default `https://api.octavideo.tech`. Plain `http` only for localhost (a local stack). */
9
+ apiUrl?: string;
10
+ /** Where `embedUrl` points. Default `https://player.octavideo.tech`. */
11
+ playerUrl?: string;
12
+ /** How long to wait for each attempt, answer included, in milliseconds (rounded up to a whole one). Default 10 000. */
13
+ timeout?: number;
14
+ /** How many times to retry after a network failure, a timeout, or a 429, 502, 503 or 504. Default 2. */
15
+ maxRetries?: number;
16
+ /** A `fetch` to use instead of the global one (for tests, proxies or instrumentation). */
17
+ fetch?: typeof globalThis.fetch;
18
+ /**
19
+ * Lets the client run in a browser page. Don't: anyone who opens the page can read the key, and with it make
20
+ * OTPs for every video in the library. Make OTPs on your server instead.
21
+ */
22
+ dangerouslyAllowBrowser?: boolean;
23
+ }
24
+ export interface CreateOtpParams {
25
+ /** The video to play. It must be in this library, and READY. */
26
+ videoId: string;
27
+ /**
28
+ * How long the OTP is valid, in seconds: 30 to 3600 (the API refuses others). Omitted or 0: the API's default,
29
+ * 300. The OTP can be reused until it expires.
30
+ */
31
+ ttl?: number;
32
+ /** Binds playback to one viewer IP. **Not available yet:** the API answers 400 `ip_binding_unavailable`. */
33
+ ip?: string;
34
+ /** Text drawn over the video for this viewer (the user-based watermark), up to 255 characters. */
35
+ watermark?: string;
36
+ }
37
+ export interface RequestOptions {
38
+ /** Cancels the request (and any retry still waiting). */
39
+ signal?: AbortSignal;
40
+ }
41
+ /** A playback OTP: put it in the embed URL for one viewer. */
42
+ export interface PlaybackOtp {
43
+ otp: string;
44
+ videoId: string;
45
+ expiresAt: Date;
46
+ }
47
+ export declare class OctaVideo {
48
+ #private;
49
+ readonly libraryId: string;
50
+ readonly apiUrl: string;
51
+ readonly playerUrl: string;
52
+ readonly timeout: number;
53
+ readonly maxRetries: number;
54
+ constructor(options: OctaVideoOptions);
55
+ /**
56
+ * Creates a playback OTP for one viewer: `POST /v1/libraries/{libraryId}/otp`.
57
+ * Make a new one each time you serve the page, and don't cache the page with it.
58
+ */
59
+ createOtp(params: CreateOtpParams, options?: RequestOptions): Promise<PlaybackOtp>;
60
+ /** The player's address for a viewer: the `src` of the embed iframe. */
61
+ embedUrl(otp: PlaybackOtp): string;
62
+ embedUrl(videoId: string, otp: string): string;
63
+ }
64
+ /**
65
+ * Retry-After in milliseconds: whole seconds, capped at 30 s. Undefined if absent or anything else (an HTTP date
66
+ * included), which falls back to the backoff. Seconds only, because .NET normalizes a date header before the SDK can
67
+ * read it, so the two SDKs couldn't read dates alike; they read seconds alike, as fixtures/retry-after.json checks.
68
+ * Exported for the tests only (index.ts doesn't).
69
+ */
70
+ export declare function retryAfter(headers: Headers): number | undefined;
package/dist/client.js ADDED
@@ -0,0 +1,230 @@
1
+ import { APIError, ConnectionError, OctaVideoError, TimeoutError, errorFrom } from './errors.js';
2
+ import { VERSION } from './version.js';
3
+ export const DEFAULT_API_URL = 'https://api.octavideo.tech';
4
+ export const DEFAULT_PLAYER_URL = 'https://player.octavideo.tech';
5
+ const DEFAULT_TIMEOUT_MS = 10_000;
6
+ const MAX_TIMEOUT_MS = 2_147_483_647; // setTimeout's limit: a longer one fires at once
7
+ const DEFAULT_MAX_RETRIES = 2;
8
+ const RETRY_STATUSES = new Set([429, 502, 503, 504]);
9
+ const MAX_RETRY_WAIT_MS = 30_000;
10
+ const HEADER_SAFE = /^[\x21-\x7e]+$/; // printable ASCII, no spaces: what a Bearer token can hold
11
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
12
+ export class OctaVideo {
13
+ libraryId;
14
+ apiUrl;
15
+ playerUrl;
16
+ timeout;
17
+ maxRetries;
18
+ // A private field: console.log, JSON.stringify and util.inspect never show it.
19
+ #apiKey;
20
+ #fetch;
21
+ constructor(options) {
22
+ if (typeof options !== 'object' || options === null) {
23
+ throw new OctaVideoError('new OctaVideo() needs { libraryId, apiKey }.');
24
+ }
25
+ if (typeof options.libraryId !== 'string' || options.libraryId.trim() === '') {
26
+ throw new OctaVideoError('libraryId is required.');
27
+ }
28
+ if (typeof options.apiKey !== 'string' || options.apiKey.trim() === '') {
29
+ throw new OctaVideoError('apiKey is required.');
30
+ }
31
+ const apiKey = options.apiKey.trim();
32
+ if (!HEADER_SAFE.test(apiKey)) {
33
+ // Never echo the key: this message ends up in logs.
34
+ throw new OctaVideoError('apiKey has a character a key never has (a line break, a space or a non-ASCII character). ' +
35
+ 'Check how it was loaded, e.g. quotes in your .env file.');
36
+ }
37
+ if (isBrowser() && options.dangerouslyAllowBrowser !== true) {
38
+ throw new OctaVideoError('@octavideo/node runs on your server: in a browser, anyone could read the API key. ' +
39
+ 'Create OTPs on your server and send the page only the embed URL.');
40
+ }
41
+ const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
42
+ if (!Number.isFinite(timeout) || timeout <= 0 || timeout > MAX_TIMEOUT_MS) {
43
+ throw new OctaVideoError(`timeout must be a number of milliseconds, above 0 and at most ${MAX_TIMEOUT_MS}.`);
44
+ }
45
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
46
+ if (!Number.isInteger(maxRetries) || maxRetries < 0) {
47
+ throw new OctaVideoError('maxRetries must be a whole number, 0 or more.');
48
+ }
49
+ const fetchImpl = options.fetch ?? globalThis.fetch;
50
+ if (typeof fetchImpl !== 'function')
51
+ throw new OctaVideoError('No fetch: use Node 22.12 or later, or pass one.');
52
+ this.libraryId = options.libraryId.trim();
53
+ this.#apiKey = apiKey;
54
+ this.apiUrl = baseUrl(options.apiUrl ?? DEFAULT_API_URL, 'apiUrl', true);
55
+ this.playerUrl = baseUrl(options.playerUrl ?? DEFAULT_PLAYER_URL, 'playerUrl', false);
56
+ this.timeout = Math.ceil(timeout); // AbortSignal.timeout takes whole milliseconds only
57
+ this.maxRetries = maxRetries;
58
+ this.#fetch = fetchImpl;
59
+ }
60
+ /**
61
+ * Creates a playback OTP for one viewer: `POST /v1/libraries/{libraryId}/otp`.
62
+ * Make a new one each time you serve the page, and don't cache the page with it.
63
+ */
64
+ async createOtp(params, options = {}) {
65
+ const body = { video_id: params?.videoId };
66
+ if (params?.ttl !== undefined) {
67
+ // JSON has no NaN or Infinity (they'd go as null, and the API would use its default): refuse them here.
68
+ if (typeof params.ttl !== 'number' || !Number.isFinite(params.ttl)) {
69
+ throw new OctaVideoError('ttl must be a number of seconds.');
70
+ }
71
+ body['ttl'] = params.ttl;
72
+ }
73
+ if (params?.ip !== undefined)
74
+ body['ip'] = params.ip;
75
+ if (params?.watermark !== undefined)
76
+ body['watermark'] = params.watermark;
77
+ const [status, data] = await this.#post(`/v1/libraries/${encodeURIComponent(this.libraryId)}/otp`, body, options.signal);
78
+ return toPlaybackOtp(status, data);
79
+ }
80
+ embedUrl(videoOrOtp, otp) {
81
+ const [videoId, code] = typeof videoOrOtp === 'string' ? [videoOrOtp, otp] : [videoOrOtp?.videoId, videoOrOtp?.otp];
82
+ if (typeof videoId !== 'string' || videoId === '' || typeof code !== 'string' || code === '') {
83
+ throw new OctaVideoError('embedUrl needs a video ID and an OTP.');
84
+ }
85
+ return `${this.playerUrl}/embed/${encodeURIComponent(videoId)}?otp=${encodeURIComponent(code)}`;
86
+ }
87
+ /** Sends one POST, with the retries. Returns the answer's status and its `data`. */
88
+ async #post(path, body, signal) {
89
+ const url = this.apiUrl + path;
90
+ const json = JSON.stringify(body);
91
+ // One attempt after another: each waits for the last (await in the loop on purpose).
92
+ for (let attempt = 0;; attempt++) {
93
+ signal?.throwIfAborted();
94
+ const timeoutSignal = AbortSignal.timeout(this.timeout);
95
+ let answer;
96
+ try {
97
+ answer = await this.#send(url, json, signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal);
98
+ }
99
+ catch (error) {
100
+ if (signal?.aborted)
101
+ throw signal.reason; // the caller cancelled: no retry
102
+ if (attempt >= this.maxRetries)
103
+ throw this.#unanswered(error, timeoutSignal.aborted);
104
+ await sleep(backoff(attempt), signal);
105
+ continue;
106
+ }
107
+ const { status, statusText, headers, text } = answer;
108
+ if (status >= 200 && status < 300)
109
+ return [status, readData(status, text)];
110
+ if (!RETRY_STATUSES.has(status) || attempt >= this.maxRetries)
111
+ throw errorFrom(status, statusText, text);
112
+ await sleep(retryAfter(headers) ?? backoff(attempt), signal);
113
+ }
114
+ }
115
+ /**
116
+ * The error for an attempt with no answer. `timedOut` is our own timer, whatever error the fetch in use threw for
117
+ * it (Node's fetch: TimeoutError; others: a plain AbortError).
118
+ */
119
+ #unanswered(cause, timedOut) {
120
+ return timedOut
121
+ ? new TimeoutError(`No answer from ${this.apiUrl} within ${this.timeout} ms.`, { cause })
122
+ : new ConnectionError(`Couldn't reach ${this.apiUrl}.`, { cause });
123
+ }
124
+ /**
125
+ * One attempt. The whole answer, body included, is read here: a body that stalls or breaks off fails the
126
+ * attempt like a lost connection does.
127
+ */
128
+ async #send(url, json, signal) {
129
+ const response = await this.#fetch(url, {
130
+ method: 'POST',
131
+ headers: {
132
+ Accept: 'application/json',
133
+ Authorization: `Bearer ${this.#apiKey}`,
134
+ 'Content-Type': 'application/json',
135
+ 'User-Agent': `octavideo-node/${VERSION}`,
136
+ },
137
+ body: json,
138
+ signal,
139
+ });
140
+ return { status: response.status, statusText: response.statusText, headers: response.headers, text: await response.text() };
141
+ }
142
+ }
143
+ function readData(status, text) {
144
+ try {
145
+ const parsed = JSON.parse(text);
146
+ if (typeof parsed === 'object' && parsed !== null && 'data' in parsed)
147
+ return parsed.data;
148
+ }
149
+ catch {
150
+ // falls through
151
+ }
152
+ throw new APIError(status, 'unexpected_response', 'The answer had no data.', [], text.slice(0, 1000));
153
+ }
154
+ function toPlaybackOtp(status, data) {
155
+ const value = (typeof data === 'object' && data !== null ? data : {});
156
+ const expiresAt = typeof value['expires_at'] === 'string' ? new Date(value['expires_at']) : undefined;
157
+ if (typeof value['otp'] !== 'string' ||
158
+ typeof value['video_id'] !== 'string' ||
159
+ expiresAt === undefined ||
160
+ Number.isNaN(expiresAt.getTime())) {
161
+ throw new APIError(status, 'unexpected_response', 'The answer had no otp, video_id or expires_at.', [], data);
162
+ }
163
+ return { otp: value['otp'], videoId: value['video_id'], expiresAt };
164
+ }
165
+ /** 0.5 s, 1 s, 2 s, … up to 8 s, with ±25 % jitter. */
166
+ function backoff(attempt) {
167
+ const base = Math.min(500 * 2 ** attempt, 8_000);
168
+ return base * (0.75 + Math.random() * 0.5);
169
+ }
170
+ /**
171
+ * Retry-After in milliseconds: whole seconds, capped at 30 s. Undefined if absent or anything else (an HTTP date
172
+ * included), which falls back to the backoff. Seconds only, because .NET normalizes a date header before the SDK can
173
+ * read it, so the two SDKs couldn't read dates alike; they read seconds alike, as fixtures/retry-after.json checks.
174
+ * Exported for the tests only (index.ts doesn't).
175
+ */
176
+ export function retryAfter(headers) {
177
+ const header = headers.get('retry-after')?.trim();
178
+ if (!header || !/^\d+$/.test(header))
179
+ return undefined;
180
+ return Math.min(Number(header) * 1000, MAX_RETRY_WAIT_MS);
181
+ }
182
+ function sleep(ms, signal) {
183
+ return new Promise((resolve, reject) => {
184
+ if (signal?.aborted)
185
+ return reject(signal.reason);
186
+ const timer = setTimeout(() => {
187
+ signal?.removeEventListener('abort', onAbort);
188
+ resolve();
189
+ }, ms);
190
+ const onAbort = () => {
191
+ clearTimeout(timer);
192
+ reject(signal?.reason);
193
+ };
194
+ signal?.addEventListener('abort', onAbort, { once: true });
195
+ });
196
+ }
197
+ /**
198
+ * An absolute http(s) address without a trailing slash, a query, a fragment or a user name. The API's address
199
+ * carries the key, so plain http is allowed only for localhost, 127.0.0.1 or [::1].
200
+ */
201
+ function baseUrl(value, name, carriesKey) {
202
+ let url;
203
+ try {
204
+ url = new URL(value);
205
+ }
206
+ catch {
207
+ throw new OctaVideoError(`${name} must be an absolute address, like https://api.octavideo.tech.`);
208
+ }
209
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
210
+ throw new OctaVideoError(`${name} must be an http or https address.`);
211
+ }
212
+ if (carriesKey && url.protocol === 'http:' && !LOOPBACK_HOSTS.has(url.hostname)) {
213
+ throw new OctaVideoError(`${name} must use https: over plain http the API key would travel unencrypted.`);
214
+ }
215
+ // Not url.search or url.hash: both are empty for a bare "?" or "#", which href keeps.
216
+ if (url.href.includes('?') || url.href.includes('#')) {
217
+ throw new OctaVideoError(`${name} can't have a query or a fragment.`);
218
+ }
219
+ // Refused, not stripped: the address goes into error messages.
220
+ if (url.username || url.password)
221
+ throw new OctaVideoError(`${name} can't have a user name or a password.`);
222
+ let href = url.href;
223
+ while (href.endsWith('/'))
224
+ href = href.slice(0, -1);
225
+ return href;
226
+ }
227
+ function isBrowser() {
228
+ const g = globalThis;
229
+ return g.window !== undefined && g.document !== undefined;
230
+ }
@@ -0,0 +1,65 @@
1
+ /** Every error this package throws is an `OctaVideoError`. */
2
+ export declare class OctaVideoError extends Error {
3
+ name: string;
4
+ }
5
+ /** One field the API refused, from a `validation_failed` answer. */
6
+ export interface FieldError {
7
+ /** The field as you sent it, e.g. `video_id` or `ttl`. */
8
+ field: string;
9
+ /** Why, e.g. `required`, `uuid`, `min`, `max`. */
10
+ code: string;
11
+ message: string;
12
+ }
13
+ /**
14
+ * The API answered with an error. `code` is the API's own (`invalid_api_key`, `video_not_found`,
15
+ * `video_not_ready`, `validation_failed`, …): check it rather than the message. An answer that isn't the API's
16
+ * JSON (a proxy's HTML page, say) has the code `unexpected_response`.
17
+ */
18
+ export declare class APIError extends OctaVideoError {
19
+ name: string;
20
+ readonly status: number;
21
+ readonly code: string;
22
+ /** The fields the API refused, for `validation_failed`; empty otherwise. */
23
+ readonly fields: readonly FieldError[];
24
+ /** The answer's body: parsed JSON, or the start of its text. */
25
+ readonly body: unknown;
26
+ constructor(status: number, code: string, message: string, fields: readonly FieldError[], body: unknown);
27
+ }
28
+ /** 400: the request was refused (`validation_failed`, `bad_body`, `ip_binding_unavailable`, …). */
29
+ export declare class BadRequestError extends APIError {
30
+ name: string;
31
+ }
32
+ /** 401: the key is wrong, or the library doesn't exist (`invalid_api_key`), or no key was sent. */
33
+ export declare class AuthenticationError extends APIError {
34
+ name: string;
35
+ }
36
+ /** 403. */
37
+ export declare class PermissionDeniedError extends APIError {
38
+ name: string;
39
+ }
40
+ /** 404: e.g. `video_not_found`, a video that isn't in this library. */
41
+ export declare class NotFoundError extends APIError {
42
+ name: string;
43
+ }
44
+ /** 409: e.g. `video_not_ready`, a video that is still uploading or encoding. */
45
+ export declare class ConflictError extends APIError {
46
+ name: string;
47
+ }
48
+ /** 429: too many requests, after the retries. */
49
+ export declare class RateLimitError extends APIError {
50
+ name: string;
51
+ }
52
+ /** 5xx: a problem on OctaVideo's side, after the retries for 502, 503 and 504. */
53
+ export declare class InternalServerError extends APIError {
54
+ name: string;
55
+ }
56
+ /** The request didn't get an answer: the network failed, after the retries. */
57
+ export declare class ConnectionError extends OctaVideoError {
58
+ name: string;
59
+ }
60
+ /** No answer within the timeout, after the retries. */
61
+ export declare class TimeoutError extends ConnectionError {
62
+ name: string;
63
+ }
64
+ /** Turns an answer that isn't 2xx (already read in full) into the matching `APIError`. */
65
+ export declare function errorFrom(status: number, statusText: string, text: string): APIError;
package/dist/errors.js ADDED
@@ -0,0 +1,106 @@
1
+ /** Every error this package throws is an `OctaVideoError`. */
2
+ export class OctaVideoError extends Error {
3
+ name = 'OctaVideoError';
4
+ }
5
+ /**
6
+ * The API answered with an error. `code` is the API's own (`invalid_api_key`, `video_not_found`,
7
+ * `video_not_ready`, `validation_failed`, …): check it rather than the message. An answer that isn't the API's
8
+ * JSON (a proxy's HTML page, say) has the code `unexpected_response`.
9
+ */
10
+ export class APIError extends OctaVideoError {
11
+ name = 'APIError';
12
+ status;
13
+ code;
14
+ /** The fields the API refused, for `validation_failed`; empty otherwise. */
15
+ fields;
16
+ /** The answer's body: parsed JSON, or the start of its text. */
17
+ body;
18
+ constructor(status, code, message, fields, body) {
19
+ super(`${status} ${code}: ${message}`);
20
+ this.status = status;
21
+ this.code = code;
22
+ this.fields = fields;
23
+ this.body = body;
24
+ }
25
+ }
26
+ /** 400: the request was refused (`validation_failed`, `bad_body`, `ip_binding_unavailable`, …). */
27
+ export class BadRequestError extends APIError {
28
+ name = 'BadRequestError';
29
+ }
30
+ /** 401: the key is wrong, or the library doesn't exist (`invalid_api_key`), or no key was sent. */
31
+ export class AuthenticationError extends APIError {
32
+ name = 'AuthenticationError';
33
+ }
34
+ /** 403. */
35
+ export class PermissionDeniedError extends APIError {
36
+ name = 'PermissionDeniedError';
37
+ }
38
+ /** 404: e.g. `video_not_found`, a video that isn't in this library. */
39
+ export class NotFoundError extends APIError {
40
+ name = 'NotFoundError';
41
+ }
42
+ /** 409: e.g. `video_not_ready`, a video that is still uploading or encoding. */
43
+ export class ConflictError extends APIError {
44
+ name = 'ConflictError';
45
+ }
46
+ /** 429: too many requests, after the retries. */
47
+ export class RateLimitError extends APIError {
48
+ name = 'RateLimitError';
49
+ }
50
+ /** 5xx: a problem on OctaVideo's side, after the retries for 502, 503 and 504. */
51
+ export class InternalServerError extends APIError {
52
+ name = 'InternalServerError';
53
+ }
54
+ /** The request didn't get an answer: the network failed, after the retries. */
55
+ export class ConnectionError extends OctaVideoError {
56
+ name = 'ConnectionError';
57
+ }
58
+ /** No answer within the timeout, after the retries. */
59
+ export class TimeoutError extends ConnectionError {
60
+ name = 'TimeoutError';
61
+ }
62
+ const BODY_TEXT_LIMIT = 1000;
63
+ /** Turns an answer that isn't 2xx (already read in full) into the matching `APIError`. */
64
+ export function errorFrom(status, statusText, text) {
65
+ let parsed;
66
+ try {
67
+ parsed = JSON.parse(text);
68
+ }
69
+ catch {
70
+ parsed = undefined;
71
+ }
72
+ const error = isRecord(parsed) && isRecord(parsed['error']) ? parsed['error'] : undefined;
73
+ const code = typeof error?.['code'] === 'string' ? error['code'] : 'unexpected_response';
74
+ const statusLine = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status}`;
75
+ const message = typeof error?.['message'] === 'string' ? error['message'] : statusLine;
76
+ const fields = Array.isArray(error?.['field']) ? error['field'].filter(isFieldError) : [];
77
+ const body = parsed ?? text.slice(0, BODY_TEXT_LIMIT);
78
+ const ErrorClass = errorClassFor(status);
79
+ return new ErrorClass(status, code, message, fields, body);
80
+ }
81
+ function errorClassFor(status) {
82
+ if (status === 400)
83
+ return BadRequestError;
84
+ if (status === 401)
85
+ return AuthenticationError;
86
+ if (status === 403)
87
+ return PermissionDeniedError;
88
+ if (status === 404)
89
+ return NotFoundError;
90
+ if (status === 409)
91
+ return ConflictError;
92
+ if (status === 429)
93
+ return RateLimitError;
94
+ if (status >= 500)
95
+ return InternalServerError;
96
+ return APIError;
97
+ }
98
+ function isRecord(value) {
99
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
100
+ }
101
+ function isFieldError(value) {
102
+ return (isRecord(value) &&
103
+ typeof value['field'] === 'string' &&
104
+ typeof value['code'] === 'string' &&
105
+ typeof value['message'] === 'string');
106
+ }
@@ -0,0 +1,3 @@
1
+ export { OctaVideo, DEFAULT_API_URL, DEFAULT_PLAYER_URL, type OctaVideoOptions, type CreateOtpParams, type RequestOptions, type PlaybackOtp, } from './client.js';
2
+ export { OctaVideoError, APIError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, RateLimitError, InternalServerError, ConnectionError, TimeoutError, type FieldError, } from './errors.js';
3
+ export { VERSION } from './version.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { OctaVideo, DEFAULT_API_URL, DEFAULT_PLAYER_URL, } from './client.js';
2
+ export { OctaVideoError, APIError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, RateLimitError, InternalServerError, ConnectionError, TimeoutError, } from './errors.js';
3
+ export { VERSION } from './version.js';
@@ -0,0 +1 @@
1
+ export declare const VERSION = "0.1.1";
@@ -0,0 +1,2 @@
1
+ // Kept equal to package.json's version (test/package.test.ts checks).
2
+ export const VERSION = '0.1.1';
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@octavideo/node",
3
+ "version": "0.1.1",
4
+ "description": "OctaVideo for your server: playback OTPs for the videos in your library.",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "homepage": "https://docs.octavideo.tech/developers/sdks",
7
+ "keywords": [
8
+ "octavideo",
9
+ "video",
10
+ "otp",
11
+ "streaming"
12
+ ],
13
+ "type": "module",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "main": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "files": [
24
+ "dist",
25
+ "README.md"
26
+ ],
27
+ "sideEffects": false,
28
+ "engines": {
29
+ "node": ">=22.12"
30
+ },
31
+ "scripts": {
32
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && node scripts/fix-dts.mjs",
33
+ "typecheck": "tsc -p tsconfig.json",
34
+ "test": "node --test 'test/*.test.ts'",
35
+ "check": "pnpm typecheck && pnpm test && pnpm build",
36
+ "prepublishOnly": "pnpm typecheck && pnpm test",
37
+ "prepack": "pnpm build"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^24.19.4",
41
+ "typescript": "7.0.2"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ }
46
+ }