@cicord/react 0.0.0-bootstrap.0 → 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/LICENSE +202 -0
- package/README.md +48 -0
- package/dist/index.d.mts +277 -0
- package/dist/index.mjs +742 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +67 -1
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,742 @@
|
|
|
1
|
+
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
2
|
+
import { Fragment, jsx } from "react/jsx-runtime";
|
|
3
|
+
import { CicordApiError, resolveRoute } from "@cicord/client";
|
|
4
|
+
// src/cache.ts
|
|
5
|
+
const IDLE = Object.freeze({
|
|
6
|
+
status: "idle",
|
|
7
|
+
data: void 0,
|
|
8
|
+
error: void 0,
|
|
9
|
+
fetching: false,
|
|
10
|
+
updatedAt: 0
|
|
11
|
+
});
|
|
12
|
+
const hashKey = (key) => JSON.stringify(key);
|
|
13
|
+
var QueryCache = class {
|
|
14
|
+
#entries = /* @__PURE__ */ new Map();
|
|
15
|
+
#entry(hash) {
|
|
16
|
+
let entry = this.#entries.get(hash);
|
|
17
|
+
if (!entry) {
|
|
18
|
+
entry = {
|
|
19
|
+
state: IDLE,
|
|
20
|
+
promise: void 0,
|
|
21
|
+
controller: void 0,
|
|
22
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
23
|
+
fn: void 0
|
|
24
|
+
};
|
|
25
|
+
this.#entries.set(hash, entry);
|
|
26
|
+
}
|
|
27
|
+
return entry;
|
|
28
|
+
}
|
|
29
|
+
#set(entry, state) {
|
|
30
|
+
entry.state = state;
|
|
31
|
+
for (const listener of Array.from(entry.listeners)) listener();
|
|
32
|
+
}
|
|
33
|
+
getState(key) {
|
|
34
|
+
return this.#entries.get(hashKey(key))?.state ?? IDLE;
|
|
35
|
+
}
|
|
36
|
+
subscribe(key, listener) {
|
|
37
|
+
const entry = this.#entry(hashKey(key));
|
|
38
|
+
entry.listeners.add(listener);
|
|
39
|
+
return () => entry.listeners.delete(listener);
|
|
40
|
+
}
|
|
41
|
+
/** Fetches unless a request is in flight (or data exists and `force` is false). */
|
|
42
|
+
fetch(key, fn, options = {}) {
|
|
43
|
+
const entry = this.#entry(hashKey(key));
|
|
44
|
+
entry.fn = fn;
|
|
45
|
+
if (entry.promise) return entry.promise;
|
|
46
|
+
if (!options.force && entry.state.status === "success") return Promise.resolve(entry.state.data);
|
|
47
|
+
const controller = new AbortController();
|
|
48
|
+
entry.controller = controller;
|
|
49
|
+
this.#set(entry, {
|
|
50
|
+
...entry.state,
|
|
51
|
+
status: entry.state.status === "success" ? "success" : "loading",
|
|
52
|
+
fetching: true
|
|
53
|
+
});
|
|
54
|
+
const promise = fn(controller.signal).then((data) => {
|
|
55
|
+
if (entry.promise === promise) {
|
|
56
|
+
entry.promise = void 0;
|
|
57
|
+
this.#set(entry, {
|
|
58
|
+
status: "success",
|
|
59
|
+
data,
|
|
60
|
+
error: void 0,
|
|
61
|
+
fetching: false,
|
|
62
|
+
updatedAt: Date.now()
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
return data;
|
|
66
|
+
}, (error) => {
|
|
67
|
+
if (entry.promise === promise) {
|
|
68
|
+
entry.promise = void 0;
|
|
69
|
+
this.#set(entry, {
|
|
70
|
+
...entry.state,
|
|
71
|
+
status: "error",
|
|
72
|
+
error,
|
|
73
|
+
fetching: false,
|
|
74
|
+
updatedAt: Date.now()
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
throw error;
|
|
78
|
+
});
|
|
79
|
+
entry.promise = promise;
|
|
80
|
+
return promise;
|
|
81
|
+
}
|
|
82
|
+
setData(key, data) {
|
|
83
|
+
const entry = this.#entry(hashKey(key));
|
|
84
|
+
const next = typeof data === "function" ? data(entry.state.data) : data;
|
|
85
|
+
entry.controller?.abort();
|
|
86
|
+
entry.promise = void 0;
|
|
87
|
+
this.#set(entry, {
|
|
88
|
+
status: "success",
|
|
89
|
+
data: next,
|
|
90
|
+
error: void 0,
|
|
91
|
+
fetching: false,
|
|
92
|
+
updatedAt: Date.now()
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Marks queries whose key starts with `prefix` as stale and refetches the ones that are
|
|
97
|
+
* currently observed. Without a prefix, every query is invalidated.
|
|
98
|
+
*/
|
|
99
|
+
invalidate(prefix = []) {
|
|
100
|
+
const pending = [];
|
|
101
|
+
for (const [hash, entry] of this.#entries) {
|
|
102
|
+
const key = JSON.parse(hash);
|
|
103
|
+
if (!prefix.every((part, i) => key[i] === part)) continue;
|
|
104
|
+
entry.controller?.abort();
|
|
105
|
+
entry.promise = void 0;
|
|
106
|
+
if (entry.listeners.size > 0 && entry.fn) pending.push(this.fetch(key, entry.fn, { force: true }).catch(() => void 0));
|
|
107
|
+
else this.#entries.delete(hash);
|
|
108
|
+
}
|
|
109
|
+
return Promise.all(pending).then(() => void 0);
|
|
110
|
+
}
|
|
111
|
+
clear() {
|
|
112
|
+
for (const entry of this.#entries.values()) entry.controller?.abort();
|
|
113
|
+
this.#entries.clear();
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
// src/provider.tsx
|
|
117
|
+
const CicordContext = createContext(null);
|
|
118
|
+
function CicordProvider({ client, server, cache, children }) {
|
|
119
|
+
const [ownCache] = useState(() => new QueryCache());
|
|
120
|
+
const store = cache ?? ownCache;
|
|
121
|
+
useEffect(() => client.onSessionChange(() => {
|
|
122
|
+
if (!client.session()) {
|
|
123
|
+
store.setData(["cicord", "me"], null);
|
|
124
|
+
store.invalidate(["cicord", "portal"]);
|
|
125
|
+
store.invalidate(["cicord", "plugin"]);
|
|
126
|
+
}
|
|
127
|
+
}), [client, store]);
|
|
128
|
+
const value = useMemo(() => ({
|
|
129
|
+
client,
|
|
130
|
+
server,
|
|
131
|
+
cache: store
|
|
132
|
+
}), [
|
|
133
|
+
client,
|
|
134
|
+
server,
|
|
135
|
+
store
|
|
136
|
+
]);
|
|
137
|
+
return /* @__PURE__ */ jsx(CicordContext.Provider, {
|
|
138
|
+
value,
|
|
139
|
+
children
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
function useCicord() {
|
|
143
|
+
const value = useContext(CicordContext);
|
|
144
|
+
if (!value) throw new Error("@cicord/react: wrap your app in <CicordProvider client={…}>");
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
function useCicordClient() {
|
|
148
|
+
return useCicord().client;
|
|
149
|
+
}
|
|
150
|
+
/** The given server key, or the provider's (undefined while unknown: hooks then wait). */
|
|
151
|
+
function useServerKey(server) {
|
|
152
|
+
const fallback = useCicord().server;
|
|
153
|
+
return server ?? fallback;
|
|
154
|
+
}
|
|
155
|
+
// src/hooks.ts
|
|
156
|
+
/** Cached query bound to the provider's cache. `key: null` disables the query. */
|
|
157
|
+
function useCicordQuery(key, fn, options = {}) {
|
|
158
|
+
const { cache } = useCicord();
|
|
159
|
+
const enabled = key !== null && (options.enabled ?? true);
|
|
160
|
+
const hash = key ? hashKey(key) : "";
|
|
161
|
+
const fnRef = useRef(fn);
|
|
162
|
+
fnRef.current = fn;
|
|
163
|
+
const keyRef = useRef(key);
|
|
164
|
+
keyRef.current = key;
|
|
165
|
+
const subscribe = useCallback((listener) => keyRef.current ? cache.subscribe(keyRef.current, listener) : () => {}, [cache, hash]);
|
|
166
|
+
const getSnapshot = useCallback(() => keyRef.current ? cache.getState(keyRef.current) : void 0, [cache, hash]);
|
|
167
|
+
const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
168
|
+
useEffect(() => {
|
|
169
|
+
if (!enabled || !keyRef.current) return;
|
|
170
|
+
cache.fetch(keyRef.current, (signal) => fnRef.current(signal)).catch(() => void 0);
|
|
171
|
+
}, [
|
|
172
|
+
cache,
|
|
173
|
+
hash,
|
|
174
|
+
enabled
|
|
175
|
+
]);
|
|
176
|
+
const refetch = useCallback(async () => {
|
|
177
|
+
if (!keyRef.current) return void 0;
|
|
178
|
+
try {
|
|
179
|
+
return await cache.fetch(keyRef.current, (signal) => fnRef.current(signal), { force: true });
|
|
180
|
+
} catch {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
}, [cache]);
|
|
184
|
+
const status = state?.status ?? "idle";
|
|
185
|
+
return {
|
|
186
|
+
data: state?.data,
|
|
187
|
+
error: state?.error,
|
|
188
|
+
status: enabled && status === "idle" ? "loading" : status,
|
|
189
|
+
isLoading: enabled && (status === "idle" || status === "loading"),
|
|
190
|
+
isFetching: state?.fetching ?? false,
|
|
191
|
+
refetch
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
const cicordKeys = {
|
|
195
|
+
me: () => ["cicord", "me"],
|
|
196
|
+
portalServers: () => [
|
|
197
|
+
"cicord",
|
|
198
|
+
"portal",
|
|
199
|
+
"servers"
|
|
200
|
+
],
|
|
201
|
+
portalServer: (server) => [
|
|
202
|
+
"cicord",
|
|
203
|
+
"portal",
|
|
204
|
+
server
|
|
205
|
+
],
|
|
206
|
+
member: (server) => [
|
|
207
|
+
"cicord",
|
|
208
|
+
"portal",
|
|
209
|
+
server,
|
|
210
|
+
"me"
|
|
211
|
+
],
|
|
212
|
+
plugin: (server, bot, instance, path, query) => [
|
|
213
|
+
"cicord",
|
|
214
|
+
"plugin",
|
|
215
|
+
server,
|
|
216
|
+
bot,
|
|
217
|
+
instance,
|
|
218
|
+
path,
|
|
219
|
+
query ? JSON.stringify(query) : null
|
|
220
|
+
]
|
|
221
|
+
};
|
|
222
|
+
const nullOn401 = async (promise) => {
|
|
223
|
+
try {
|
|
224
|
+
return await promise;
|
|
225
|
+
} catch (error) {
|
|
226
|
+
if (error instanceof CicordApiError && error.code === "unauthenticated") return null;
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
/** Current user (`GET /me`); `data` is `null` when logged out. */
|
|
231
|
+
function useMe() {
|
|
232
|
+
const { client } = useCicord();
|
|
233
|
+
return useCicordQuery(cicordKeys.me(), (signal) => client.meOrNull({ signal }));
|
|
234
|
+
}
|
|
235
|
+
const exchanges = /* @__PURE__ */ new WeakMap();
|
|
236
|
+
/** The login credential left in the current URL: `cicord_token` (bot link) or, in token mode, `cicord_code`. */
|
|
237
|
+
function urlCredential(param, tokenMode) {
|
|
238
|
+
if (typeof location === "undefined") return null;
|
|
239
|
+
const params = new URL(location.href).searchParams;
|
|
240
|
+
return params.get(param) ?? (tokenMode ? params.get("cicord_code") : null);
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Exchanges the `cicord_token` of the current URL (signed link sent by a bot) — or, in token
|
|
244
|
+
* mode, the `cicord_code` of an OAuth login — for a session, once. The parameter is removed
|
|
245
|
+
* from the address bar immediately. On success, the cached user and member queries are
|
|
246
|
+
* refreshed.
|
|
247
|
+
*/
|
|
248
|
+
function useLinkTokenLogin(options = {}) {
|
|
249
|
+
const { client, cache } = useCicord();
|
|
250
|
+
const param = options.param ?? "cicord_token";
|
|
251
|
+
const tokenMode = client.authMode === "token";
|
|
252
|
+
const [state, setState] = useState(() => {
|
|
253
|
+
const token = urlCredential(param, tokenMode);
|
|
254
|
+
const inflight = token ? exchanges.get(client)?.get(token) : void 0;
|
|
255
|
+
return token || inflight ? { status: "pending" } : { status: "none" };
|
|
256
|
+
});
|
|
257
|
+
const tokenRef = useRef(urlCredential(param, tokenMode));
|
|
258
|
+
useEffect(() => {
|
|
259
|
+
const token = tokenRef.current;
|
|
260
|
+
if (!token) return void 0;
|
|
261
|
+
let perClient = exchanges.get(client);
|
|
262
|
+
if (!perClient) {
|
|
263
|
+
perClient = /* @__PURE__ */ new Map();
|
|
264
|
+
exchanges.set(client, perClient);
|
|
265
|
+
}
|
|
266
|
+
let promise = perClient.get(token);
|
|
267
|
+
if (!promise) {
|
|
268
|
+
promise = client.auth.exchangeLinkToken({ param });
|
|
269
|
+
perClient.set(token, promise);
|
|
270
|
+
}
|
|
271
|
+
let active = true;
|
|
272
|
+
const exchange = promise;
|
|
273
|
+
const settle = async () => {
|
|
274
|
+
let me;
|
|
275
|
+
try {
|
|
276
|
+
me = await exchange;
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if (active) setState({
|
|
279
|
+
status: "error",
|
|
280
|
+
error
|
|
281
|
+
});
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
if (!active) return;
|
|
285
|
+
if (me) {
|
|
286
|
+
cache.setData(cicordKeys.me(), me);
|
|
287
|
+
cache.invalidate(["cicord", "portal"]);
|
|
288
|
+
cache.invalidate(["cicord", "plugin"]);
|
|
289
|
+
setState({
|
|
290
|
+
status: "success",
|
|
291
|
+
me
|
|
292
|
+
});
|
|
293
|
+
} else setState({ status: "none" });
|
|
294
|
+
};
|
|
295
|
+
settle();
|
|
296
|
+
return () => {
|
|
297
|
+
active = false;
|
|
298
|
+
};
|
|
299
|
+
}, [
|
|
300
|
+
client,
|
|
301
|
+
cache,
|
|
302
|
+
param
|
|
303
|
+
]);
|
|
304
|
+
return state;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* The token-mode session (`null` in cookie mode or when logged out), updated on login,
|
|
308
|
+
* logout and expiry.
|
|
309
|
+
*/
|
|
310
|
+
function useSession() {
|
|
311
|
+
const { client } = useCicord();
|
|
312
|
+
const subscribe = useCallback((fn) => client.onSessionChange(fn), [client]);
|
|
313
|
+
return useSyncExternalStore(subscribe, () => client.session()?.token ?? null, () => null) ? client.session() : null;
|
|
314
|
+
}
|
|
315
|
+
/** Logs out and clears every cached query. */
|
|
316
|
+
function useLogout() {
|
|
317
|
+
const { client, cache } = useCicord();
|
|
318
|
+
return useCallback(async () => {
|
|
319
|
+
await client.auth.logout();
|
|
320
|
+
cache.clear();
|
|
321
|
+
cache.setData(cicordKeys.me(), null);
|
|
322
|
+
}, [client, cache]);
|
|
323
|
+
}
|
|
324
|
+
function usePortalServers() {
|
|
325
|
+
const { client } = useCicord();
|
|
326
|
+
return useCicordQuery(cicordKeys.portalServers(), (signal) => client.portal.servers({ signal }));
|
|
327
|
+
}
|
|
328
|
+
/** `GET /portal/{server}` for the given (or provider's) server. */
|
|
329
|
+
function usePortalServer(server) {
|
|
330
|
+
const { client } = useCicord();
|
|
331
|
+
const key = useServerKey(server);
|
|
332
|
+
return useCicordQuery(key ? cicordKeys.portalServer(key) : null, (signal) => client.portal.server(key, { signal }));
|
|
333
|
+
}
|
|
334
|
+
/** The viewer as a member of the server; `data` is `null` when logged out. */
|
|
335
|
+
function useMember(server) {
|
|
336
|
+
const { client } = useCicord();
|
|
337
|
+
const key = useServerKey(server);
|
|
338
|
+
return useCicordQuery(key ? cicordKeys.member(key) : null, (signal) => nullOn401(client.portal.me(key, { signal })));
|
|
339
|
+
}
|
|
340
|
+
/** The viewer's roles on the server ([] when logged out or loading). */
|
|
341
|
+
function useRoles(server) {
|
|
342
|
+
return useMember(server).data?.member.roles ?? [];
|
|
343
|
+
}
|
|
344
|
+
/** Finds the instance of a plugin exposed on the server's portal (first match). */
|
|
345
|
+
function usePortalPlugin(plugin, options = {}) {
|
|
346
|
+
const server = usePortalServer(options.server);
|
|
347
|
+
return {
|
|
348
|
+
instance: server.data?.plugins.find((p) => (options.instance ? p.instance === options.instance : p.plugin === plugin) && (options.bot === void 0 || p.bot === options.bot)),
|
|
349
|
+
status: server.status,
|
|
350
|
+
error: server.error
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
/** `GET` on a plugin route, cached. Pass `ref: undefined` to wait. */
|
|
354
|
+
function usePluginQuery(ref, path, options = {}) {
|
|
355
|
+
const { client } = useCicord();
|
|
356
|
+
const server = useServerKey(ref?.server);
|
|
357
|
+
return useCicordQuery(ref && server ? cicordKeys.plugin(server, ref.bot, ref.instance, path, options.query) : null, (signal) => client.plugin(server, ref.bot, ref.instance).get(path, options.query, { signal }), options.enabled === void 0 ? {} : { enabled: options.enabled });
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* `POST`/`PUT`/`PATCH`/`DELETE` on a plugin route. On success, the plugin's cached queries are
|
|
361
|
+
* refetched (and the member query too, since plugins often change roles).
|
|
362
|
+
*/
|
|
363
|
+
function usePluginMutation(ref, path, options = {}) {
|
|
364
|
+
const { client, cache } = useCicord();
|
|
365
|
+
const server = useServerKey(ref?.server);
|
|
366
|
+
const [state, setState] = useState({
|
|
367
|
+
status: "idle",
|
|
368
|
+
data: void 0,
|
|
369
|
+
error: void 0
|
|
370
|
+
});
|
|
371
|
+
const optionsRef = useRef(options);
|
|
372
|
+
optionsRef.current = options;
|
|
373
|
+
const mutateAsync = useCallback(async (body) => {
|
|
374
|
+
if (!ref || !server) throw new Error("@cicord/react: usePluginMutation called before the plugin is known");
|
|
375
|
+
setState({
|
|
376
|
+
status: "pending",
|
|
377
|
+
data: void 0,
|
|
378
|
+
error: void 0
|
|
379
|
+
});
|
|
380
|
+
try {
|
|
381
|
+
const { method = "POST", invalidate = true, onSuccess } = optionsRef.current;
|
|
382
|
+
const result = await client.plugin(server, ref.bot, ref.instance).request(method, path, body === void 0 ? {} : { body });
|
|
383
|
+
setState({
|
|
384
|
+
status: "success",
|
|
385
|
+
data: result,
|
|
386
|
+
error: void 0
|
|
387
|
+
});
|
|
388
|
+
if (invalidate) {
|
|
389
|
+
cache.invalidate([
|
|
390
|
+
"cicord",
|
|
391
|
+
"plugin",
|
|
392
|
+
server,
|
|
393
|
+
ref.bot,
|
|
394
|
+
ref.instance
|
|
395
|
+
]);
|
|
396
|
+
cache.invalidate(cicordKeys.member(server));
|
|
397
|
+
}
|
|
398
|
+
onSuccess?.(result);
|
|
399
|
+
return result;
|
|
400
|
+
} catch (error) {
|
|
401
|
+
setState({
|
|
402
|
+
status: "error",
|
|
403
|
+
data: void 0,
|
|
404
|
+
error
|
|
405
|
+
});
|
|
406
|
+
throw error;
|
|
407
|
+
}
|
|
408
|
+
}, [
|
|
409
|
+
client,
|
|
410
|
+
cache,
|
|
411
|
+
server,
|
|
412
|
+
ref?.bot,
|
|
413
|
+
ref?.instance,
|
|
414
|
+
path
|
|
415
|
+
]);
|
|
416
|
+
return {
|
|
417
|
+
...state,
|
|
418
|
+
isPending: state.status === "pending",
|
|
419
|
+
mutateAsync,
|
|
420
|
+
mutate: useCallback((body) => void mutateAsync(body).catch(() => void 0), [mutateAsync]),
|
|
421
|
+
reset: useCallback(() => setState({
|
|
422
|
+
status: "idle",
|
|
423
|
+
data: void 0,
|
|
424
|
+
error: void 0
|
|
425
|
+
}), [])
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
function routeTarget(o) {
|
|
429
|
+
return {
|
|
430
|
+
...o.server ? { server: o.server } : {},
|
|
431
|
+
...o.bot ? { bot: o.bot } : {},
|
|
432
|
+
...o.instance ? { instance: o.instance } : {}
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* `GET` on a typed plugin route, cached: the instance is found by plugin name in
|
|
437
|
+
* `PortalServer.plugins` and the types come from the generated `src/cicord-routes.d.ts`
|
|
438
|
+
* (`PluginRouteRegistry`).
|
|
439
|
+
*
|
|
440
|
+
* ```ts
|
|
441
|
+
* const board = useRouteQuery("levels", "GET /leaderboard", { query: { limit: 50 } });
|
|
442
|
+
* const poll = useRouteQuery("polls", "GET /polls/:id", { params: { id } });
|
|
443
|
+
* ```
|
|
444
|
+
*
|
|
445
|
+
* `instance` is the plugin instance: undefined while the server loads or when the plugin is
|
|
446
|
+
* not installed (the query then stays idle).
|
|
447
|
+
*/
|
|
448
|
+
function useRouteQuery(plugin, route, ...options) {
|
|
449
|
+
const opts = options[0] ?? {};
|
|
450
|
+
const { client } = useCicord();
|
|
451
|
+
const { instance } = usePortalPlugin(plugin, routeTarget(opts));
|
|
452
|
+
const server = useServerKey(opts.server);
|
|
453
|
+
let path;
|
|
454
|
+
let invalid;
|
|
455
|
+
try {
|
|
456
|
+
[, path] = resolveRoute(route, opts.params);
|
|
457
|
+
} catch (error) {
|
|
458
|
+
invalid = error;
|
|
459
|
+
}
|
|
460
|
+
const query = opts.query;
|
|
461
|
+
return {
|
|
462
|
+
...useCicordQuery(instance && server ? cicordKeys.plugin(server, instance.bot, instance.instance, path ?? `${route} ${JSON.stringify(opts.params ?? {})}`, query) : null, (signal) => invalid !== void 0 || path === void 0 ? Promise.reject(invalid) : client.plugin(server, instance.bot, instance.instance).get(path, query, { signal }), opts.enabled === void 0 ? {} : { enabled: opts.enabled }),
|
|
463
|
+
instance
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* `POST`/`PUT`/`PATCH`/`DELETE` on a typed plugin route: `mutate({ params, body })`. On
|
|
468
|
+
* success, the plugin's cached queries are refetched (and the member query too).
|
|
469
|
+
*/
|
|
470
|
+
function useRouteMutation(plugin, route, options = {}) {
|
|
471
|
+
const { client, cache } = useCicord();
|
|
472
|
+
const { instance } = usePortalPlugin(plugin, routeTarget(options));
|
|
473
|
+
const server = useServerKey(options.server);
|
|
474
|
+
const [state, setState] = useState({
|
|
475
|
+
status: "idle",
|
|
476
|
+
data: void 0,
|
|
477
|
+
error: void 0
|
|
478
|
+
});
|
|
479
|
+
const optionsRef = useRef(options);
|
|
480
|
+
optionsRef.current = options;
|
|
481
|
+
const mutateAsync = useCallback(async (input) => {
|
|
482
|
+
if (!instance || !server) throw new Error(`@cicord/react: the ${plugin} plugin is not installed on this server`);
|
|
483
|
+
const { params, body } = input;
|
|
484
|
+
setState({
|
|
485
|
+
status: "pending",
|
|
486
|
+
data: void 0,
|
|
487
|
+
error: void 0
|
|
488
|
+
});
|
|
489
|
+
try {
|
|
490
|
+
const [method, path] = resolveRoute(route, params);
|
|
491
|
+
const result = await client.plugin(server, instance.bot, instance.instance).request(method, path, body === void 0 ? {} : { body });
|
|
492
|
+
setState({
|
|
493
|
+
status: "success",
|
|
494
|
+
data: result,
|
|
495
|
+
error: void 0
|
|
496
|
+
});
|
|
497
|
+
const { invalidate = true, onSuccess } = optionsRef.current;
|
|
498
|
+
if (invalidate) {
|
|
499
|
+
cache.invalidate([
|
|
500
|
+
"cicord",
|
|
501
|
+
"plugin",
|
|
502
|
+
server,
|
|
503
|
+
instance.bot,
|
|
504
|
+
instance.instance
|
|
505
|
+
]);
|
|
506
|
+
cache.invalidate(cicordKeys.member(server));
|
|
507
|
+
}
|
|
508
|
+
onSuccess?.(result);
|
|
509
|
+
return result;
|
|
510
|
+
} catch (error) {
|
|
511
|
+
setState({
|
|
512
|
+
status: "error",
|
|
513
|
+
data: void 0,
|
|
514
|
+
error
|
|
515
|
+
});
|
|
516
|
+
throw error;
|
|
517
|
+
}
|
|
518
|
+
}, [
|
|
519
|
+
client,
|
|
520
|
+
cache,
|
|
521
|
+
server,
|
|
522
|
+
instance?.bot,
|
|
523
|
+
instance?.instance,
|
|
524
|
+
plugin,
|
|
525
|
+
route
|
|
526
|
+
]);
|
|
527
|
+
return {
|
|
528
|
+
...state,
|
|
529
|
+
instance,
|
|
530
|
+
isPending: state.status === "pending",
|
|
531
|
+
mutateAsync,
|
|
532
|
+
mutate: useCallback((input) => void mutateAsync(input).catch(() => void 0), [mutateAsync]),
|
|
533
|
+
reset: useCallback(() => setState({
|
|
534
|
+
status: "idle",
|
|
535
|
+
data: void 0,
|
|
536
|
+
error: void 0
|
|
537
|
+
}), [])
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
// src/onboarding.tsx
|
|
541
|
+
function optionRoles(step) {
|
|
542
|
+
return new Set(step.options.map((o) => o.role));
|
|
543
|
+
}
|
|
544
|
+
/** State machine behind `<OnboardingFlow>` (headless: render whatever you want). */
|
|
545
|
+
function useOnboarding(options = {}) {
|
|
546
|
+
const found = usePortalPlugin(options.plugin ?? "onboarding", {
|
|
547
|
+
...options.server ? { server: options.server } : {},
|
|
548
|
+
...options.bot ? { bot: options.bot } : {},
|
|
549
|
+
...options.instance ? { instance: options.instance } : {}
|
|
550
|
+
});
|
|
551
|
+
const explicit = options.bot && options.instance;
|
|
552
|
+
const plugin = useMemo(() => {
|
|
553
|
+
if (explicit) return {
|
|
554
|
+
bot: options.bot,
|
|
555
|
+
instance: options.instance,
|
|
556
|
+
...options.server ? { server: options.server } : {}
|
|
557
|
+
};
|
|
558
|
+
if (!found.instance) return void 0;
|
|
559
|
+
return {
|
|
560
|
+
bot: found.instance.bot,
|
|
561
|
+
instance: found.instance.instance,
|
|
562
|
+
...options.server ? { server: options.server } : {}
|
|
563
|
+
};
|
|
564
|
+
}, [
|
|
565
|
+
explicit,
|
|
566
|
+
options.bot,
|
|
567
|
+
options.instance,
|
|
568
|
+
options.server,
|
|
569
|
+
found.instance
|
|
570
|
+
]);
|
|
571
|
+
const onCompleteRef = useRef(options.onComplete);
|
|
572
|
+
onCompleteRef.current = options.onComplete;
|
|
573
|
+
const query = usePluginQuery(plugin, "/steps");
|
|
574
|
+
const mutation = usePluginMutation(plugin, "/complete");
|
|
575
|
+
const steps = useMemo(() => query.data?.steps ?? [], [query.data]);
|
|
576
|
+
const [index, setIndex] = useState(0);
|
|
577
|
+
const [answers, setAnswers] = useState({});
|
|
578
|
+
const [result, setResult] = useState(void 0);
|
|
579
|
+
const [serverErrors, setServerErrors] = useState({});
|
|
580
|
+
useEffect(() => {
|
|
581
|
+
if (!query.data) return;
|
|
582
|
+
setAnswers(Object.fromEntries(query.data.steps.map((s) => [s.id, [...s.selected]])));
|
|
583
|
+
setIndex((i) => Math.min(i, Math.max(0, query.data.steps.length - 1)));
|
|
584
|
+
}, [query.data]);
|
|
585
|
+
const total = steps.length;
|
|
586
|
+
const step = steps[index];
|
|
587
|
+
const resolveStep = useCallback((stepId) => stepId ? steps.find((s) => s.id === stepId) : step, [steps, step]);
|
|
588
|
+
const selected = useCallback((stepId) => {
|
|
589
|
+
const s = resolveStep(stepId);
|
|
590
|
+
return s ? answers[s.id] ?? [] : [];
|
|
591
|
+
}, [answers, resolveStep]);
|
|
592
|
+
const setAnswer = useCallback((stepId, roles) => {
|
|
593
|
+
const s = steps.find((x) => x.id === stepId);
|
|
594
|
+
if (!s) return;
|
|
595
|
+
const allowed = optionRoles(s);
|
|
596
|
+
const clean = [...new Set(roles)].filter((r) => allowed.has(r));
|
|
597
|
+
setAnswers((a) => ({
|
|
598
|
+
...a,
|
|
599
|
+
[stepId]: s.multiple ? clean : clean.slice(-1)
|
|
600
|
+
}));
|
|
601
|
+
setServerErrors((e) => {
|
|
602
|
+
if (!(stepId in e)) return e;
|
|
603
|
+
const { [stepId]: _removed, ...rest } = e;
|
|
604
|
+
return rest;
|
|
605
|
+
});
|
|
606
|
+
}, [steps]);
|
|
607
|
+
const toggle = useCallback((role, stepId) => {
|
|
608
|
+
const s = resolveStep(stepId);
|
|
609
|
+
if (!s || !optionRoles(s).has(role)) return;
|
|
610
|
+
const current = answers[s.id] ?? [];
|
|
611
|
+
const has = current.includes(role);
|
|
612
|
+
if (s.multiple) setAnswer(s.id, has ? current.filter((r) => r !== role) : [...current, role]);
|
|
613
|
+
else setAnswer(s.id, has ? [] : [role]);
|
|
614
|
+
}, [
|
|
615
|
+
answers,
|
|
616
|
+
resolveStep,
|
|
617
|
+
setAnswer
|
|
618
|
+
]);
|
|
619
|
+
const stepValid = useCallback((s) => !s.required || (answers[s.id]?.length ?? 0) > 0, [answers]);
|
|
620
|
+
const canContinue = step ? stepValid(step) : false;
|
|
621
|
+
const submit = useCallback(async () => {
|
|
622
|
+
const firstInvalid = steps.findIndex((s) => !stepValid(s));
|
|
623
|
+
if (firstInvalid >= 0) {
|
|
624
|
+
setIndex(firstInvalid);
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
const payload = Object.fromEntries(steps.map((s) => [s.id, answers[s.id] ?? []]));
|
|
628
|
+
try {
|
|
629
|
+
const response = await mutation.mutateAsync({ answers: payload });
|
|
630
|
+
setResult(response);
|
|
631
|
+
setServerErrors({});
|
|
632
|
+
onCompleteRef.current?.(response);
|
|
633
|
+
return response;
|
|
634
|
+
} catch (error) {
|
|
635
|
+
if (error instanceof CicordApiError && error.diagnostics.length > 0) {
|
|
636
|
+
const byStep = {};
|
|
637
|
+
for (const d of error.diagnostics) {
|
|
638
|
+
const id = /^\/answers\/([^/]+)/.exec(d.path ?? "")?.[1];
|
|
639
|
+
if (id && !(id in byStep)) byStep[id] = d.message;
|
|
640
|
+
}
|
|
641
|
+
setServerErrors(byStep);
|
|
642
|
+
const first = steps.findIndex((s) => s.id in byStep);
|
|
643
|
+
if (first >= 0) setIndex(first);
|
|
644
|
+
}
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
}, [
|
|
648
|
+
steps,
|
|
649
|
+
answers,
|
|
650
|
+
stepValid,
|
|
651
|
+
mutation
|
|
652
|
+
]);
|
|
653
|
+
const next = useCallback(() => {
|
|
654
|
+
if (!step || !canContinue) return;
|
|
655
|
+
if (index >= total - 1) submit();
|
|
656
|
+
else setIndex(index + 1);
|
|
657
|
+
}, [
|
|
658
|
+
step,
|
|
659
|
+
canContinue,
|
|
660
|
+
index,
|
|
661
|
+
total,
|
|
662
|
+
submit
|
|
663
|
+
]);
|
|
664
|
+
const back = useCallback(() => setIndex((i) => Math.max(0, i - 1)), []);
|
|
665
|
+
const goTo = useCallback((i) => setIndex(Math.max(0, Math.min(total - 1, i))), [total]);
|
|
666
|
+
const restart = useCallback(() => {
|
|
667
|
+
setResult(void 0);
|
|
668
|
+
mutation.reset();
|
|
669
|
+
setIndex(0);
|
|
670
|
+
}, [mutation]);
|
|
671
|
+
let status;
|
|
672
|
+
if (result) status = "complete";
|
|
673
|
+
else if (mutation.isPending) status = "submitting";
|
|
674
|
+
else if (!plugin) status = found.status === "error" ? "error" : found.status === "success" ? "unavailable" : "loading";
|
|
675
|
+
else if (query.status === "error") status = query.error instanceof CicordApiError && query.error.code === "unauthenticated" ? "unauthenticated" : "error";
|
|
676
|
+
else if (!query.data) status = "loading";
|
|
677
|
+
else status = "ready";
|
|
678
|
+
const error = status === "error" ? found.error ?? query.error : mutation.error;
|
|
679
|
+
const stepErrors = useMemo(() => {
|
|
680
|
+
const out = { ...serverErrors };
|
|
681
|
+
if (mutation.error instanceof CicordApiError && mutation.error.diagnostics.length === 0 && step) out[step.id] ??= mutation.error.message;
|
|
682
|
+
return out;
|
|
683
|
+
}, [
|
|
684
|
+
serverErrors,
|
|
685
|
+
mutation.error,
|
|
686
|
+
step
|
|
687
|
+
]);
|
|
688
|
+
const completedSteps = steps.filter((s, i) => i < index && stepValid(s)).length;
|
|
689
|
+
return {
|
|
690
|
+
status,
|
|
691
|
+
error,
|
|
692
|
+
data: query.data,
|
|
693
|
+
plugin,
|
|
694
|
+
steps,
|
|
695
|
+
index,
|
|
696
|
+
step,
|
|
697
|
+
total,
|
|
698
|
+
isFirst: index === 0,
|
|
699
|
+
isLast: index === total - 1,
|
|
700
|
+
progress: status === "complete" ? 1 : total === 0 ? 0 : completedSteps / total,
|
|
701
|
+
answers,
|
|
702
|
+
selected,
|
|
703
|
+
isSelected: (role, stepId) => selected(stepId).includes(role),
|
|
704
|
+
toggle,
|
|
705
|
+
setAnswer,
|
|
706
|
+
canContinue,
|
|
707
|
+
stepErrors,
|
|
708
|
+
next,
|
|
709
|
+
back,
|
|
710
|
+
goTo,
|
|
711
|
+
submit,
|
|
712
|
+
result,
|
|
713
|
+
restart,
|
|
714
|
+
reload: () => void query.refetch()
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Headless onboarding flow for the `onboarding` plugin (`GET /steps`, `POST /complete`).
|
|
719
|
+
*
|
|
720
|
+
* ```tsx
|
|
721
|
+
* <OnboardingFlow>
|
|
722
|
+
* {(flow) => flow.status === "ready" && (
|
|
723
|
+
* <section>
|
|
724
|
+
* <h2>{flow.step?.title}</h2>
|
|
725
|
+
* {flow.step?.options.map((o) => (
|
|
726
|
+
* <button key={o.role} aria-pressed={flow.isSelected(o.role)} onClick={() => flow.toggle(o.role)}>
|
|
727
|
+
* {o.emoji} {o.label}
|
|
728
|
+
* </button>
|
|
729
|
+
* ))}
|
|
730
|
+
* <button disabled={!flow.canContinue} onClick={flow.next}>{flow.isLast ? "Finish" : "Next"}</button>
|
|
731
|
+
* </section>
|
|
732
|
+
* )}
|
|
733
|
+
* </OnboardingFlow>
|
|
734
|
+
* ```
|
|
735
|
+
*/
|
|
736
|
+
function OnboardingFlow({ children, ...options }) {
|
|
737
|
+
const flow = useOnboarding(options);
|
|
738
|
+
return /* @__PURE__ */ jsx(Fragment, { children: children(flow) });
|
|
739
|
+
}
|
|
740
|
+
export { CicordProvider, OnboardingFlow, QueryCache, cicordKeys, hashKey, useCicord, useCicordClient, useCicordQuery, useLinkTokenLogin, useLogout, useMe, useMember, useOnboarding, usePluginMutation, usePluginQuery, usePortalPlugin, usePortalServer, usePortalServers, useRoles, useRouteMutation, useRouteQuery, useServerKey, useSession };
|
|
741
|
+
|
|
742
|
+
//# sourceMappingURL=index.mjs.map
|