diffio 0.4.62 → 1.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.
Files changed (60) hide show
  1. package/README.md +208 -296
  2. package/dist/Client.d.ts +85 -148
  3. package/dist/Client.js +73 -798
  4. package/dist/api/resources/account.d.ts +38 -0
  5. package/dist/api/resources/account.js +96 -0
  6. package/dist/api/resources/editing.d.ts +54 -0
  7. package/dist/api/resources/editing.js +168 -0
  8. package/dist/api/resources/generations.d.ts +52 -0
  9. package/dist/api/resources/generations.js +145 -0
  10. package/dist/api/resources/index.d.ts +5 -7
  11. package/dist/api/resources/index.js +18 -15
  12. package/dist/api/resources/models.d.ts +9 -0
  13. package/dist/api/resources/models.js +23 -0
  14. package/dist/api/resources/projects.d.ts +51 -0
  15. package/dist/api/resources/projects.js +128 -0
  16. package/dist/api/types.d.ts +423 -222
  17. package/dist/api/types.js +2 -0
  18. package/dist/core/edgeUpload.d.ts +39 -39
  19. package/dist/core/edgeUpload.js +170 -125
  20. package/dist/core/files.d.ts +15 -0
  21. package/dist/core/files.js +121 -0
  22. package/dist/core/node.d.ts +7 -0
  23. package/dist/core/node.js +17 -0
  24. package/dist/core/pagination.d.ts +33 -0
  25. package/dist/core/pagination.js +64 -0
  26. package/dist/core/poll.d.ts +23 -0
  27. package/dist/core/poll.js +30 -0
  28. package/dist/core/retry.d.ts +8 -7
  29. package/dist/core/retry.js +39 -25
  30. package/dist/core/transport.d.ts +75 -0
  31. package/dist/core/transport.js +220 -0
  32. package/dist/core/url.d.ts +10 -0
  33. package/dist/core/url.js +38 -0
  34. package/dist/core/webhookSignature.d.ts +20 -0
  35. package/dist/core/webhookSignature.js +147 -0
  36. package/dist/errors/index.d.ts +60 -18
  37. package/dist/errors/index.js +61 -13
  38. package/dist/index.d.ts +8 -1
  39. package/dist/index.js +9 -1
  40. package/dist/version.d.ts +1 -1
  41. package/dist/version.js +1 -1
  42. package/package.json +2 -7
  43. package/dist/BaseClient.d.ts +0 -26
  44. package/dist/BaseClient.js +0 -17
  45. package/dist/api/resources/account/client/Client.d.ts +0 -15
  46. package/dist/api/resources/account/client/Client.js +0 -15
  47. package/dist/api/resources/apiKeys/client/Client.d.ts +0 -27
  48. package/dist/api/resources/apiKeys/client/Client.js +0 -21
  49. package/dist/api/resources/audioIsolation/client/Client.d.ts +0 -43
  50. package/dist/api/resources/audioIsolation/client/Client.js +0 -33
  51. package/dist/api/resources/generations/client/Client.d.ts +0 -48
  52. package/dist/api/resources/generations/client/Client.js +0 -36
  53. package/dist/api/resources/projects/client/Client.d.ts +0 -21
  54. package/dist/api/resources/projects/client/Client.js +0 -19
  55. package/dist/api/resources/usage/client/Client.d.ts +0 -11
  56. package/dist/api/resources/usage/client/Client.js +0 -12
  57. package/dist/api/resources/webhooks/client/Client.d.ts +0 -29
  58. package/dist/api/resources/webhooks/client/Client.js +0 -76
  59. package/dist/api/serialization.d.ts +0 -21
  60. package/dist/api/serialization.js +0 -274
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isNode = void 0;
4
+ exports.nodeRequire = nodeRequire;
5
+ /** True in Node (not in browsers, even with a `process` shim). */
6
+ const isNode = () => typeof process !== "undefined" && Boolean(process.versions?.node) &&
7
+ typeof globalThis.window === "undefined";
8
+ exports.isNode = isNode;
9
+ /**
10
+ * Loads a Node built-in. The id is a variable so browser bundlers do not try to bundle Node modules; the
11
+ * SDK only calls this on Node code paths (file paths, node:crypto).
12
+ */
13
+ function nodeRequire(id) {
14
+ if (!(0, exports.isNode)() || typeof require !== "function")
15
+ return undefined;
16
+ return require(id);
17
+ }
@@ -0,0 +1,33 @@
1
+ /** The wire shape of every v2 list: `{"object": "list", "data": [...], "next_cursor": string | null}`. */
2
+ export interface ListResponse<T> {
3
+ object: "list";
4
+ data: T[];
5
+ next_cursor: string | null;
6
+ }
7
+ /**
8
+ * One page of a list. `data` and `next_cursor` are exactly as on the wire. `for await (const item of page)`
9
+ * walks this page and every later one.
10
+ */
11
+ export declare class Page<T> implements ListResponse<T>, AsyncIterable<T> {
12
+ readonly object: "list";
13
+ readonly data: T[];
14
+ readonly next_cursor: string | null;
15
+ private readonly fetchPage;
16
+ constructor(response: ListResponse<T>, fetchPage: (cursor: string) => Promise<Page<T>>);
17
+ hasNextPage(): boolean;
18
+ /** Fetches the page after this one; null on the last page. */
19
+ getNextPage(): Promise<Page<T> | null>;
20
+ /** Every page from this one on. */
21
+ iterPages(): AsyncGenerator<Page<T>, void, undefined>;
22
+ [Symbol.asyncIterator](): AsyncGenerator<T, void, undefined>;
23
+ toJSON(): ListResponse<T>;
24
+ }
25
+ /**
26
+ * What list methods return: await it for the first `Page`, or `for await` it directly to walk every item of
27
+ * every page (the SDK fetches the next page when it needs it).
28
+ */
29
+ export declare class PagePromise<T> extends Promise<Page<T>> implements AsyncIterable<T> {
30
+ static get [Symbol.species](): PromiseConstructor;
31
+ static from<T>(load: () => Promise<Page<T>>): PagePromise<T>;
32
+ [Symbol.asyncIterator](): AsyncGenerator<T, void, undefined>;
33
+ }
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PagePromise = exports.Page = void 0;
4
+ /**
5
+ * One page of a list. `data` and `next_cursor` are exactly as on the wire. `for await (const item of page)`
6
+ * walks this page and every later one.
7
+ */
8
+ class Page {
9
+ constructor(response, fetchPage) {
10
+ this.object = "list";
11
+ this.data = Array.isArray(response?.data) ? response.data : [];
12
+ this.next_cursor = typeof response?.next_cursor === "string" && response.next_cursor ? response.next_cursor : null;
13
+ this.fetchPage = fetchPage;
14
+ }
15
+ hasNextPage() {
16
+ return this.next_cursor !== null;
17
+ }
18
+ /** Fetches the page after this one; null on the last page. */
19
+ async getNextPage() {
20
+ return this.next_cursor ? this.fetchPage(this.next_cursor) : null;
21
+ }
22
+ /** Every page from this one on. */
23
+ async *iterPages() {
24
+ let page = this;
25
+ while (page) {
26
+ yield page;
27
+ page = await page.getNextPage();
28
+ }
29
+ }
30
+ async *[Symbol.asyncIterator]() {
31
+ for await (const page of this.iterPages()) {
32
+ for (const item of page.data)
33
+ yield item;
34
+ }
35
+ }
36
+ toJSON() {
37
+ return { object: "list", data: this.data, next_cursor: this.next_cursor };
38
+ }
39
+ }
40
+ exports.Page = Page;
41
+ /**
42
+ * What list methods return: await it for the first `Page`, or `for await` it directly to walk every item of
43
+ * every page (the SDK fetches the next page when it needs it).
44
+ */
45
+ class PagePromise extends Promise {
46
+ static get [Symbol.species]() {
47
+ return Promise;
48
+ }
49
+ static from(load) {
50
+ let resolveFn;
51
+ let rejectFn;
52
+ const promise = new PagePromise((resolve, reject) => {
53
+ resolveFn = resolve;
54
+ rejectFn = reject;
55
+ });
56
+ load().then(resolveFn, rejectFn);
57
+ return promise;
58
+ }
59
+ async *[Symbol.asyncIterator]() {
60
+ const page = await this;
61
+ yield* page;
62
+ }
63
+ }
64
+ exports.PagePromise = PagePromise;
@@ -0,0 +1,23 @@
1
+ /** Options of the `wait` helpers. */
2
+ export interface WaitOptions<T> {
3
+ /** Seconds to keep polling before throwing DiffioTimeoutError. */
4
+ timeout?: number;
5
+ /** Seconds between polls (default 2). */
6
+ pollInterval?: number;
7
+ /** Called with every state read, the last one included. */
8
+ onProgress?: (resource: T) => void | Promise<void>;
9
+ signal?: AbortSignal;
10
+ }
11
+ /**
12
+ * Polls `read` until `isDone` says it finished. A resource whose `status` is `failed` throws
13
+ * DiffioResourceFailedError with its `error.code` and `error.message`.
14
+ */
15
+ export declare function pollUntil<T extends {
16
+ status: string;
17
+ error?: {
18
+ code?: string;
19
+ message?: string;
20
+ } | null;
21
+ }>(read: () => Promise<T>, isDone: (resource: T) => boolean, what: string, options: WaitOptions<T> & {
22
+ defaultTimeout: number;
23
+ }): Promise<T>;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pollUntil = pollUntil;
4
+ const errors_1 = require("../errors");
5
+ const retry_1 = require("./retry");
6
+ /**
7
+ * Polls `read` until `isDone` says it finished. A resource whose `status` is `failed` throws
8
+ * DiffioResourceFailedError with its `error.code` and `error.message`.
9
+ */
10
+ async function pollUntil(read, isDone, what, options) {
11
+ const timeoutSeconds = options.timeout ?? options.defaultTimeout;
12
+ const intervalMs = Math.max(0, (options.pollInterval ?? 2) * 1000);
13
+ const deadline = Date.now() + timeoutSeconds * 1000;
14
+ for (;;) {
15
+ const resource = await read();
16
+ if (options.onProgress)
17
+ await options.onProgress(resource);
18
+ if (resource.status === "failed") {
19
+ const code = resource.error?.code ?? "failed";
20
+ const message = resource.error?.message ?? `The ${what} failed.`;
21
+ throw new errors_1.DiffioResourceFailedError(code, message, resource);
22
+ }
23
+ if (isDone(resource))
24
+ return resource;
25
+ if (Date.now() + intervalMs > deadline) {
26
+ throw new errors_1.DiffioTimeoutError(`Timed out after ${timeoutSeconds} s waiting for the ${what} (last status ${resource.status}).`, resource);
27
+ }
28
+ await (0, retry_1.sleep)(intervalMs, options.signal);
29
+ }
30
+ }
@@ -1,7 +1,8 @@
1
- export declare function sleep(ms: number): Promise<void>;
2
- export interface RetryOptions {
3
- maxRetries: number;
4
- retryBackoff: number;
5
- retryStatusCodes: number[];
6
- }
7
- export declare function requestWithRetries(requestFn: () => Promise<Response>, { maxRetries, retryBackoff, retryStatusCodes }: RetryOptions): Promise<Response>;
1
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
2
+ /** Statuses worth sending again: timeouts, rate limits and server-side failures. */
3
+ export declare const DEFAULT_RETRY_STATUS_CODES: number[];
4
+ /**
5
+ * Delay before retry number `attempt` (1 = first retry): `backoff * 2^(attempt-1)` seconds with up to 25 %
6
+ * jitter, capped at 8 s, or the server's `Retry-After` (seconds, capped at 60 s) when it sent one.
7
+ */
8
+ export declare function retryDelayMs(attempt: number, backoffSeconds: number, retryAfter?: string | null): number;
@@ -1,31 +1,45 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_RETRY_STATUS_CODES = void 0;
3
4
  exports.sleep = sleep;
4
- exports.requestWithRetries = requestWithRetries;
5
- function sleep(ms) {
6
- return new Promise((resolve) => setTimeout(resolve, ms));
7
- }
8
- async function requestWithRetries(requestFn, { maxRetries, retryBackoff, retryStatusCodes }) {
9
- let attempt = 0;
10
- while (true) {
11
- try {
12
- const response = await requestFn();
13
- if (retryStatusCodes.length > 0 &&
14
- retryStatusCodes.includes(response.status) &&
15
- attempt < maxRetries) {
16
- response.body?.cancel?.();
17
- await sleep(retryBackoff * 1000 * 2 ** attempt);
18
- attempt += 1;
19
- continue;
20
- }
21
- return response;
22
- }
23
- catch (error) {
24
- if (attempt >= maxRetries) {
25
- throw error;
26
- }
27
- await sleep(retryBackoff * 1000 * 2 ** attempt);
28
- attempt += 1;
5
+ exports.retryDelayMs = retryDelayMs;
6
+ function sleep(ms, signal) {
7
+ return new Promise((resolve, reject) => {
8
+ if (signal?.aborted) {
9
+ reject(abortReason(signal));
10
+ return;
29
11
  }
12
+ const timer = setTimeout(() => {
13
+ signal?.removeEventListener("abort", onAbort);
14
+ resolve();
15
+ }, ms);
16
+ const onAbort = () => {
17
+ clearTimeout(timer);
18
+ reject(abortReason(signal));
19
+ };
20
+ signal?.addEventListener("abort", onAbort, { once: true });
21
+ });
22
+ }
23
+ function abortReason(signal) {
24
+ const reason = signal?.reason;
25
+ if (reason)
26
+ return reason;
27
+ const error = new Error("The operation was aborted.");
28
+ error.name = "AbortError";
29
+ return error;
30
+ }
31
+ /** Statuses worth sending again: timeouts, rate limits and server-side failures. */
32
+ exports.DEFAULT_RETRY_STATUS_CODES = [408, 429, 500, 502, 503, 504];
33
+ /**
34
+ * Delay before retry number `attempt` (1 = first retry): `backoff * 2^(attempt-1)` seconds with up to 25 %
35
+ * jitter, capped at 8 s, or the server's `Retry-After` (seconds, capped at 60 s) when it sent one.
36
+ */
37
+ function retryDelayMs(attempt, backoffSeconds, retryAfter) {
38
+ if (retryAfter) {
39
+ const seconds = Number(retryAfter);
40
+ if (Number.isFinite(seconds) && seconds >= 0)
41
+ return Math.min(60, seconds) * 1000;
30
42
  }
43
+ const base = Math.min(8, backoffSeconds * 2 ** Math.max(0, attempt - 1)) * 1000;
44
+ return Math.round(base * (1 + Math.random() * 0.25));
31
45
  }
@@ -0,0 +1,75 @@
1
+ import { DiffioApiError } from "../errors";
2
+ import { type HeaderRecord } from "./headers";
3
+ import { Supplier } from "./supplier";
4
+ /** Options every method accepts as its last argument. */
5
+ export interface RequestOptions {
6
+ /** Sent as `Diffio-End-User`: act for one end user of your product. Overrides the client's `endUser`. */
7
+ endUser?: string | null;
8
+ /**
9
+ * Sent as `Idempotency-Key` on the three calls that honour it (`projects.create`, `generations.create`,
10
+ * `edits.create`). When left out the SDK makes one per call, so its own retries never create twice.
11
+ */
12
+ idempotencyKey?: string;
13
+ /** Seconds before one HTTP attempt gives up. */
14
+ timeout?: number;
15
+ /** Retries after the first attempt (idempotent calls only). */
16
+ maxRetries?: number;
17
+ signal?: AbortSignal;
18
+ /** Extra headers for this call. */
19
+ headers?: Record<string, string | null | undefined>;
20
+ /** Use another API key for this call. */
21
+ apiKey?: string;
22
+ }
23
+ export interface TransportOptions {
24
+ apiKey?: Supplier<string | undefined>;
25
+ baseUrl?: Supplier<string | undefined>;
26
+ endUser?: string | null;
27
+ timeout?: number;
28
+ maxRetries?: number;
29
+ retryBackoff?: number;
30
+ retryStatusCodes?: number[];
31
+ headers?: HeaderRecord;
32
+ fetch?: typeof fetch;
33
+ }
34
+ export interface ApiRequest {
35
+ method: "GET" | "POST" | "PUT" | "DELETE";
36
+ path: string;
37
+ body?: unknown;
38
+ /** Whether repeating the request is harmless; only these are retried. */
39
+ idempotent: boolean;
40
+ /** Send no API key (public routes such as `GET /models` and `GET /shares/{id}`). */
41
+ noAuth?: boolean;
42
+ /** Never send `Diffio-End-User` (account-level routes such as `POST /webhooks/portal` refuse it). */
43
+ accountLevel?: boolean;
44
+ /** This operation honours `Idempotency-Key`: send the caller's key, or make one. */
45
+ acceptsIdempotencyKey?: boolean;
46
+ /** Default timeout in seconds when neither the call nor the client sets one. */
47
+ defaultTimeout?: number;
48
+ options?: RequestOptions;
49
+ }
50
+ export declare const DEFAULT_TIMEOUT_SECONDS = 60;
51
+ export declare const DEFAULT_MAX_RETRIES = 2;
52
+ export declare const DEFAULT_RETRY_BACKOFF_SECONDS = 0.5;
53
+ export { isNode } from "./node";
54
+ export declare const readEnv: (name: string) => string | undefined;
55
+ /** A random v4 UUID from WebCrypto when present, else Math.random (only used for idempotency keys). */
56
+ export declare function randomId(): string;
57
+ /** Builds the typed error for a non-2xx answer from its body (v2 error shape) and headers. */
58
+ export declare function apiErrorFromResponse(status: number, body: unknown, headers: Headers | null): DiffioApiError;
59
+ /** Runs `fetch` with a timeout and an optional caller signal; a timeout becomes DiffioTimeoutError. */
60
+ export declare function fetchWithTimeout(fetchFn: typeof fetch, url: string, init: RequestInit, timeoutMs: number | undefined, signal?: AbortSignal): Promise<Response>;
61
+ /** Sends v2 API requests: auth, SDK headers, end-user and idempotency headers, retries and typed errors. */
62
+ export declare class Transport {
63
+ readonly options: TransportOptions;
64
+ constructor(options: TransportOptions);
65
+ get fetchFn(): typeof fetch;
66
+ baseUrl(): Promise<string>;
67
+ retryPolicy(options?: RequestOptions): {
68
+ maxRetries: number;
69
+ backoff: number;
70
+ statuses: number[];
71
+ };
72
+ private buildHeaders;
73
+ /** Sends one request and returns the parsed JSON body; throws DiffioApiError on a refusal. */
74
+ request<T>(request: ApiRequest): Promise<T>;
75
+ }
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = exports.readEnv = exports.isNode = exports.DEFAULT_RETRY_BACKOFF_SECONDS = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_TIMEOUT_SECONDS = void 0;
4
+ exports.randomId = randomId;
5
+ exports.apiErrorFromResponse = apiErrorFromResponse;
6
+ exports.fetchWithTimeout = fetchWithTimeout;
7
+ const version_1 = require("../version");
8
+ const errors_1 = require("../errors");
9
+ const headers_1 = require("./headers");
10
+ const supplier_1 = require("./supplier");
11
+ const retry_1 = require("./retry");
12
+ const url_1 = require("./url");
13
+ exports.DEFAULT_TIMEOUT_SECONDS = 60;
14
+ exports.DEFAULT_MAX_RETRIES = 2;
15
+ exports.DEFAULT_RETRY_BACKOFF_SECONDS = 0.5;
16
+ /** Status codes v2 answers without a code of its own, as the API maps them (api_v2_http.py). */
17
+ const CODE_BY_STATUS = {
18
+ 400: "invalid_request",
19
+ 401: "unauthenticated",
20
+ 402: "payment_required",
21
+ 403: "permission_denied",
22
+ 404: "not_found",
23
+ 405: "method_not_allowed",
24
+ 409: "conflict",
25
+ 413: "payload_too_large",
26
+ 415: "unsupported_media_type",
27
+ 429: "rate_limited",
28
+ 500: "internal_error",
29
+ 502: "internal_error",
30
+ 503: "unavailable",
31
+ 504: "unavailable"
32
+ };
33
+ const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
34
+ var node_1 = require("./node");
35
+ Object.defineProperty(exports, "isNode", { enumerable: true, get: function () { return node_1.isNode; } });
36
+ const node_2 = require("./node");
37
+ const readEnv = (name) => {
38
+ if (typeof process === "undefined" || !process.env)
39
+ return undefined;
40
+ const value = process.env[name];
41
+ return value && value.trim() ? value.trim() : undefined;
42
+ };
43
+ exports.readEnv = readEnv;
44
+ /** A random v4 UUID from WebCrypto when present, else Math.random (only used for idempotency keys). */
45
+ function randomId() {
46
+ const cryptoObject = globalThis.crypto;
47
+ if (cryptoObject?.randomUUID)
48
+ return cryptoObject.randomUUID();
49
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
50
+ const random = (Math.random() * 16) | 0;
51
+ return (char === "x" ? random : (random & 0x3) | 0x8).toString(16);
52
+ });
53
+ }
54
+ function isAbortError(error) {
55
+ return isRecord(error) && error.name === "AbortError" ||
56
+ (error instanceof Error && error.name === "AbortError");
57
+ }
58
+ /** Builds the typed error for a non-2xx answer from its body (v2 error shape) and headers. */
59
+ function apiErrorFromResponse(status, body, headers) {
60
+ const error = isRecord(body) && isRecord(body.error) ? body.error : null;
61
+ const code = error && typeof error.code === "string" && error.code ? error.code : CODE_BY_STATUS[status] ??
62
+ (status >= 500 ? "internal_error" : "invalid_request");
63
+ const message = error && typeof error.message === "string" && error.message
64
+ ? error.message
65
+ : typeof body === "string" && body.trim() && body.length < 500
66
+ ? body.trim()
67
+ : `Request failed with HTTP ${status}`;
68
+ const requestId = error && typeof error.request_id === "string"
69
+ ? error.request_id
70
+ : headers?.get("x-request-id") ?? null;
71
+ const details = error && isRecord(error.details) ? error.details : {};
72
+ return new errors_1.DiffioApiError({ status, code, message, request_id: requestId, details, headers, body });
73
+ }
74
+ /** Runs `fetch` with a timeout and an optional caller signal; a timeout becomes DiffioTimeoutError. */
75
+ async function fetchWithTimeout(fetchFn, url, init, timeoutMs, signal) {
76
+ const controller = new AbortController();
77
+ let timedOut = false;
78
+ const onAbort = () => controller.abort();
79
+ if (signal) {
80
+ if (signal.aborted)
81
+ controller.abort();
82
+ else
83
+ signal.addEventListener("abort", onAbort, { once: true });
84
+ }
85
+ const timer = timeoutMs != null && timeoutMs > 0
86
+ ? setTimeout(() => {
87
+ timedOut = true;
88
+ controller.abort();
89
+ }, timeoutMs)
90
+ : null;
91
+ try {
92
+ return await fetchFn(url, { ...init, signal: controller.signal });
93
+ }
94
+ catch (error) {
95
+ if (timedOut)
96
+ throw new errors_1.DiffioTimeoutError(`Request timed out after ${Math.round((timeoutMs ?? 0) / 1000)} s`);
97
+ throw error;
98
+ }
99
+ finally {
100
+ if (timer)
101
+ clearTimeout(timer);
102
+ signal?.removeEventListener("abort", onAbort);
103
+ }
104
+ }
105
+ /** Sends v2 API requests: auth, SDK headers, end-user and idempotency headers, retries and typed errors. */
106
+ class Transport {
107
+ constructor(options) {
108
+ this.options = options;
109
+ }
110
+ get fetchFn() {
111
+ const fetchFn = this.options.fetch ?? (globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined);
112
+ if (!fetchFn)
113
+ throw new errors_1.DiffioError("fetch is not available in this runtime; pass options.fetch");
114
+ return fetchFn;
115
+ }
116
+ async baseUrl() {
117
+ const base = (await supplier_1.Supplier.get(this.options.baseUrl)) ?? (0, exports.readEnv)("DIFFIO_API_BASE_URL") ?? url_1.DEFAULT_BASE_URL;
118
+ return (0, url_1.resolveApiBaseUrl)(base);
119
+ }
120
+ retryPolicy(options) {
121
+ return {
122
+ maxRetries: Math.max(0, options?.maxRetries ?? this.options.maxRetries ?? exports.DEFAULT_MAX_RETRIES),
123
+ backoff: this.options.retryBackoff ?? exports.DEFAULT_RETRY_BACKOFF_SECONDS,
124
+ statuses: this.options.retryStatusCodes ?? retry_1.DEFAULT_RETRY_STATUS_CODES
125
+ };
126
+ }
127
+ async buildHeaders(request) {
128
+ const options = request.options;
129
+ const sdkHeaders = {
130
+ Accept: "application/json",
131
+ "X-Diffio-SDK-Language": "JavaScript",
132
+ "X-Diffio-SDK-Name": "diffio",
133
+ "X-Diffio-SDK-Version": version_1.DIFFIO_SDK_VERSION
134
+ };
135
+ // Browsers would need User-Agent in the CORS allow list, so only Node sends it.
136
+ if ((0, node_2.isNode)())
137
+ sdkHeaders["User-Agent"] = `diffio-js/${version_1.DIFFIO_SDK_VERSION}`;
138
+ const extra = {};
139
+ if (!request.noAuth) {
140
+ const apiKey = options?.apiKey ?? (await supplier_1.Supplier.get(this.options.apiKey)) ?? (0, exports.readEnv)("DIFFIO_API_KEY");
141
+ if (!apiKey) {
142
+ throw new errors_1.DiffioError("No API key: pass apiKey to new DiffioClient(...) or set DIFFIO_API_KEY.");
143
+ }
144
+ extra.Authorization = `Bearer ${apiKey}`;
145
+ }
146
+ const endUser = options?.endUser !== undefined ? options.endUser : this.options.endUser;
147
+ if (endUser && !request.noAuth && !request.accountLevel)
148
+ extra["Diffio-End-User"] = endUser;
149
+ if (request.body !== undefined)
150
+ extra["Content-Type"] = "application/json";
151
+ return (0, headers_1.resolveHeaders)((0, headers_1.mergeHeaders)(sdkHeaders, this.options.headers, extra, options?.headers));
152
+ }
153
+ /** Sends one request and returns the parsed JSON body; throws DiffioApiError on a refusal. */
154
+ async request(request) {
155
+ const options = request.options;
156
+ const url = `${await this.baseUrl()}${request.path}`;
157
+ const headers = await this.buildHeaders(request);
158
+ let idempotent = request.idempotent;
159
+ if (request.acceptsIdempotencyKey) {
160
+ headers["Idempotency-Key"] = options?.idempotencyKey ?? randomId();
161
+ idempotent = true;
162
+ }
163
+ const body = request.body === undefined ? undefined : JSON.stringify(request.body);
164
+ const timeoutSeconds = options?.timeout ?? this.options.timeout ?? request.defaultTimeout ?? exports.DEFAULT_TIMEOUT_SECONDS;
165
+ const { maxRetries, backoff, statuses } = this.retryPolicy(options);
166
+ const fetchFn = this.fetchFn;
167
+ for (let attempt = 0;; attempt += 1) {
168
+ const canRetry = idempotent && attempt < maxRetries;
169
+ let response;
170
+ try {
171
+ response = await fetchWithTimeout(fetchFn, url, { method: request.method, headers, body }, timeoutSeconds * 1000, options?.signal);
172
+ }
173
+ catch (error) {
174
+ if (options?.signal?.aborted || (isAbortError(error) && !(error instanceof errors_1.DiffioTimeoutError)))
175
+ throw error;
176
+ if (canRetry) {
177
+ await (0, retry_1.sleep)((0, retry_1.retryDelayMs)(attempt + 1, backoff), options?.signal);
178
+ continue;
179
+ }
180
+ if (error instanceof errors_1.DiffioError)
181
+ throw error;
182
+ const message = error instanceof Error ? error.message : String(error);
183
+ throw new errors_1.DiffioConnectionError(`Could not reach the Diffio API: ${message}`, error);
184
+ }
185
+ if (response.ok) {
186
+ const text = await response.text();
187
+ if (!text)
188
+ return {};
189
+ try {
190
+ return JSON.parse(text);
191
+ }
192
+ catch {
193
+ throw new errors_1.DiffioApiError({
194
+ status: response.status,
195
+ code: "invalid_response",
196
+ message: "The Diffio API answered with a body that is not JSON.",
197
+ request_id: response.headers.get("x-request-id"),
198
+ headers: response.headers,
199
+ body: text
200
+ });
201
+ }
202
+ }
203
+ if (canRetry && statuses.includes(response.status)) {
204
+ await response.arrayBuffer().catch(() => undefined);
205
+ await (0, retry_1.sleep)((0, retry_1.retryDelayMs)(attempt + 1, backoff, response.headers.get("retry-after")), options?.signal);
206
+ continue;
207
+ }
208
+ const text = await response.text().catch(() => "");
209
+ let parsed = text || null;
210
+ try {
211
+ parsed = text ? JSON.parse(text) : null;
212
+ }
213
+ catch {
214
+ parsed = text;
215
+ }
216
+ throw apiErrorFromResponse(response.status, parsed, response.headers);
217
+ }
218
+ }
219
+ }
220
+ exports.Transport = Transport;
@@ -1 +1,11 @@
1
1
  export declare function join(base: string, ...paths: string[]): string;
2
+ export declare const DEFAULT_BASE_URL = "https://api.diffio.ai";
3
+ /**
4
+ * Turns a host (`https://api.diffio.ai`) or a versioned base (`.../v2`) into the v2 base URL.
5
+ * A base ending in `/v1` (the old SDK's documented value) is moved to `/v2`.
6
+ */
7
+ export declare function resolveApiBaseUrl(base: string): string;
8
+ /** Encodes one path segment (a project, generation, export, turn or share id). */
9
+ export declare function segment(value: string, name: string): string;
10
+ /** Builds `?a=1&b=2` from defined, non-null values; empty when there are none. */
11
+ export declare function queryString(params?: Record<string, string | number | boolean | null | undefined>): string;
package/dist/core/url.js CHANGED
@@ -1,6 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_BASE_URL = void 0;
3
4
  exports.join = join;
5
+ exports.resolveApiBaseUrl = resolveApiBaseUrl;
6
+ exports.segment = segment;
7
+ exports.queryString = queryString;
4
8
  function join(base, ...paths) {
5
9
  const trimmedBase = base.replace(/\/+$/, "");
6
10
  const trimmedPaths = paths
@@ -12,3 +16,37 @@ function join(base, ...paths) {
12
16
  }
13
17
  return [trimmedBase, ...trimmedPaths].join("/");
14
18
  }
19
+ exports.DEFAULT_BASE_URL = "https://api.diffio.ai";
20
+ const API_VERSION_PREFIX = "v2";
21
+ /**
22
+ * Turns a host (`https://api.diffio.ai`) or a versioned base (`.../v2`) into the v2 base URL.
23
+ * A base ending in `/v1` (the old SDK's documented value) is moved to `/v2`.
24
+ */
25
+ function resolveApiBaseUrl(base) {
26
+ const trimmed = base.trim().replace(/\/+$/, "");
27
+ if (trimmed.endsWith(`/${API_VERSION_PREFIX}`))
28
+ return trimmed;
29
+ if (trimmed.endsWith("/v1"))
30
+ return `${trimmed.slice(0, -3)}/${API_VERSION_PREFIX}`;
31
+ return `${trimmed}/${API_VERSION_PREFIX}`;
32
+ }
33
+ /** Encodes one path segment (a project, generation, export, turn or share id). */
34
+ function segment(value, name) {
35
+ if (typeof value !== "string" || value.trim() === "") {
36
+ throw new TypeError(`${name} is required`);
37
+ }
38
+ return encodeURIComponent(value);
39
+ }
40
+ /** Builds `?a=1&b=2` from defined, non-null values; empty when there are none. */
41
+ function queryString(params) {
42
+ if (!params)
43
+ return "";
44
+ const search = new URLSearchParams();
45
+ for (const [key, value] of Object.entries(params)) {
46
+ if (value === undefined || value === null)
47
+ continue;
48
+ search.append(key, String(value));
49
+ }
50
+ const text = search.toString();
51
+ return text ? `?${text}` : "";
52
+ }
@@ -0,0 +1,20 @@
1
+ import type { WebhookEvent } from "../api/types";
2
+ export type WebhookHeaders = Headers | Record<string, string | string[] | undefined | null>;
3
+ export interface VerifySignatureOptions {
4
+ /** How far the timestamp may be from now, in seconds (default 300, as Svix). */
5
+ toleranceSeconds?: number;
6
+ /** "Now" in seconds since the epoch, for tests. */
7
+ now?: number;
8
+ }
9
+ export type WebhookPayload = string | Uint8Array | ArrayBuffer;
10
+ /**
11
+ * Checks a delivery's signature and timestamp with node:crypto and returns the parsed event.
12
+ * Pass the raw request body exactly as received (not re-serialized JSON). Throws
13
+ * DiffioWebhookVerificationError when anything does not check out. Node only; elsewhere use
14
+ * `verifySignatureAsync`.
15
+ */
16
+ export declare function verifyWebhookSignature(payload: WebhookPayload, headers: WebhookHeaders, secret: string, options?: VerifySignatureOptions): WebhookEvent;
17
+ /** Same check with WebCrypto, for browsers, edge runtimes, Deno and Bun (works in Node 18+ too). */
18
+ export declare function verifyWebhookSignatureAsync(payload: WebhookPayload, headers: WebhookHeaders, secret: string, options?: VerifySignatureOptions): Promise<WebhookEvent>;
19
+ /** Signs a payload the way Svix does; for tests of your own webhook handler. */
20
+ export declare function signWebhookPayload(payload: string, secret: string, id: string, timestamp: number): string;