plsremind 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/rest.d.ts ADDED
@@ -0,0 +1,212 @@
1
+ import type { AdminUser, Connection, ConnectionTest, Delivery, DeliveryResult, FollowUp, Identity, Info, Intent, Invite, Item, ItemInput, ItemStatus, List, ListName, LoginProvider, LookupResult, ManualReminder, NewPasswordAccount, Order, Page, PersonalToken, Priority, ProviderType, QuietHours, Registration, ReminderLogEntry, ReminderPlan, Role, ScheduledReminder, Settings, Subitem, User, UserConnection, UserSummary } from "./types.js";
2
+ export interface RestOptions {
3
+ /** The address of the hub. In a browser it may be left out and is the page's own. */
4
+ url?: string | undefined;
5
+ /** A personal token or a connection token. */
6
+ token?: string | undefined;
7
+ /** "session" uses the login cookie of the dashboard instead of a token. */
8
+ auth?: "session";
9
+ /** false turns off waiting out a 429. */
10
+ retry?: boolean;
11
+ fetch?: typeof fetch;
12
+ }
13
+ export interface CallOptions {
14
+ signal?: AbortSignal;
15
+ }
16
+ export interface UserOptions extends CallOptions {
17
+ /** The user to act for. Defaults to the caller; a connection must name one. */
18
+ user?: string;
19
+ }
20
+ export interface WriteOptions extends UserOptions {
21
+ /** Comes back as `nonce` in every gateway event this call causes. */
22
+ nonce?: string;
23
+ }
24
+ export interface AdminWriteOptions extends CallOptions {
25
+ nonce?: string;
26
+ }
27
+ export interface ListItemsQuery {
28
+ listId?: string;
29
+ status?: ItemStatus | "all";
30
+ hasDue?: boolean;
31
+ dueBefore?: Date;
32
+ dueAfter?: Date;
33
+ sort?: "created" | "due" | "priority" | "completed";
34
+ order?: "asc" | "desc";
35
+ limit?: number;
36
+ cursor?: string | undefined;
37
+ }
38
+ export interface UserChanges {
39
+ displayName?: string;
40
+ timezone?: string;
41
+ locale?: string | null;
42
+ preferences?: Readonly<Record<string, unknown>>;
43
+ quietHours?: QuietHours | null;
44
+ }
45
+ export interface ProviderInput {
46
+ type?: ProviderType;
47
+ name?: string;
48
+ loginEnabled?: boolean;
49
+ linkEnabled?: boolean;
50
+ clientId?: string;
51
+ clientSecret?: string;
52
+ issuerUrl?: string;
53
+ }
54
+ /** Every call of the REST API as a method named after its operation in the API reference. */
55
+ export declare class RestClient {
56
+ #private;
57
+ constructor(options?: RestOptions);
58
+ /** Walks a listing page by page. Pass a function that fetches the page after a cursor. */
59
+ pages<T>(fetchPage: (cursor: string | undefined) => Promise<Page<T>>): AsyncGenerator<Page<T>, void, undefined>;
60
+ /** The address to send the browser to for logging in with, or linking, an account elsewhere. */
61
+ oauthStartUrl(provider: string, options?: {
62
+ intent?: "login" | "link";
63
+ inviteCode?: string;
64
+ }): string;
65
+ getInfo(options?: CallOptions): Promise<Info>;
66
+ setup(account: NewPasswordAccount, options?: CallOptions): Promise<User>;
67
+ login(credentials: {
68
+ username: string;
69
+ password: string;
70
+ }, options?: CallOptions): Promise<User>;
71
+ logout(options?: CallOptions): Promise<void>;
72
+ register(account: NewPasswordAccount & {
73
+ inviteCode?: string;
74
+ }, options?: CallOptions): Promise<User>;
75
+ getUser(options?: UserOptions): Promise<User | UserSummary>;
76
+ updateUser(changes: UserChanges, options?: WriteOptions): Promise<User>;
77
+ deleteUser(options?: WriteOptions): Promise<void>;
78
+ listIdentities(options?: UserOptions): Promise<Identity[]>;
79
+ /** The address of a linked account's picture, for an `<img>` in a browser that is logged in. */
80
+ identityAvatarUrl(id: string, options?: UserOptions): string;
81
+ getIdentityAvatar(id: string, options?: UserOptions): Promise<Blob>;
82
+ unlinkIdentity(id: string, options?: WriteOptions): Promise<void>;
83
+ setPassword(body: {
84
+ newPassword: string;
85
+ currentPassword?: string;
86
+ username?: string;
87
+ }, options?: WriteOptions): Promise<void>;
88
+ getSettings(options?: CallOptions): Promise<Settings>;
89
+ updateSettings(changes: {
90
+ name?: string;
91
+ registration?: Registration;
92
+ }, options?: CallOptions): Promise<Settings>;
93
+ listInvites(options?: CallOptions): Promise<Invite[]>;
94
+ createInvite(body?: {
95
+ expiresIn?: number;
96
+ }, options?: CallOptions): Promise<Invite>;
97
+ deleteInvite(id: string, options?: CallOptions): Promise<void>;
98
+ listUsers(query?: {
99
+ limit?: number;
100
+ cursor?: string | undefined;
101
+ }, options?: CallOptions): Promise<Page<AdminUser>>;
102
+ updateUserAccess(id: string, changes: {
103
+ role?: Role;
104
+ disabled?: boolean;
105
+ }, options?: AdminWriteOptions): Promise<AdminUser>;
106
+ adminDeleteUser(id: string, options?: AdminWriteOptions): Promise<void>;
107
+ resetPassword(id: string, body: {
108
+ newPassword: string;
109
+ }, options?: CallOptions): Promise<void>;
110
+ listTokens(options?: UserOptions): Promise<PersonalToken[]>;
111
+ createToken(body: {
112
+ name: string;
113
+ remind?: boolean;
114
+ }, options?: WriteOptions): Promise<PersonalToken>;
115
+ updateToken(id: string, changes: {
116
+ name?: string;
117
+ remind?: boolean;
118
+ }, options?: WriteOptions): Promise<PersonalToken>;
119
+ deleteToken(id: string, options?: WriteOptions): Promise<void>;
120
+ listLists(options?: UserOptions): Promise<List[]>;
121
+ createList(body: ListName, options?: WriteOptions): Promise<List>;
122
+ reorderLists(order: Order, options?: WriteOptions): Promise<List[]>;
123
+ renameList(id: string, body: ListName, options?: WriteOptions): Promise<List>;
124
+ /** Items in the list move to the inbox. */
125
+ deleteList(id: string, options?: WriteOptions): Promise<void>;
126
+ listReminderPlans(options?: UserOptions): Promise<ReminderPlan[]>;
127
+ setReminderPlan(priority: Priority, plan: {
128
+ before: readonly number[];
129
+ followUp: FollowUp;
130
+ }, options?: WriteOptions): Promise<ReminderPlan>;
131
+ resetReminderPlan(priority: Priority, options?: WriteOptions): Promise<void>;
132
+ listItems(query?: ListItemsQuery, options?: UserOptions): Promise<Page<Item>>;
133
+ createItem(input: ItemInput & {
134
+ title: string;
135
+ }, options?: WriteOptions): Promise<Item>;
136
+ getItem(id: string, options?: UserOptions): Promise<Item>;
137
+ updateItem(id: string, changes: ItemInput & {
138
+ status?: ItemStatus;
139
+ }, options?: WriteOptions): Promise<Item>;
140
+ deleteItem(id: string, options?: WriteOptions): Promise<void>;
141
+ createSubitem(itemId: string, body: {
142
+ title: string;
143
+ }, options?: WriteOptions): Promise<Subitem>;
144
+ reorderSubitems(itemId: string, order: Order, options?: WriteOptions): Promise<Subitem[]>;
145
+ updateSubitem(itemId: string, subitemId: string, changes: {
146
+ title?: string;
147
+ done?: boolean;
148
+ }, options?: WriteOptions): Promise<Subitem>;
149
+ deleteSubitem(itemId: string, subitemId: string, options?: WriteOptions): Promise<void>;
150
+ /** The reminders an open item still has ahead, earliest first. */
151
+ getItemSchedule(itemId: string, options?: UserOptions): Promise<ScheduledReminder[]>;
152
+ listReminders(itemId: string, options?: UserOptions): Promise<ManualReminder[]>;
153
+ /** `at` is a moment, `in` a span from now in milliseconds. */
154
+ createReminder(itemId: string, when: {
155
+ at: Date;
156
+ } | {
157
+ in: number;
158
+ }, options?: WriteOptions): Promise<ManualReminder>;
159
+ deleteReminder(itemId: string, reminderId: string, options?: WriteOptions): Promise<void>;
160
+ /** For connections: the hub user behind an account at the connection's provider. */
161
+ lookupUser(externalId: string, options?: CallOptions): Promise<LookupResult>;
162
+ listUserConnections(options?: UserOptions): Promise<UserConnection[]>;
163
+ setConnectionGrant(id: string, grant: {
164
+ enabled?: boolean;
165
+ remind?: boolean;
166
+ }, options?: WriteOptions): Promise<UserConnection>;
167
+ /** Asks the app to show that it reaches the user. Too soon after the last one is a 429 at once. */
168
+ startConnectionTest(id: string, options?: WriteOptions): Promise<ConnectionTest>;
169
+ getConnectionTest(id: string, testId: string, options?: UserOptions): Promise<ConnectionTest>;
170
+ listConnections(options?: CallOptions): Promise<Connection[]>;
171
+ createConnection(body: {
172
+ name: string;
173
+ provider: string;
174
+ description?: string;
175
+ allowedIntents?: readonly Intent[];
176
+ installUrl?: string;
177
+ }, options?: CallOptions): Promise<Connection>;
178
+ updateConnection(id: string, changes: {
179
+ name?: string;
180
+ description?: string;
181
+ enabled?: boolean;
182
+ allowedIntents?: readonly Intent[];
183
+ installUrl?: string;
184
+ }, options?: CallOptions): Promise<Connection>;
185
+ deleteConnection(id: string, options?: CallOptions): Promise<void>;
186
+ /** The answer carries the new token. The old one stops working. */
187
+ rotateConnectionToken(id: string, options?: CallOptions): Promise<Connection>;
188
+ listProviders(options?: CallOptions): Promise<LoginProvider[]>;
189
+ setProvider(key: string, body: ProviderInput, options?: CallOptions): Promise<LoginProvider>;
190
+ deleteProvider(key: string, options?: CallOptions): Promise<void>;
191
+ /** The open deliveries of the calling token, for adapters that do not use the gateway. */
192
+ listDeliveries(options?: CallOptions): Promise<Delivery[]>;
193
+ /** Confirms that a reminder reached the person, or says why not, which the user gets to see. */
194
+ acknowledgeDelivery(id: string, outcome: {
195
+ status: "delivered";
196
+ } | {
197
+ status: "failed";
198
+ reason: string;
199
+ }, options?: CallOptions): Promise<DeliveryResult>;
200
+ /** Says how a test the user asked for went, which the user gets to see. */
201
+ reportTest(id: string, outcome: {
202
+ status: "delivered";
203
+ } | {
204
+ status: "failed";
205
+ reason: string;
206
+ }, options?: CallOptions): Promise<ConnectionTest>;
207
+ listReminderLog(query?: {
208
+ itemId?: string;
209
+ limit?: number;
210
+ cursor?: string | undefined;
211
+ }, options?: UserOptions): Promise<Page<ReminderLogEntry>>;
212
+ }
package/dist/rest.js ADDED
@@ -0,0 +1,394 @@
1
+ import { camelKeys, fromWire, toWire } from "./convert.js";
2
+ import { ApiError, NetworkError } from "./errors.js";
3
+ const maxRetries = 3;
4
+ const longestWait = 30_000;
5
+ function seg(value) {
6
+ return encodeURIComponent(value);
7
+ }
8
+ /** Every call of the REST API as a method named after its operation in the API reference. */
9
+ export class RestClient {
10
+ #base;
11
+ #token;
12
+ #session;
13
+ #retry;
14
+ #fetch;
15
+ constructor(options = {}) {
16
+ if (options.token !== undefined && options.auth !== undefined) {
17
+ throw new TypeError('Give either a token or auth: "session", not both.');
18
+ }
19
+ const origin = globalThis.location?.origin;
20
+ const url = options.url ?? origin;
21
+ if (!url)
22
+ throw new TypeError("The address of the hub is missing: pass { url }.");
23
+ this.#base = `${url.replace(/\/+$/, "")}/api/v1`;
24
+ this.#token = options.token;
25
+ this.#session = options.auth === "session";
26
+ this.#retry = options.retry !== false;
27
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
28
+ }
29
+ async #request(method, path, request = {}) {
30
+ const options = request.options;
31
+ let target = path;
32
+ if (request.user) {
33
+ const named = typeof options?.user === "string" ? options.user : undefined;
34
+ const user = named === "@me" ? undefined : named;
35
+ if (user === undefined && this.#token?.startsWith("plsr_con_")) {
36
+ throw new TypeError("A connection must say which user it acts for: pass { user }.");
37
+ }
38
+ target = `/users/${user === undefined ? "@me" : seg(user)}${path}`;
39
+ }
40
+ // An empty or dot segment would be folded away on the way out and reach another call.
41
+ if (target
42
+ .split("/")
43
+ .slice(1)
44
+ .some((part) => part === "" || part === "." || part === "..")) {
45
+ throw new TypeError("An id in the path is empty or a dot segment.");
46
+ }
47
+ const url = new URL(this.#base + target);
48
+ if (request.query !== null && typeof request.query === "object") {
49
+ for (const [key, value] of Object.entries(toWire(request.query))) {
50
+ if (value !== null)
51
+ url.searchParams.set(key, String(value));
52
+ }
53
+ }
54
+ const headers = { accept: request.raw ? "*/*" : "application/json" };
55
+ if (this.#token !== undefined)
56
+ headers.authorization = `Bearer ${this.#token}`;
57
+ if (typeof options?.nonce === "string")
58
+ headers["x-request-nonce"] = options.nonce;
59
+ const init = { method, headers };
60
+ if (request.body !== undefined) {
61
+ headers["content-type"] = "application/json";
62
+ init.body = JSON.stringify(toWire(request.body));
63
+ }
64
+ if (this.#session)
65
+ init.credentials = "include";
66
+ const signal = options?.signal instanceof AbortSignal ? options.signal : undefined;
67
+ if (signal)
68
+ init.signal = signal;
69
+ for (let attempt = 0;; attempt++) {
70
+ let response;
71
+ try {
72
+ response = await this.#fetch(url.toString(), init);
73
+ }
74
+ catch (cause) {
75
+ if (signal?.aborted)
76
+ throw cause;
77
+ throw new NetworkError(`The hub did not answer ${method} ${target}.`, cause);
78
+ }
79
+ if (response.status === 429 && this.#retry && !request.noRetry && attempt < maxRetries) {
80
+ const asked = response.headers.get("retry-after");
81
+ const wait = asked === null || asked.trim() === "" ? Number.NaN : Number(asked) * 1000;
82
+ if (wait >= 0 && wait < longestWait) {
83
+ await response.body?.cancel().catch(() => { });
84
+ await pause(wait, signal);
85
+ continue;
86
+ }
87
+ }
88
+ if (request.raw && response.ok) {
89
+ try {
90
+ return (await response.blob());
91
+ }
92
+ catch (cause) {
93
+ if (signal?.aborted)
94
+ throw cause;
95
+ throw new NetworkError(`The answer to ${method} ${target} broke off.`, cause);
96
+ }
97
+ }
98
+ return read(response, method, target, signal);
99
+ }
100
+ }
101
+ /** Walks a listing page by page. Pass a function that fetches the page after a cursor. */
102
+ async *pages(fetchPage) {
103
+ let cursor;
104
+ do {
105
+ const page = await fetchPage(cursor);
106
+ yield page;
107
+ cursor = page.nextCursor ?? undefined;
108
+ } while (cursor !== undefined);
109
+ }
110
+ /** The address to send the browser to for logging in with, or linking, an account elsewhere. */
111
+ oauthStartUrl(provider, options = {}) {
112
+ const url = new URL(`${this.#base}/auth/oauth/${seg(provider)}/start`);
113
+ if (options.intent !== undefined)
114
+ url.searchParams.set("intent", options.intent);
115
+ if (options.inviteCode !== undefined)
116
+ url.searchParams.set("invite_code", options.inviteCode);
117
+ return url.toString();
118
+ }
119
+ async getInfo(options) {
120
+ const info = await this.#request("GET", "/info", { options });
121
+ // Hubs from before login and link listed only the methods that log in.
122
+ const loginMethods = info.loginMethods?.map((method) => ({ ...method, login: method.login ?? true, link: method.link ?? false }));
123
+ return loginMethods ? { ...info, loginMethods: loginMethods } : info;
124
+ }
125
+ setup(account, options) {
126
+ return this.#request("POST", "/setup", { body: account, options });
127
+ }
128
+ login(credentials, options) {
129
+ return this.#request("POST", "/auth/login", { body: credentials, options });
130
+ }
131
+ logout(options) {
132
+ return this.#request("POST", "/auth/logout", { options });
133
+ }
134
+ register(account, options) {
135
+ return this.#request("POST", "/auth/register", { body: account, options });
136
+ }
137
+ getUser(options) {
138
+ return this.#request("GET", "", { user: true, options });
139
+ }
140
+ updateUser(changes, options) {
141
+ return this.#request("PATCH", "", { user: true, body: changes, options });
142
+ }
143
+ deleteUser(options) {
144
+ return this.#request("DELETE", "", { user: true, options });
145
+ }
146
+ listIdentities(options) {
147
+ return this.#request("GET", "/identities", { user: true, options });
148
+ }
149
+ /** The address of a linked account's picture, for an `<img>` in a browser that is logged in. */
150
+ identityAvatarUrl(id, options) {
151
+ const named = typeof options?.user === "string" ? options.user : "@me";
152
+ const user = named === "@me" ? named : seg(named);
153
+ return `${this.#base}/users/${user}/identities/${seg(id)}/avatar`;
154
+ }
155
+ getIdentityAvatar(id, options) {
156
+ return this.#request("GET", `/identities/${seg(id)}/avatar`, {
157
+ user: true,
158
+ options,
159
+ raw: true,
160
+ });
161
+ }
162
+ unlinkIdentity(id, options) {
163
+ return this.#request("DELETE", `/identities/${seg(id)}`, { user: true, options });
164
+ }
165
+ setPassword(body, options) {
166
+ return this.#request("PUT", "/password", { user: true, body, options });
167
+ }
168
+ getSettings(options) {
169
+ return this.#request("GET", "/admin/settings", { options });
170
+ }
171
+ updateSettings(changes, options) {
172
+ return this.#request("PATCH", "/admin/settings", { body: changes, options });
173
+ }
174
+ listInvites(options) {
175
+ return this.#request("GET", "/admin/invites", { options });
176
+ }
177
+ createInvite(body = {}, options) {
178
+ return this.#request("POST", "/admin/invites", { body, options });
179
+ }
180
+ deleteInvite(id, options) {
181
+ return this.#request("DELETE", `/admin/invites/${seg(id)}`, { options });
182
+ }
183
+ listUsers(query = {}, options) {
184
+ return this.#request("GET", "/admin/users", { query, options });
185
+ }
186
+ updateUserAccess(id, changes, options) {
187
+ return this.#request("PATCH", `/admin/users/${seg(id)}`, { body: changes, options });
188
+ }
189
+ adminDeleteUser(id, options) {
190
+ return this.#request("DELETE", `/admin/users/${seg(id)}`, { options });
191
+ }
192
+ resetPassword(id, body, options) {
193
+ return this.#request("PUT", `/admin/users/${seg(id)}/password`, { body, options });
194
+ }
195
+ listTokens(options) {
196
+ return this.#request("GET", "/tokens", { user: true, options });
197
+ }
198
+ createToken(body, options) {
199
+ return this.#request("POST", "/tokens", { user: true, body, options });
200
+ }
201
+ updateToken(id, changes, options) {
202
+ return this.#request("PATCH", `/tokens/${seg(id)}`, { user: true, body: changes, options });
203
+ }
204
+ deleteToken(id, options) {
205
+ return this.#request("DELETE", `/tokens/${seg(id)}`, { user: true, options });
206
+ }
207
+ listLists(options) {
208
+ return this.#request("GET", "/lists", { user: true, options });
209
+ }
210
+ createList(body, options) {
211
+ return this.#request("POST", "/lists", { user: true, body, options });
212
+ }
213
+ reorderLists(order, options) {
214
+ return this.#request("PUT", "/lists/order", { user: true, body: order, options });
215
+ }
216
+ renameList(id, body, options) {
217
+ return this.#request("PATCH", `/lists/${seg(id)}`, { user: true, body, options });
218
+ }
219
+ /** Items in the list move to the inbox. */
220
+ deleteList(id, options) {
221
+ return this.#request("DELETE", `/lists/${seg(id)}`, { user: true, options });
222
+ }
223
+ listReminderPlans(options) {
224
+ return this.#request("GET", "/reminder-plans", { user: true, options });
225
+ }
226
+ setReminderPlan(priority, plan, options) {
227
+ const path = `/reminder-plans/${seg(priority)}`;
228
+ return this.#request("PUT", path, { user: true, body: plan, options });
229
+ }
230
+ resetReminderPlan(priority, options) {
231
+ return this.#request("DELETE", `/reminder-plans/${seg(priority)}`, { user: true, options });
232
+ }
233
+ listItems(query = {}, options) {
234
+ return this.#request("GET", "/items", { user: true, query, options });
235
+ }
236
+ createItem(input, options) {
237
+ return this.#request("POST", "/items", { user: true, body: input, options });
238
+ }
239
+ getItem(id, options) {
240
+ return this.#request("GET", `/items/${seg(id)}`, { user: true, options });
241
+ }
242
+ updateItem(id, changes, options) {
243
+ return this.#request("PATCH", `/items/${seg(id)}`, { user: true, body: changes, options });
244
+ }
245
+ deleteItem(id, options) {
246
+ return this.#request("DELETE", `/items/${seg(id)}`, { user: true, options });
247
+ }
248
+ createSubitem(itemId, body, options) {
249
+ return this.#request("POST", `/items/${seg(itemId)}/subitems`, { user: true, body, options });
250
+ }
251
+ reorderSubitems(itemId, order, options) {
252
+ const path = `/items/${seg(itemId)}/subitems/order`;
253
+ return this.#request("PUT", path, { user: true, body: order, options });
254
+ }
255
+ updateSubitem(itemId, subitemId, changes, options) {
256
+ const path = `/items/${seg(itemId)}/subitems/${seg(subitemId)}`;
257
+ return this.#request("PATCH", path, { user: true, body: changes, options });
258
+ }
259
+ deleteSubitem(itemId, subitemId, options) {
260
+ const path = `/items/${seg(itemId)}/subitems/${seg(subitemId)}`;
261
+ return this.#request("DELETE", path, { user: true, options });
262
+ }
263
+ /** The reminders an open item still has ahead, earliest first. */
264
+ getItemSchedule(itemId, options) {
265
+ return this.#request("GET", `/items/${seg(itemId)}/schedule`, { user: true, options });
266
+ }
267
+ listReminders(itemId, options) {
268
+ return this.#request("GET", `/items/${seg(itemId)}/reminders`, { user: true, options });
269
+ }
270
+ /** `at` is a moment, `in` a span from now in milliseconds. */
271
+ createReminder(itemId, when, options) {
272
+ const path = `/items/${seg(itemId)}/reminders`;
273
+ return this.#request("POST", path, { user: true, body: when, options });
274
+ }
275
+ deleteReminder(itemId, reminderId, options) {
276
+ const path = `/items/${seg(itemId)}/reminders/${seg(reminderId)}`;
277
+ return this.#request("DELETE", path, { user: true, options });
278
+ }
279
+ /** For connections: the hub user behind an account at the connection's provider. */
280
+ lookupUser(externalId, options) {
281
+ const query = { externalId };
282
+ return this.#request("GET", "/connection/users/lookup", { query, options });
283
+ }
284
+ listUserConnections(options) {
285
+ return this.#request("GET", "/connections", { user: true, options });
286
+ }
287
+ setConnectionGrant(id, grant, options) {
288
+ return this.#request("PUT", `/connections/${seg(id)}`, { user: true, body: grant, options });
289
+ }
290
+ /** Asks the app to show that it reaches the user. Too soon after the last one is a 429 at once. */
291
+ startConnectionTest(id, options) {
292
+ // Waiting out the limit would look like a button that hangs.
293
+ return this.#request("POST", `/connections/${seg(id)}/tests`, {
294
+ user: true,
295
+ options,
296
+ noRetry: true,
297
+ });
298
+ }
299
+ getConnectionTest(id, testId, options) {
300
+ return this.#request("GET", `/connections/${seg(id)}/tests/${seg(testId)}`, {
301
+ user: true,
302
+ options,
303
+ });
304
+ }
305
+ listConnections(options) {
306
+ return this.#request("GET", "/admin/connections", { options });
307
+ }
308
+ createConnection(body, options) {
309
+ return this.#request("POST", "/admin/connections", { body, options });
310
+ }
311
+ updateConnection(id, changes, options) {
312
+ return this.#request("PATCH", `/admin/connections/${seg(id)}`, { body: changes, options });
313
+ }
314
+ deleteConnection(id, options) {
315
+ return this.#request("DELETE", `/admin/connections/${seg(id)}`, { options });
316
+ }
317
+ /** The answer carries the new token. The old one stops working. */
318
+ rotateConnectionToken(id, options) {
319
+ return this.#request("POST", `/admin/connections/${seg(id)}/token`, { options });
320
+ }
321
+ listProviders(options) {
322
+ return this.#request("GET", "/admin/providers", { options });
323
+ }
324
+ setProvider(key, body, options) {
325
+ return this.#request("PUT", `/admin/providers/${seg(key)}`, { body, options });
326
+ }
327
+ deleteProvider(key, options) {
328
+ return this.#request("DELETE", `/admin/providers/${seg(key)}`, { options });
329
+ }
330
+ /** The open deliveries of the calling token, for adapters that do not use the gateway. */
331
+ listDeliveries(options) {
332
+ return this.#request("GET", "/deliveries", { options });
333
+ }
334
+ /** Confirms that a reminder reached the person, or says why not, which the user gets to see. */
335
+ acknowledgeDelivery(id, outcome, options) {
336
+ return this.#request("PUT", `/deliveries/${seg(id)}`, { body: outcome, options });
337
+ }
338
+ /** Says how a test the user asked for went, which the user gets to see. */
339
+ reportTest(id, outcome, options) {
340
+ return this.#request("PUT", `/deliveries/tests/${seg(id)}`, { body: outcome, options });
341
+ }
342
+ listReminderLog(query = {}, options) {
343
+ return this.#request("GET", "/reminder-log", { user: true, query, options });
344
+ }
345
+ }
346
+ async function read(response, method, target, signal) {
347
+ let text;
348
+ try {
349
+ text = await response.text();
350
+ }
351
+ catch (cause) {
352
+ if (signal?.aborted)
353
+ throw cause;
354
+ throw new NetworkError(`The answer to ${method} ${target} broke off.`, cause);
355
+ }
356
+ let parsed;
357
+ let readable = text !== "" || !response.ok || response.status === 204;
358
+ if (text !== "") {
359
+ try {
360
+ parsed = JSON.parse(text);
361
+ }
362
+ catch {
363
+ readable = false;
364
+ }
365
+ }
366
+ if (!response.ok) {
367
+ const error = parsed?.error;
368
+ if (error !== null && typeof error === "object" && typeof error.code === "string") {
369
+ throw new ApiError(response.status, error.code, typeof error.message === "string" ? error.message : error.code, error.fields !== null && typeof error.fields === "object"
370
+ ? camelKeys(error.fields)
371
+ : undefined);
372
+ }
373
+ throw new ApiError(response.status, "unknown", `The hub answered ${response.status}.`);
374
+ }
375
+ if (!readable) {
376
+ throw new NetworkError(`The answer to ${method} ${target} was empty or not JSON.`);
377
+ }
378
+ return fromWire(parsed);
379
+ }
380
+ function pause(ms, signal) {
381
+ return new Promise((resolve, reject) => {
382
+ signal?.throwIfAborted();
383
+ const timer = setTimeout(done, ms);
384
+ function done() {
385
+ signal?.removeEventListener("abort", aborted);
386
+ resolve();
387
+ }
388
+ function aborted() {
389
+ clearTimeout(timer);
390
+ reject(signal.reason);
391
+ }
392
+ signal?.addEventListener("abort", aborted, { once: true });
393
+ });
394
+ }