@worqio/sdk 0.0.0-stage → 0.1.2

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,2 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export {};
@@ -0,0 +1,27 @@
1
+ import { methods, type OperationTypes } from "./gen/methods.gen.js";
2
+ import { WorqioError } from "./error.js";
3
+ import { type RequestOptions, type WorqioOptions } from "./request.js";
4
+ export { WorqioError };
5
+ export type { RequestOptions, WorqioOptions } from "./request.js";
6
+ export type * from "./gen/types.gen.js";
7
+ type Part<Data, Key> = Key extends keyof Data ? NonNullable<Data[Key]> : never;
8
+ type EmptyUnlessPresent<T> = [T] extends [Record<string, never>] ? object : T;
9
+ type Simplify<T> = {
10
+ [K in keyof T]: T[K];
11
+ };
12
+ type Input<Data> = Simplify<EmptyUnlessPresent<Part<Data, "path">> & EmptyUnlessPresent<Part<Data, "query">> & EmptyUnlessPresent<Part<Data, "body">>>;
13
+ type Args<T> = {} extends T ? [input?: T, options?: RequestOptions] : [input: T, options?: RequestOptions];
14
+ type Method<Data, Result> = (...args: Args<Input<Data>>) => Promise<Result>;
15
+ type Iterator<Data, Result> = Result extends {
16
+ data: readonly (infer Item)[];
17
+ } ? {
18
+ all: (...args: Args<Input<Data>>) => AsyncIterableIterator<Item>;
19
+ } : object;
20
+ type Client<Tree> = {
21
+ readonly [Key in keyof Tree]: Tree[Key] extends {
22
+ operationId: infer Id extends keyof OperationTypes;
23
+ list: infer List;
24
+ } ? Method<OperationTypes[Id][0], OperationTypes[Id][1]> & (List extends true ? Iterator<OperationTypes[Id][0], OperationTypes[Id][1]> : object) : Client<Tree[Key]>;
25
+ };
26
+ export type Worqio = Client<typeof methods>;
27
+ export declare const Worqio: new (options: WorqioOptions) => Worqio;
package/dist/index.js ADDED
@@ -0,0 +1,41 @@
1
+ import { methods } from "./gen/methods.gen.js";
2
+ import { WorqioError } from "./error.js";
3
+ import { createRequest, } from "./request.js";
4
+ export { WorqioError };
5
+ function isMethod(value) {
6
+ return typeof value.operationId === "string";
7
+ }
8
+ function bindMethods(tree, request) {
9
+ return Object.fromEntries(Object.entries(tree).map(([name, value]) => {
10
+ if (!isMethod(value))
11
+ return [name, bindMethods(value, request)];
12
+ const call = (input, options) => request(value, input, options);
13
+ if (!value.list)
14
+ return [name, call];
15
+ return [
16
+ name,
17
+ Object.assign(call, {
18
+ async *all(input = {}, options) {
19
+ let cursor = typeof input.cursor === "string" && input.cursor ? input.cursor : undefined;
20
+ const seen = new Set();
21
+ for (;;) {
22
+ if (cursor)
23
+ seen.add(cursor);
24
+ const page = (await call({ ...input, cursor }, options));
25
+ if (page.nextCursor && seen.has(page.nextCursor))
26
+ throw new WorqioError(200, "api.pagination_error", "The API repeated a pagination cursor");
27
+ yield* page.data;
28
+ if (!page.nextCursor)
29
+ return;
30
+ cursor = page.nextCursor;
31
+ }
32
+ },
33
+ }),
34
+ ];
35
+ }));
36
+ }
37
+ export const Worqio = class Worqio {
38
+ constructor(options) {
39
+ Object.assign(this, bindMethods(methods, createRequest(options)));
40
+ }
41
+ };
@@ -0,0 +1,18 @@
1
+ export interface RequestOptions {
2
+ idempotencyKey?: string;
3
+ signal?: AbortSignal;
4
+ }
5
+ export interface WorqioOptions {
6
+ apiKey: string;
7
+ baseUrl?: string;
8
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
9
+ maxRetries?: number;
10
+ }
11
+ export interface MethodDescriptor {
12
+ operationId: string;
13
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
14
+ path: string;
15
+ readOnly: boolean;
16
+ list: boolean;
17
+ }
18
+ export declare function createRequest({ apiKey, baseUrl, fetch: send, maxRetries, }: WorqioOptions): (route: MethodDescriptor, input?: Record<string, unknown>, { idempotencyKey, signal }?: RequestOptions) => Promise<unknown>;
@@ -0,0 +1,139 @@
1
+ import { WorqioError } from "./error.js";
2
+ const MAX_RETRY_AFTER_MS = 60_000;
3
+ // HTTP-date accepts IMF-fixdate and the two obsolete formats defined by HTTP.
4
+ const HTTP_DATE = /^(?:(?:[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4}|[A-Z][a-z]+, \d{2}-[A-Z][a-z]{2}-\d{2}) \d{2}:\d{2}:\d{2} GMT|[A-Z][a-z]{2} [A-Z][a-z]{2} (?: \d|\d{2}) \d{2}:\d{2}:\d{2} \d{4})$/;
5
+ function retryDelay(header, attempt) {
6
+ if (header !== null) {
7
+ if (/^\d+$/.test(header))
8
+ return Math.min(Number(header) * 1000, MAX_RETRY_AFTER_MS);
9
+ if (HTTP_DATE.test(header)) {
10
+ const date = Date.parse(header);
11
+ if (Number.isFinite(date))
12
+ return Math.min(Math.max(0, date - Date.now()), MAX_RETRY_AFTER_MS);
13
+ }
14
+ }
15
+ return Math.min(250 * 2 ** attempt, 8_000);
16
+ }
17
+ function pause(ms, signal) {
18
+ signal?.throwIfAborted();
19
+ return new Promise((resolve, reject) => {
20
+ const timer = setTimeout(() => {
21
+ signal?.removeEventListener("abort", abort);
22
+ resolve();
23
+ }, ms);
24
+ const abort = () => {
25
+ clearTimeout(timer);
26
+ reject(signal?.reason);
27
+ };
28
+ signal?.addEventListener("abort", abort, { once: true });
29
+ });
30
+ }
31
+ const networkCodes = new Set([
32
+ "ECONNABORTED",
33
+ "ECONNREFUSED",
34
+ "ECONNRESET",
35
+ "EHOSTUNREACH",
36
+ "ENETDOWN",
37
+ "ENETUNREACH",
38
+ "EPIPE",
39
+ "ETIMEDOUT",
40
+ "EAI_AGAIN",
41
+ "ENOTFOUND",
42
+ "UND_ERR_CONNECT_TIMEOUT",
43
+ "UND_ERR_HEADERS_TIMEOUT",
44
+ "UND_ERR_BODY_TIMEOUT",
45
+ "UND_ERR_SOCKET",
46
+ ]);
47
+ function retryableTransportError(error) {
48
+ if (!(error instanceof Error))
49
+ return false;
50
+ const cause = error.cause ?? error;
51
+ if (typeof cause === "object" &&
52
+ cause !== null &&
53
+ "code" in cause &&
54
+ typeof cause.code === "string")
55
+ return networkCodes.has(cause.code);
56
+ // Browser Fetch and injected Fetch shims can report network failures without a system code.
57
+ return (error instanceof TypeError &&
58
+ /^(?:network(?:\b|error)|failed to fetch\b|fetch failed\b|load failed\b|terminated\b|error sending request\b)/i.test(error.message));
59
+ }
60
+ function decodeResponse(response, text) {
61
+ let value;
62
+ try {
63
+ value = JSON.parse(text);
64
+ }
65
+ catch {
66
+ if (response.ok) {
67
+ throw new WorqioError(response.status, "api.invalid_response", "The API returned an invalid JSON response", response.headers.get("X-Request-Id") ?? undefined);
68
+ }
69
+ }
70
+ if (response.ok)
71
+ return value;
72
+ const error = value?.error;
73
+ throw new WorqioError(response.status, typeof error?.code === "string" ? error.code : "api.http_error", typeof error?.message === "string" ? error.message : `HTTP ${response.status}`, typeof error?.requestId === "string"
74
+ ? error.requestId
75
+ : (response.headers.get("X-Request-Id") ?? undefined), error?.details, error?.issues);
76
+ }
77
+ export function createRequest({ apiKey, baseUrl = "https://api.worqio.ai/v1", fetch: send = globalThis.fetch, maxRetries = 2, }) {
78
+ if (!apiKey || /[^!-~]/.test(apiKey))
79
+ throw new TypeError("Invalid apiKey");
80
+ if (!Number.isSafeInteger(maxRetries) || maxRetries < 0)
81
+ throw new RangeError("maxRetries must be a non-negative integer");
82
+ const base = baseUrl.replace(/\/+$/, "");
83
+ const authorization = `Bearer ${apiKey}`;
84
+ return async function request(route, input = {}, { idempotencyKey, signal } = {}) {
85
+ const data = { ...input };
86
+ const path = route.path.replace(/\{(\w+)\}/g, (_, field) => {
87
+ const value = String(data[field] ?? "");
88
+ if (!value || value === "." || value === "..")
89
+ throw new TypeError(`Invalid path parameter: ${field}`);
90
+ delete data[field];
91
+ return encodeURIComponent(value);
92
+ });
93
+ const url = new URL(base + path);
94
+ const headers = new Headers({ Accept: "application/json", Authorization: authorization });
95
+ let body;
96
+ if (route.method === "GET") {
97
+ for (const [name, value] of Object.entries(data)) {
98
+ for (const item of Array.isArray(value) ? value : [value]) {
99
+ if (item !== undefined && item !== null)
100
+ url.searchParams.append(name, String(item));
101
+ }
102
+ }
103
+ }
104
+ else {
105
+ headers.set("Content-Type", "application/json");
106
+ body = JSON.stringify(data);
107
+ }
108
+ if (!route.readOnly && idempotencyKey)
109
+ headers.set("Idempotency-Key", idempotencyKey);
110
+ const retries = route.readOnly || idempotencyKey ? maxRetries : 0;
111
+ const init = { method: route.method, headers, body, signal, redirect: "manual" };
112
+ for (let attempt = 0;; attempt++) {
113
+ signal?.throwIfAborted();
114
+ let delay;
115
+ try {
116
+ const response = await send(url.href, init);
117
+ signal?.throwIfAborted();
118
+ if (response.status === 204)
119
+ return undefined;
120
+ if (response.status === 429 && attempt < retries) {
121
+ delay = retryDelay(response.headers.get("Retry-After"), attempt);
122
+ await response.body?.cancel().catch(() => { });
123
+ }
124
+ else {
125
+ const text = response.ok ? await response.text() : await response.text().catch(() => "");
126
+ signal?.throwIfAborted();
127
+ return decodeResponse(response, text);
128
+ }
129
+ }
130
+ catch (error) {
131
+ signal?.throwIfAborted();
132
+ if (attempt >= retries || !retryableTransportError(error))
133
+ throw error;
134
+ delay = retryDelay(null, attempt);
135
+ }
136
+ await pause(delay, signal);
137
+ }
138
+ };
139
+ }