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/client.js ADDED
@@ -0,0 +1,199 @@
1
+ import { CacheStore } from "./cache.js";
2
+ import { fromWire } from "./convert.js";
3
+ import { Emitter } from "./emitter.js";
4
+ import { GatewayError } from "./errors.js";
5
+ import { hubEventNames } from "./events.js";
6
+ import { Gateway } from "./gateway.js";
7
+ import { RestClient } from "./rest.js";
8
+ const hubEvents = new Set(hubEventNames);
9
+ const withoutOld = new Set([
10
+ "user.sync",
11
+ "user.gone",
12
+ "delivery.created",
13
+ "delivery.closed",
14
+ "delivery.test",
15
+ ]);
16
+ /** A gateway session with a cache of what it covers, typed events and the REST API. */
17
+ export class Client {
18
+ /** Every call of the REST API. Answers do not change the cache; the events that follow do. */
19
+ rest;
20
+ /** The state the session covers, kept current by the gateway. */
21
+ cache;
22
+ #store = new CacheStore();
23
+ #events = new Emitter();
24
+ #options;
25
+ #internals;
26
+ #status = "idle";
27
+ #principal;
28
+ #intents;
29
+ #gateway;
30
+ #connecting;
31
+ #settle;
32
+ #ready;
33
+ #waiting = new Set();
34
+ #unhook;
35
+ constructor(options = {}, internals = {}) {
36
+ this.#options = options;
37
+ this.#internals = internals;
38
+ this.rest = new RestClient(options);
39
+ this.cache = this.#store.cache;
40
+ }
41
+ /** Who the client is logged in as. Set once the gateway said READY. */
42
+ get principal() {
43
+ return this.#principal;
44
+ }
45
+ /** The intents of the session, or the ones asked for while there is none yet. */
46
+ get intents() {
47
+ return this.#intents ?? this.#options.intents ?? [];
48
+ }
49
+ get status() {
50
+ return this.#status;
51
+ }
52
+ /**
53
+ * Resolves once the state of every user of the session is in the cache. Rejects with a
54
+ * GatewayError if the first attempt fails; later drops are reconnected without the caller.
55
+ */
56
+ connect() {
57
+ if (this.#connecting)
58
+ return this.#connecting;
59
+ const intents = this.#options.intents;
60
+ if (!intents || intents.length === 0) {
61
+ return Promise.reject(new TypeError("connect() needs intents: pass { intents: [...] }."));
62
+ }
63
+ const createSocket = this.#internals.createSocket ?? ((url) => new WebSocket(url));
64
+ const gateway = new Gateway({
65
+ url: async () => (await this.rest.getInfo()).gatewayUrl,
66
+ token: this.#options.token,
67
+ intents,
68
+ createSocket,
69
+ random: this.#internals.random ?? Math.random,
70
+ onDispatch: (name, data) => {
71
+ try {
72
+ this.#dispatch(name, data);
73
+ }
74
+ catch (error) {
75
+ this.#failed(name, error);
76
+ }
77
+ },
78
+ onDisconnected: (code, reason) => {
79
+ this.#emit("disconnected", { code, reason });
80
+ },
81
+ onClosed: (error) => this.#closed(error),
82
+ onStatus: (status) => {
83
+ this.#status = status;
84
+ },
85
+ });
86
+ this.#gateway = gateway;
87
+ this.#connecting = new Promise((resolve, reject) => {
88
+ this.#settle = { resolve, reject };
89
+ });
90
+ this.#hook(gateway);
91
+ gateway.start();
92
+ return this.#connecting;
93
+ }
94
+ /** Ends the session and every retry. The cache stays readable; connect() starts over. */
95
+ close() {
96
+ if (!this.#gateway)
97
+ return;
98
+ this.#teardown();
99
+ this.#status = "idle";
100
+ this.#settle?.reject(new GatewayError("The client was closed."));
101
+ this.#settle = undefined;
102
+ }
103
+ /** Calls the handler for every event of that name. Returns a function that unsubscribes. */
104
+ on(name, handler) {
105
+ return this.#events.on(name, handler);
106
+ }
107
+ /** Like on(), for the next event of that name only. */
108
+ once(name, handler) {
109
+ return this.#events.once(name, handler);
110
+ }
111
+ #teardown() {
112
+ this.#gateway?.stop();
113
+ this.#gateway = undefined;
114
+ this.#connecting = undefined;
115
+ this.#ready = undefined;
116
+ this.#waiting.clear();
117
+ this.#unhook?.();
118
+ this.#unhook = undefined;
119
+ }
120
+ #closed(error) {
121
+ this.#teardown();
122
+ this.#status = "closed";
123
+ const settle = this.#settle;
124
+ this.#settle = undefined;
125
+ this.#emit("closed", { code: error.code, reason: error.message });
126
+ settle?.reject(error);
127
+ }
128
+ #dispatch(name, data) {
129
+ if (name === "READY") {
130
+ const ready = fromWire(data);
131
+ this.#principal = ready.principal;
132
+ this.#intents = ready.intents;
133
+ this.#ready = { principal: ready.principal, users: ready.users, intents: ready.intents };
134
+ this.#waiting = new Set(ready.users);
135
+ const self = "userId" in ready.principal ? ready.principal.userId : undefined;
136
+ for (const userId of this.#store.begin(ready.users, ready.intents, self)) {
137
+ this.#emit("user.gone", { userId });
138
+ }
139
+ this.#arrived();
140
+ return;
141
+ }
142
+ if (name === "RESUMED") {
143
+ this.#emit("resumed", {});
144
+ return;
145
+ }
146
+ if (!hubEvents.has(name))
147
+ return;
148
+ const applied = this.#store.apply(name, data);
149
+ const event = withoutOld.has(name)
150
+ ? applied.event
151
+ : { ...applied.event, old: applied.old };
152
+ this.#emit(name, event);
153
+ const userId = event.userId;
154
+ if (applied.synced !== undefined) {
155
+ this.#emit("user.ready", { userId: applied.synced });
156
+ this.#arrived(applied.synced);
157
+ }
158
+ else if (name === "user.gone" && userId !== undefined) {
159
+ this.#arrived(userId);
160
+ }
161
+ }
162
+ #arrived(userId) {
163
+ if (userId !== undefined && !this.#waiting.delete(userId))
164
+ return;
165
+ if (this.#waiting.size > 0 || !this.#ready)
166
+ return;
167
+ const ready = this.#ready;
168
+ this.#ready = undefined;
169
+ this.#settle?.resolve();
170
+ this.#settle = undefined;
171
+ this.#emit("ready", ready);
172
+ }
173
+ #emit(name, event) {
174
+ this.#events.emit(name, event, (error) => this.#failed(name, error));
175
+ }
176
+ #failed(name, error) {
177
+ if (name === "error" || !this.#events.has("error")) {
178
+ console.error(`plsremind: handling "${name}" failed`, error);
179
+ return;
180
+ }
181
+ this.#emit("error", { error, event: name });
182
+ }
183
+ #hook(gateway) {
184
+ const page = globalThis;
185
+ if (typeof page.addEventListener !== "function")
186
+ return;
187
+ const online = () => gateway.wake();
188
+ const visible = () => {
189
+ if (page.document?.visibilityState === "visible")
190
+ gateway.wake();
191
+ };
192
+ page.addEventListener("online", online);
193
+ page.document?.addEventListener?.("visibilitychange", visible);
194
+ this.#unhook = () => {
195
+ page.removeEventListener?.("online", online);
196
+ page.document?.removeEventListener?.("visibilitychange", visible);
197
+ };
198
+ }
199
+ }
@@ -0,0 +1,8 @@
1
+ /** Renames the keys of a flat object without reading anything into its values. */
2
+ export declare function camelKeys<V>(value: Record<string, V>): Record<string, V>;
3
+ /** Turns a value in the API's form into the SDK's: camelCase names, Dates, milliseconds. */
4
+ export declare function fromWire<T = unknown>(value: unknown): T;
5
+ /** The opposite of fromWire, for request bodies. Fields that are undefined are left out. */
6
+ export declare function toWire(value: unknown): unknown;
7
+ /** Microseconds since 1970 of an RFC 3339 instant, which a Date would round to milliseconds. */
8
+ export declare function microsOf(text: string): bigint;
@@ -0,0 +1,123 @@
1
+ import { formatDuration, parseDuration } from "./duration.js";
2
+ const instants = new Set([
3
+ "created_at",
4
+ "updated_at",
5
+ "due_at",
6
+ "completed_at",
7
+ "remind_at",
8
+ "scheduled_for",
9
+ "fire_at",
10
+ "fired_at",
11
+ "expires_at",
12
+ "used_at",
13
+ "last_used_at",
14
+ "closed_at",
15
+ "at",
16
+ ]);
17
+ const camelNames = new Map();
18
+ const snakeNames = new Map();
19
+ function camel(name) {
20
+ let out = camelNames.get(name);
21
+ if (out === undefined) {
22
+ out = name.replace(/_+([a-z0-9])/g, (_, letter) => letter.toUpperCase());
23
+ camelNames.set(name, out);
24
+ }
25
+ return out;
26
+ }
27
+ function snake(name) {
28
+ let out = snakeNames.get(name);
29
+ if (out === undefined) {
30
+ out = name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
31
+ snakeNames.set(name, out);
32
+ }
33
+ return out;
34
+ }
35
+ /** Renames the keys of a flat object without reading anything into its values. */
36
+ export function camelKeys(value) {
37
+ const out = {};
38
+ for (const [key, field] of Object.entries(value))
39
+ out[camel(key)] = field;
40
+ return out;
41
+ }
42
+ /** Turns a value in the API's form into the SDK's: camelCase names, Dates, milliseconds. */
43
+ export function fromWire(value) {
44
+ return read(value);
45
+ }
46
+ function read(value) {
47
+ if (Array.isArray(value))
48
+ return value.map(read);
49
+ if (value === null || typeof value !== "object")
50
+ return value;
51
+ const out = {};
52
+ for (const [key, field] of Object.entries(value)) {
53
+ out[camel(key)] = readField(key, field);
54
+ }
55
+ return out;
56
+ }
57
+ function readField(key, field) {
58
+ if (key === "preferences")
59
+ return field;
60
+ if (typeof field === "string") {
61
+ if (instants.has(key)) {
62
+ const date = new Date(field);
63
+ return Number.isNaN(date.getTime()) ? field : date;
64
+ }
65
+ if (key === "offset")
66
+ return duration(field) ?? field;
67
+ return field;
68
+ }
69
+ if (key === "before" && Array.isArray(field)) {
70
+ const parts = field.map((part) => (typeof part === "string" ? duration(part) : undefined));
71
+ if (parts.every((part) => part !== undefined))
72
+ return parts;
73
+ }
74
+ return read(field);
75
+ }
76
+ // A newer hub may write a value this SDK cannot read. It is then handed on as it came.
77
+ function duration(text) {
78
+ try {
79
+ return parseDuration(text);
80
+ }
81
+ catch {
82
+ return undefined;
83
+ }
84
+ }
85
+ /** The opposite of fromWire, for request bodies. Fields that are undefined are left out. */
86
+ export function toWire(value) {
87
+ if (Array.isArray(value))
88
+ return value.map(toWire);
89
+ if (value instanceof Date)
90
+ return value.toISOString();
91
+ if (value === null || typeof value !== "object")
92
+ return value;
93
+ const out = {};
94
+ for (const [key, field] of Object.entries(value)) {
95
+ if (field === undefined)
96
+ continue;
97
+ out[snake(key)] = writeField(key, field);
98
+ }
99
+ return out;
100
+ }
101
+ function writeField(key, field) {
102
+ if (key === "preferences")
103
+ return field;
104
+ if ((key === "in" || key === "expiresIn") && typeof field === "number") {
105
+ return formatDuration(field);
106
+ }
107
+ if (key === "before" && Array.isArray(field) && field.every((part) => typeof part === "number")) {
108
+ return field.map(formatDuration);
109
+ }
110
+ return toWire(field);
111
+ }
112
+ const instant = /^(.*?)(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/i;
113
+ /** Microseconds since 1970 of an RFC 3339 instant, which a Date would round to milliseconds. */
114
+ export function microsOf(text) {
115
+ const match = instant.exec(text);
116
+ if (!match)
117
+ throw new RangeError(`not an instant: ${JSON.stringify(text)}`);
118
+ const seconds = Date.parse(`${match[1]}${match[3]}`);
119
+ if (Number.isNaN(seconds))
120
+ throw new RangeError(`not an instant: ${JSON.stringify(text)}`);
121
+ const fraction = (match[2] ?? "").slice(0, 6).padEnd(6, "0");
122
+ return BigInt(seconds) * 1000n + BigInt(fraction);
123
+ }
@@ -0,0 +1,4 @@
1
+ /** Reads a duration as the API writes it ("3d", "1d12h", "90m") into milliseconds. */
2
+ export declare function parseDuration(text: string): number;
3
+ /** Writes milliseconds the way the API reads durations. Only whole minutes above zero. */
4
+ export declare function formatDuration(ms: number): string;
@@ -0,0 +1,35 @@
1
+ const units = [
2
+ ["d", 86_400_000],
3
+ ["h", 3_600_000],
4
+ ["m", 60_000],
5
+ ];
6
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?$/;
7
+ /** Reads a duration as the API writes it ("3d", "1d12h", "90m") into milliseconds. */
8
+ export function parseDuration(text) {
9
+ const match = pattern.exec(text);
10
+ if (!match || text === "") {
11
+ throw new RangeError(`invalid duration ${JSON.stringify(text)}`);
12
+ }
13
+ let total = 0;
14
+ units.forEach(([, size], i) => {
15
+ const part = match[i + 1];
16
+ if (part !== undefined)
17
+ total += Number(part) * size;
18
+ });
19
+ return total;
20
+ }
21
+ /** Writes milliseconds the way the API reads durations. Only whole minutes above zero. */
22
+ export function formatDuration(ms) {
23
+ if (!Number.isFinite(ms) || ms <= 0 || ms % 60_000 !== 0) {
24
+ throw new RangeError(`a duration must be a positive number of whole minutes, got ${ms}`);
25
+ }
26
+ let rest = ms;
27
+ let text = "";
28
+ for (const [suffix, size] of units) {
29
+ const count = Math.floor(rest / size);
30
+ if (count > 0)
31
+ text += `${count}${suffix}`;
32
+ rest -= count * size;
33
+ }
34
+ return text;
35
+ }
@@ -0,0 +1,10 @@
1
+ type Handler<E> = (event: E) => unknown;
2
+ export declare class Emitter<M> {
3
+ #private;
4
+ on<K extends keyof M>(name: K, handler: Handler<M[K]>): () => void;
5
+ once<K extends keyof M>(name: K, handler: Handler<M[K]>): () => void;
6
+ has(name: keyof M): boolean;
7
+ /** Runs the handlers in the order they were added. Promises are not waited for. */
8
+ emit<K extends keyof M>(name: K, event: M[K], onError: (error: unknown) => void): void;
9
+ }
10
+ export {};
@@ -0,0 +1,39 @@
1
+ export class Emitter {
2
+ #handlers = new Map();
3
+ on(name, handler) {
4
+ const own = (event) => handler(event);
5
+ let handlers = this.#handlers.get(name);
6
+ if (!handlers)
7
+ this.#handlers.set(name, (handlers = new Set()));
8
+ handlers.add(own);
9
+ return () => {
10
+ handlers.delete(own);
11
+ };
12
+ }
13
+ once(name, handler) {
14
+ const off = this.on(name, (event) => {
15
+ off();
16
+ return handler(event);
17
+ });
18
+ return off;
19
+ }
20
+ has(name) {
21
+ return (this.#handlers.get(name)?.size ?? 0) > 0;
22
+ }
23
+ /** Runs the handlers in the order they were added. Promises are not waited for. */
24
+ emit(name, event, onError) {
25
+ const handlers = this.#handlers.get(name);
26
+ if (!handlers)
27
+ return;
28
+ for (const handler of [...handlers]) {
29
+ try {
30
+ const result = handler(event);
31
+ if (result instanceof Promise)
32
+ result.catch(onError);
33
+ }
34
+ catch (error) {
35
+ onError(error);
36
+ }
37
+ }
38
+ }
39
+ }
@@ -0,0 +1,21 @@
1
+ /** The hub answered with an error. */
2
+ export declare class ApiError extends Error {
3
+ readonly name = "ApiError";
4
+ readonly status: number;
5
+ readonly code: string;
6
+ /** What is wrong with which field of the request, by the field's SDK name. */
7
+ readonly fields: Readonly<Record<string, string>> | undefined;
8
+ constructor(status: number, code: string, message: string, fields?: Readonly<Record<string, string>>);
9
+ }
10
+ /** The hub did not answer, or not in a way that could be read. */
11
+ export declare class NetworkError extends Error {
12
+ readonly name = "NetworkError";
13
+ constructor(message: string, cause?: unknown);
14
+ }
15
+ /** The gateway connection ended and will not be tried again. */
16
+ export declare class GatewayError extends Error {
17
+ readonly name = "GatewayError";
18
+ /** The close code, if the hub gave one. */
19
+ readonly code: number | undefined;
20
+ constructor(message: string, code?: number, cause?: unknown);
21
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,31 @@
1
+ /** The hub answered with an error. */
2
+ export class ApiError extends Error {
3
+ name = "ApiError";
4
+ status;
5
+ code;
6
+ /** What is wrong with which field of the request, by the field's SDK name. */
7
+ fields;
8
+ constructor(status, code, message, fields) {
9
+ super(message);
10
+ this.status = status;
11
+ this.code = code;
12
+ this.fields = fields;
13
+ }
14
+ }
15
+ /** The hub did not answer, or not in a way that could be read. */
16
+ export class NetworkError extends Error {
17
+ name = "NetworkError";
18
+ constructor(message, cause) {
19
+ super(message, { cause });
20
+ }
21
+ }
22
+ /** The gateway connection ended and will not be tried again. */
23
+ export class GatewayError extends Error {
24
+ name = "GatewayError";
25
+ /** The close code, if the hub gave one. */
26
+ code;
27
+ constructor(message, code, cause) {
28
+ super(message, { cause });
29
+ this.code = code;
30
+ }
31
+ }
@@ -0,0 +1,152 @@
1
+ import type { Delivery, DeliveryStatus, DeliveryTest, Intent, Item, List, ManualReminder, Profile, ReminderPlan, Subitem, UserConnection } from "./types.js";
2
+ /** Who made a change. Compare `id` with `client.principal.id` to recognise your own. */
3
+ export interface Actor {
4
+ readonly kind: "session" | "personal_token" | "connection";
5
+ readonly id: string;
6
+ }
7
+ /** Who the client is logged in as. `id` is the token, login or connection it came with. */
8
+ export type Principal = {
9
+ readonly kind: "personal_token" | "session";
10
+ readonly id: string;
11
+ readonly userId: string;
12
+ } | {
13
+ readonly kind: "connection";
14
+ readonly id: string;
15
+ readonly connection: {
16
+ readonly id: string;
17
+ readonly name: string;
18
+ readonly provider: string;
19
+ };
20
+ };
21
+ export interface ChangeEvent<D, O = D> {
22
+ /** The user the change is about. */
23
+ readonly userId: string;
24
+ /** Null when the hub made the change by itself. */
25
+ readonly actor: Actor | null;
26
+ /** The nonce of the request that made the change, if it sent one. */
27
+ readonly nonce: string | null;
28
+ /** The whole object after the change. */
29
+ readonly data: D;
30
+ /** The object as the cache held it before, if it held one. */
31
+ readonly old: O | undefined;
32
+ }
33
+ export type UserUpdatedEvent = ChangeEvent<Profile>;
34
+ export type ConnectionUpdatedEvent = ChangeEvent<UserConnection, never>;
35
+ export type ListCreatedEvent = ChangeEvent<List>;
36
+ export type ListUpdatedEvent = ChangeEvent<List>;
37
+ export type ListDeletedEvent = ChangeEvent<{
38
+ readonly id: string;
39
+ }, List>;
40
+ export type ItemCreatedEvent = ChangeEvent<Item>;
41
+ export type ItemUpdatedEvent = ChangeEvent<Item>;
42
+ export type ItemDeletedEvent = ChangeEvent<{
43
+ readonly id: string;
44
+ }, Item>;
45
+ export type SubitemCreatedEvent = ChangeEvent<Subitem>;
46
+ export type SubitemUpdatedEvent = ChangeEvent<Subitem>;
47
+ export type SubitemDeletedEvent = ChangeEvent<{
48
+ readonly id: string;
49
+ readonly itemId: string;
50
+ }, Subitem>;
51
+ export type ReminderCreatedEvent = ChangeEvent<ManualReminder>;
52
+ export type ReminderDeletedEvent = ChangeEvent<{
53
+ readonly id: string;
54
+ readonly itemId: string;
55
+ }, ManualReminder>;
56
+ export type PlanUpdatedEvent = ChangeEvent<ReminderPlan>;
57
+ export interface DeliveryCreatedEvent {
58
+ readonly userId: string;
59
+ readonly actor: null;
60
+ readonly nonce: null;
61
+ readonly data: Delivery;
62
+ }
63
+ export interface DeliveryTestEvent {
64
+ readonly userId: string;
65
+ readonly actor: null;
66
+ readonly nonce: null;
67
+ readonly data: DeliveryTest;
68
+ }
69
+ export interface DeliveryClosedEvent {
70
+ readonly userId: string;
71
+ readonly actor: null;
72
+ readonly nonce: null;
73
+ readonly data: {
74
+ readonly id: string;
75
+ readonly status: DeliveryStatus;
76
+ };
77
+ }
78
+ /** One part of a user's state as it arrives. Most code wants `user.ready` instead. */
79
+ export interface UserSyncEvent {
80
+ readonly userId: string;
81
+ readonly chunk: {
82
+ readonly index: number;
83
+ readonly count: number;
84
+ };
85
+ readonly user?: Profile;
86
+ readonly lists?: readonly List[];
87
+ readonly items?: readonly Item[];
88
+ readonly plans?: readonly ReminderPlan[];
89
+ readonly history?: readonly Item[];
90
+ readonly historyCursor?: string | null;
91
+ }
92
+ /** A connection lost a user, or a new session no longer covers them. */
93
+ export interface UserGoneEvent {
94
+ readonly userId: string;
95
+ }
96
+ export interface ReadyEvent {
97
+ readonly principal: Principal;
98
+ readonly users: readonly string[];
99
+ readonly intents: readonly Intent[];
100
+ }
101
+ export interface UserReadyEvent {
102
+ readonly userId: string;
103
+ }
104
+ export type ResumedEvent = Readonly<Record<string, never>>;
105
+ export interface DisconnectedEvent {
106
+ readonly code: number | undefined;
107
+ readonly reason: string;
108
+ }
109
+ export interface ClosedEvent {
110
+ readonly code: number | undefined;
111
+ readonly reason: string;
112
+ }
113
+ export interface ErrorEvent {
114
+ readonly error: unknown;
115
+ /** The event that was being handled. */
116
+ readonly event: string;
117
+ }
118
+ export interface EventMap {
119
+ "user.sync": UserSyncEvent;
120
+ "user.gone": UserGoneEvent;
121
+ "user.updated": UserUpdatedEvent;
122
+ "connection.updated": ConnectionUpdatedEvent;
123
+ "list.created": ListCreatedEvent;
124
+ "list.updated": ListUpdatedEvent;
125
+ "list.deleted": ListDeletedEvent;
126
+ "item.created": ItemCreatedEvent;
127
+ "item.updated": ItemUpdatedEvent;
128
+ "item.deleted": ItemDeletedEvent;
129
+ "subitem.created": SubitemCreatedEvent;
130
+ "subitem.updated": SubitemUpdatedEvent;
131
+ "subitem.deleted": SubitemDeletedEvent;
132
+ "reminder.created": ReminderCreatedEvent;
133
+ "reminder.deleted": ReminderDeletedEvent;
134
+ "plan.updated": PlanUpdatedEvent;
135
+ "delivery.created": DeliveryCreatedEvent;
136
+ "delivery.closed": DeliveryClosedEvent;
137
+ /** The user asked to see that this app reaches them; answer with `rest.reportTest`. */
138
+ "delivery.test": DeliveryTestEvent;
139
+ /** After every new login, once the state of every user is complete. */
140
+ ready: ReadyEvent;
141
+ /** One user's state is complete. */
142
+ "user.ready": UserReadyEvent;
143
+ /** A dropped connection was picked up again without losing anything. */
144
+ resumed: ResumedEvent;
145
+ /** The connection is gone and is being opened again. */
146
+ disconnected: DisconnectedEvent;
147
+ /** The client gave up: the first connect failed, or the hub refuses the token or intents. */
148
+ closed: ClosedEvent;
149
+ /** A handler threw or its promise rejected, or an event could not be taken in. */
150
+ error: ErrorEvent;
151
+ }
152
+ export declare const hubEventNames: readonly ["user.sync", "user.gone", "user.updated", "connection.updated", "list.created", "list.updated", "list.deleted", "item.created", "item.updated", "item.deleted", "subitem.created", "subitem.updated", "subitem.deleted", "reminder.created", "reminder.deleted", "plan.updated", "delivery.created", "delivery.closed", "delivery.test"];
package/dist/events.js ADDED
@@ -0,0 +1,21 @@
1
+ export const hubEventNames = [
2
+ "user.sync",
3
+ "user.gone",
4
+ "user.updated",
5
+ "connection.updated",
6
+ "list.created",
7
+ "list.updated",
8
+ "list.deleted",
9
+ "item.created",
10
+ "item.updated",
11
+ "item.deleted",
12
+ "subitem.created",
13
+ "subitem.updated",
14
+ "subitem.deleted",
15
+ "reminder.created",
16
+ "reminder.deleted",
17
+ "plan.updated",
18
+ "delivery.created",
19
+ "delivery.closed",
20
+ "delivery.test",
21
+ ];
@@ -0,0 +1,34 @@
1
+ import { GatewayError } from "./errors.js";
2
+ export interface SocketLike {
3
+ send(text: string): void;
4
+ close(code?: number): void;
5
+ onopen: (() => void) | null;
6
+ onmessage: ((event: {
7
+ data: unknown;
8
+ }) => void) | null;
9
+ onclose: ((event: {
10
+ code: number;
11
+ reason: string;
12
+ }) => void) | null;
13
+ onerror: (() => void) | null;
14
+ }
15
+ export interface GatewayOptions {
16
+ url: () => Promise<string>;
17
+ token: string | undefined;
18
+ intents: readonly string[];
19
+ createSocket: (url: string) => SocketLike;
20
+ random: () => number;
21
+ onDispatch: (name: string, data: unknown) => void;
22
+ onDisconnected: (code: number | undefined, reason: string) => void;
23
+ onClosed: (error: GatewayError) => void;
24
+ onStatus: (status: "connecting" | "connected" | "reconnecting") => void;
25
+ }
26
+ /** One gateway session kept alive across drops. It knows nothing about what the events mean. */
27
+ export declare class Gateway {
28
+ #private;
29
+ constructor(options: GatewayOptions);
30
+ start(): void;
31
+ stop(): void;
32
+ /** Connects now instead of sitting out the rest of a wait. */
33
+ wake(): void;
34
+ }