@timbereye/sdk 0.0.0-stage → 0.2.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/CHANGELOG.md +123 -0
- package/LICENSE +202 -0
- package/README.md +346 -2
- package/dist/cjs/case.d.ts +23 -0
- package/dist/cjs/case.js +54 -0
- package/dist/cjs/client.d.ts +98 -0
- package/dist/cjs/client.js +132 -0
- package/dist/cjs/errors.d.ts +63 -0
- package/dist/cjs/errors.js +107 -0
- package/dist/cjs/generated/schema.d.ts +14862 -0
- package/dist/cjs/generated/schema.js +6 -0
- package/dist/cjs/http.d.ts +104 -0
- package/dist/cjs/http.js +253 -0
- package/dist/cjs/index.d.ts +14 -0
- package/dist/cjs/index.js +29 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +31 -0
- package/dist/cjs/pagination.js +52 -0
- package/dist/cjs/resources.d.ts +11195 -0
- package/dist/cjs/resources.js +506 -0
- package/dist/cjs/runtime.d.ts +20 -0
- package/dist/cjs/runtime.js +74 -0
- package/dist/cjs/types.d.ts +649 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/units.d.ts +26 -0
- package/dist/cjs/units.js +45 -0
- package/dist/cjs/webhooks.d.ts +67 -0
- package/dist/cjs/webhooks.js +213 -0
- package/dist/esm/case.d.ts +23 -0
- package/dist/esm/case.js +47 -0
- package/dist/esm/client.d.ts +98 -0
- package/dist/esm/client.js +128 -0
- package/dist/esm/errors.d.ts +63 -0
- package/dist/esm/errors.js +93 -0
- package/dist/esm/generated/schema.d.ts +14862 -0
- package/dist/esm/generated/schema.js +5 -0
- package/dist/esm/http.d.ts +104 -0
- package/dist/esm/http.js +247 -0
- package/dist/esm/index.d.ts +14 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/pagination.d.ts +31 -0
- package/dist/esm/pagination.js +49 -0
- package/dist/esm/resources.d.ts +11195 -0
- package/dist/esm/resources.js +503 -0
- package/dist/esm/runtime.d.ts +20 -0
- package/dist/esm/runtime.js +46 -0
- package/dist/esm/types.d.ts +649 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/units.d.ts +26 -0
- package/dist/esm/units.js +38 -0
- package/dist/esm/webhooks.d.ts +67 -0
- package/dist/esm/webhooks.js +208 -0
- package/package.json +51 -5
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
export declare const DEFAULT_BASE_URL = "https://api.timbereye.com/v1";
|
|
2
|
+
export declare const DEFAULT_MAX_RETRIES = 2;
|
|
3
|
+
export declare const DEFAULT_TIMEOUT_MS = 60000;
|
|
4
|
+
export type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
|
|
5
|
+
export interface ClientOptions {
|
|
6
|
+
/**
|
|
7
|
+
* The API's address. `new Timbereye()` uses this option, else `TIMBEREYE_API_URL` from the environment (where
|
|
8
|
+
* there is one), else `https://api.timbereye.com/v1`.
|
|
9
|
+
*/
|
|
10
|
+
baseUrl?: string;
|
|
11
|
+
/** Defaults to the global `fetch`. */
|
|
12
|
+
fetch?: FetchLike;
|
|
13
|
+
/** Retries after the first attempt. Default 2. */
|
|
14
|
+
maxRetries?: number;
|
|
15
|
+
/**
|
|
16
|
+
* The longest `Retry-After` the client waits out before retrying, in milliseconds. A response that asks for a
|
|
17
|
+
* longer wait (an hourly or daily limit) is not retried: its error is thrown at once, with `retryAfterSeconds`.
|
|
18
|
+
* Set it where a person is waiting for an answer. Unset, the client waits at most 60 s and retries.
|
|
19
|
+
*/
|
|
20
|
+
maxRetryWaitMs?: number;
|
|
21
|
+
/** Per-attempt timeout in milliseconds. Default 60000. */
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
/** Dashboard session tokens only: sends `Timbereye-Mode`. API keys carry their mode in the key. */
|
|
24
|
+
mode?: "live" | "test";
|
|
25
|
+
/** Allow a secret or restricted key in a browser. Do not: ship capture tokens to browsers instead. */
|
|
26
|
+
dangerouslyAllowBrowser?: boolean;
|
|
27
|
+
/** Advanced (used by tests): replaces the backoff sleep. */
|
|
28
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
29
|
+
/** Advanced (used by tests): replaces `Math.random` in backoff jitter. */
|
|
30
|
+
random?: () => number;
|
|
31
|
+
}
|
|
32
|
+
export interface RequestOptions {
|
|
33
|
+
/** Overrides the automatic `Idempotency-Key`. Also the way to set one on PATCH, PUT and DELETE. */
|
|
34
|
+
idempotencyKey?: string;
|
|
35
|
+
/** Per-attempt timeout for this call. */
|
|
36
|
+
timeoutMs?: number;
|
|
37
|
+
/** Retries for this call. */
|
|
38
|
+
maxRetries?: number;
|
|
39
|
+
/** Aborts the call, including any retry wait. Aborts are never retried. */
|
|
40
|
+
signal?: AbortSignal;
|
|
41
|
+
/**
|
|
42
|
+
* Called with the status and headers of every response the call receives, including failed attempts that
|
|
43
|
+
* are retried, before the result or error is returned. For the request id, `Idempotent-Replayed` and the
|
|
44
|
+
* rate-limit headers. It must not throw; an exception from it is ignored.
|
|
45
|
+
*/
|
|
46
|
+
onResponse?: (response: ResponseInfo) => void;
|
|
47
|
+
}
|
|
48
|
+
/** What `onResponse` receives. */
|
|
49
|
+
export interface ResponseInfo {
|
|
50
|
+
status: number;
|
|
51
|
+
/** The `Request-Id` header, for support. */
|
|
52
|
+
requestId: string | null;
|
|
53
|
+
/** `true` when the server answered from a stored response for the same `Idempotency-Key`. */
|
|
54
|
+
idempotentReplayed: boolean;
|
|
55
|
+
/** `RateLimit-Limit` and `RateLimit-Remaining`, when sent. */
|
|
56
|
+
rateLimit: {
|
|
57
|
+
limit: number | null;
|
|
58
|
+
remaining: number | null;
|
|
59
|
+
};
|
|
60
|
+
/** All response headers, names lower-cased. */
|
|
61
|
+
headers: Record<string, string>;
|
|
62
|
+
/** The `Idempotency-Key` this call sent, when it sent one. */
|
|
63
|
+
idempotencyKey: string | null;
|
|
64
|
+
}
|
|
65
|
+
export interface Operation {
|
|
66
|
+
method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
|
|
67
|
+
path: string;
|
|
68
|
+
query?: Record<string, unknown>;
|
|
69
|
+
body?: unknown;
|
|
70
|
+
form?: FormData;
|
|
71
|
+
/** For POSTs that only compute (`/places/validate`): the API ignores an idempotency key. */
|
|
72
|
+
noIdempotency?: boolean;
|
|
73
|
+
headers?: Record<string, string>;
|
|
74
|
+
/** The answer is a file (a PDF), not JSON: the call resolves to a `BinaryResponse`. */
|
|
75
|
+
binary?: boolean;
|
|
76
|
+
}
|
|
77
|
+
/** A file the API answered with (`application/pdf`): its bytes, type and the file name it suggests. */
|
|
78
|
+
export interface BinaryResponse {
|
|
79
|
+
data: Uint8Array;
|
|
80
|
+
contentType: string;
|
|
81
|
+
/** From `Content-Disposition`, when the API names one. */
|
|
82
|
+
fileName: string | null;
|
|
83
|
+
}
|
|
84
|
+
/** Seconds or an HTTP date, as milliseconds; null when absent or unparseable. */
|
|
85
|
+
export declare function parseRetryAfter(value: string | null, nowMs?: number): number | null;
|
|
86
|
+
export declare class Transport {
|
|
87
|
+
private readonly apiKey;
|
|
88
|
+
private readonly options;
|
|
89
|
+
readonly baseUrl: string;
|
|
90
|
+
private readonly fetchImpl;
|
|
91
|
+
private readonly maxRetries;
|
|
92
|
+
private readonly timeoutMs;
|
|
93
|
+
private readonly sleep;
|
|
94
|
+
private readonly random;
|
|
95
|
+
constructor(apiKey: string, options?: ClientOptions);
|
|
96
|
+
request<T>(op: Operation, opts?: RequestOptions): Promise<T>;
|
|
97
|
+
private backoff;
|
|
98
|
+
private attempt;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Retry policy for responses: 429, 5xx except 501 (an operation the server has not built; retrying cannot
|
|
102
|
+
* help), and 409 only while a request with the same key is in flight.
|
|
103
|
+
*/
|
|
104
|
+
export declare function shouldRetryStatus(status: number, code: string | null): boolean;
|
package/dist/esm/http.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { camelToSnake, toCamel, toSnake } from "./case.js";
|
|
2
|
+
import { AbortError, ConnectionError, TimeoutError, errorFromResponse, RateLimitError, TimbereyeError, } from "./errors.js";
|
|
3
|
+
import { randomUUID } from "./runtime.js";
|
|
4
|
+
export const DEFAULT_BASE_URL = "https://api.timbereye.com/v1";
|
|
5
|
+
export const DEFAULT_MAX_RETRIES = 2;
|
|
6
|
+
export const DEFAULT_TIMEOUT_MS = 60000;
|
|
7
|
+
const MAX_BACKOFF_MS = 8000;
|
|
8
|
+
const BASE_BACKOFF_MS = 500;
|
|
9
|
+
const MAX_RETRY_AFTER_MS = 60000;
|
|
10
|
+
function defaultSleep(ms, signal) {
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
if (signal?.aborted)
|
|
13
|
+
return reject(new AbortError());
|
|
14
|
+
const t = setTimeout(() => {
|
|
15
|
+
signal?.removeEventListener("abort", onAbort);
|
|
16
|
+
resolve();
|
|
17
|
+
}, ms);
|
|
18
|
+
const onAbort = () => {
|
|
19
|
+
clearTimeout(t);
|
|
20
|
+
reject(new AbortError());
|
|
21
|
+
};
|
|
22
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
/** Seconds or an HTTP date, as milliseconds; null when absent or unparseable. */
|
|
26
|
+
export function parseRetryAfter(value, nowMs = Date.now()) {
|
|
27
|
+
if (value === null || value.trim() === "")
|
|
28
|
+
return null;
|
|
29
|
+
if (/^\d+(\.\d+)?$/.test(value.trim()))
|
|
30
|
+
return Math.round(Number(value) * 1000);
|
|
31
|
+
const at = Date.parse(value);
|
|
32
|
+
return Number.isNaN(at) ? null : Math.max(0, at - nowMs);
|
|
33
|
+
}
|
|
34
|
+
function buildQuery(query) {
|
|
35
|
+
if (!query)
|
|
36
|
+
return "";
|
|
37
|
+
const sp = new URLSearchParams();
|
|
38
|
+
for (const [k, v] of Object.entries(toSnake(query))) {
|
|
39
|
+
if (v === undefined || v === null)
|
|
40
|
+
continue;
|
|
41
|
+
if (k === "expand") {
|
|
42
|
+
// `expand[]=a&expand[]=b`; values are field names, so accept camelCase for them too.
|
|
43
|
+
for (const e of v)
|
|
44
|
+
sp.append("expand[]", camelToSnake(e));
|
|
45
|
+
}
|
|
46
|
+
else if (Array.isArray(v)) {
|
|
47
|
+
for (const e of v)
|
|
48
|
+
sp.append(k, String(e));
|
|
49
|
+
}
|
|
50
|
+
else if (typeof v === "object") {
|
|
51
|
+
// `metadata[booking]=B123`: a free-form map keeps its keys exactly as given.
|
|
52
|
+
for (const [mk, mv] of Object.entries(v))
|
|
53
|
+
sp.append(`${k}[${mk}]`, String(mv));
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
sp.append(k, String(v));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const s = sp.toString();
|
|
60
|
+
return s ? `?${s}` : "";
|
|
61
|
+
}
|
|
62
|
+
export class Transport {
|
|
63
|
+
constructor(apiKey, options = {}) {
|
|
64
|
+
this.apiKey = apiKey;
|
|
65
|
+
this.options = options;
|
|
66
|
+
if (typeof apiKey !== "string" || apiKey.trim() === "") {
|
|
67
|
+
throw new TimbereyeError({ message: "A Timbereye API key is required", type: "client_error" });
|
|
68
|
+
}
|
|
69
|
+
const inBrowser = typeof window !== "undefined" &&
|
|
70
|
+
typeof globalThis.document !== "undefined";
|
|
71
|
+
if (inBrowser && /^te_(live|test)_(sk|rk)_/.test(apiKey) && !options.dangerouslyAllowBrowser) {
|
|
72
|
+
throw new TimbereyeError({
|
|
73
|
+
message: "Refusing to use a secret or restricted key in a browser. Mint a capture token on your server instead, or set dangerouslyAllowBrowser.",
|
|
74
|
+
type: "client_error",
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
78
|
+
this.fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
79
|
+
this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
80
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
81
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
82
|
+
this.random = options.random ?? Math.random;
|
|
83
|
+
}
|
|
84
|
+
async request(op, opts = {}) {
|
|
85
|
+
const url = this.baseUrl + op.path + buildQuery(op.query);
|
|
86
|
+
const headers = {
|
|
87
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
88
|
+
Accept: op.binary ? "application/pdf, application/json" : "application/json",
|
|
89
|
+
...op.headers,
|
|
90
|
+
};
|
|
91
|
+
if (this.options.mode)
|
|
92
|
+
headers["Timbereye-Mode"] = this.options.mode;
|
|
93
|
+
let body;
|
|
94
|
+
if (op.form)
|
|
95
|
+
body = op.form;
|
|
96
|
+
else if (op.body !== undefined) {
|
|
97
|
+
body = JSON.stringify(toSnake(op.body));
|
|
98
|
+
headers["Content-Type"] = "application/json";
|
|
99
|
+
}
|
|
100
|
+
// One key per logical call, reused by every retry of it.
|
|
101
|
+
const key = opts.idempotencyKey ?? (op.method === "POST" && !op.noIdempotency ? randomUUID() : undefined);
|
|
102
|
+
if (key !== undefined)
|
|
103
|
+
headers["Idempotency-Key"] = key;
|
|
104
|
+
const maxRetries = opts.maxRetries ?? this.maxRetries;
|
|
105
|
+
const timeoutMs = opts.timeoutMs ?? this.timeoutMs;
|
|
106
|
+
for (let attempt = 0;; attempt++) {
|
|
107
|
+
if (opts.signal?.aborted)
|
|
108
|
+
throw new AbortError();
|
|
109
|
+
let failure;
|
|
110
|
+
let retryAfterMs = null;
|
|
111
|
+
let res;
|
|
112
|
+
try {
|
|
113
|
+
res = await this.attempt(url, { method: op.method, headers, body }, timeoutMs, opts.signal, op.binary === true);
|
|
114
|
+
}
|
|
115
|
+
catch (e) {
|
|
116
|
+
if (e instanceof AbortError)
|
|
117
|
+
throw e;
|
|
118
|
+
failure = e; // attempt() only throws AbortError or ConnectionError
|
|
119
|
+
}
|
|
120
|
+
if (res) {
|
|
121
|
+
notify(opts.onResponse, res, key ?? null);
|
|
122
|
+
if (res.status >= 200 && res.status < 300 && op.binary && res.bytes) {
|
|
123
|
+
const disposition = res.headers["content-disposition"] ?? "";
|
|
124
|
+
const named = /filename="?([^";]+)"?/i.exec(disposition);
|
|
125
|
+
const file = {
|
|
126
|
+
data: res.bytes,
|
|
127
|
+
contentType: res.headers["content-type"] ?? "application/octet-stream",
|
|
128
|
+
fileName: named ? named[1] : null,
|
|
129
|
+
};
|
|
130
|
+
return file;
|
|
131
|
+
}
|
|
132
|
+
if (res.status >= 200 && res.status < 300) {
|
|
133
|
+
try {
|
|
134
|
+
return toCamel(JSON.parse(res.text));
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
throw new TimbereyeError({
|
|
138
|
+
message: "Response was not valid JSON",
|
|
139
|
+
type: "api_error",
|
|
140
|
+
status: res.status,
|
|
141
|
+
requestId: res.requestId,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
let parsed = null;
|
|
146
|
+
try {
|
|
147
|
+
parsed = JSON.parse(res.text);
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
// non-JSON error body (a proxy's HTML page); fall back to the status
|
|
151
|
+
}
|
|
152
|
+
failure = errorFromResponse(res.status, parsed, res.requestId);
|
|
153
|
+
retryAfterMs = parseRetryAfter(res.retryAfter);
|
|
154
|
+
if (failure instanceof RateLimitError && retryAfterMs !== null)
|
|
155
|
+
failure.retryAfterSeconds = retryAfterMs / 1000;
|
|
156
|
+
if (!shouldRetryStatus(res.status, failure.code))
|
|
157
|
+
throw failure;
|
|
158
|
+
}
|
|
159
|
+
if (attempt >= maxRetries)
|
|
160
|
+
throw failure;
|
|
161
|
+
const maxWaitMs = this.options.maxRetryWaitMs;
|
|
162
|
+
if (maxWaitMs !== undefined && retryAfterMs !== null && retryAfterMs > maxWaitMs)
|
|
163
|
+
throw failure;
|
|
164
|
+
await this.sleep(retryAfterMs !== null ? Math.min(retryAfterMs, MAX_RETRY_AFTER_MS) : this.backoff(attempt), opts.signal);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
backoff(attempt) {
|
|
168
|
+
const ceiling = Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** attempt);
|
|
169
|
+
return Math.round(ceiling * (0.5 + 0.5 * this.random()));
|
|
170
|
+
}
|
|
171
|
+
async attempt(url, init, timeoutMs, signal, binary = false) {
|
|
172
|
+
const controller = new AbortController();
|
|
173
|
+
let timedOut = false;
|
|
174
|
+
const timer = setTimeout(() => {
|
|
175
|
+
timedOut = true;
|
|
176
|
+
controller.abort();
|
|
177
|
+
}, timeoutMs);
|
|
178
|
+
const onAbort = () => controller.abort();
|
|
179
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
180
|
+
try {
|
|
181
|
+
const res = await this.fetchImpl(url, { ...init, signal: controller.signal });
|
|
182
|
+
// A file is read as bytes; an error is JSON whatever was asked for.
|
|
183
|
+
const bytes = binary && res.status >= 200 && res.status < 300
|
|
184
|
+
? new Uint8Array(await res.arrayBuffer())
|
|
185
|
+
: undefined;
|
|
186
|
+
const text = bytes === undefined ? await res.text() : "";
|
|
187
|
+
return {
|
|
188
|
+
status: res.status,
|
|
189
|
+
text,
|
|
190
|
+
bytes,
|
|
191
|
+
requestId: res.headers.get("Request-Id"),
|
|
192
|
+
retryAfter: res.headers.get("Retry-After"),
|
|
193
|
+
headers: headersOf(res.headers),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
catch (e) {
|
|
197
|
+
if (signal?.aborted)
|
|
198
|
+
throw new AbortError();
|
|
199
|
+
if (timedOut)
|
|
200
|
+
throw new TimeoutError(timeoutMs);
|
|
201
|
+
if (e instanceof ConnectionError)
|
|
202
|
+
throw e;
|
|
203
|
+
throw new ConnectionError(`Could not reach the Timbereye API: ${e?.message ?? String(e)}`, e);
|
|
204
|
+
}
|
|
205
|
+
finally {
|
|
206
|
+
clearTimeout(timer);
|
|
207
|
+
signal?.removeEventListener("abort", onAbort);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
function headersOf(h) {
|
|
212
|
+
const out = {};
|
|
213
|
+
h.forEach((value, key) => {
|
|
214
|
+
out[key.toLowerCase()] = value;
|
|
215
|
+
});
|
|
216
|
+
return out;
|
|
217
|
+
}
|
|
218
|
+
function notify(callback, res, idempotencyKey) {
|
|
219
|
+
if (!callback)
|
|
220
|
+
return;
|
|
221
|
+
const number = (name) => {
|
|
222
|
+
const v = res.headers[name];
|
|
223
|
+
return v !== undefined && /^\d+$/.test(v) ? Number(v) : null;
|
|
224
|
+
};
|
|
225
|
+
try {
|
|
226
|
+
callback({
|
|
227
|
+
status: res.status,
|
|
228
|
+
requestId: res.requestId,
|
|
229
|
+
idempotentReplayed: res.headers["idempotent-replayed"] === "true",
|
|
230
|
+
rateLimit: { limit: number("ratelimit-limit"), remaining: number("ratelimit-remaining") },
|
|
231
|
+
headers: res.headers,
|
|
232
|
+
idempotencyKey,
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
// a faulty observer must not break the call
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Retry policy for responses: 429, 5xx except 501 (an operation the server has not built; retrying cannot
|
|
241
|
+
* help), and 409 only while a request with the same key is in flight.
|
|
242
|
+
*/
|
|
243
|
+
export function shouldRetryStatus(status, code) {
|
|
244
|
+
if (status === 429 || (status >= 500 && status !== 501))
|
|
245
|
+
return true;
|
|
246
|
+
return status === 409 && code === "idempotency_request_in_progress";
|
|
247
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export { Timbereye } from "./client.js";
|
|
2
|
+
export { Timbereye as default } from "./client.js";
|
|
3
|
+
export type { ClientOptions, RequestOptions, ResponseInfo, FetchLike } from "./http.js";
|
|
4
|
+
export type { TimbereyeOptions, WebhookHelpers, WebhookResponse, WebhookRouteHandler } from "./client.js";
|
|
5
|
+
export { TimbereyeError, InvalidRequestError, AuthenticationError, PermissionError, RateLimitError, ApiError, ConnectionError, TimeoutError, AbortError, WebhookSignatureError, } from "./errors.js";
|
|
6
|
+
export type { ErrorType } from "./errors.js";
|
|
7
|
+
export type { Page, PagedResult, ListResult, AutoPaging } from "./pagination.js";
|
|
8
|
+
export { verifyWebhook, generateTestWebhookHeaders } from "./webhooks.js";
|
|
9
|
+
export type { VerifyOptions, HeadersInput, WebhookRequest, TestWebhookParams } from "./webhooks.js";
|
|
10
|
+
export { formatLength, formatDiameter, formatWeight, formatVolume } from "./units.js";
|
|
11
|
+
export type { DisplayUnits, UnitsSource } from "./units.js";
|
|
12
|
+
export { toCamel, toSnake } from "./case.js";
|
|
13
|
+
export type { Camel } from "./case.js";
|
|
14
|
+
export type * from "./types.js";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { Timbereye } from "./client.js";
|
|
2
|
+
export { Timbereye as default } from "./client.js";
|
|
3
|
+
export { TimbereyeError, InvalidRequestError, AuthenticationError, PermissionError, RateLimitError, ApiError, ConnectionError, TimeoutError, AbortError, WebhookSignatureError, } from "./errors.js";
|
|
4
|
+
export { verifyWebhook, generateTestWebhookHeaders } from "./webhooks.js";
|
|
5
|
+
export { formatLength, formatDiameter, formatWeight, formatVolume } from "./units.js";
|
|
6
|
+
export { toCamel, toSnake } from "./case.js";
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { RequestOptions } from "./http.js";
|
|
2
|
+
export interface Page<T> {
|
|
3
|
+
object: "list";
|
|
4
|
+
data: T[];
|
|
5
|
+
hasMore: boolean;
|
|
6
|
+
nextCursor: string | null;
|
|
7
|
+
}
|
|
8
|
+
/** The ways to walk a list beyond its first page. */
|
|
9
|
+
export interface AutoPaging<T> extends AsyncIterable<T> {
|
|
10
|
+
/** Call `fn` for each item; return `false` from it to stop early. */
|
|
11
|
+
autoPagingEach(fn: (item: T) => void | boolean | Promise<void | boolean>): Promise<void>;
|
|
12
|
+
/** Collect items across pages, stopping at `limit` items. */
|
|
13
|
+
autoPagingToArray(opts: {
|
|
14
|
+
limit: number;
|
|
15
|
+
}): Promise<T[]>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A page that can also continue: `for await (const item of page)` walks this page's items and then every later
|
|
19
|
+
* page. The extra members are not enumerable, so the page still serialises (JSON, spread) as a plain `Page`, and
|
|
20
|
+
* they survive being returned from an `async` function, which a bare `ListResult` does not.
|
|
21
|
+
*/
|
|
22
|
+
export type PagedResult<T> = Page<T> & AutoPaging<T>;
|
|
23
|
+
/**
|
|
24
|
+
* What every list method returns: await it for one page (itself iterable, see {@link PagedResult}), or
|
|
25
|
+
* `for await` it directly to walk every item across pages (`startingAfter` is advanced with each page's
|
|
26
|
+
* `nextCursor`).
|
|
27
|
+
*/
|
|
28
|
+
export type ListResult<T> = Promise<PagedResult<T>> & AutoPaging<T>;
|
|
29
|
+
export declare function makeList<T, P extends {
|
|
30
|
+
startingAfter?: string;
|
|
31
|
+
}>(fetchPage: (params: P, opts?: RequestOptions) => Promise<Page<T>>, params: P | undefined, opts: RequestOptions | undefined): ListResult<T>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
function define(target, key, value) {
|
|
2
|
+
Object.defineProperty(target, key, { value, enumerable: false, configurable: true, writable: true });
|
|
3
|
+
}
|
|
4
|
+
export function makeList(fetchPage, params, opts) {
|
|
5
|
+
const p0 = (params ?? {});
|
|
6
|
+
// Adds the walking members to a page; the next page is fetched, and decorated, on demand.
|
|
7
|
+
const decorate = (page) => {
|
|
8
|
+
async function* iterate() {
|
|
9
|
+
let current = page;
|
|
10
|
+
for (;;) {
|
|
11
|
+
for (const item of current.data)
|
|
12
|
+
yield item;
|
|
13
|
+
if (!current.hasMore || !current.nextCursor)
|
|
14
|
+
return;
|
|
15
|
+
current = await fetchPage({ ...p0, startingAfter: current.nextCursor }, opts);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const each = async (fn) => {
|
|
19
|
+
for await (const item of iterate()) {
|
|
20
|
+
if ((await fn(item)) === false)
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
const toArray = async ({ limit }) => {
|
|
25
|
+
if (!Number.isInteger(limit) || limit < 1)
|
|
26
|
+
throw new RangeError("autoPagingToArray needs a positive integer limit");
|
|
27
|
+
const out = [];
|
|
28
|
+
for await (const item of iterate()) {
|
|
29
|
+
out.push(item);
|
|
30
|
+
if (out.length >= limit)
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
};
|
|
35
|
+
define(page, Symbol.asyncIterator, iterate);
|
|
36
|
+
define(page, "autoPagingEach", each);
|
|
37
|
+
define(page, "autoPagingToArray", toArray);
|
|
38
|
+
return page;
|
|
39
|
+
};
|
|
40
|
+
const first = fetchPage(p0, opts).then(decorate);
|
|
41
|
+
// The promise carries the same members, so `list().autoPagingToArray(...)` works without awaiting first.
|
|
42
|
+
const result = first;
|
|
43
|
+
result[Symbol.asyncIterator] = async function* () {
|
|
44
|
+
yield* await first;
|
|
45
|
+
};
|
|
46
|
+
result.autoPagingEach = async (fn) => (await first).autoPagingEach(fn);
|
|
47
|
+
result.autoPagingToArray = async (o) => (await first).autoPagingToArray(o);
|
|
48
|
+
return result;
|
|
49
|
+
}
|