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