@chatwise/node 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.
- package/CHANGELOG.md +12 -0
- package/LICENSE +202 -0
- package/README.md +506 -2
- package/dist/cjs/client.d.ts +20 -0
- package/dist/cjs/client.js +32 -0
- package/dist/cjs/core/errors.d.ts +91 -0
- package/dist/cjs/core/errors.js +131 -0
- package/dist/cjs/core/http.d.ts +74 -0
- package/dist/cjs/core/http.js +336 -0
- package/dist/cjs/core/pagination.d.ts +35 -0
- package/dist/cjs/core/pagination.js +101 -0
- package/dist/cjs/generated/types.d.ts +969 -0
- package/dist/cjs/generated/types.js +3 -0
- package/dist/cjs/index.d.ts +15 -0
- package/dist/cjs/index.js +25 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/resources/conversations.d.ts +20 -0
- package/dist/cjs/resources/conversations.js +32 -0
- package/dist/cjs/resources/messages.d.ts +46 -0
- package/dist/cjs/resources/messages.js +60 -0
- package/dist/cjs/resources/webhook-deliveries.d.ts +27 -0
- package/dist/cjs/resources/webhook-deliveries.js +42 -0
- package/dist/cjs/resources/webhook-endpoints.d.ts +54 -0
- package/dist/cjs/resources/webhook-endpoints.js +82 -0
- package/dist/cjs/resources/webhook-event-types.d.ts +13 -0
- package/dist/cjs/resources/webhook-event-types.js +22 -0
- package/dist/cjs/resources/whatsapp-templates.d.ts +48 -0
- package/dist/cjs/resources/whatsapp-templates.js +69 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +74 -0
- package/dist/cjs/webhooks.js +123 -0
- package/dist/esm/client.d.ts +20 -0
- package/dist/esm/client.js +28 -0
- package/dist/esm/core/errors.d.ts +91 -0
- package/dist/esm/core/errors.js +113 -0
- package/dist/esm/core/http.d.ts +74 -0
- package/dist/esm/core/http.js +332 -0
- package/dist/esm/core/pagination.d.ts +35 -0
- package/dist/esm/core/pagination.js +95 -0
- package/dist/esm/generated/types.d.ts +969 -0
- package/dist/esm/generated/types.js +2 -0
- package/dist/esm/index.d.ts +15 -0
- package/dist/esm/index.js +4 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/resources/conversations.d.ts +20 -0
- package/dist/esm/resources/conversations.js +28 -0
- package/dist/esm/resources/messages.d.ts +46 -0
- package/dist/esm/resources/messages.js +56 -0
- package/dist/esm/resources/webhook-deliveries.d.ts +27 -0
- package/dist/esm/resources/webhook-deliveries.js +38 -0
- package/dist/esm/resources/webhook-endpoints.d.ts +54 -0
- package/dist/esm/resources/webhook-endpoints.js +78 -0
- package/dist/esm/resources/webhook-event-types.d.ts +13 -0
- package/dist/esm/resources/webhook-event-types.js +18 -0
- package/dist/esm/resources/whatsapp-templates.d.ts +48 -0
- package/dist/esm/resources/whatsapp-templates.js +65 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +74 -0
- package/dist/esm/webhooks.js +118 -0
- package/package.json +79 -4
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RequestAbortedError = exports.RequestTimeoutError = exports.ConnectionError = exports.ServerError = exports.RateLimitError = exports.PayloadTooLargeError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.PaymentRequiredError = exports.AuthenticationError = exports.BadRequestError = exports.APIError = exports.ChatwiseError = void 0;
|
|
4
|
+
exports.apiError = apiError;
|
|
5
|
+
/** The base of every error this package throws. */
|
|
6
|
+
class ChatwiseError extends Error {
|
|
7
|
+
// Written out in each class, because minifiers rename classes.
|
|
8
|
+
name = 'ChatwiseError';
|
|
9
|
+
}
|
|
10
|
+
exports.ChatwiseError = ChatwiseError;
|
|
11
|
+
const text = (value) => (typeof value === 'string' && value ? value : undefined);
|
|
12
|
+
function readFieldErrors(body) {
|
|
13
|
+
if (Array.isArray(body.errors)) {
|
|
14
|
+
return body.errors.flatMap((entry) => typeof entry?.path === 'string' && typeof entry.message === 'string' ? [{ path: entry.path, message: entry.message }] : []);
|
|
15
|
+
}
|
|
16
|
+
const field = text(body.field);
|
|
17
|
+
return field ? [{ path: field, message: text(body.message) ?? '' }] : [];
|
|
18
|
+
}
|
|
19
|
+
/** Chatwise answered with an error. Each status has a subclass. */
|
|
20
|
+
class APIError extends ChatwiseError {
|
|
21
|
+
name = 'APIError';
|
|
22
|
+
/** The HTTP status. */
|
|
23
|
+
status;
|
|
24
|
+
/** A code to check in your program, such as `TEMPLATE_EXISTS`, when the error has one. */
|
|
25
|
+
code;
|
|
26
|
+
/** What was wrong with which field, when the API says so. */
|
|
27
|
+
fieldErrors;
|
|
28
|
+
/** Quote it when you contact support. Only some 500s have one. */
|
|
29
|
+
errorId;
|
|
30
|
+
/** How long the API asks to wait before another request, in milliseconds. From `Retry-After`. */
|
|
31
|
+
retryAfterMs;
|
|
32
|
+
method;
|
|
33
|
+
/** The path of the request, without its query. */
|
|
34
|
+
path;
|
|
35
|
+
/** The parsed body of the response, or its text when it wasn't JSON. */
|
|
36
|
+
body;
|
|
37
|
+
constructor({ status, method, path, body, retryAfterMs }) {
|
|
38
|
+
const fields = typeof body === 'object' && body !== null ? body : {};
|
|
39
|
+
const fieldErrors = readFieldErrors(fields);
|
|
40
|
+
let message = text(fields.message) ?? `Chatwise answered ${status} to ${method} ${path}`;
|
|
41
|
+
if (Array.isArray(fields.errors) && fieldErrors.length) {
|
|
42
|
+
message += ` (${fieldErrors.map((error) => `${error.path}: ${error.message}`).join('; ')})`;
|
|
43
|
+
}
|
|
44
|
+
super(message);
|
|
45
|
+
this.status = status;
|
|
46
|
+
this.code = text(fields.code);
|
|
47
|
+
this.fieldErrors = fieldErrors;
|
|
48
|
+
this.errorId = text(fields.errorId);
|
|
49
|
+
this.retryAfterMs = retryAfterMs;
|
|
50
|
+
this.method = method;
|
|
51
|
+
this.path = path;
|
|
52
|
+
this.body = body;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
exports.APIError = APIError;
|
|
56
|
+
/** 400: a parameter, field, cursor or id is invalid. `fieldErrors` says which. */
|
|
57
|
+
class BadRequestError extends APIError {
|
|
58
|
+
name = 'BadRequestError';
|
|
59
|
+
}
|
|
60
|
+
exports.BadRequestError = BadRequestError;
|
|
61
|
+
/**
|
|
62
|
+
* 401: the API key is missing, invalid, expired or revoked. With the message `Invalid API key`, Chatwise
|
|
63
|
+
* couldn't check the key: try again.
|
|
64
|
+
*/
|
|
65
|
+
class AuthenticationError extends APIError {
|
|
66
|
+
name = 'AuthenticationError';
|
|
67
|
+
}
|
|
68
|
+
exports.AuthenticationError = AuthenticationError;
|
|
69
|
+
/** 402: sending is paused for the workspace. */
|
|
70
|
+
class PaymentRequiredError extends APIError {
|
|
71
|
+
name = 'PaymentRequiredError';
|
|
72
|
+
}
|
|
73
|
+
exports.PaymentRequiredError = PaymentRequiredError;
|
|
74
|
+
/** 403: the key lacks a scope, or WhatsApp has to be reconnected (`code` is `WHATSAPP_REAUTH_REQUIRED`). */
|
|
75
|
+
class PermissionDeniedError extends APIError {
|
|
76
|
+
name = 'PermissionDeniedError';
|
|
77
|
+
}
|
|
78
|
+
exports.PermissionDeniedError = PermissionDeniedError;
|
|
79
|
+
/** 404: it doesn't exist in the key's workspace. */
|
|
80
|
+
class NotFoundError extends APIError {
|
|
81
|
+
name = 'NotFoundError';
|
|
82
|
+
}
|
|
83
|
+
exports.NotFoundError = NotFoundError;
|
|
84
|
+
/** 409: a template submission conflicts with an earlier one. `code` says how. */
|
|
85
|
+
class ConflictError extends APIError {
|
|
86
|
+
name = 'ConflictError';
|
|
87
|
+
}
|
|
88
|
+
exports.ConflictError = ConflictError;
|
|
89
|
+
/** 413: the request body is larger than 100 KB. */
|
|
90
|
+
class PayloadTooLargeError extends APIError {
|
|
91
|
+
name = 'PayloadTooLargeError';
|
|
92
|
+
}
|
|
93
|
+
exports.PayloadTooLargeError = PayloadTooLargeError;
|
|
94
|
+
/** 429: too many requests with this key. Wait `retryAfterMs`. */
|
|
95
|
+
class RateLimitError extends APIError {
|
|
96
|
+
name = 'RateLimitError';
|
|
97
|
+
}
|
|
98
|
+
exports.RateLimitError = RateLimitError;
|
|
99
|
+
/** 5xx: something failed in Chatwise, or WhatsApp refused a message. The request may have been carried out. */
|
|
100
|
+
class ServerError extends APIError {
|
|
101
|
+
name = 'ServerError';
|
|
102
|
+
}
|
|
103
|
+
exports.ServerError = ServerError;
|
|
104
|
+
/** There was no complete answer: the network failed, or the answer was cut off. The request may have been carried out. */
|
|
105
|
+
class ConnectionError extends ChatwiseError {
|
|
106
|
+
name = 'ConnectionError';
|
|
107
|
+
}
|
|
108
|
+
exports.ConnectionError = ConnectionError;
|
|
109
|
+
/** An attempt took longer than `timeoutMs`. The request may have been carried out. */
|
|
110
|
+
class RequestTimeoutError extends ConnectionError {
|
|
111
|
+
name = 'RequestTimeoutError';
|
|
112
|
+
}
|
|
113
|
+
exports.RequestTimeoutError = RequestTimeoutError;
|
|
114
|
+
/** Your `signal` aborted the request. The request may have been carried out. `cause` is the signal's reason. */
|
|
115
|
+
class RequestAbortedError extends ChatwiseError {
|
|
116
|
+
name = 'RequestAbortedError';
|
|
117
|
+
}
|
|
118
|
+
exports.RequestAbortedError = RequestAbortedError;
|
|
119
|
+
function apiError(details) {
|
|
120
|
+
switch (details.status) {
|
|
121
|
+
case 400: return new BadRequestError(details);
|
|
122
|
+
case 401: return new AuthenticationError(details);
|
|
123
|
+
case 402: return new PaymentRequiredError(details);
|
|
124
|
+
case 403: return new PermissionDeniedError(details);
|
|
125
|
+
case 404: return new NotFoundError(details);
|
|
126
|
+
case 409: return new ConflictError(details);
|
|
127
|
+
case 413: return new PayloadTooLargeError(details);
|
|
128
|
+
case 429: return new RateLimitError(details);
|
|
129
|
+
default: return details.status >= 500 ? new ServerError(details) : new APIError(details);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** An `AbortSignal`. */
|
|
2
|
+
export interface AbortSignalLike {
|
|
3
|
+
readonly aborted: boolean;
|
|
4
|
+
readonly reason?: unknown;
|
|
5
|
+
addEventListener(type: 'abort', listener: () => void): void;
|
|
6
|
+
removeEventListener(type: 'abort', listener: () => void): void;
|
|
7
|
+
}
|
|
8
|
+
/** A `fetch` response. */
|
|
9
|
+
export interface ResponseLike {
|
|
10
|
+
readonly status: number;
|
|
11
|
+
readonly headers: {
|
|
12
|
+
get(name: string): string | null;
|
|
13
|
+
};
|
|
14
|
+
/** A `ReadableStream`. An answer without one is read with `text()`, however long it is. */
|
|
15
|
+
readonly body?: unknown;
|
|
16
|
+
text(): Promise<string>;
|
|
17
|
+
}
|
|
18
|
+
/** A `fetch` function, such as the global one. It receives the API key, in the `Authorization` header. */
|
|
19
|
+
export type FetchLike = (url: string, init: {
|
|
20
|
+
method: string;
|
|
21
|
+
headers: Record<string, string>;
|
|
22
|
+
body?: string;
|
|
23
|
+
redirect: 'manual';
|
|
24
|
+
signal: any;
|
|
25
|
+
}) => Promise<ResponseLike>;
|
|
26
|
+
export interface ChatwiseOptions {
|
|
27
|
+
/** The API key. Without it, the `CHATWISE_API_KEY` environment variable. */
|
|
28
|
+
apiKey?: string | undefined;
|
|
29
|
+
/**
|
|
30
|
+
* Where the API is. It must be https, except on this machine.
|
|
31
|
+
* @defaultValue 'https://api.chatwise.so'
|
|
32
|
+
*/
|
|
33
|
+
baseUrl?: string | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* How long one attempt may take, in milliseconds. Waits between attempts don't count.
|
|
36
|
+
* @defaultValue 60000
|
|
37
|
+
*/
|
|
38
|
+
timeoutMs?: number | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* How many times to retry what is safe to retry: reads, and creating a template, after a 429, a 5xx or
|
|
41
|
+
* a network error; anything else only after a 429, because such a request wasn't carried out.
|
|
42
|
+
* @defaultValue 2
|
|
43
|
+
*/
|
|
44
|
+
maxRetries?: number | undefined;
|
|
45
|
+
/** A `fetch` to use instead of the global one. */
|
|
46
|
+
fetch?: FetchLike | undefined;
|
|
47
|
+
}
|
|
48
|
+
/** Options of a single call. */
|
|
49
|
+
export interface RequestOptions {
|
|
50
|
+
/** Aborts the call, including its waits between attempts. */
|
|
51
|
+
signal?: AbortSignalLike | undefined;
|
|
52
|
+
/** How long one attempt may take, in milliseconds. Overrides the client's. */
|
|
53
|
+
timeoutMs?: number | undefined;
|
|
54
|
+
/** How many times to retry what is safe to retry. Overrides the client's. */
|
|
55
|
+
maxRetries?: number | undefined;
|
|
56
|
+
}
|
|
57
|
+
export interface Operation {
|
|
58
|
+
method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
|
59
|
+
path: string;
|
|
60
|
+
query?: object | undefined;
|
|
61
|
+
body?: object | undefined;
|
|
62
|
+
headers?: Record<string, string> | undefined;
|
|
63
|
+
/** The route takes an idempotency key, so repeating it can't do it twice. */
|
|
64
|
+
idempotent?: boolean;
|
|
65
|
+
}
|
|
66
|
+
/** Makes a request and returns the body of its answer. */
|
|
67
|
+
export type Requester = (operation: Operation, options?: RequestOptions) => Promise<Record<string, unknown>>;
|
|
68
|
+
/** A path with its ids. An id that would change the path, such as `..`, is refused. */
|
|
69
|
+
export declare function path(strings: TemplateStringsArray, ...ids: string[]): string;
|
|
70
|
+
/**
|
|
71
|
+
* The function every resource makes its requests with. The key stays in this closure: it is on no
|
|
72
|
+
* object, so printing a client can't show it.
|
|
73
|
+
*/
|
|
74
|
+
export declare function createRequester(options: ChatwiseOptions): Requester;
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.path = path;
|
|
4
|
+
exports.createRequester = createRequester;
|
|
5
|
+
const version_js_1 = require("../version.js");
|
|
6
|
+
const errors_js_1 = require("./errors.js");
|
|
7
|
+
const DEFAULT_BASE_URL = 'https://api.chatwise.so';
|
|
8
|
+
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
9
|
+
const DEFAULT_MAX_RETRIES = 2;
|
|
10
|
+
/** The longest wait setTimeout can hold. A longer one would end at once. */
|
|
11
|
+
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
12
|
+
/** Chatwise asks for 60 seconds. A call doesn't wait for much longer than that: it fails instead. */
|
|
13
|
+
const MAX_RETRY_AFTER_MS = 90_000;
|
|
14
|
+
/** The most that is read of an answer. The API's are far smaller: compressed, a few hundred KB can hold 300 MB. */
|
|
15
|
+
const MAX_BODY_BYTES = 33_554_432; // 32 MB. Not a multiplication, which bundlers keep when nothing uses it.
|
|
16
|
+
const MAX_ERROR_BODY_BYTES = 1_048_576;
|
|
17
|
+
const REDACTED = '[redacted]';
|
|
18
|
+
function checkTimeout(value) {
|
|
19
|
+
if (!Number.isInteger(value) || value < 1 || value > MAX_TIMEOUT_MS) {
|
|
20
|
+
throw new errors_js_1.ChatwiseError(`timeoutMs must be a whole number of milliseconds from 1 to ${MAX_TIMEOUT_MS}.`);
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
function checkRetries(value) {
|
|
25
|
+
if (!Number.isInteger(value) || value < 0 || value > 10) {
|
|
26
|
+
throw new errors_js_1.ChatwiseError('maxRetries must be a whole number from 0 to 10.');
|
|
27
|
+
}
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
function checkSignal(signal) {
|
|
31
|
+
if (signal !== undefined && (typeof signal !== 'object' || signal === null || typeof signal.addEventListener !== 'function')) {
|
|
32
|
+
throw new errors_js_1.ChatwiseError('signal must be an AbortSignal. Of an AbortController, pass its `signal`.');
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function environmentKey() {
|
|
36
|
+
// Not every runtime has `process`.
|
|
37
|
+
return typeof process === 'undefined' ? undefined : process.env?.CHATWISE_API_KEY;
|
|
38
|
+
}
|
|
39
|
+
function checkKey(value) {
|
|
40
|
+
if (typeof value !== 'string' || !value.trim()) {
|
|
41
|
+
throw new errors_js_1.ChatwiseError('No API key. Pass `apiKey`, or set the CHATWISE_API_KEY environment variable.');
|
|
42
|
+
}
|
|
43
|
+
const key = value.trim();
|
|
44
|
+
// fetch refuses other characters with an error that quotes the header, and so the key.
|
|
45
|
+
if (!/^[\x21-\x7e]+$/.test(key)) {
|
|
46
|
+
throw new errors_js_1.ChatwiseError('The API key has spaces, line breaks or other characters a key can\'t have.');
|
|
47
|
+
}
|
|
48
|
+
return key;
|
|
49
|
+
}
|
|
50
|
+
function checkBaseUrl(value) {
|
|
51
|
+
let url;
|
|
52
|
+
try {
|
|
53
|
+
url = new URL(value);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
throw new errors_js_1.ChatwiseError('baseUrl is not a valid URL.');
|
|
57
|
+
}
|
|
58
|
+
const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) || url.hostname.endsWith('.localhost');
|
|
59
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {
|
|
60
|
+
throw new errors_js_1.ChatwiseError('baseUrl must be https, or the API key would be sent unencrypted. Only this machine may use http.');
|
|
61
|
+
}
|
|
62
|
+
if (url.username || url.password || url.search || url.hash) {
|
|
63
|
+
throw new errors_js_1.ChatwiseError('baseUrl can\'t have a username, password, query or fragment.');
|
|
64
|
+
}
|
|
65
|
+
return (url.origin + url.pathname).replace(/\/+$/, '');
|
|
66
|
+
}
|
|
67
|
+
/** A path with its ids. An id that would change the path, such as `..`, is refused. */
|
|
68
|
+
function path(strings, ...ids) {
|
|
69
|
+
return strings.reduce((result, part, index) => {
|
|
70
|
+
const id = ids[index - 1];
|
|
71
|
+
if (typeof id !== 'string') {
|
|
72
|
+
throw new errors_js_1.ChatwiseError('An id must be a string. Ids can be larger than a JavaScript number can hold, so keep them as strings.');
|
|
73
|
+
}
|
|
74
|
+
if (!id || id === '.' || id === '..')
|
|
75
|
+
throw new errors_js_1.ChatwiseError('An id can\'t be empty, "." or "..".');
|
|
76
|
+
let encoded;
|
|
77
|
+
try {
|
|
78
|
+
encoded = encodeURIComponent(id);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw new errors_js_1.ChatwiseError('An id can\'t have half of a character in it.');
|
|
82
|
+
}
|
|
83
|
+
return result + encoded + part;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function queryString(query = {}) {
|
|
87
|
+
const search = new URLSearchParams();
|
|
88
|
+
for (const [name, value] of Object.entries(query)) {
|
|
89
|
+
if (value === undefined)
|
|
90
|
+
continue;
|
|
91
|
+
// Leaving it out would answer with everything, when one conversation's messages were wanted.
|
|
92
|
+
if (value === null)
|
|
93
|
+
throw new errors_js_1.ChatwiseError(`${name} is null. Leave it out, or pass undefined, not to filter by it.`);
|
|
94
|
+
if (value instanceof Date) {
|
|
95
|
+
if (Number.isNaN(value.getTime()))
|
|
96
|
+
throw new errors_js_1.ChatwiseError(`${name} is not a valid date.`);
|
|
97
|
+
search.set(name, value.toISOString());
|
|
98
|
+
}
|
|
99
|
+
else if (typeof value === 'number' && !Number.isSafeInteger(value)) {
|
|
100
|
+
throw new errors_js_1.ChatwiseError(`${name} is not a whole number JavaScript can hold exactly. Pass ids as strings.`);
|
|
101
|
+
}
|
|
102
|
+
else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
103
|
+
search.set(name, String(value));
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
throw new errors_js_1.ChatwiseError(`${name} must be a string, number, boolean or Date.`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const text = search.toString();
|
|
110
|
+
return text && `?${text}`;
|
|
111
|
+
}
|
|
112
|
+
function serialize(body) {
|
|
113
|
+
try {
|
|
114
|
+
return JSON.stringify(body);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
throw new errors_js_1.ChatwiseError('The request can\'t be written as JSON. Pass ids as strings, not as BigInt.');
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** `Retry-After` in milliseconds: it is a number of seconds or a date. */
|
|
121
|
+
function parseRetryAfter(value) {
|
|
122
|
+
const text = value?.trim();
|
|
123
|
+
if (!text)
|
|
124
|
+
return undefined;
|
|
125
|
+
// However long: one that isn't read would be a retry right away.
|
|
126
|
+
if (/^\d+(?:\.\d+)?$/.test(text))
|
|
127
|
+
return Math.min(Math.ceil(Number(text) * 1000), Number.MAX_SAFE_INTEGER);
|
|
128
|
+
// Date.parse reads some numbers as dates too.
|
|
129
|
+
const date = /\bGMT$/.test(text) ? Date.parse(text) : NaN;
|
|
130
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
|
|
131
|
+
}
|
|
132
|
+
/** How long to wait before retrying after `error`, or undefined not to retry. `attempt` counts from 0. */
|
|
133
|
+
function retryDelay(error, attempt, { method, idempotent = false }) {
|
|
134
|
+
const limited = error instanceof errors_js_1.APIError && error.status === 429;
|
|
135
|
+
const failed = error instanceof errors_js_1.ConnectionError || (error instanceof errors_js_1.APIError && error.status >= 500);
|
|
136
|
+
// An answer with a code says what to do about a template that was submitted, such as to wait for
|
|
137
|
+
// Meta. Asking again right away would only replace it with "already in progress".
|
|
138
|
+
const safe = method === 'GET' || (idempotent && !(error instanceof errors_js_1.APIError && error.code !== undefined));
|
|
139
|
+
if (!limited && !(safe && failed))
|
|
140
|
+
return undefined;
|
|
141
|
+
const retryAfter = error instanceof errors_js_1.APIError ? error.retryAfterMs : undefined;
|
|
142
|
+
if (retryAfter !== undefined) {
|
|
143
|
+
if (retryAfter > MAX_RETRY_AFTER_MS)
|
|
144
|
+
return undefined;
|
|
145
|
+
// Up to a second more, so that callers limited together don't come back together.
|
|
146
|
+
return Math.ceil(retryAfter + Math.random() * 1000);
|
|
147
|
+
}
|
|
148
|
+
const backoff = Math.min(8000, 500 * 2 ** attempt);
|
|
149
|
+
return Math.ceil(backoff * (0.75 + Math.random() * 0.25));
|
|
150
|
+
}
|
|
151
|
+
/** An answer's text, or undefined if it has more than `maxBytes`. The rest isn't read then. */
|
|
152
|
+
async function readText(response, maxBytes, signal) {
|
|
153
|
+
const stream = response.body;
|
|
154
|
+
// Locked: a custom fetch read it, to log it for example, and answers with a text() of its own.
|
|
155
|
+
if (typeof stream?.getReader !== 'function' || stream.locked) {
|
|
156
|
+
const text = await response.text();
|
|
157
|
+
return text.length > maxBytes ? undefined : text;
|
|
158
|
+
}
|
|
159
|
+
const reader = stream.getReader();
|
|
160
|
+
// Not awaited: a stream that doesn't end its cancellation can't hold the call up.
|
|
161
|
+
const cancel = () => void Promise.resolve().then(() => reader.cancel()).catch(() => undefined);
|
|
162
|
+
signal.addEventListener('abort', cancel);
|
|
163
|
+
try {
|
|
164
|
+
const decoder = new TextDecoder();
|
|
165
|
+
let text = '';
|
|
166
|
+
let bytes = 0;
|
|
167
|
+
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
|
|
168
|
+
bytes += chunk.value.byteLength;
|
|
169
|
+
if (bytes > maxBytes) {
|
|
170
|
+
cancel();
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
174
|
+
}
|
|
175
|
+
return text + decoder.decode();
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
signal.removeEventListener('abort', cancel);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function aborted(signal) {
|
|
182
|
+
return new errors_js_1.RequestAbortedError('The request was aborted.', { cause: signal.reason });
|
|
183
|
+
}
|
|
184
|
+
function sleep(ms, signal) {
|
|
185
|
+
return new Promise((resolve, reject) => {
|
|
186
|
+
const finish = (settle) => {
|
|
187
|
+
clearTimeout(timer);
|
|
188
|
+
signal?.removeEventListener('abort', onAbort);
|
|
189
|
+
settle();
|
|
190
|
+
};
|
|
191
|
+
const onAbort = () => finish(() => reject(aborted(signal)));
|
|
192
|
+
const timer = setTimeout(() => finish(resolve), ms);
|
|
193
|
+
signal?.addEventListener('abort', onAbort);
|
|
194
|
+
if (signal?.aborted)
|
|
195
|
+
onAbort();
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* The function every resource makes its requests with. The key stays in this closure: it is on no
|
|
200
|
+
* object, so printing a client can't show it.
|
|
201
|
+
*/
|
|
202
|
+
function createRequester(options) {
|
|
203
|
+
// A key that is passed by itself would be ignored, for the environment's.
|
|
204
|
+
if (typeof options !== 'object' || options === null)
|
|
205
|
+
throw new errors_js_1.ChatwiseError('Pass the options as an object, such as `{ apiKey }`.');
|
|
206
|
+
const apiKey = checkKey(options.apiKey ?? environmentKey());
|
|
207
|
+
const baseUrl = checkBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL);
|
|
208
|
+
const defaultTimeoutMs = checkTimeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
209
|
+
const defaultMaxRetries = checkRetries(options.maxRetries ?? DEFAULT_MAX_RETRIES);
|
|
210
|
+
const customFetch = options.fetch;
|
|
211
|
+
if (customFetch !== undefined && typeof customFetch !== 'function')
|
|
212
|
+
throw new errors_js_1.ChatwiseError('fetch must be a function.');
|
|
213
|
+
const encodedKey = encodeURIComponent(apiKey);
|
|
214
|
+
const redact = (value) => value.replaceAll(apiKey, REDACTED).replaceAll(encodedKey, REDACTED);
|
|
215
|
+
/** A parsed body without the key, which the JSON may have written with escapes. */
|
|
216
|
+
function redactBody(value) {
|
|
217
|
+
if (typeof value === 'string')
|
|
218
|
+
return redact(value);
|
|
219
|
+
if (Array.isArray(value))
|
|
220
|
+
return value.map(redactBody);
|
|
221
|
+
if (typeof value !== 'object' || value === null)
|
|
222
|
+
return value;
|
|
223
|
+
return Object.fromEntries(Object.entries(value).map(([name, inner]) => [redact(name), redactBody(inner)]));
|
|
224
|
+
}
|
|
225
|
+
/** An error from fetch, as a new one with only its message and code. The original can hold the request's headers. */
|
|
226
|
+
function redactedCause(error, depth = 0) {
|
|
227
|
+
if (typeof error !== 'object' || error === null)
|
|
228
|
+
return undefined;
|
|
229
|
+
const { name, message, code, cause } = error;
|
|
230
|
+
const inner = depth < 3 ? redactedCause(cause, depth + 1) : undefined;
|
|
231
|
+
const copy = new Error(typeof message === 'string' ? redact(message) : '', inner && { cause: inner });
|
|
232
|
+
if (typeof name === 'string')
|
|
233
|
+
copy.name = redact(name);
|
|
234
|
+
return typeof code === 'string' ? Object.assign(copy, { code: redact(code) }) : copy;
|
|
235
|
+
}
|
|
236
|
+
function connectionError(error, method, requestPath) {
|
|
237
|
+
const cause = redactedCause(error);
|
|
238
|
+
const detail = cause?.cause?.message || cause?.message;
|
|
239
|
+
return new errors_js_1.ConnectionError(`No complete answer from Chatwise to ${method} ${requestPath}${detail ? `: ${detail}` : ''}`, cause && { cause });
|
|
240
|
+
}
|
|
241
|
+
function parse(text) {
|
|
242
|
+
try {
|
|
243
|
+
return { body: JSON.parse(text), isJson: true };
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
return { body: text.slice(0, 1000), isJson: false };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async function attempt({ method, headers }, requestPath, url, body, timeoutMs, signal) {
|
|
250
|
+
if (signal?.aborted)
|
|
251
|
+
throw aborted(signal);
|
|
252
|
+
const controller = new AbortController();
|
|
253
|
+
let interruption;
|
|
254
|
+
let interrupt;
|
|
255
|
+
// Raced against fetch, so that a fetch that ignores its signal can't outlast the timeout.
|
|
256
|
+
const interrupted = new Promise((_, reject) => {
|
|
257
|
+
interrupt = (error) => {
|
|
258
|
+
interruption ??= error;
|
|
259
|
+
reject(error);
|
|
260
|
+
controller.abort();
|
|
261
|
+
};
|
|
262
|
+
});
|
|
263
|
+
interrupted.catch(() => undefined);
|
|
264
|
+
const onAbort = () => interrupt(aborted(signal));
|
|
265
|
+
const timer = setTimeout(() => interrupt(new errors_js_1.RequestTimeoutError(`Chatwise didn't answer ${method} ${requestPath} within ${timeoutMs} ms.`)), timeoutMs);
|
|
266
|
+
try {
|
|
267
|
+
signal?.addEventListener('abort', onAbort);
|
|
268
|
+
const send = async () => {
|
|
269
|
+
const response = await (customFetch ?? globalThis.fetch)(url, {
|
|
270
|
+
method,
|
|
271
|
+
headers: {
|
|
272
|
+
Accept: 'application/json',
|
|
273
|
+
Authorization: `Bearer ${apiKey}`,
|
|
274
|
+
'User-Agent': `chatwise-node/${version_js_1.VERSION}`,
|
|
275
|
+
...(body !== undefined && { 'Content-Type': 'application/json' }),
|
|
276
|
+
...headers,
|
|
277
|
+
},
|
|
278
|
+
...(body !== undefined && { body }),
|
|
279
|
+
// Following a redirect could send the key elsewhere, or a POST twice. The API has none. (Node's
|
|
280
|
+
// fetch itself repeats a request after a 421, which says that it wasn't processed.)
|
|
281
|
+
redirect: 'manual',
|
|
282
|
+
signal: controller.signal,
|
|
283
|
+
});
|
|
284
|
+
const { status } = response;
|
|
285
|
+
const maxBytes = status >= 200 && status < 300 ? MAX_BODY_BYTES : MAX_ERROR_BODY_BYTES;
|
|
286
|
+
return { status, retryAfter: response.headers.get('retry-after'), text: await readText(response, maxBytes, controller.signal) };
|
|
287
|
+
};
|
|
288
|
+
return await Promise.race([send(), interrupted]);
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
// By identity: fetch can throw one of this package's errors, with the key in it or a status that
|
|
292
|
+
// would be retried.
|
|
293
|
+
if (interruption !== undefined && error === interruption)
|
|
294
|
+
throw error;
|
|
295
|
+
throw connectionError(error, method, requestPath);
|
|
296
|
+
}
|
|
297
|
+
finally {
|
|
298
|
+
clearTimeout(timer);
|
|
299
|
+
signal?.removeEventListener('abort', onAbort);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return async function request(operation, options) {
|
|
303
|
+
const { signal, timeoutMs, maxRetries } = options ?? {};
|
|
304
|
+
checkSignal(signal);
|
|
305
|
+
const { method } = operation;
|
|
306
|
+
// For errors, which can show it.
|
|
307
|
+
const requestPath = redact(operation.path);
|
|
308
|
+
const timeout = timeoutMs === undefined ? defaultTimeoutMs : checkTimeout(timeoutMs);
|
|
309
|
+
const retries = maxRetries === undefined ? defaultMaxRetries : checkRetries(maxRetries);
|
|
310
|
+
const url = baseUrl + operation.path + queryString(operation.query);
|
|
311
|
+
const requestBody = operation.body && serialize(operation.body);
|
|
312
|
+
for (let count = 0;; count++) {
|
|
313
|
+
try {
|
|
314
|
+
const { status, retryAfter, text } = await attempt(operation, requestPath, url, requestBody, timeout, signal);
|
|
315
|
+
if (status >= 200 && status < 300) {
|
|
316
|
+
if (text === undefined) {
|
|
317
|
+
throw new errors_js_1.ConnectionError(`Chatwise answered ${status} to ${method} ${requestPath}, but with more than the API answers.`);
|
|
318
|
+
}
|
|
319
|
+
const { body, isJson } = parse(text);
|
|
320
|
+
if (isJson && typeof body === 'object' && body !== null && 'data' in body)
|
|
321
|
+
return body;
|
|
322
|
+
// It was carried out, or it seems so. The answer is cut off, or not from the API.
|
|
323
|
+
throw new errors_js_1.ConnectionError(`Chatwise answered ${status} to ${method} ${requestPath}, but the answer is incomplete or not the API's.`);
|
|
324
|
+
}
|
|
325
|
+
const { body } = parse(redact(text ?? ''));
|
|
326
|
+
throw (0, errors_js_1.apiError)({ status, method, path: requestPath, body: redactBody(body), retryAfterMs: parseRetryAfter(retryAfter) });
|
|
327
|
+
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
const delay = count < retries ? retryDelay(error, count, operation) : undefined;
|
|
330
|
+
if (delay === undefined)
|
|
331
|
+
throw error;
|
|
332
|
+
await sleep(delay, signal);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { RequestOptions, Requester } from './http.js';
|
|
2
|
+
/** One page of a list. Iterating over it goes through this page's items and those of the pages after it. */
|
|
3
|
+
export declare class Page<Item> implements AsyncIterable<Item> {
|
|
4
|
+
#private;
|
|
5
|
+
/** The items of this page. */
|
|
6
|
+
readonly data: Item[];
|
|
7
|
+
/** Where the next page starts, or null on the last page. Pass it as `cursor`, with the same filters and order. */
|
|
8
|
+
readonly nextCursor: string | null;
|
|
9
|
+
hasNextPage(): boolean;
|
|
10
|
+
/** The next page, or null after the last one. */
|
|
11
|
+
getNextPage(): Promise<Page<Item> | null>;
|
|
12
|
+
/** This page and the ones after it. */
|
|
13
|
+
pages(): AsyncGenerator<Page<Item>, void, undefined>;
|
|
14
|
+
/** The items of this page and of the pages after it. */
|
|
15
|
+
[Symbol.asyncIterator](): AsyncGenerator<Item, void, undefined>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A list that isn't read yet. `await` it for its first page, or iterate over it with `for await` for
|
|
19
|
+
* every item. Nothing is requested before that.
|
|
20
|
+
*/
|
|
21
|
+
export declare class PagePromise<Item> implements Promise<Page<Item>>, AsyncIterable<Item> {
|
|
22
|
+
#private;
|
|
23
|
+
get [Symbol.toStringTag](): string;
|
|
24
|
+
then<Result1 = Page<Item>, Result2 = never>(onFulfilled?: ((page: Page<Item>) => Result1 | PromiseLike<Result1>) | null, onRejected?: ((reason: any) => Result2 | PromiseLike<Result2>) | null): Promise<Result1 | Result2>;
|
|
25
|
+
catch<Result = never>(onRejected?: ((reason: any) => Result | PromiseLike<Result>) | null): Promise<Page<Item> | Result>;
|
|
26
|
+
finally(onFinally?: (() => void) | null): Promise<Page<Item>>;
|
|
27
|
+
/** The pages, from the first. */
|
|
28
|
+
pages(): AsyncGenerator<Page<Item>, void, undefined>;
|
|
29
|
+
/** The items of every page. */
|
|
30
|
+
[Symbol.asyncIterator](): AsyncGenerator<Item, void, undefined>;
|
|
31
|
+
}
|
|
32
|
+
/** A list with pages. `path` is a function so that a bad id rejects like every other error. */
|
|
33
|
+
export declare function list<Item>(request: Requester, path: () => string, params: {
|
|
34
|
+
cursor?: string | undefined;
|
|
35
|
+
}, options: RequestOptions | undefined): PagePromise<Item>;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PagePromise = exports.Page = void 0;
|
|
4
|
+
exports.list = list;
|
|
5
|
+
const errors_js_1 = require("./errors.js");
|
|
6
|
+
/** One page of a list. Iterating over it goes through this page's items and those of the pages after it. */
|
|
7
|
+
class Page {
|
|
8
|
+
/** The items of this page. */
|
|
9
|
+
data;
|
|
10
|
+
/** Where the next page starts, or null on the last page. Pass it as `cursor`, with the same filters and order. */
|
|
11
|
+
nextCursor;
|
|
12
|
+
#next;
|
|
13
|
+
/** @internal */
|
|
14
|
+
constructor(data, nextCursor, next) {
|
|
15
|
+
this.data = data;
|
|
16
|
+
this.nextCursor = nextCursor;
|
|
17
|
+
this.#next = next;
|
|
18
|
+
}
|
|
19
|
+
hasNextPage() {
|
|
20
|
+
return this.nextCursor !== null;
|
|
21
|
+
}
|
|
22
|
+
/** The next page, or null after the last one. */
|
|
23
|
+
async getNextPage() {
|
|
24
|
+
return this.nextCursor === null ? null : this.#next(this.nextCursor);
|
|
25
|
+
}
|
|
26
|
+
/** This page and the ones after it. */
|
|
27
|
+
async *pages() {
|
|
28
|
+
yield this;
|
|
29
|
+
const seen = new Set([this.nextCursor]);
|
|
30
|
+
for (let page = await this.getNextPage(); page; page = await page.getNextPage()) {
|
|
31
|
+
yield page;
|
|
32
|
+
if (page.nextCursor !== null && seen.has(page.nextCursor))
|
|
33
|
+
throw new errors_js_1.ChatwiseError('Chatwise answered with the same pages again.');
|
|
34
|
+
seen.add(page.nextCursor);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** The items of this page and of the pages after it. */
|
|
38
|
+
async *[Symbol.asyncIterator]() {
|
|
39
|
+
for await (const page of this.pages())
|
|
40
|
+
yield* page.data;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
exports.Page = Page;
|
|
44
|
+
/**
|
|
45
|
+
* A list that isn't read yet. `await` it for its first page, or iterate over it with `for await` for
|
|
46
|
+
* every item. Nothing is requested before that.
|
|
47
|
+
*/
|
|
48
|
+
class PagePromise {
|
|
49
|
+
#load;
|
|
50
|
+
#first;
|
|
51
|
+
/** @internal */
|
|
52
|
+
constructor(load) {
|
|
53
|
+
this.#load = load;
|
|
54
|
+
}
|
|
55
|
+
get [Symbol.toStringTag]() {
|
|
56
|
+
return 'PagePromise';
|
|
57
|
+
}
|
|
58
|
+
#page() {
|
|
59
|
+
return (this.#first ??= this.#load());
|
|
60
|
+
}
|
|
61
|
+
then(onFulfilled,
|
|
62
|
+
// `any`, as in Promise itself.
|
|
63
|
+
onRejected) {
|
|
64
|
+
return this.#page().then(onFulfilled, onRejected);
|
|
65
|
+
}
|
|
66
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
67
|
+
catch(onRejected) {
|
|
68
|
+
return this.#page().catch(onRejected);
|
|
69
|
+
}
|
|
70
|
+
finally(onFinally) {
|
|
71
|
+
return this.#page().finally(onFinally);
|
|
72
|
+
}
|
|
73
|
+
/** The pages, from the first. */
|
|
74
|
+
async *pages() {
|
|
75
|
+
yield* (await this.#page()).pages();
|
|
76
|
+
}
|
|
77
|
+
/** The items of every page. */
|
|
78
|
+
async *[Symbol.asyncIterator]() {
|
|
79
|
+
yield* await this.#page();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
exports.PagePromise = PagePromise;
|
|
83
|
+
/** A list with pages. `path` is a function so that a bad id rejects like every other error. */
|
|
84
|
+
function list(request, path, params, options) {
|
|
85
|
+
// A copy, so that changing the filters afterwards, or one of their dates, doesn't change what the next
|
|
86
|
+
// page is of.
|
|
87
|
+
const query = Object.fromEntries(Object.entries({ ...params }).map(([name, value]) => [name, value instanceof Date ? new Date(value) : value]));
|
|
88
|
+
const load = async (cursor) => {
|
|
89
|
+
const operation = { method: 'GET', path: path(), query: { ...query, cursor } };
|
|
90
|
+
const { data, pagination } = await request(operation, options);
|
|
91
|
+
const nextCursor = pagination?.nextCursor;
|
|
92
|
+
if (!Array.isArray(data) || (nextCursor !== null && typeof nextCursor !== 'string')) {
|
|
93
|
+
throw new errors_js_1.ChatwiseError(`Chatwise answered ${operation.path} with a list this version doesn't understand.`);
|
|
94
|
+
}
|
|
95
|
+
if (nextCursor !== null && nextCursor === cursor) {
|
|
96
|
+
throw new errors_js_1.ChatwiseError(`Chatwise answered ${operation.path} with the same page again.`);
|
|
97
|
+
}
|
|
98
|
+
return new Page(data, nextCursor, load);
|
|
99
|
+
};
|
|
100
|
+
return new PagePromise(() => load(query.cursor));
|
|
101
|
+
}
|