@theholocron/holocron-plugin-discord 5.0.0-alpha.4 → 5.0.0-alpha.400

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/index.mjs CHANGED
@@ -1,58 +1,2122 @@
1
- import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
2
- //#region src/auth.ts
1
+ import { AuthError, ElevationRequiredError, ProviderApiError, connectionProbe, createResolveToken } from "@theholocron/cli";
2
+ import { errorMessage } from "@theholocron/misc-utils";
3
+ import { ApplicationFlag, ChannelType, MessageFlag, createDiscordBotClient, createDiscordClient, createDiscordOAuthClient, findVerifiedConnection, parseWebhookUrl, permissionNames, permissions } from "@theholocron/discord-client";
4
+ // src/verify-bot-token.ts
5
+ /** Checks a Discord bot token by asking for the bot's own application; resolves to its name and id, or the failure message. */
6
+ async function verifyBotToken(botToken, opts = {}) {
7
+ try {
8
+ const app = await createDiscordBotClient({
9
+ botToken,
10
+ ...opts.unsafeBotBaseUrl && opts.baseUrl ? { baseUrl: opts.baseUrl } : {},
11
+ ...opts.fetch ? { fetch: opts.fetch } : {}
12
+ }).application.get();
13
+ return {
14
+ ok: true,
15
+ subject: `bot: ${app.name} (id: ${app.id})`
16
+ };
17
+ } catch (err) {
18
+ return {
19
+ ok: false,
20
+ message: errorMessage(err)
21
+ };
22
+ }
23
+ }
24
+ // src/auth.ts
25
+ /** Resolves the Discord webhook URL from `--token`, `HOLOCRON_DISCORD_WEBHOOK`, `DISCORD_WEBHOOK_URL` or the keyring, and throws an `AuthError` when none is set. */
3
26
  const resolveToken = createResolveToken({
4
27
  envName: "HOLOCRON_DISCORD_WEBHOOK",
5
28
  vendorEnvName: "DISCORD_WEBHOOK_URL",
6
29
  keyringService: "discord",
7
30
  errorMessage: "no Discord webhook URL found. Pass --token <WEBHOOK_URL>, set HOLOCRON_DISCORD_WEBHOOK / DISCORD_WEBHOOK_URL, or run: holocron auth set discord <https://discord.com/api/webhooks/...>"
8
31
  });
9
- //#endregion
10
- //#region src/rest.ts
11
- function createDiscordClient({ baseUrl, fetch: fetchImpl } = {}) {
12
- const base = baseUrl ?? "https://discord.com/api/v10";
13
- const f = fetchImpl ?? globalThis.fetch;
14
- return { webhooks: {
15
- get: async (id, token) => {
16
- const res = await f(`${base}/webhooks/${id}/${token}`, { method: "GET" });
17
- if (!res.ok) throw new ProviderApiError(`Discord webhook not found or invalid (${res.status})`, res.status, void 0);
18
- return res.json();
19
- },
20
- execute: async (id, token, content) => {
21
- const res = await f(`${base}/webhooks/${id}/${token}`, {
22
- method: "POST",
23
- headers: { "content-type": "application/json" },
24
- body: JSON.stringify({ content })
32
+ /** Resolves the Discord bot token used to provision channels, roles and webhooks, from `HOLOCRON_DISCORD_BOT_TOKEN`, `DISCORD_BOT_TOKEN` or the keyring. */
33
+ const resolveBotToken = createResolveToken({
34
+ envName: "HOLOCRON_DISCORD_BOT_TOKEN",
35
+ vendorEnvName: "DISCORD_BOT_TOKEN",
36
+ keyringService: "discord.holonet",
37
+ errorMessage: "no Discord bot token found. Set HOLOCRON_DISCORD_BOT_TOKEN (or DISCORD_BOT_TOKEN), or run: holocron auth set discord.holonet <token> — it is the bot token from the Discord developer portal (Bot → Reset Token), not a webhook URL."
38
+ });
39
+ /** Resolves the Discord application's OAuth client secret used to sign members in, from `HOLOCRON_DISCORD_CLIENT_SECRET`, `DISCORD_CLIENT_SECRET` or the keyring. */
40
+ const resolveClientSecret = createResolveToken({
41
+ envName: "HOLOCRON_DISCORD_CLIENT_SECRET",
42
+ vendorEnvName: "DISCORD_CLIENT_SECRET",
43
+ keyringService: "discord.holonet.oauth",
44
+ errorMessage: "no Discord client secret found. Set HOLOCRON_DISCORD_CLIENT_SECRET (or DISCORD_CLIENT_SECRET), or run: holocron auth set discord.holonet.oauth <secret> — it is the client secret from the developer portal (OAuth2 → Reset Secret), which the API cannot create or read."
45
+ });
46
+ /**
47
+ * Every token this plugin takes, for `holocron doctor tokens`. `verifyToken` checks a webhook URL, so the bot token has
48
+ * its own `verify` (it asks for the bot's application) and the OAuth client secret, which cannot be checked without a
49
+ * sign-in, is listed but not handed to it. The webhook is the last resort for a post that names no
50
+ * channel, alias or `defaultChannel`, so nothing needs it by default (`optional`).
51
+ */
52
+ const tokens = [
53
+ {
54
+ ...resolveToken.token,
55
+ optional: true
56
+ },
57
+ {
58
+ ...resolveBotToken.token,
59
+ verify: (token) => verifyBotToken(token)
60
+ },
61
+ {
62
+ ...resolveClientSecret.token,
63
+ verifiable: false
64
+ }
65
+ ];
66
+ // src/capabilities/discussions.ts
67
+ /** Discord's cap on the text of one message. */
68
+ const MAX_MESSAGE = 2e3;
69
+ /**
70
+ * The line that ends a post's first message and makes it findable and comparable: `-# sync: <key> | <state>`, where
71
+ * `-#` is Discord's small print. `key` is the document's path; `state` is the state the post and the document last
72
+ * agreed on, empty when none. A state is a tag's name, which may hold spaces (`changes requested`).
73
+ */
74
+ const FOOTER = /^-# sync: (.+) \| (.*)$/m;
75
+ /** The paragraph of a first message that names the pull request, as `discussionBody` writes it. */
76
+ const PR_LINE = /^PR: \[#\d+\]\(<[^>]*>\)$/m;
77
+ /**
78
+ * The first line of a first message, which names the document: its id (`SPEC-0007`), or the id as a link to the file
79
+ * (`[SPEC-0007](<address>)`), as `discussionBody` writes it.
80
+ */
81
+ const ID_LINE = /^(?:\[[A-Z]+-\d+\]\(<[^>\n]*>\)|[A-Z]+-\d+)$/;
82
+ /**
83
+ * Discussion posts for documents, in a Discord forum channel: one post per document, found again by the footer of its
84
+ * first message, with the document's state shown as the post's one tag. The posts of a forum are read once per
85
+ * instance, active and archived, and the copy is kept current by this instance's own writes.
86
+ */
87
+ var DiscordDiscussions = class DiscordDiscussions {
88
+ deps;
89
+ forums = /* @__PURE__ */ new Map();
90
+ constructor(deps) {
91
+ this.deps = deps;
92
+ }
93
+ /** The forum channel named `name`, or an error that says how to make it. */
94
+ async forum(name) {
95
+ const found = (await this.deps.channels()).find((c) => c.type === ChannelType.Forum && c.name.toLowerCase() === name.toLowerCase());
96
+ if (!found) throw new Error(`no forum named \`${name}\` -- declare it in the layout with \`kind: "forum"\` and run setup`);
97
+ return found;
98
+ }
99
+ /** The id of the forum's tag named `state`, or an error that lists the tags it has. */
100
+ tagId(forum, state) {
101
+ const tags = forum.available_tags ?? [];
102
+ const tag = tags.find((t) => t.name.toLowerCase() === state.toLowerCase());
103
+ if (!tag) throw new Error(`\`${forum.name}\` has no tag named \`${state}\` (it has ${tags.map((t) => `\`${t.name}\``).join(", ") || "none"}) -- add it to the layout and run setup`);
104
+ return tag.id;
105
+ }
106
+ /** The posts of a forum by key, read once: every thread's first message, for its footer. */
107
+ posts(forum) {
108
+ let loaded = this.forums.get(forum.id);
109
+ if (!loaded) {
110
+ loaded = this.load(forum).catch((err) => {
111
+ this.forums.delete(forum.id);
112
+ throw err;
25
113
  });
26
- if (!res.ok) throw new ProviderApiError(`Discord webhook POST failed (${res.status})`, res.status, void 0);
114
+ this.forums.set(forum.id, loaded);
27
115
  }
28
- } };
116
+ return loaded;
117
+ }
118
+ async load(forum) {
119
+ const bot = this.deps.bot();
120
+ const entries = /* @__PURE__ */ new Map();
121
+ for (const thread of await bot.threads.inChannel(this.deps.guild(), forum.id)) {
122
+ const first = await bot.channels.message(thread.id, thread.id).catch(() => void 0);
123
+ const footer = first ? FOOTER.exec(first.content) : null;
124
+ if (first && footer) {
125
+ const entry = {
126
+ key: footer[1],
127
+ thread,
128
+ content: first.content,
129
+ synced: footer[2] || void 0,
130
+ duplicates: []
131
+ };
132
+ const held = entries.get(entry.key);
133
+ if (!held) entries.set(entry.key, entry);
134
+ else if (BigInt(thread.id) < BigInt(held.thread.id)) {
135
+ entry.duplicates = [held.thread, ...held.duplicates];
136
+ entries.set(entry.key, entry);
137
+ } else held.duplicates.push(thread);
138
+ }
139
+ }
140
+ return entries;
141
+ }
142
+ /** A post as the caller sees it: its address, the one tag it carries as its state, and what it last synced. */
143
+ view(forum, entry) {
144
+ const names = (entry.thread.applied_tags ?? []).map((id) => (forum.available_tags ?? []).find((t) => t.id === id)?.name);
145
+ const state = names.length === 1 ? names[0] : void 0;
146
+ return {
147
+ url: `https://discord.com/channels/${this.deps.guild()}/${entry.thread.id}`,
148
+ key: entry.key,
149
+ title: entry.thread.name,
150
+ ...state ? { state } : {},
151
+ ...entry.synced ? { synced: entry.synced } : {},
152
+ ...PR_LINE.test(entry.content) ? { prLine: PR_LINE.exec(entry.content)[0] } : {},
153
+ ...ID_LINE.test(entry.content.split("\n")[0]) ? { idLine: entry.content.split("\n")[0] } : {},
154
+ ...entry.thread.thread_metadata.locked ? { closed: true } : {}
155
+ };
156
+ }
157
+ /** The first message for a post: the body, cut to fit, then the footer. */
158
+ static message(body, key, synced) {
159
+ const footer = `-# sync: ${key} | ${synced}`;
160
+ const room = MAX_MESSAGE - footer.length - 2;
161
+ return `${body.length > room ? `${body.slice(0, room - 1)}…` : body}\n\n${footer}`;
162
+ }
163
+ /**
164
+ * `content` with its pull request line set to `line`: replaced where it is, added after the other paragraphs when the
165
+ * message names none, taken out when `line` is empty. Every other paragraph and the footer stay as they were.
166
+ */
167
+ static withPrLine(content, line) {
168
+ const footer = FOOTER.exec(content);
169
+ const body = content.slice(0, footer.index).trimEnd();
170
+ const paragraphs = (body ? body.split("\n\n") : []).filter((p) => !PR_LINE.test(p));
171
+ if (line) paragraphs.push(line);
172
+ const next = [...paragraphs, footer[0]].join("\n\n");
173
+ if (next.length > MAX_MESSAGE) throw new Error(`the pull request line would take the first message past ${MAX_MESSAGE} characters`);
174
+ return next;
175
+ }
176
+ /**
177
+ * `content` with its first line, which names the document, set to `line`. Every other paragraph and the footer stay as
178
+ * they were. A message that does not start with an id is refused rather than guessed at.
179
+ */
180
+ static withIdLine(content, line) {
181
+ const first = content.split("\n")[0];
182
+ if (!ID_LINE.test(first)) throw new Error("the first message does not start with the document's id");
183
+ const next = `${line}${content.slice(first.length)}`;
184
+ if (next.length > MAX_MESSAGE) throw new Error(`the id line would take the first message past ${MAX_MESSAGE} characters`);
185
+ return next;
186
+ }
187
+ /**
188
+ * The post for `key`; failing that, the one a recorded address names, which is the document's post when its file has
189
+ * moved. Only a post of this forum is found, and a malformed or foreign address names none.
190
+ */
191
+ static find(posts, key, url) {
192
+ const direct = posts.get(key);
193
+ if (direct) return direct;
194
+ const thread = url ? /\/channels\/\d+\/(\d+)\/?$/.exec(url)?.[1] : void 0;
195
+ return thread === void 0 ? void 0 : [...posts.values()].find((e) => e.thread.id === thread);
196
+ }
197
+ /** Find the post for `key`, or make it in the state asked for. */
198
+ async ensure(input) {
199
+ const forum = await this.forum(input.channel);
200
+ const posts = await this.posts(forum);
201
+ const existing = DiscordDiscussions.find(posts, input.key, input.url);
202
+ if (existing) {
203
+ const moved = existing.key !== input.key;
204
+ if (moved) await this.update(input.channel, existing.key, { key: input.key });
205
+ return {
206
+ post: this.view(forum, existing),
207
+ created: false,
208
+ ...moved ? { rekeyed: true } : {}
209
+ };
210
+ }
211
+ const tag = this.tagId(forum, input.state);
212
+ const content = DiscordDiscussions.message(input.body, input.key, input.state);
213
+ const made = await this.deps.bot().threads.createForumPost(forum.id, {
214
+ name: input.title,
215
+ applied_tags: [tag],
216
+ message: {
217
+ content,
218
+ ...this.flags(input.channel, input.quiet)
219
+ }
220
+ });
221
+ await this.react(made.id, input.channel);
222
+ const thread = input.closed ? {
223
+ ...made,
224
+ ...await this.deps.bot().threads.modify(made.id, {
225
+ archived: true,
226
+ locked: true
227
+ })
228
+ } : made;
229
+ const entry = {
230
+ key: input.key,
231
+ thread,
232
+ content,
233
+ synced: input.state,
234
+ duplicates: []
235
+ };
236
+ posts.set(input.key, entry);
237
+ return {
238
+ post: this.view(forum, entry),
239
+ created: true
240
+ };
241
+ }
242
+ /** The `flags` a message in `channel` carries: no notification when `quiet`, no link previews in a feed forum. */
243
+ flags(channel, quiet) {
244
+ const flags = (quiet ? MessageFlag.SuppressNotifications : 0) | (this.deps.suppressEmbeds?.(channel) ? MessageFlag.SuppressEmbeds : 0);
245
+ return flags === 0 ? {} : { flags };
246
+ }
247
+ /** The `flags` of an edit: only the link previews can be changed on a message already sent. */
248
+ editFlags(channel) {
249
+ return this.deps.suppressEmbeds?.(channel) ? { flags: MessageFlag.SuppressEmbeds } : {};
250
+ }
251
+ /**
252
+ * Puts the layout's starter reactions on the first message of a post just made (its id is the post's). One that
253
+ * fails (the bot lacks Add Reactions, an emoji Discord does not know) is skipped: the post is already made, and a
254
+ * missing reaction must not fail the sync.
255
+ */
256
+ async react(post, channel) {
257
+ for (const emoji of this.deps.starterReactions?.(channel) ?? []) await this.deps.bot().channels.addReaction(post, post, emoji).catch(() => void 0);
258
+ }
259
+ /** The post for `key` (or the one `url` names, when the file moved), or `undefined`. It writes nothing. */
260
+ async read(channel, key, url) {
261
+ const forum = await this.forum(channel);
262
+ const entry = DiscordDiscussions.find(await this.posts(forum), key, url);
263
+ return entry ? this.view(forum, entry) : void 0;
264
+ }
265
+ /**
266
+ * Change the post for `key`: its key (the file moved), its title, its tag, whether it is closed, the state it
267
+ * records as last synced, the line that names the pull request, and the line that names the document (the id, plain or as a link). A closed post is archived and locked. To write to one it is unarchived first and closed again after, and one that is
268
+ * being reopened is unarchived and unlocked.
269
+ */
270
+ async update(channel, key, patch) {
271
+ const forum = await this.forum(channel);
272
+ const posts = await this.posts(forum);
273
+ const entry = posts.get(key);
274
+ if (!entry) throw new Error(`no discussion post for \`${key}\` in \`${channel}\``);
275
+ const bot = this.deps.bot();
276
+ const thread = entry.thread;
277
+ const wasClosed = thread.thread_metadata.locked;
278
+ const wantClosed = patch.closed ?? wasClosed;
279
+ const reopening = wasClosed && !wantClosed;
280
+ const change = {};
281
+ if (patch.title !== void 0 && patch.title !== thread.name) change.name = patch.title;
282
+ if (patch.state !== void 0) change.applied_tags = [this.tagId(forum, patch.state)];
283
+ const nextKey = patch.key ?? key;
284
+ const footerEdited = nextKey !== key || patch.synced !== void 0 && patch.synced !== entry.synced;
285
+ const base = patch.body === void 0 ? entry.content : DiscordDiscussions.message(patch.body, key, entry.synced ?? "");
286
+ const withPr = patch.prLine === void 0 ? base : DiscordDiscussions.withPrLine(base, patch.prLine);
287
+ const withId = patch.idLine === void 0 ? withPr : DiscordDiscussions.withIdLine(withPr, patch.idLine);
288
+ const edited = footerEdited || withId !== entry.content;
289
+ if ((Object.keys(change).length > 0 || edited || reopening) && thread.thread_metadata.archived) change.archived = false;
290
+ if (reopening) change.locked = false;
291
+ if (Object.keys(change).length > 0) entry.thread = {
292
+ ...thread,
293
+ ...await bot.threads.modify(thread.id, change)
294
+ };
295
+ if (edited) {
296
+ const synced = patch.synced ?? entry.synced ?? "";
297
+ const content = withId.replace(FOOTER, () => `-# sync: ${nextKey} | ${synced}`);
298
+ await bot.channels.editMessage(thread.id, thread.id, {
299
+ content,
300
+ ...this.editFlags(channel)
301
+ });
302
+ entry.content = content;
303
+ entry.synced = synced || void 0;
304
+ if (nextKey !== key) {
305
+ posts.delete(key);
306
+ entry.key = nextKey;
307
+ posts.set(nextKey, entry);
308
+ }
309
+ }
310
+ if (wantClosed && (!wasClosed || change.archived === false)) entry.thread = {
311
+ ...entry.thread,
312
+ ...await bot.threads.modify(thread.id, {
313
+ archived: true,
314
+ locked: true
315
+ })
316
+ };
317
+ }
318
+ /**
319
+ * Append a message to the post for `key`, mentioning no one. A post that is archived or locked is unarchived and
320
+ * unlocked for the write and put back as it was, also when the write fails.
321
+ */
322
+ async post(channel, key, content, opts = {}) {
323
+ const entry = (await this.posts(await this.forum(channel))).get(key);
324
+ if (!entry) throw new Error(`no discussion post for \`${key}\` in \`${channel}\``);
325
+ const bot = this.deps.bot();
326
+ const { archived, locked } = entry.thread.thread_metadata;
327
+ const reopen = archived || locked;
328
+ if (reopen) entry.thread = {
329
+ ...entry.thread,
330
+ ...await bot.threads.modify(entry.thread.id, {
331
+ archived: false,
332
+ locked: false
333
+ })
334
+ };
335
+ try {
336
+ const text = content.length > MAX_MESSAGE ? `${content.slice(0, 1999)}…` : content;
337
+ await bot.channels.createMessage(entry.thread.id, {
338
+ content: text,
339
+ ...this.flags(channel, opts.quiet)
340
+ });
341
+ } finally {
342
+ if (reopen) entry.thread = {
343
+ ...entry.thread,
344
+ ...await bot.threads.modify(entry.thread.id, {
345
+ archived,
346
+ locked
347
+ })
348
+ };
349
+ }
350
+ }
351
+ /** The text of the recent messages of the post for `key`, newest first; empty when there is no post. */
352
+ async messages(channel, key, limit = 50) {
353
+ const entry = (await this.posts(await this.forum(channel))).get(key);
354
+ if (!entry) return [];
355
+ return (await this.deps.bot().channels.messages(entry.thread.id, Math.min(Math.max(limit, 1), 100))).map((m) => m.content);
356
+ }
357
+ /** Keep the oldest post that carries `key` and delete the others. Returns how many were deleted. */
358
+ async dedupe(channel, key) {
359
+ const entry = (await this.posts(await this.forum(channel))).get(key);
360
+ if (!entry) return 0;
361
+ const bot = this.deps.bot();
362
+ let deleted = 0;
363
+ while (entry.duplicates.length > 0) {
364
+ await bot.threads.delete(entry.duplicates[0].id);
365
+ entry.duplicates.shift();
366
+ deleted++;
367
+ }
368
+ return deleted;
369
+ }
370
+ };
371
+ // src/capabilities/notifications.ts
372
+ /** Discord's numeric settings, by the names the layout uses. */
373
+ const VERIFICATION = {
374
+ none: 0,
375
+ low: 1,
376
+ medium: 2,
377
+ high: 3,
378
+ highest: 4
379
+ };
380
+ const NOTIFICATIONS = {
381
+ all: 0,
382
+ mentions: 1
383
+ };
384
+ const FILTER = {
385
+ off: 0,
386
+ noRoles: 1,
387
+ all: 2
388
+ };
389
+ const nameOf = (map, value) => Object.keys(map).find((k) => map[k] === value);
390
+ /** What the bot needs in the server to do everything `setup` does. The invite link asks for exactly these. */
391
+ const BOT_NEEDS = [
392
+ "ViewChannel",
393
+ "SendMessages",
394
+ "ReadMessageHistory",
395
+ "ManageChannels",
396
+ "ManageRoles",
397
+ "ManageWebhooks",
398
+ "ManageGuild",
399
+ "CreatePublicThreads",
400
+ "CreatePrivateThreads",
401
+ "SendMessagesInThreads"
402
+ ];
403
+ /** The OAuth2 scopes Discord offers an application, as its own application page lists them. Exact, lower-case. */
404
+ const SCOPES = /* @__PURE__ */ new Set([
405
+ "applications.builds.read",
406
+ "applications.commands",
407
+ "applications.commands.permissions.update",
408
+ "applications.entitlements",
409
+ "applications.store.update",
410
+ "bot",
411
+ "connections",
412
+ "email",
413
+ "gdm.join",
414
+ "guilds",
415
+ "guilds.join",
416
+ "guilds.members.read",
417
+ "identify",
418
+ "messages.read",
419
+ "openid",
420
+ "role_connections.write",
421
+ "rpc",
422
+ "rpc.activities.write",
423
+ "rpc.notifications.read",
424
+ "rpc.screenshare.read",
425
+ "rpc.screenshare.write",
426
+ "rpc.video.read",
427
+ "rpc.video.write",
428
+ "rpc.voice.read",
429
+ "rpc.voice.write",
430
+ "webhook.incoming"
431
+ ]);
432
+ /** The locales Discord accepts for a server's preferred language. */
433
+ const LOCALES = /* @__PURE__ */ new Set([
434
+ "id",
435
+ "da",
436
+ "de",
437
+ "en-GB",
438
+ "en-US",
439
+ "es-ES",
440
+ "es-419",
441
+ "fr",
442
+ "hr",
443
+ "it",
444
+ "lt",
445
+ "hu",
446
+ "nl",
447
+ "no",
448
+ "pl",
449
+ "pt-BR",
450
+ "ro",
451
+ "fi",
452
+ "sv-SE",
453
+ "vi",
454
+ "tr",
455
+ "cs",
456
+ "el",
457
+ "bg",
458
+ "ru",
459
+ "uk",
460
+ "hi",
461
+ "th",
462
+ "zh-CN",
463
+ "ja",
464
+ "zh-TW",
465
+ "ko"
466
+ ]);
467
+ /** "applied a, b; " for the start of a message about a step that stopped part-way, or nothing. */
468
+ function appliedPrefix(applied) {
469
+ return applied.length > 0 ? `applied ${applied.join(", ")}; but ` : "";
29
470
  }
30
- /** Parse a Discord webhook URL into its id and token parts. */
31
- function parseWebhookUrl(url) {
32
- const match = url.match(/webhooks\/(\d+)\/([^/?#]+)/);
33
- if (!match) throw new Error(`Invalid Discord webhook URL: ${url}`);
34
- return {
35
- id: match[1],
36
- token: match[2]
37
- };
471
+ /** A layout name to Discord's number, undefined when the layout leaves it out; an unknown name is an error, not an omission. */
472
+ function s_(name, map) {
473
+ if (name === void 0) return void 0;
474
+ if (!Object.hasOwn(map, name)) throw new Error(`unknown value ${JSON.stringify(name)}; use one of ${Object.keys(map).join(", ")}`);
475
+ return map[name];
476
+ }
477
+ /** `#rrggbb` to Discord's integer colour. */
478
+ function colorToInt(hex) {
479
+ if (!/^#[0-9a-fA-F]{6}$/.test(hex)) throw new Error(`invalid colour ${JSON.stringify(hex)}: use #rrggbb`);
480
+ return Number.parseInt(hex.slice(1), 16);
38
481
  }
39
- //#endregion
40
- //#region src/capabilities/notifications.ts
41
- var DiscordNotifications = class {
482
+ /** Discord's integer colour to `#rrggbb`. 0 is Discord's "no colour", and is what `#000000` means too. */
483
+ function colorToHex(color) {
484
+ return `#${color.toString(16).padStart(6, "0")}`;
485
+ }
486
+ /** An error as one line: the message, plus Discord's own response body when there is one. */
487
+ function reason(err) {
488
+ return err instanceof ProviderApiError && err.details ? `${errorMessage(err)}: ${String(err.details).slice(0, 200)}` : errorMessage(err);
489
+ }
490
+ /**
491
+ * What @everyone loses when a channel is read-only. Only sending: Discord refuses (403) any change to the
492
+ * thread permissions on an existing text channel from a bot whose own role lacks them, and Holonet's
493
+ * does. Members can therefore still start threads in a read-only channel until the bot is given those
494
+ * permissions; see {@link THREAD_BITS} for how channels that already carry them are read.
495
+ */
496
+ const POST = ["SendMessages"];
497
+ const THREAD_MASK = ~BigInt(permissions([
498
+ "SendMessagesInThreads",
499
+ "CreatePublicThreads",
500
+ "CreatePrivateThreads"
501
+ ]));
502
+ /** What the bot keeps in a channel it has locked down, so it can still manage it and post. */
503
+ const BOT_KEEPS = [
504
+ "ViewChannel",
505
+ "SendMessages",
506
+ "ReadMessageHistory",
507
+ "ManageChannels",
508
+ "ManageWebhooks"
509
+ ];
510
+ /**
511
+ * Overwrites as a comparable set: order and the shape of the array do not matter, and the thread
512
+ * permissions are left out (setup does not manage them, so their presence is not a difference).
513
+ */
514
+ function overwriteKey(list) {
515
+ return (list ?? []).map((o) => ({
516
+ ...o,
517
+ allow: BigInt(o.allow) & THREAD_MASK,
518
+ deny: BigInt(o.deny) & THREAD_MASK
519
+ })).filter((o) => o.allow !== 0n || o.deny !== 0n).map((o) => `${o.id}:${o.type}:${o.allow}:${o.deny}`).sort().join("|");
520
+ }
521
+ /**
522
+ * Desired overwrites with the thread permissions of the existing ones laid back in. Discord refuses
523
+ * any change to those from this bot, so a replacement list must carry them over untouched or the
524
+ * whole edit is rejected, even when it changes nothing but what we do manage.
525
+ */
526
+ function keepThreadBits(desired, existing) {
527
+ const threads = ~THREAD_MASK;
528
+ const merged = desired.map((o) => ({ ...o }));
529
+ for (const old of existing ?? []) {
530
+ const allow = BigInt(old.allow) & threads;
531
+ const deny = BigInt(old.deny) & threads;
532
+ if (allow === 0n && deny === 0n) continue;
533
+ const same = merged.find((o) => o.id === old.id && o.type === old.type);
534
+ if (same) {
535
+ same.allow = (BigInt(same.allow) | allow).toString();
536
+ same.deny = (BigInt(same.deny) | deny).toString();
537
+ } else merged.push({
538
+ id: old.id,
539
+ type: old.type,
540
+ allow: allow.toString(),
541
+ deny: deny.toString()
542
+ });
543
+ }
544
+ return merged;
545
+ }
546
+ let idCounter = 0;
547
+ /** A snowflake-shaped id for a new onboarding question or answer, which Discord asks the sender to make. */
548
+ const newId = () => String((BigInt(Date.now()) - 1420070400000n << 22n) + BigInt(idCounter++ % 4096));
549
+ /** The Discord implementation of the `notifications` capability: sends messages through webhooks and provisions the server's channels, roles and webhooks with the bot. */
550
+ var DiscordNotifications = class DiscordNotifications {
42
551
  client;
43
552
  opts;
44
553
  defaultWebhookUrl;
554
+ bot;
555
+ oauth;
556
+ /** The capability this class provides, always `"notifications"`. */
45
557
  key = "notifications";
558
+ /** The provider name, `"discord"`. */
46
559
  providerName = "discord";
47
- constructor(client, opts, defaultWebhookUrl) {
560
+ constructor(client, opts, defaultWebhookUrl, bot = () => {
561
+ throw new Error("no Discord bot client configured");
562
+ }, oauth = () => {
563
+ throw new Error("no Discord OAuth client configured");
564
+ }) {
48
565
  this.client = client;
49
566
  this.opts = opts;
50
567
  this.defaultWebhookUrl = defaultWebhookUrl;
568
+ this.bot = bot;
569
+ this.oauth = oauth;
570
+ }
571
+ /**
572
+ * Sign a member in with Discord to learn which GitHub account they own. Asks only for `identify` and
573
+ * `connections`, reads the account Discord has verified, and revokes the token before returning: nothing
574
+ * about the sign-in is kept.
575
+ */
576
+ signIn() {
577
+ return {
578
+ authorizeUrl: async ({ redirectUri, state }) => (await this.oauth(redirectUri)).authorizeUrl({ state }),
579
+ complete: async ({ redirectUri, code }) => {
580
+ const client = await this.oauth(redirectUri);
581
+ const token = await client.exchangeCode(code);
582
+ try {
583
+ const [user, connections] = await Promise.all([client.user(token.access_token), client.connections(token.access_token)]);
584
+ const github = findVerifiedConnection(connections, "github");
585
+ return {
586
+ member: user.id,
587
+ name: user.global_name ?? user.username,
588
+ ...github ? { github: {
589
+ id: github.id,
590
+ login: github.name
591
+ } } : {}
592
+ };
593
+ } finally {
594
+ await client.revoke(token.access_token).catch(() => {});
595
+ }
596
+ }
597
+ };
598
+ }
599
+ get layout() {
600
+ return this.opts.layout;
51
601
  }
52
602
  async send(channel, message) {
53
- const { id, token } = parseWebhookUrl(this.resolve(channel || this.opts.defaultChannel || ""));
603
+ const webhookUrl = this.resolve(channel || this.opts.defaultChannel || "");
604
+ const { id, token } = parseWebhookUrl(webhookUrl);
54
605
  await this.client.webhooks.execute(id, token, message);
55
606
  }
607
+ /**
608
+ * `holocron doctor`: the bot token is valid and can see the configured server.
609
+ * Null when no `guildId` is set -- a post-only config has no bot to check. A
610
+ * `layout` without a `guildId` is a half-written provisioning config, so that
611
+ * fails instead of passing as post-only.
612
+ */
613
+ async whoami() {
614
+ if (!this.opts.guildId) {
615
+ if (this.opts.layout) throw new Error("`layout` is set but `guildId` is not — add the server id to the discord provider options");
616
+ return null;
617
+ }
618
+ const bot = this.bot();
619
+ const me = await bot.users.me();
620
+ return { target: `${(await bot.guilds.get(this.opts.guildId)).name} (as ${me.username})` };
621
+ }
622
+ /**
623
+ * Read-only: what is on the server, for the parts of `layout` we will compare. Webhooks are
624
+ * listed only for channels the layout gives one (one request each), so the cost scales with
625
+ * the layout, not with the server.
626
+ */
627
+ async inspect(layout) {
628
+ const bot = this.bot();
629
+ const channels = await this.channelList();
630
+ const categoryName = new Map(channels.filter((c) => c.type === ChannelType.Category).map((c) => [c.id, c.name]));
631
+ const wantsWebhook = new Set((layout.categories ?? []).flatMap((c) => (c.channels ?? []).filter((ch) => ch.webhook || ch.feeds?.monitoring || ch.feeds?.errors).map((ch) => ch.name.toLowerCase())));
632
+ const wantsPrs = new Set((layout.categories ?? []).flatMap((c) => (c.channels ?? []).filter((ch) => ch.feeds?.prs).map((ch) => ch.name.toLowerCase())));
633
+ const text = channels.filter((c) => c.type === ChannelType.Text || c.type === ChannelType.Announcement || c.type === ChannelType.Forum);
634
+ const found = [];
635
+ for (const c of text) {
636
+ let webhooks = [];
637
+ let webhookAvatars = [];
638
+ let webhookIds = {};
639
+ let webhooksError;
640
+ if (wantsWebhook.has(c.name.toLowerCase())) try {
641
+ const hooks = await bot.channels.webhooks(c.id);
642
+ webhooks = hooks.map((w) => w.name ?? "");
643
+ webhookAvatars = hooks.filter((w) => w.avatar).map((w) => w.name ?? "");
644
+ webhookIds = Object.fromEntries(hooks.map((w) => [(w.name ?? "").toLowerCase(), w.id]));
645
+ } catch (err) {
646
+ webhooksError = reason(err);
647
+ }
648
+ let botThreads;
649
+ let botThreadsError;
650
+ if (c.type === ChannelType.Forum && wantsPrs.has(c.name.toLowerCase())) try {
651
+ botThreads = await this.botThreadsIn(c.permission_overwrites ?? []);
652
+ } catch (err) {
653
+ botThreadsError = reason(err);
654
+ }
655
+ const category = c.parent_id ? categoryName.get(c.parent_id) : void 0;
656
+ found.push({
657
+ name: c.name,
658
+ ...category ? { category } : {},
659
+ ...c.topic ? { topic: c.topic } : {},
660
+ ...c.type === ChannelType.Forum ? {
661
+ kind: "forum",
662
+ tags: (c.available_tags ?? []).map(DiscordNotifications.tagOf),
663
+ ...c.default_reaction_emoji?.emoji_name ? { defaultReaction: c.default_reaction_emoji.emoji_name } : {}
664
+ } : {},
665
+ webhooks,
666
+ webhookAvatars,
667
+ webhookIds,
668
+ ...webhooksError ? { webhooksError } : {},
669
+ ...botThreads ? { botThreads } : {},
670
+ ...botThreadsError ? { botThreadsError } : {}
671
+ });
672
+ }
673
+ let roles = [];
674
+ let rolesError;
675
+ if ((layout.roles ?? []).length > 0) try {
676
+ roles = (await bot.guilds.roles(this.guild())).map((r) => {
677
+ return {
678
+ name: r.name,
679
+ id: r.id,
680
+ mentionable: r.mentionable,
681
+ color: colorToHex(r.color),
682
+ ...r.hoist !== void 0 ? { hoist: r.hoist } : {},
683
+ ...r.permissions !== void 0 ? { permissions: permissionNames(r.permissions) } : {}
684
+ };
685
+ });
686
+ } catch (err) {
687
+ rolesError = reason(err);
688
+ }
689
+ const nameOfChannel = (id) => channels.find((c) => c.id === id)?.name ?? id;
690
+ const channelName = (id) => id ? nameOfChannel(id) : void 0;
691
+ let server;
692
+ let serverError;
693
+ if (layout.server) try {
694
+ const guild = await bot.guilds.get(this.guild());
695
+ const verification = nameOf(VERIFICATION, guild.verification_level);
696
+ const defaultNotifications = nameOf(NOTIFICATIONS, guild.default_message_notifications);
697
+ const contentFilter = nameOf(FILTER, guild.explicit_content_filter);
698
+ const systemChannel = channelName(guild.system_channel_id);
699
+ const rulesChannel = channelName(guild.rules_channel_id);
700
+ const updatesChannel = channelName(guild.public_updates_channel_id);
701
+ server = {
702
+ ...verification ? { verification } : {},
703
+ ...defaultNotifications ? { defaultNotifications } : {},
704
+ ...contentFilter ? { contentFilter } : {},
705
+ ...systemChannel ? { systemChannel } : {},
706
+ ...rulesChannel ? { rulesChannel } : {},
707
+ ...updatesChannel ? { updatesChannel } : {},
708
+ community: (guild.features ?? []).includes("COMMUNITY"),
709
+ ...guild.description !== void 0 && guild.description !== null ? { description: guild.description } : {},
710
+ ...guild.preferred_locale ? { locale: guild.preferred_locale } : {}
711
+ };
712
+ } catch (err) {
713
+ serverError = reason(err);
714
+ }
715
+ let pinned;
716
+ let pinnedError;
717
+ if (layout.pinned) try {
718
+ pinned = await this.pinnedStates(layout.pinned);
719
+ } catch (err) {
720
+ pinnedError = reason(err);
721
+ }
722
+ let welcome;
723
+ let welcomeError;
724
+ if (layout.welcome) try {
725
+ const guild = await bot.guilds.get(this.guild());
726
+ const screen = await this.welcomeScreenOf();
727
+ welcome = {
728
+ enabled: (guild.features ?? []).includes("WELCOME_SCREEN_ENABLED"),
729
+ description: screen.description ?? "",
730
+ channels: (screen.welcome_channels ?? []).map((c) => ({
731
+ channel: nameOfChannel(c.channel_id),
732
+ description: c.description,
733
+ ...c.emoji_name ? { emoji: c.emoji_name } : {}
734
+ }))
735
+ };
736
+ } catch (err) {
737
+ welcomeError = reason(err);
738
+ }
739
+ let onboarding;
740
+ let onboardingError;
741
+ if (layout.onboarding) try {
742
+ const found = await bot.guilds.onboarding(this.guild());
743
+ const roleOf = (id) => roles.find((r) => r.id === id)?.name ?? id;
744
+ onboarding = {
745
+ enabled: found.enabled,
746
+ defaultChannels: found.default_channel_ids.map(nameOfChannel),
747
+ prompts: found.prompts.map((p) => ({
748
+ title: p.title,
749
+ singleSelect: p.single_select,
750
+ required: p.required,
751
+ options: p.options.map((o) => ({
752
+ title: o.title,
753
+ ...o.description ? { description: o.description } : {},
754
+ ...o.emoji?.name ?? o.emoji_name ? { emoji: o.emoji?.name ?? o.emoji_name } : {},
755
+ channels: (o.channel_ids ?? []).map(nameOfChannel),
756
+ roles: (o.role_ids ?? []).map(roleOf)
757
+ }))
758
+ }))
759
+ };
760
+ } catch (err) {
761
+ onboardingError = reason(err);
762
+ }
763
+ let application;
764
+ let applicationError;
765
+ if (layout.application) try {
766
+ const app = await bot.application.get();
767
+ const install = app.install_params;
768
+ application = {
769
+ ...app.description ? { description: app.description } : {},
770
+ tags: app.tags ?? [],
771
+ ...install ? { install: {
772
+ scopes: install.scopes,
773
+ permissions: permissionNames(install.permissions)
774
+ } } : {},
775
+ ...app.terms_of_service_url ? { termsUrl: app.terms_of_service_url } : {},
776
+ ...app.privacy_policy_url ? { privacyUrl: app.privacy_policy_url } : {},
777
+ ...app.role_connections_verification_url ? { roleConnectionsUrl: app.role_connections_verification_url } : {},
778
+ intents: { members: DiscordNotifications.membersIntentOn(app.flags ?? 0) },
779
+ redirectUris: app.redirect_uris ?? []
780
+ };
781
+ } catch (err) {
782
+ applicationError = reason(err);
783
+ }
784
+ let everyone;
785
+ let everyoneError;
786
+ if (layout.everyone) try {
787
+ const role = (await bot.guilds.roles(this.guild())).find((r) => r.id === this.guild());
788
+ if (role?.permissions === void 0) throw new Error("the server has no @everyone role to read");
789
+ everyone = { permissions: permissionNames(role.permissions) };
790
+ } catch (err) {
791
+ everyoneError = reason(err);
792
+ }
793
+ const roleName = (id) => roles.find((r) => r.id === id)?.name ?? id;
794
+ found.forEach((entry, i) => {
795
+ entry.access = this.accessOf(text[i].permission_overwrites, roleName);
796
+ });
797
+ const categoryAccess = {};
798
+ for (const c of channels.filter((c) => c.type === ChannelType.Category)) categoryAccess[c.name] = this.accessOf(c.permission_overwrites, roleName);
799
+ let botPermissions;
800
+ let botPermissionsError;
801
+ try {
802
+ botPermissions = await this.missingBotPermissions();
803
+ } catch (err) {
804
+ botPermissionsError = reason(err);
805
+ }
806
+ return {
807
+ categories: [...categoryName.values()],
808
+ categoryAccess,
809
+ ...botPermissions ? { botPermissions } : {},
810
+ ...botPermissionsError ? { botPermissionsError } : {},
811
+ ...server ? { server } : {},
812
+ ...serverError ? { serverError } : {},
813
+ ...welcome ? { welcome } : {},
814
+ ...welcomeError ? { welcomeError } : {},
815
+ ...pinned ? { pinned } : {},
816
+ ...pinnedError ? { pinnedError } : {},
817
+ ...onboarding ? { onboarding } : {},
818
+ ...onboardingError ? { onboardingError } : {},
819
+ ...application ? { application } : {},
820
+ ...applicationError ? { applicationError } : {},
821
+ ...everyone ? { everyone } : {},
822
+ ...everyoneError ? { everyoneError } : {},
823
+ channels: found,
824
+ roles,
825
+ ...rolesError ? { rolesError } : {}
826
+ };
827
+ }
828
+ /**
829
+ * What the bot keeps: the usual set, Pin Messages when the layout pins messages, and Manage Threads when it
830
+ * declares a forum (a post's tags are applied by the bot, and a moderated tag only by someone who can manage threads),
831
+ * and Add Reactions when a forum has `starterReactions` (without it the bot skips them and the post still gets made).
832
+ */
833
+ needs() {
834
+ const channels = (this.opts.layout?.categories ?? []).flatMap((c) => c.channels ?? []);
835
+ const forum = channels.some((ch) => ch.kind === "forum");
836
+ const reacts = channels.some((ch) => (ch.starterReactions ?? []).length > 0);
837
+ return [
838
+ ...BOT_NEEDS,
839
+ ...this.opts.layout?.pinned?.length ? ["PinMessages"] : [],
840
+ ...forum ? ["ManageThreads"] : [],
841
+ ...reacts ? ["AddReactions"] : []
842
+ ];
843
+ }
844
+ /** Where to re-invite the bot so its role holds what `setup` needs. Re-authorising updates the role in place. */
845
+ async inviteUrl(names = this.needs()) {
846
+ const url = new URL("https://discord.com/oauth2/authorize");
847
+ url.searchParams.set("client_id", await this.botId());
848
+ url.searchParams.set("scope", "bot");
849
+ url.searchParams.set("permissions", permissions(names));
850
+ url.searchParams.set("guild_id", this.guild());
851
+ return url.toString();
852
+ }
853
+ /** Changing server settings needs Manage Server; an empty edit proves the bot has it without changing anything. */
854
+ async preflight(layout) {
855
+ if (!layout.server) return;
856
+ try {
857
+ await this.bot().guilds.modify(this.guild(), {});
858
+ } catch (err) {
859
+ throw await this.manageServerHint(err);
860
+ }
861
+ }
862
+ /** The one role with this name, or an error saying why not: two would mean granting something to the wrong members. */
863
+ static pickRole(roles, name, who) {
864
+ const found = roles.filter((r) => DiscordNotifications.same(r.name, name));
865
+ if (found.length === 0) throw new Error(`${who} names the role \`${name}\`, which does not exist on the server yet`);
866
+ if (found.length > 1) throw new Error(`${who} names the role \`${name}\`, but ${found.length} roles have that name (ids ${found.map((r) => r.id).join(", ")}) -- delete or rename the extras`);
867
+ return found[0].id;
868
+ }
869
+ /**
870
+ * The one text or announcement channel with this name, or an error saying why not. A forum counts only for a
871
+ * setting that can point at one (`forums`): the welcome screen and onboarding can; a pinned message and the server's
872
+ * own channels cannot.
873
+ */
874
+ static pickChannelId(channels, name, who, forums = false) {
875
+ const named = channels.filter((c) => (c.type === ChannelType.Text || c.type === ChannelType.Announcement || forums && c.type === ChannelType.Forum) && DiscordNotifications.same(c.name, name));
876
+ if (named.length === 0) throw new Error(`${who} name the channel \`${name}\`, which does not exist on the server yet`);
877
+ if (named.length > 1) throw new Error(`${who} name the channel \`${name}\`, but ${named.length} channels have that name (ids ${named.map((c) => c.id).join(", ")}) -- rename one`);
878
+ return named[0].id;
879
+ }
880
+ /** True for a 403 that is about permissions, not about the bot being unable to see the server at all. */
881
+ static missingPermissions(err) {
882
+ return err instanceof ProviderApiError && err.status === 403 && !/Missing Access|\b50001\b/.test(String(err.details));
883
+ }
884
+ /** An invite link, or nothing when building it needs a request that fails: the advice must not depend on one. */
885
+ async inviteOrNothing(names) {
886
+ try {
887
+ return await this.inviteUrl(names);
888
+ } catch {
889
+ return;
890
+ }
891
+ }
892
+ /**
893
+ * Changing a role's permissions is refused (403) when the role would gain one the bot does not hold itself: Discord
894
+ * lets a bot give only what it has. The bot's own role is managed by its integration, so it cannot be edited by
895
+ * hand; re-authorising the bot with the permissions setup needs updates it in place.
896
+ */
897
+ async rolePermissionsHint(role, err) {
898
+ if (!DiscordNotifications.missingPermissions(err)) return err;
899
+ const link = await this.inviteOrNothing();
900
+ return new Error(`role \`${role}\`: Discord refused to change its permissions: a bot can give a role only permissions it holds itself, and the bot's own role is managed by its integration, so it cannot be edited by hand. Re-invite the bot with the permissions setup needs${link ? ` (this updates its role in place): ${link}` : " (this updates its role in place)"}`, { cause: err });
901
+ }
902
+ /** Turning community on or off needs Administrator, which is more than the bot should keep. */
903
+ async communityHint(err, applied, turningOn) {
904
+ if (!(err instanceof ProviderApiError && err.status === 403)) return err;
905
+ const link = await this.inviteOrNothing(["Administrator"]);
906
+ const byHand = turningOn ? "turn them on once in Discord (Server Settings → Enable Community; setup then keeps everything else in line)" : "turn them off once in Discord (Server Settings → Community Settings → Disable Community)";
907
+ const viaBot = link ? `give Holonet Administrator for one run and take it away again afterwards: ${link}` : "re-invite Holonet with the Administrator permission for one run, and take it away again afterwards";
908
+ const revoke = await this.inviteOrNothing();
909
+ return new ElevationRequiredError(`${appliedPrefix(applied)}turning community features ${turningOn ? "on" : "off"} was refused (Discord said: ${String(err.details).slice(0, 120)}), which means Holonet lacks the Administrator permission it needs for that. Either ${byHand}, or ${viaBot}. If Holonet already has Administrator, check that it is still in the server`, {
910
+ permission: "Administrator",
911
+ ...link ? { grantUrl: link } : {},
912
+ ...revoke ? { revokeUrl: revoke } : {},
913
+ ...applied.length > 0 ? { applied } : {}
914
+ }, { cause: err });
915
+ }
916
+ /** A 403 on a server edit becomes the explanation and the invite link; anything else is passed on as it is. */
917
+ async manageServerHint(err) {
918
+ if (!DiscordNotifications.missingPermissions(err)) return err;
919
+ const link = await this.inviteOrNothing();
920
+ return new Error(`the bot is not allowed to change server settings: its role lacks Manage Server. Re-invite it with the permissions setup needs${link ? ` (this updates its role in place): ${link}` : " (this updates its role in place)"}`, { cause: err });
921
+ }
922
+ async ensureServer(settings) {
923
+ const bot = this.bot();
924
+ const guild = await bot.guilds.get(this.guild());
925
+ const channels = await this.channelList();
926
+ const idOf = (name) => DiscordNotifications.pickChannelId(channels, name, "server settings");
927
+ const patch = {};
928
+ const updated = [];
929
+ const set = (label, key, want, have) => {
930
+ if (want !== void 0 && want !== have) {
931
+ patch[key] = want;
932
+ updated.push(label);
933
+ }
934
+ };
935
+ set("verification", "verification_level", s_(settings.verification, VERIFICATION), guild.verification_level);
936
+ set("defaultNotifications", "default_message_notifications", s_(settings.defaultNotifications, NOTIFICATIONS), guild.default_message_notifications);
937
+ set("contentFilter", "explicit_content_filter", s_(settings.contentFilter, FILTER), guild.explicit_content_filter);
938
+ set("systemChannel", "system_channel_id", settings.systemChannel && idOf(settings.systemChannel), guild.system_channel_id);
939
+ set("rulesChannel", "rules_channel_id", settings.rulesChannel && idOf(settings.rulesChannel), guild.rules_channel_id);
940
+ const updatesId = settings.updatesChannel ? idOf(settings.updatesChannel) : void 0;
941
+ const updatesChanged = updatesId !== void 0 && updatesId !== guild.public_updates_channel_id;
942
+ set("description", "description", settings.description, guild.description ?? "");
943
+ set("locale", "preferred_locale", settings.locale, guild.preferred_locale);
944
+ const community = (guild.features ?? []).includes("COMMUNITY");
945
+ const toggleCommunity = settings.community !== void 0 && settings.community !== community;
946
+ const updatesWithCommunity = updatesId !== void 0 && toggleCommunity && settings.community === true;
947
+ const communityAfter = toggleCommunity ? settings.community === true : community;
948
+ if (updatesChanged && !updatesWithCommunity) {
949
+ if (!communityAfter) throw new Error(`\`updatesChannel\` can only be set while community features are on, but they are off and the layout does not turn them on -- add \`community: true\` or remove \`updatesChannel\``);
950
+ patch.public_updates_channel_id = updatesId;
951
+ updated.push("updatesChannel");
952
+ }
953
+ const ordinary = async () => {
954
+ if (Object.keys(patch).length === 0) return;
955
+ let after;
956
+ try {
957
+ after = await bot.guilds.modify(this.guild(), patch);
958
+ } catch (err) {
959
+ throw await this.manageServerHint(err);
960
+ }
961
+ const stuck = Object.keys(patch).filter((k) => {
962
+ const got = after[k];
963
+ return patch[k] !== (k === "description" ? got ?? "" : got);
964
+ });
965
+ if (stuck.length > 0) throw new Error(`sent ${stuck.join(", ")} but the server came back different -- Discord may have refused a part of it`);
966
+ };
967
+ const toggle = async () => {
968
+ if (!toggleCommunity) return;
969
+ const freshGuild = await bot.guilds.get(this.guild());
970
+ const fresh = freshGuild.features ?? [];
971
+ const wanted = settings.community ? [.../* @__PURE__ */ new Set([...fresh, "COMMUNITY"])] : fresh.filter((f) => f !== "COMMUNITY");
972
+ const turningOn = settings.community === true;
973
+ const rulesSent = turningOn ? (settings.rulesChannel ? idOf(settings.rulesChannel) : freshGuild.rules_channel_id) || void 0 : void 0;
974
+ const updatesSent = turningOn ? (updatesWithCommunity ? updatesId : freshGuild.public_updates_channel_id) || void 0 : void 0;
975
+ let after;
976
+ try {
977
+ after = await bot.guilds.modify(this.guild(), {
978
+ features: wanted,
979
+ ...rulesSent ? { rules_channel_id: rulesSent } : {},
980
+ ...updatesSent ? { public_updates_channel_id: updatesSent } : {}
981
+ });
982
+ } catch (err) {
983
+ throw await this.communityHint(err, updated, settings.community === true);
984
+ }
985
+ const nowFeatures = after.features ?? [];
986
+ if (wanted.includes("COMMUNITY") !== nowFeatures.includes("COMMUNITY")) throw new Error(`${appliedPrefix(updated)}sent the community feature but the server came back different -- community features need a rules channel, an updates channel, verification of at least low and the content filter on all members`);
987
+ if (settings.community) {
988
+ const lost = fresh.filter((f) => f !== "COMMUNITY" && !nowFeatures.includes(f));
989
+ if (lost.length > 0) throw new Error(`turned community on, but the server no longer has ${lost.join(", ")} -- another admin may have changed its features at the same time; check Server Settings and re-run`);
990
+ }
991
+ if (settings.rulesChannel && rulesSent && after.rules_channel_id !== rulesSent) throw new Error(`${appliedPrefix(updated)}turned community on, but the server did not keep ${settings.rulesChannel} as its rules channel`);
992
+ if (updatesWithCommunity && after.public_updates_channel_id !== updatesId) throw new Error(`${appliedPrefix(updated)}turned community on, but the server did not keep ${settings.updatesChannel} as its updates channel`);
993
+ if (updatesWithCommunity && updatesChanged) updated.push("updatesChannel");
994
+ updated.push("community");
995
+ };
996
+ if (toggleCommunity && settings.community === false) {
997
+ await toggle();
998
+ await ordinary();
999
+ } else {
1000
+ await ordinary();
1001
+ await toggle();
1002
+ }
1003
+ return { updated };
1004
+ }
1005
+ /** What the bot's roles give it server-wide (the owner holds every permission), before any channel overwrite. */
1006
+ async serverPermissions() {
1007
+ const bot = this.bot();
1008
+ const me = await this.botId();
1009
+ if ((await this.serverOwner()).isBot) return {
1010
+ owner: true,
1011
+ bits: 0n,
1012
+ held: /* @__PURE__ */ new Set(),
1013
+ me
1014
+ };
1015
+ const [member, roles] = await Promise.all([bot.guilds.member(this.guild(), me), bot.guilds.roles(this.guild())]);
1016
+ const held = /* @__PURE__ */ new Set([this.guild(), ...member.roles]);
1017
+ return {
1018
+ owner: false,
1019
+ bits: roles.filter((r) => held.has(r.id)).reduce((all, r) => all | BigInt(r.permissions ?? "0"), 0n),
1020
+ held,
1021
+ me
1022
+ };
1023
+ }
1024
+ /**
1025
+ * The permissions `needs()` lists that the bot's roles do not give it server-wide, in plain words ("Manage Threads"),
1026
+ * with the invite link that asks for them again when some are missing. The owner and an Administrator hold every
1027
+ * permission. Channel overwrites are not looked at: the forum's own check does that.
1028
+ */
1029
+ async missingBotPermissions() {
1030
+ const { owner, bits } = await this.serverPermissions();
1031
+ const has = (name) => {
1032
+ const bit = BigInt(permissions([name]));
1033
+ return (bits & bit) === bit;
1034
+ };
1035
+ const missing = owner || has("Administrator") ? [] : [...new Set(this.needs())].filter((n) => !has(n));
1036
+ if (missing.length === 0) return { missing: [] };
1037
+ return {
1038
+ missing: missing.map((n) => n.replace(/([a-z])([A-Z])/g, "$1 $2")),
1039
+ inviteUrl: await this.inviteUrl()
1040
+ };
1041
+ }
1042
+ async holdsPermission(permission) {
1043
+ const { owner, bits } = await this.serverPermissions();
1044
+ if (owner) return true;
1045
+ const has = (name) => {
1046
+ const bit = BigInt(permissions([name]));
1047
+ return (bits & bit) === bit;
1048
+ };
1049
+ return has("Administrator") || has(permission);
1050
+ }
1051
+ /**
1052
+ * What a member holding `bits` through the roles in `held` has in a channel, in the order Discord applies the
1053
+ * channel's overwrites: @everyone, then the roles, then the member itself.
1054
+ */
1055
+ static afterOverwrites(bits, held, me, guild, list) {
1056
+ const apply = (now, found) => {
1057
+ const deny = found.reduce((all, o) => all | BigInt(o.deny), 0n);
1058
+ const allow = found.reduce((all, o) => all | BigInt(o.allow), 0n);
1059
+ return now & ~deny | allow;
1060
+ };
1061
+ let now = apply(bits, list.filter((o) => o.id === guild));
1062
+ now = apply(now, list.filter((o) => o.type === 0 && o.id !== guild && held.has(o.id)));
1063
+ return apply(now, list.filter((o) => o.type === 1 && o.id === me));
1064
+ }
1065
+ /**
1066
+ * What the bot can do with the threads of a forum: start posts and reply (`post`) and tag and close them (`manage`).
1067
+ * The owner and an Administrator hold every permission, whatever the forum's overwrites say.
1068
+ */
1069
+ async botThreadsIn(overwrites) {
1070
+ const { owner, bits, held, me } = await this.serverPermissions();
1071
+ if (owner || (bits & BigInt(permissions(["Administrator"]))) !== 0n) return {
1072
+ post: true,
1073
+ manage: true
1074
+ };
1075
+ const now = DiscordNotifications.afterOverwrites(bits, held, me, this.guild(), overwrites);
1076
+ const has = (names) => {
1077
+ const bit = BigInt(permissions(names));
1078
+ return (now & bit) === bit;
1079
+ };
1080
+ return {
1081
+ post: has([
1082
+ "ViewChannel",
1083
+ "CreatePublicThreads",
1084
+ "SendMessagesInThreads"
1085
+ ]),
1086
+ manage: has(["ManageThreads"])
1087
+ };
1088
+ }
1089
+ /**
1090
+ * Whether a channel's own overwrites take a permission away from a bot whose roles grant it, in the order Discord
1091
+ * applies them: @everyone, then the bot's roles, then the bot itself. Read fresh, since a person may have just edited them.
1092
+ */
1093
+ async channelDenies(permission, channelId) {
1094
+ const { owner, bits, held, me } = await this.serverPermissions();
1095
+ const bit = BigInt(permissions([permission]));
1096
+ if (owner || (bits & BigInt(permissions(["Administrator"]))) !== 0n || (bits & bit) !== bit) return false;
1097
+ const channel = (await this.bot().guilds.channels(this.guild())).find((c) => c.id === channelId);
1098
+ return (DiscordNotifications.afterOverwrites(bits, held, me, this.guild(), channel?.permission_overwrites ?? []) & bit) !== bit;
1099
+ }
1100
+ /** The messages this bot posted in a channel, pinned or not, among the channel's last hundred. */
1101
+ async ownMessages(channelId) {
1102
+ const me = await this.botId();
1103
+ return (await this.bot().channels.messages(channelId, 100)).filter((m) => m.author?.id === me).map((m) => ({
1104
+ id: m.id,
1105
+ content: m.content,
1106
+ pinned: m.pinned === true
1107
+ }));
1108
+ }
1109
+ /**
1110
+ * The layout's text with each `#name` that is one of the server's channels turned into Discord's own link to it
1111
+ * (`<#id>`), so the message shows clickable channels. A name that matches no channel, or more than one, is left as written.
1112
+ */
1113
+ static linkChannels(content, channels) {
1114
+ const idsByName = /* @__PURE__ */ new Map();
1115
+ for (const c of channels) {
1116
+ if (c.type === ChannelType.Category) continue;
1117
+ idsByName.set(c.name.toLowerCase(), [...idsByName.get(c.name.toLowerCase()) ?? [], c.id]);
1118
+ }
1119
+ return content.split(/(https?:\/\/\S+)/).map((part, i) => i % 2 === 1 ? part : part.replace(/(?<=^|[\s([{"'*_~>])#([\p{L}\p{N}_-]+)/giu, (whole, name) => {
1120
+ const ids = idsByName.get(name.toLowerCase());
1121
+ return ids?.length === 1 ? `<#${ids[0]}>` : whole;
1122
+ })).join("");
1123
+ }
1124
+ /**
1125
+ * The text of a pinned message. The CLI reads a message's `file` into `content` before it calls the provider, so
1126
+ * the text is only missing when a caller skipped that.
1127
+ */
1128
+ static pinText(pin) {
1129
+ if (pin.content === void 0) throw new Error(`the pinned message for #${pin.channel} has no text: its \`file\` was not read before the layout reached the provider`);
1130
+ return pin.content;
1131
+ }
1132
+ /** The layout's messages grouped by channel, in the order the channels first appear, with channel names linked. */
1133
+ static pinsByChannel(pinned, channels) {
1134
+ const byChannel = /* @__PURE__ */ new Map();
1135
+ for (const pin of pinned) {
1136
+ const key = pin.channel.toLowerCase();
1137
+ const content = DiscordNotifications.linkChannels(DiscordNotifications.pinText(pin), channels);
1138
+ byChannel.set(key, [.../* @__PURE__ */ new Set([...byChannel.get(key) ?? [], content])]);
1139
+ }
1140
+ return byChannel;
1141
+ }
1142
+ /**
1143
+ * What differs in one channel: the declared messages that are not pinned yet, and the bot's pinned messages the
1144
+ * layout does not declare (or declares once and the bot pinned twice). The layout is the whole set of the bot's
1145
+ * pins in a channel it names.
1146
+ */
1147
+ static pinDrift(own, wanted) {
1148
+ const pinned = own.filter((m) => m.pinned).sort((a, b) => BigInt(a.id) < BigInt(b.id) ? -1 : 1);
1149
+ const kept = /* @__PURE__ */ new Set();
1150
+ const extras = pinned.filter((m) => {
1151
+ if (!wanted.includes(m.content) || kept.has(m.content)) return true;
1152
+ kept.add(m.content);
1153
+ return false;
1154
+ });
1155
+ return {
1156
+ missing: wanted.filter((c) => !kept.has(c)),
1157
+ extras
1158
+ };
1159
+ }
1160
+ /** Whether each pinned message is in place: pinned by this bot with exactly the layout's text, and nothing else of the bot's pinned beside it. */
1161
+ async pinnedStates(pinned) {
1162
+ const channels = await this.channelList();
1163
+ const verdicts = /* @__PURE__ */ new Map();
1164
+ for (const [channel, wanted] of DiscordNotifications.pinsByChannel(pinned, channels)) {
1165
+ const own = await this.ownMessages(DiscordNotifications.pickChannelId(channels, channel, "pinned messages"));
1166
+ const drift = DiscordNotifications.pinDrift(own, wanted);
1167
+ verdicts.set(channel, {
1168
+ missing: new Set(drift.missing),
1169
+ extras: drift.extras.length,
1170
+ anyPinned: own.some((m) => m.pinned)
1171
+ });
1172
+ }
1173
+ return pinned.map((pin) => {
1174
+ const v = verdicts.get(pin.channel.toLowerCase());
1175
+ const state = v.missing.has(DiscordNotifications.linkChannels(DiscordNotifications.pinText(pin), channels)) ? v.anyPinned ? "different" : "missing" : v.extras > 0 ? "different" : "ok";
1176
+ return {
1177
+ channel: pin.channel,
1178
+ state
1179
+ };
1180
+ });
1181
+ }
1182
+ discussionStore;
1183
+ /** The discussion posts of this instance's forum channels, which read each forum once. */
1184
+ discussions() {
1185
+ return this.discussionStore ??= new DiscordDiscussions({
1186
+ bot: () => this.bot(),
1187
+ guild: () => this.guild(),
1188
+ channels: () => this.channelList(),
1189
+ starterReactions: (channel) => (this.opts.layout?.categories ?? []).flatMap((c) => c.channels ?? []).find((c) => DiscordNotifications.same(c.name, channel))?.starterReactions ?? [],
1190
+ suppressEmbeds: (channel) => Boolean((this.opts.layout?.categories ?? []).flatMap((c) => c.channels ?? []).find((c) => DiscordNotifications.same(c.name, channel))?.feeds?.prs)
1191
+ });
1192
+ }
1193
+ /** Finds the post for a document in a forum channel, or makes it. See {@link DiscordDiscussions}. */
1194
+ ensureDiscussion(input) {
1195
+ return this.discussions().ensure(input);
1196
+ }
1197
+ /** The post for a document in a forum channel, or `undefined`. */
1198
+ readDiscussion(channel, key, url) {
1199
+ return this.discussions().read(channel, key, url);
1200
+ }
1201
+ /** Changes a document's post: its title, its tag, the state last synced, the pull request line. */
1202
+ updateDiscussion(channel, key, patch) {
1203
+ return this.discussions().update(channel, key, patch);
1204
+ }
1205
+ /** Appends a message to a document's post, reopening and closing it again if it was closed. */
1206
+ postDiscussionMessage(channel, key, content, opts) {
1207
+ return this.discussions().post(channel, key, content, opts);
1208
+ }
1209
+ /** The text of a post's recent messages, newest first. */
1210
+ readDiscussionMessages(channel, key, limit) {
1211
+ return this.discussions().messages(channel, key, limit);
1212
+ }
1213
+ /** Keeps the oldest post for `key` and deletes the others; returns how many it deleted. */
1214
+ dedupeDiscussion(channel, key) {
1215
+ return this.discussions().dedupe(channel, key);
1216
+ }
1217
+ /**
1218
+ * Posts `content` (up to 2000 characters) in a text channel as the bot, without letting it mention anyone. A `#name`
1219
+ * that is one of the server's channels is linked.
1220
+ */
1221
+ async postMessage(channel, content) {
1222
+ const channels = await this.channelList();
1223
+ const channelId = DiscordNotifications.pickChannelId(channels, channel, "a posted message");
1224
+ const linked = DiscordNotifications.linkChannels(content, channels);
1225
+ await this.bot().channels.createMessage(channelId, { content: linked.slice(0, 2e3) });
1226
+ }
1227
+ async ensurePinned(pinned) {
1228
+ const bot = this.bot();
1229
+ const channels = await this.channelList();
1230
+ const updated = [];
1231
+ const byChannel = DiscordNotifications.pinsByChannel(pinned, channels);
1232
+ for (const [channel, wanted] of byChannel) {
1233
+ const long = wanted.find((content) => content.length > 2e3);
1234
+ if (long) throw new Error(`the pinned message for #${channel} is ${long.length} characters once its channel names are linked; Discord allows up to 2000`);
1235
+ }
1236
+ for (const [channel, wanted] of byChannel) {
1237
+ const channelId = DiscordNotifications.pickChannelId(channels, channel, "pinned messages");
1238
+ const own = await this.ownMessages(channelId);
1239
+ const drift = DiscordNotifications.pinDrift(own, wanted);
1240
+ if (drift.missing.length === 0 && drift.extras.length === 0) continue;
1241
+ let extras = drift.extras;
1242
+ for (const content of drift.missing) {
1243
+ const orphan = own.find((m) => !m.pinned && m.content === content);
1244
+ const posted = orphan ?? await bot.channels.createMessage(channelId, { content });
1245
+ try {
1246
+ try {
1247
+ await bot.channels.pin(channelId, posted.id);
1248
+ } catch (err) {
1249
+ if (!(err instanceof ProviderApiError && /\b30003\b/.test(String(err.details))) || extras.length === 0) throw err;
1250
+ for (const old of extras) await bot.channels.deleteMessage(channelId, old.id);
1251
+ extras = [];
1252
+ await bot.channels.pin(channelId, posted.id);
1253
+ }
1254
+ } catch (err) {
1255
+ if (!orphan) await bot.channels.deleteMessage(channelId, posted.id).catch(() => void 0);
1256
+ throw await this.pinHint(err, channel);
1257
+ }
1258
+ }
1259
+ for (const old of extras) await bot.channels.deleteMessage(channelId, old.id);
1260
+ if (drift.missing.length > 0) {
1261
+ const after = DiscordNotifications.pinDrift(await this.ownMessages(channelId), wanted);
1262
+ for (const dup of after.extras) await bot.channels.deleteMessage(channelId, dup.id);
1263
+ }
1264
+ updated.push(`#${channel}`);
1265
+ }
1266
+ return { updated };
1267
+ }
1268
+ /** A 403 on pinning becomes the missing permission and a link that grants it, which `setup` can walk a person through. */
1269
+ async pinHint(err, channel) {
1270
+ if (!DiscordNotifications.missingPermissions(err)) return err;
1271
+ if (await this.channelDenies("PinMessages", DiscordNotifications.pickChannelId(await this.channelList(), channel, "pinned messages")).catch(() => false)) return new Error(`the bot could not pin the message in #${channel}: its role has Pin Messages, but the channel's permissions take it away. Remove that override under Edit Channel → Permissions, then run setup again`, { cause: err });
1272
+ const link = await this.inviteOrNothing([...BOT_NEEDS, "PinMessages"]);
1273
+ return new ElevationRequiredError(`the bot could not pin the message in #${channel}: its role lacks Pin Messages. Re-invite it with that permission${link ? ` (this updates its role in place): ${link}` : ""}`, {
1274
+ permission: "PinMessages",
1275
+ label: "Pin Messages",
1276
+ keep: true,
1277
+ ...link ? { grantUrl: link } : {}
1278
+ }, { cause: err });
1279
+ }
1280
+ /** A 403 on the welcome screen or onboarding becomes the likely reason; anything else is passed on. */
1281
+ static communityFeatureHint(err, what) {
1282
+ if (!(err instanceof ProviderApiError && err.status === 403)) return err;
1283
+ return new Error(`the bot is not allowed to change ${what} (Discord said: ${String(err.details).slice(0, 120)}). It needs Manage Server, and the server needs community features on`, { cause: err });
1284
+ }
1285
+ /** The numeric code Discord puts in the JSON body of an error, or undefined when the body is not that. */
1286
+ static codeOf(err) {
1287
+ try {
1288
+ return JSON.parse(String(err.details)).code;
1289
+ } catch {
1290
+ return;
1291
+ }
1292
+ }
1293
+ /** The welcome screen; a server that never had one answers 404 (10069), which is an empty screen. */
1294
+ async welcomeScreenOf() {
1295
+ try {
1296
+ return await this.bot().guilds.welcomeScreen(this.guild());
1297
+ } catch (err) {
1298
+ if (err instanceof ProviderApiError && err.status === 404 && DiscordNotifications.codeOf(err) === 10069) return {
1299
+ description: null,
1300
+ welcome_channels: []
1301
+ };
1302
+ throw err;
1303
+ }
1304
+ }
1305
+ async ensureWelcome(welcome) {
1306
+ const bot = this.bot();
1307
+ const channels = await this.channelList();
1308
+ const idOf = (name) => DiscordNotifications.pickChannelId(channels, name, "the welcome screen", true);
1309
+ const wanted = {
1310
+ enabled: welcome.enabled ?? true,
1311
+ description: welcome.description,
1312
+ welcome_channels: welcome.channels.map((c) => ({
1313
+ channel_id: idOf(c.channel),
1314
+ description: c.description,
1315
+ emoji_name: c.emoji ?? null,
1316
+ emoji_id: null
1317
+ }))
1318
+ };
1319
+ const normalise = (list) => JSON.stringify(list.map((c) => [
1320
+ c.channel_id,
1321
+ c.description,
1322
+ c.emoji_name ?? null,
1323
+ c.emoji_id ?? null
1324
+ ]));
1325
+ let guild;
1326
+ let screen;
1327
+ try {
1328
+ guild = await bot.guilds.get(this.guild());
1329
+ screen = await this.welcomeScreenOf();
1330
+ } catch (err) {
1331
+ throw DiscordNotifications.communityFeatureHint(err, "the welcome screen");
1332
+ }
1333
+ const updated = [];
1334
+ if ((guild.features ?? []).includes("WELCOME_SCREEN_ENABLED") !== wanted.enabled) updated.push("enabled");
1335
+ if ((screen.description ?? "") !== wanted.description) updated.push("description");
1336
+ if (normalise(screen.welcome_channels ?? []) !== normalise(wanted.welcome_channels)) updated.push("channels");
1337
+ if (updated.length === 0) return { updated };
1338
+ let after;
1339
+ try {
1340
+ after = await bot.guilds.modifyWelcomeScreen(this.guild(), wanted);
1341
+ } catch (err) {
1342
+ throw DiscordNotifications.communityFeatureHint(err, "the welcome screen");
1343
+ }
1344
+ if ((after.description ?? "") !== wanted.description || normalise(after.welcome_channels ?? []) !== normalise(wanted.welcome_channels)) throw new Error("sent the welcome screen but it came back different -- Discord may have refused a part of it");
1345
+ if (((await bot.guilds.get(this.guild())).features ?? []).includes("WELCOME_SCREEN_ENABLED") !== wanted.enabled) throw new Error(`sent the welcome screen but it is still ${wanted.enabled ? "off" : "on"} -- Discord may have refused the switch`);
1346
+ return { updated };
1347
+ }
1348
+ /** An onboarding prompt reduced to what the layout can state, so the server's and the layout's can be compared. */
1349
+ static onboardingKey(prompts) {
1350
+ return JSON.stringify(prompts.map((p) => [
1351
+ p.type,
1352
+ p.in_onboarding,
1353
+ p.title,
1354
+ p.single_select,
1355
+ p.required,
1356
+ p.options.map((o) => [
1357
+ o.title,
1358
+ o.description ?? "",
1359
+ [...o.channel_ids ?? []].sort(),
1360
+ [...o.role_ids ?? []].sort(),
1361
+ o.emoji?.name ?? o.emoji_name ?? null
1362
+ ])
1363
+ ]));
1364
+ }
1365
+ async ensureOnboarding(onboarding) {
1366
+ const bot = this.bot();
1367
+ const channels = await this.channelList();
1368
+ const channelId = (name) => DiscordNotifications.pickChannelId(channels, name, "onboarding", true);
1369
+ const roles = (onboarding.prompts ?? []).some((p) => p.options.some((o) => (o.roles ?? []).length > 0)) ? await this.roleList() : [];
1370
+ const roleId = (name) => DiscordNotifications.pickRole(roles, name, "onboarding");
1371
+ let current;
1372
+ try {
1373
+ current = await bot.guilds.onboarding(this.guild());
1374
+ } catch (err) {
1375
+ throw DiscordNotifications.communityFeatureHint(err, "onboarding");
1376
+ }
1377
+ const usedIds = /* @__PURE__ */ new Set();
1378
+ const prompts = onboarding.prompts === void 0 ? current.prompts : onboarding.prompts.map((p) => {
1379
+ const had = current.prompts.find((c) => c.title === p.title && !usedIds.has(c.id));
1380
+ if (had) usedIds.add(had.id);
1381
+ const hadOptions = /* @__PURE__ */ new Set();
1382
+ return {
1383
+ id: had?.id ?? newId(),
1384
+ type: 0,
1385
+ title: p.title,
1386
+ single_select: p.singleSelect ?? false,
1387
+ required: p.required ?? false,
1388
+ in_onboarding: true,
1389
+ options: p.options.map((o) => ({
1390
+ id: (() => {
1391
+ const old = had?.options.find((c) => c.title === o.title && !hadOptions.has(c.id));
1392
+ if (old) hadOptions.add(old.id);
1393
+ return old?.id ?? newId();
1394
+ })(),
1395
+ title: o.title,
1396
+ description: o.description ?? null,
1397
+ channel_ids: (o.channels ?? []).map(channelId),
1398
+ role_ids: (o.roles ?? []).map(roleId),
1399
+ emoji_name: o.emoji ?? null
1400
+ }))
1401
+ };
1402
+ });
1403
+ const defaultChannels = onboarding.defaultChannels === void 0 ? current.default_channel_ids : onboarding.defaultChannels.map(channelId);
1404
+ const enabled = onboarding.enabled ?? current.enabled;
1405
+ const updated = [];
1406
+ if (enabled !== current.enabled) updated.push("enabled");
1407
+ if (JSON.stringify([...defaultChannels].sort()) !== JSON.stringify([...current.default_channel_ids].sort())) updated.push("defaultChannels");
1408
+ if (DiscordNotifications.onboardingKey(prompts) !== DiscordNotifications.onboardingKey(current.prompts)) updated.push("prompts");
1409
+ if (updated.length === 0) return { updated };
1410
+ const body = {
1411
+ prompts,
1412
+ default_channel_ids: defaultChannels,
1413
+ enabled,
1414
+ mode: current.mode ?? 0
1415
+ };
1416
+ let after;
1417
+ try {
1418
+ after = await bot.guilds.modifyOnboarding(this.guild(), body);
1419
+ } catch (err) {
1420
+ throw DiscordNotifications.communityFeatureHint(err, "onboarding");
1421
+ }
1422
+ if (after.enabled !== enabled || JSON.stringify([...after.default_channel_ids].sort()) !== JSON.stringify([...defaultChannels].sort()) || DiscordNotifications.onboardingKey(after.prompts) !== DiscordNotifications.onboardingKey(prompts)) throw new Error("sent onboarding but it came back different -- Discord may have refused a part of it");
1423
+ return { updated };
1424
+ }
1425
+ async ensureEveryone(everyone) {
1426
+ const bot = this.bot();
1427
+ const role = (await bot.guilds.roles(this.guild())).find((r) => r.id === this.guild());
1428
+ if (role?.permissions === void 0) throw new Error("the server has no @everyone role to change");
1429
+ const bit = (name) => BigInt(permissions([name]));
1430
+ const have = BigInt(role.permissions);
1431
+ const allow = everyone.allow ?? [];
1432
+ const deny = everyone.deny ?? [];
1433
+ const want = allow.reduce((acc, n) => acc | bit(n), have);
1434
+ const final = deny.reduce((acc, n) => acc & ~bit(n), want);
1435
+ if (final === have) return { updated: [] };
1436
+ const updated = [...allow.filter((n) => (have & bit(n)) === 0n), ...deny.filter((n) => (have & bit(n)) !== 0n)];
1437
+ this.roleLoad = void 0;
1438
+ if ((await bot.guilds.modifyRole(this.guild(), role.id, { permissions: String(final) })).permissions !== String(final)) throw new Error("sent the @everyone permissions but they came back different -- Discord may have refused a part of it");
1439
+ return { updated };
1440
+ }
1441
+ async ensureApplication(app) {
1442
+ const bot = this.bot();
1443
+ const current = await bot.application.get();
1444
+ const set = (list) => JSON.stringify([...new Set(list.map((n) => n.toLowerCase()))].sort());
1445
+ const exact = (list) => JSON.stringify([...new Set(list)].sort());
1446
+ const urls = [
1447
+ ["termsUrl", "terms_of_service_url"],
1448
+ ["privacyUrl", "privacy_policy_url"],
1449
+ ["roleConnectionsUrl", "role_connections_verification_url"]
1450
+ ];
1451
+ const body = {};
1452
+ const updated = [];
1453
+ if (app.description !== void 0 && (current.description ?? "") !== app.description) {
1454
+ body.description = app.description;
1455
+ updated.push("description");
1456
+ }
1457
+ if (app.tags !== void 0 && set(current.tags ?? []) !== set(app.tags)) {
1458
+ body.tags = app.tags;
1459
+ updated.push("tags");
1460
+ }
1461
+ const install = app.install && {
1462
+ scopes: app.install.scopes,
1463
+ permissions: permissions(app.install.permissions)
1464
+ };
1465
+ const haveInstall = current.install_params;
1466
+ if (install && (!haveInstall || exact(haveInstall.scopes) !== exact(install.scopes) || haveInstall.permissions !== install.permissions)) {
1467
+ body.install_params = install;
1468
+ updated.push("install");
1469
+ }
1470
+ for (const [field, key] of urls) if (app[field] !== void 0 && (current[key] ?? "") !== app[field]) {
1471
+ body[key] = app[field];
1472
+ updated.push(field);
1473
+ }
1474
+ const flagsNow = current.flags ?? 0;
1475
+ const membersWanted = app.intents?.members;
1476
+ if (membersWanted !== void 0 && membersWanted !== DiscordNotifications.membersIntentOn(flagsNow)) {
1477
+ body.flags = membersWanted ? flagsNow | ApplicationFlag.GatewayGuildMembersLimited : flagsNow & ~ApplicationFlag.GatewayGuildMembersLimited;
1478
+ updated.push("intents");
1479
+ }
1480
+ const todo = (app.redirectUris ?? []).filter((uri) => !(current.redirect_uris ?? []).includes(uri)).map((uri) => `add ${uri} under OAuth2 → Redirects in the Discord developer portal (the API does not allow setting it)`);
1481
+ if (updated.length === 0) return {
1482
+ updated,
1483
+ ...todo.length ? { todo } : {}
1484
+ };
1485
+ let after;
1486
+ try {
1487
+ after = await bot.application.modify(body);
1488
+ } catch (err) {
1489
+ if (err instanceof ProviderApiError && String(err.details).includes("APPLICATION_INSTALL_NEEDS_PUBLIC_INTEGRATION")) throw new Error("Discord only allows an install link on a public application, and this one is private (Public Bot is off). Remove `install` from the layout -- a private bot is invited with a link you build, which `setup` prints when a permission is missing -- or turn on Public Bot in the developer portal, which lets anyone add the bot", { cause: err });
1490
+ throw err;
1491
+ }
1492
+ const stuck = updated.filter((name) => {
1493
+ if (name === "description") return (after.description ?? "") !== app.description;
1494
+ if (name === "tags") return set(after.tags ?? []) !== set(app.tags);
1495
+ if (name === "intents") return DiscordNotifications.membersIntentOn(after.flags ?? 0) !== app.intents.members;
1496
+ if (name === "install") return !after.install_params || exact(after.install_params.scopes) !== exact(install.scopes) || after.install_params.permissions !== install.permissions;
1497
+ const key = urls.find(([f]) => f === name)[1];
1498
+ return (after[key] ?? "") !== app[name];
1499
+ });
1500
+ if (stuck.length > 0) throw new Error(`sent ${stuck.join(", ")} but Discord did not keep ${stuck.length === 1 ? "it" : "them"} -- it may not accept that field from a bot, so set it in the developer portal`);
1501
+ return {
1502
+ updated,
1503
+ ...todo.length ? { todo } : {}
1504
+ };
1505
+ }
1506
+ /** Whether the Server Members Intent is on: the unverified app's toggle, or the verified app's own bit. */
1507
+ static membersIntentOn(flags) {
1508
+ return (flags & (ApplicationFlag.GatewayGuildMembers | ApplicationFlag.GatewayGuildMembersLimited)) !== 0;
1509
+ }
1510
+ validateLayout(layout) {
1511
+ const app = layout.application;
1512
+ if (app) {
1513
+ if (app.description !== void 0 && app.description.length > 400) return `application: \`description\` is ${app.description.length} characters; Discord allows up to 400`;
1514
+ if (app.tags !== void 0) {
1515
+ if (app.tags.length > 5) return `application: ${app.tags.length} tags; Discord allows up to 5`;
1516
+ const long = app.tags.find((t) => t.length > 20);
1517
+ if (long !== void 0) return `application: the tag ${JSON.stringify(long)} is over 20 characters`;
1518
+ }
1519
+ const badRedirect = (app.redirectUris ?? []).find((u) => !/^https:\/\/|^http:\/\/localhost(:\d+)?\//.test(u));
1520
+ if (badRedirect !== void 0) return `application: \`redirectUris\` ${JSON.stringify(badRedirect)} must start with https:// (or http://localhost for a local sign-in)`;
1521
+ for (const [field, url] of [
1522
+ ["termsUrl", app.termsUrl],
1523
+ ["privacyUrl", app.privacyUrl],
1524
+ ["roleConnectionsUrl", app.roleConnectionsUrl]
1525
+ ]) if (url !== void 0 && !/^https:\/\//.test(url)) return `application: \`${field}\` ${JSON.stringify(url)} must start with https://`;
1526
+ if (app.install) {
1527
+ if (app.install.scopes.length === 0) return "application: `install.scopes` is empty; the link needs at least `bot`";
1528
+ const unknown = app.install.scopes.find((s) => !SCOPES.has(s));
1529
+ if (unknown !== void 0) return `application: \`install.scopes\` has ${JSON.stringify(unknown)}, which is not an OAuth2 scope Discord offers (scopes are lower-case, for example bot, applications.commands)`;
1530
+ try {
1531
+ permissions(app.install.permissions);
1532
+ } catch (err) {
1533
+ return `application: \`install.permissions\`: ${errorMessage(err)}`;
1534
+ }
1535
+ }
1536
+ }
1537
+ if (layout.everyone) try {
1538
+ permissions([...layout.everyone.allow ?? [], ...layout.everyone.deny ?? []]);
1539
+ } catch (err) {
1540
+ return `everyone: ${errorMessage(err)}`;
1541
+ }
1542
+ const questions = layout.onboarding?.prompts?.length ?? 0;
1543
+ if (questions > 5) return `onboarding: ${questions} questions; Discord allows up to 5`;
1544
+ const welcome = layout.welcome;
1545
+ if (welcome) {
1546
+ if (welcome.description.length > 140) return `welcome: \`description\` is ${welcome.description.length} characters; Discord allows up to 140`;
1547
+ if (welcome.channels.length > 5) return `welcome: ${welcome.channels.length} channels; Discord allows up to 5`;
1548
+ const long = welcome.channels.find((c) => c.description.length > 50);
1549
+ if (long) return `welcome: the description of \`${long.channel}\` is ${long.description.length} characters; Discord allows up to 50`;
1550
+ }
1551
+ const long2000 = layout.pinned?.find((p) => (p.content?.length ?? 0) > 2e3);
1552
+ if (long2000) {
1553
+ const from = long2000.file ? ` (from \`${long2000.file}\`)` : "";
1554
+ return `pinned: the message for \`${long2000.channel}\`${from} is ${long2000.content.length} characters; Discord allows up to 2000`;
1555
+ }
1556
+ const server = layout.server;
1557
+ for (const [field, map] of [
1558
+ ["verification", VERIFICATION],
1559
+ ["defaultNotifications", NOTIFICATIONS],
1560
+ ["contentFilter", FILTER]
1561
+ ]) {
1562
+ const value = server?.[field];
1563
+ if (value !== void 0 && !Object.hasOwn(map, value)) return `server: \`${field}\` is ${JSON.stringify(value)}; use one of ${Object.keys(map).join(", ")}`;
1564
+ }
1565
+ if (server?.community === false && server.updatesChannel !== void 0) return "server: `updatesChannel` can only be set while community features are on; remove it or set `community: true`";
1566
+ if (server?.locale !== void 0 && !LOCALES.has(server.locale)) return `server: \`locale\` ${JSON.stringify(server.locale)} is not a locale Discord accepts (for example en-US, en-GB, de, fr)`;
1567
+ if (server?.community === true && (server.verification === void 0 || server.verification === "none")) return "server: community features need `verification` of at least `low`";
1568
+ if (server?.community === true && server.contentFilter !== "all") return "server: community features need `contentFilter: \"all\"`";
1569
+ for (const channel of (layout.categories ?? []).flatMap((c) => c.channels ?? [])) {
1570
+ const tags = channel.tags ?? [];
1571
+ if (tags.length > 20) return `channel \`${channel.name}\`: ${tags.length} tags; Discord allows up to 20`;
1572
+ const long = tags.find((t) => t.name.length > 20);
1573
+ if (long) return `channel \`${channel.name}\`: the tag \`${long.name}\` is ${long.name.length} characters; Discord allows up to 20`;
1574
+ }
1575
+ for (const role of layout.roles ?? []) try {
1576
+ if (role.color !== void 0) colorToInt(role.color);
1577
+ if (role.permissions !== void 0) permissions(role.permissions);
1578
+ } catch (err) {
1579
+ return `role \`${role.name}\`: ${errorMessage(err)}`;
1580
+ }
1581
+ }
1582
+ botUser;
1583
+ botId() {
1584
+ return this.botUser ??= this.bot().users.me().then((u) => u.id).catch((err) => {
1585
+ this.botUser = void 0;
1586
+ throw err;
1587
+ });
1588
+ }
1589
+ /**
1590
+ * The overwrites that make a channel look like `access`. The list is exact: it replaces
1591
+ * whatever was set by hand. `[]` (public) when nothing is restricted.
1592
+ */
1593
+ async overwritesFor(access) {
1594
+ const view = access.view ?? "everyone";
1595
+ const post = access.post ?? "everyone";
1596
+ const everyoneDeny = [...view === "everyone" ? [] : ["ViewChannel"], ...post === "everyone" ? [] : POST];
1597
+ if (everyoneDeny.length === 0) return [];
1598
+ const roles = [...view === "everyone" ? [] : view, ...post === "everyone" ? [] : post].length > 0 ? await this.roleList() : [];
1599
+ const idOf = (name) => DiscordNotifications.pickRole(roles, name, "access");
1600
+ const allow = /* @__PURE__ */ new Map();
1601
+ const grant = (roleName, names) => {
1602
+ const id = idOf(roleName);
1603
+ allow.set(id, [.../* @__PURE__ */ new Set([...allow.get(id) ?? [], ...names])]);
1604
+ };
1605
+ if (view !== "everyone") for (const r of view) grant(r, ["ViewChannel"]);
1606
+ if (post !== "everyone") for (const r of post) grant(r, POST);
1607
+ return [
1608
+ {
1609
+ id: this.guild(),
1610
+ type: 0,
1611
+ allow: "0",
1612
+ deny: permissions(everyoneDeny)
1613
+ },
1614
+ ...[...allow].map(([id, names]) => ({
1615
+ id,
1616
+ type: 0,
1617
+ allow: permissions(names),
1618
+ deny: "0"
1619
+ })),
1620
+ {
1621
+ id: await this.botId(),
1622
+ type: 1,
1623
+ allow: permissions(BOT_KEEPS),
1624
+ deny: "0"
1625
+ }
1626
+ ];
1627
+ }
1628
+ /**
1629
+ * Read an access back out of a channel's overwrites, naming roles as the layout does. Only
1630
+ * overwrites of the shape {@link overwritesFor} writes can be read back; anything else
1631
+ * (a role-specific deny, a member overwrite, only some of the posting bits) means the
1632
+ * channel's real access is not something the layout can state, and is reported as `"custom"`
1633
+ * rather than guessed at.
1634
+ */
1635
+ accessOf(overwrites, roleName) {
1636
+ const list = overwrites ?? [];
1637
+ const managed = permissions(["ViewChannel", ...POST]);
1638
+ const unthreaded = (bits) => BigInt(bits) & THREAD_MASK;
1639
+ const within = (bits) => (unthreaded(bits) & ~BigInt(managed)) === 0n;
1640
+ const botSignature = permissions(BOT_KEEPS);
1641
+ let everyone;
1642
+ const roles = [];
1643
+ for (const o of list) if (o.type === 1) {
1644
+ if (o.allow !== botSignature || o.deny !== "0") return "custom";
1645
+ } else if (o.id === this.guild()) everyone = o;
1646
+ else roles.push(o);
1647
+ if (everyone && (unthreaded(everyone.allow) !== 0n || !within(everyone.deny))) return "custom";
1648
+ for (const o of roles) if (unthreaded(o.deny) !== 0n || !within(o.allow)) return "custom";
1649
+ const denied = (bit) => everyone !== void 0 && permissionNames(everyone.deny).includes(bit);
1650
+ const names = (bit) => roles.filter((o) => permissionNames(o.allow).includes(bit)).map((o) => roleName(o.id));
1651
+ return {
1652
+ view: denied("ViewChannel") ? names("ViewChannel") : "everyone",
1653
+ post: denied("SendMessages") ? names("SendMessages") : "everyone"
1654
+ };
1655
+ }
1656
+ /** The server's roles, fetched once and forgotten whenever setup changes a role. */
1657
+ roleLoad;
1658
+ roleList() {
1659
+ return this.roleLoad ??= this.bot().guilds.roles(this.guild()).catch((err) => {
1660
+ this.roleLoad = void 0;
1661
+ throw err;
1662
+ });
1663
+ }
1664
+ /** The server this run created, which takes over from `guildId` for the rest of the run. */
1665
+ createdGuild;
1666
+ guild() {
1667
+ if (this.createdGuild) return this.createdGuild;
1668
+ if (!this.opts.guildId) throw new Error("no Discord server id — set `guildId` in the discord provider options in holocron.config.ts");
1669
+ if (!/^\d{1,20}$/.test(this.opts.guildId)) throw new Error(`\`guildId\` ${JSON.stringify(this.opts.guildId)} is not a Discord server id (digits only)`);
1670
+ return this.opts.guildId;
1671
+ }
1672
+ /**
1673
+ * The server's channel list, fetched once per instance. Every ensure* call used
1674
+ * to refetch it -- about 40 identical GETs in one setup run -- and Discord
1675
+ * rate-limited the route. Our own creates and edits update the copy, so it
1676
+ * stays accurate for the run; a new run builds a new instance.
1677
+ *
1678
+ * It is the in-flight promise that is shared, not the array: callers that start
1679
+ * while the first fetch is pending all get the same snapshot, so a later
1680
+ * response can never overwrite what an earlier caller added.
1681
+ */
1682
+ channelLoad;
1683
+ channelList() {
1684
+ return this.channelLoad ??= this.bot().guilds.channels(this.guild()).catch((err) => {
1685
+ this.channelLoad = void 0;
1686
+ throw err;
1687
+ });
1688
+ }
1689
+ /**
1690
+ * Create a channel and add it to the shared list. If the create fails, Discord
1691
+ * may still have applied it (a timeout looks the same as a refusal), so forget the
1692
+ * list: the next ensure refetches the server's real state instead of creating a
1693
+ * duplicate.
1694
+ */
1695
+ async createChannel(body) {
1696
+ try {
1697
+ const made = await this.bot().guilds.createChannel(this.guild(), body);
1698
+ (await this.channelList()).push(made);
1699
+ return made;
1700
+ } catch (err) {
1701
+ this.channelLoad = void 0;
1702
+ throw err;
1703
+ }
1704
+ }
1705
+ static same(a, b) {
1706
+ return a.toLowerCase() === b.toLowerCase();
1707
+ }
1708
+ async ensureCategory(name, opts = {}) {
1709
+ const existing = (await this.channelList()).find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, name));
1710
+ const overwrites = opts.access ? await this.overwritesFor(opts.access) : void 0;
1711
+ if (existing) {
1712
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
1713
+ await this.modifyChannel(existing, { permission_overwrites: keepThreadBits(overwrites, existing.permission_overwrites) });
1714
+ return {
1715
+ id: existing.id,
1716
+ created: false,
1717
+ updated: ["access"]
1718
+ };
1719
+ }
1720
+ return {
1721
+ id: existing.id,
1722
+ created: false
1723
+ };
1724
+ }
1725
+ return {
1726
+ id: (await this.createChannel({
1727
+ name,
1728
+ type: ChannelType.Category,
1729
+ ...overwrites ? { permission_overwrites: overwrites } : {}
1730
+ })).id,
1731
+ created: true
1732
+ };
1733
+ }
1734
+ /**
1735
+ * Edit a channel and keep the shared list in step; forget the list if the edit may have half-applied.
1736
+ * Discord answers with the channel as it now is: if the overwrites that come back are not the ones we
1737
+ * sent, something else changed it at the same time, so say so instead of reporting success.
1738
+ */
1739
+ async modifyChannel(channel, patch) {
1740
+ let after;
1741
+ try {
1742
+ after = await this.bot().channels.modify(channel.id, patch);
1743
+ } catch (err) {
1744
+ this.channelLoad = void 0;
1745
+ throw err;
1746
+ }
1747
+ if (patch.permission_overwrites && overwriteKey(after.permission_overwrites) !== overwriteKey(patch.permission_overwrites)) {
1748
+ this.channelLoad = void 0;
1749
+ throw new Error(`\`${channel.name}\`: sent its access but the channel came back different -- another setup run may be changing it at the same time; re-run once it has finished`);
1750
+ }
1751
+ Object.assign(channel, patch);
1752
+ }
1753
+ /**
1754
+ * Find a channel by name. A name can exist in several categories, so with a
1755
+ * parent: prefer the one already there, then an uncategorised one (moved in);
1756
+ * never grab a channel that lives under a different category. Announcement
1757
+ * channels count: reusing one beats creating a same-named text channel.
1758
+ */
1759
+ static findChannel(channels, name, parentId, forum = false) {
1760
+ const named = channels.filter((c) => (forum ? c.type === ChannelType.Forum : c.type === ChannelType.Text || c.type === ChannelType.Announcement) && DiscordNotifications.same(c.name, name));
1761
+ if (!parentId) return named[0];
1762
+ return named.find((c) => c.parent_id === parentId) ?? named.find((c) => !c.parent_id);
1763
+ }
1764
+ /** A forum tag in the layout's terms. */
1765
+ static tagOf(tag) {
1766
+ return {
1767
+ name: tag.name,
1768
+ ...tag.emoji_name ? { emoji: tag.emoji_name } : {},
1769
+ moderated: tag.moderated
1770
+ };
1771
+ }
1772
+ /** A layout tag as Discord takes it. */
1773
+ static tagInput(tag, id) {
1774
+ return {
1775
+ ...id ? { id } : {},
1776
+ name: tag.name,
1777
+ moderated: tag.moderated ?? false,
1778
+ emoji_name: tag.emoji ?? null,
1779
+ emoji_id: null
1780
+ };
1781
+ }
1782
+ /**
1783
+ * The forum's tags once the layout's are in: every tag it has already (kept, with the emoji and `moderated` the layout
1784
+ * gives it) and each layout tag it lacks, added. A tag the layout does not list is never removed, since a post
1785
+ * carries it. Returns `undefined` when nothing differs.
1786
+ */
1787
+ static mergeTags(have, want) {
1788
+ let changed = false;
1789
+ const merged = have.map((h) => {
1790
+ const w = want.find((t) => DiscordNotifications.same(t.name, h.name));
1791
+ if (!w) return DiscordNotifications.tagInput(DiscordNotifications.tagOf(h), h.id);
1792
+ if ((w.emoji ?? null) !== h.emoji_name || (w.moderated ?? false) !== h.moderated) changed = true;
1793
+ return DiscordNotifications.tagInput(w, h.id);
1794
+ });
1795
+ const added = want.filter((w) => !have.some((h) => DiscordNotifications.same(h.name, w.name)));
1796
+ if (added.length > 0) changed = true;
1797
+ return changed ? [...merged, ...added.map((w) => DiscordNotifications.tagInput(w))] : void 0;
1798
+ }
1799
+ /**
1800
+ * Finds the text or announcement channel with this name (under the category, when given), or creates it; reports
1801
+ * whether it was created. With `kind: "forum"` it is a forum channel with the layout's tags. Discord cannot turn one
1802
+ * kind into the other and this never deletes, so a channel of the other kind with the name stops the run with the fix.
1803
+ */
1804
+ async ensureChannel(input) {
1805
+ const forum = input.kind === "forum";
1806
+ const parent = input.category ? (await this.ensureCategory(input.category)).id : void 0;
1807
+ const channels = await this.channelList();
1808
+ const existing = DiscordNotifications.findChannel(channels, input.name, parent, forum);
1809
+ if (!existing && DiscordNotifications.findChannel(channels, input.name, parent, !forum)) throw new Error(`\`${input.name}\` exists as ${forum ? "a text channel" : "a forum"}, and Discord cannot turn it into ${forum ? "a forum" : "a text channel"}. Delete it in Discord (its messages go with it), then run setup again`);
1810
+ const overwrites = input.access ? await this.overwritesFor(input.access) : void 0;
1811
+ if (existing) {
1812
+ const updated = [];
1813
+ const patch = {};
1814
+ const tags = forum && input.tags ? DiscordNotifications.mergeTags(existing.available_tags ?? [], input.tags) : void 0;
1815
+ if (tags) {
1816
+ patch.available_tags = tags;
1817
+ updated.push("tags");
1818
+ }
1819
+ if (forum && input.defaultReaction !== void 0) {
1820
+ const have = existing.default_reaction_emoji;
1821
+ if (have?.emoji_name !== input.defaultReaction || have.emoji_id) {
1822
+ patch.default_reaction_emoji = {
1823
+ emoji_id: null,
1824
+ emoji_name: input.defaultReaction
1825
+ };
1826
+ updated.push("default reaction");
1827
+ }
1828
+ }
1829
+ if (parent && existing.parent_id !== parent) {
1830
+ patch.parent_id = parent;
1831
+ updated.push("category");
1832
+ }
1833
+ if (input.topic !== void 0 && (existing.topic ?? "") !== input.topic) {
1834
+ patch.topic = input.topic;
1835
+ updated.push("topic");
1836
+ }
1837
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
1838
+ patch.permission_overwrites = keepThreadBits(overwrites, existing.permission_overwrites);
1839
+ updated.push("access");
1840
+ }
1841
+ if (updated.length > 0) await this.modifyChannel(existing, patch);
1842
+ return {
1843
+ id: existing.id,
1844
+ created: false,
1845
+ ...updated.length > 0 ? { updated } : {}
1846
+ };
1847
+ }
1848
+ return {
1849
+ id: (await this.createChannel({
1850
+ name: input.name,
1851
+ type: forum ? ChannelType.Forum : ChannelType.Text,
1852
+ ...forum && input.tags ? { available_tags: input.tags.map((t) => DiscordNotifications.tagInput(t)) } : {},
1853
+ ...forum && input.defaultReaction ? { default_reaction_emoji: {
1854
+ emoji_id: null,
1855
+ emoji_name: input.defaultReaction
1856
+ } } : {},
1857
+ ...input.topic ? { topic: input.topic } : {},
1858
+ ...parent ? { parent_id: parent } : {},
1859
+ ...overwrites ? { permission_overwrites: overwrites } : {}
1860
+ })).id,
1861
+ created: true
1862
+ };
1863
+ }
1864
+ /** Finds the webhook with this name on the channel, or creates it; the optional avatar is the picture it posts with. */
1865
+ async ensureWebhook(input) {
1866
+ const bot = this.bot();
1867
+ const parent = input.category ? (await this.channelList()).find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, input.category))?.id : void 0;
1868
+ const channel = DiscordNotifications.findChannel(await this.channelList(), input.channel, parent);
1869
+ if (!channel) throw new Error(`no channel named \`${input.channel}\` — create it first`);
1870
+ const existing = (await bot.channels.webhooks(channel.id)).find((w) => DiscordNotifications.same(w.name ?? "", input.name));
1871
+ const hook = existing ?? await bot.channels.createWebhook(channel.id, { name: input.name });
1872
+ const result = {
1873
+ created: !existing,
1874
+ ...hook.url ? { url: hook.url } : {}
1875
+ };
1876
+ if (input.avatar !== void 0 && !hook.avatar) try {
1877
+ await bot.webhooks.modify(hook.id, { avatar: input.avatar });
1878
+ result.updated = ["avatar"];
1879
+ } catch (err) {
1880
+ result.avatarError = reason(err);
1881
+ }
1882
+ return result;
1883
+ }
1884
+ async checkDelivery(input) {
1885
+ const result = {
1886
+ posted: false,
1887
+ readBack: false,
1888
+ removed: false,
1889
+ problems: []
1890
+ };
1891
+ const fail = (problem) => ({
1892
+ ...result,
1893
+ problems: [problem]
1894
+ });
1895
+ if (this.opts.baseUrl && !this.opts.unsafeBotBaseUrl) return fail("refusing to send a webhook token to a custom `baseUrl`; remove it, or set `unsafeBotBaseUrl` for a test server");
1896
+ let bot;
1897
+ let hook;
1898
+ let text = input.text;
1899
+ try {
1900
+ bot = this.bot();
1901
+ const channels = await this.channelList();
1902
+ let parent;
1903
+ if (input.category) {
1904
+ parent = channels.find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, input.category))?.id;
1905
+ if (!parent) return fail(`no category named \`${input.category}\``);
1906
+ }
1907
+ const channel = DiscordNotifications.findChannel(channels, input.channel, parent);
1908
+ if (!channel || parent && channel.parent_id !== parent) return fail(`no channel named \`${input.channel}\`${input.category ? ` under \`${input.category}\`` : ""}`);
1909
+ const named = (await bot.channels.webhooks(channel.id)).filter((w) => DiscordNotifications.same(w.name ?? "", input.name));
1910
+ if (named.length === 0) return fail(`no webhook named \`${input.name}\``);
1911
+ const usable = named.find((w) => w.token);
1912
+ if (!usable?.token) return fail(`webhook \`${input.name}\` was not created by this bot, so its token is hidden`);
1913
+ hook = {
1914
+ id: usable.id,
1915
+ token: usable.token,
1916
+ channelId: channel.id
1917
+ };
1918
+ text = input.text.replaceAll("{channel}", `<#${channel.id}>`);
1919
+ } catch (err) {
1920
+ return fail(reason(err));
1921
+ }
1922
+ let messageId;
1923
+ try {
1924
+ messageId = (await this.client.webhooks.executeAndWait(hook.id, hook.token, text)).id;
1925
+ result.posted = true;
1926
+ } catch (err) {
1927
+ result.problems.push(`the post was refused (${reason(err)})`);
1928
+ try {
1929
+ const stray = (await bot.channels.messages(hook.channelId, 100)).find((m) => m.webhook_id === hook.id && m.content === text);
1930
+ if (stray && input.keep) {
1931
+ result.posted = true;
1932
+ result.kept = true;
1933
+ result.problems.push(`the test message ${stray.id} arrived but its response was lost; it was left in place`);
1934
+ } else if (stray) {
1935
+ await bot.channels.deleteMessage(hook.channelId, stray.id);
1936
+ result.problems.push(`the test message ${stray.id} had been posted, and was removed`);
1937
+ }
1938
+ } catch {}
1939
+ return result;
1940
+ }
1941
+ try {
1942
+ result.readBack = (await bot.channels.messages(hook.channelId, 100)).some((m) => m.id === messageId);
1943
+ if (!result.readBack) result.problems.push("the post was accepted but is not in the channel");
1944
+ } catch (err) {
1945
+ result.problems.push(`could not read the channel back (${reason(err)})`);
1946
+ }
1947
+ if (input.keep) {
1948
+ result.kept = true;
1949
+ return result;
1950
+ }
1951
+ try {
1952
+ await this.client.webhooks.deleteMessage(hook.id, hook.token, messageId);
1953
+ result.removed = true;
1954
+ } catch (err) {
1955
+ result.problems.push(`could not remove the test message ${messageId} (${reason(err)})`);
1956
+ }
1957
+ return result;
1958
+ }
1959
+ async createServer(input) {
1960
+ if (this.createdGuild) {
1961
+ const existing = await this.bot().guilds.get(this.createdGuild);
1962
+ return {
1963
+ id: existing.id,
1964
+ name: existing.name
1965
+ };
1966
+ }
1967
+ if (this.opts.guildId && !input.force) throw new Error(`this config already names a server (\`guildId\` ${this.opts.guildId}); pass --force to create another one`);
1968
+ const guild = await this.botOwnedServer(input.name) ?? await this.bot().guilds.create({ name: input.name });
1969
+ this.createdGuild = guild.id;
1970
+ this.channelLoad = void 0;
1971
+ return {
1972
+ id: guild.id,
1973
+ name: guild.name
1974
+ };
1975
+ }
1976
+ /** A server this bot owns (not one it only belongs to) with exactly this name, read across every page. */
1977
+ async botOwnedServer(name) {
1978
+ let after;
1979
+ for (;;) {
1980
+ const page = await this.bot().users.guilds(after ? { after } : {});
1981
+ const hit = page.find((g) => g.owner && g.name === name);
1982
+ if (hit) return hit;
1983
+ const last = page[page.length - 1];
1984
+ if (page.length < 200 || !last) return void 0;
1985
+ after = last.id;
1986
+ }
1987
+ }
1988
+ async inviteLink(channelName) {
1989
+ const channel = DiscordNotifications.findChannel(await this.channelList(), channelName);
1990
+ if (!channel) throw new Error(`no channel named \`${channelName}\` to invite into`);
1991
+ return `https://discord.gg/${(await this.bot().channels.createInvite(channel.id, {
1992
+ max_age: 86400,
1993
+ max_uses: 1,
1994
+ unique: true
1995
+ })).code}`;
1996
+ }
1997
+ async hasMember(memberId) {
1998
+ try {
1999
+ await this.bot().guilds.member(this.guild(), memberId);
2000
+ return true;
2001
+ } catch (err) {
2002
+ if (err instanceof ProviderApiError && err.status === 404) return false;
2003
+ throw err;
2004
+ }
2005
+ }
2006
+ async transferServer(memberId) {
2007
+ await this.bot().guilds.modify(this.guild(), { owner_id: memberId });
2008
+ }
2009
+ async serverOwner() {
2010
+ const guild = await this.bot().guilds.get(this.guild());
2011
+ if (!guild.owner_id) throw new Error("Discord did not say who owns the server");
2012
+ return {
2013
+ id: guild.owner_id,
2014
+ isBot: guild.owner_id === await this.botId(),
2015
+ ...guild.name ? { name: guild.name } : {}
2016
+ };
2017
+ }
2018
+ /** The one role with this name, or an error that says what to fix: none, or more than one. */
2019
+ async roleNamed(name) {
2020
+ const matches = (await this.bot().guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, name));
2021
+ if (matches.length === 0) throw new Error(`no role named \`${name}\` — run \`holocron notifications setup\` to create it`);
2022
+ if (matches.length > 1) throw new Error(`${matches.length} roles are named \`${name}\` (ids ${matches.map((r) => r.id).join(", ")}) — delete or rename the extras so it is clear which one to manage`);
2023
+ return matches[0];
2024
+ }
2025
+ async roleMembers(roleName) {
2026
+ const role = await this.roleNamed(roleName);
2027
+ try {
2028
+ return (await this.bot().guilds.membersWithRole(this.guild(), role.id)).flatMap((m) => m.user ? [{
2029
+ id: m.user.id,
2030
+ ...m.user.username ? { name: m.user.username } : {}
2031
+ }] : []);
2032
+ } catch (err) {
2033
+ if (err instanceof ProviderApiError && err.status === 403) throw new Error("Discord refused to list the server's members: switch on the **Server Members Intent** for the bot in the developer portal (Bot → Privileged Gateway Intents), then run this again", { cause: err });
2034
+ throw err;
2035
+ }
2036
+ }
2037
+ async addRoleMember(roleName, memberId) {
2038
+ await this.bot().guilds.addMemberRole(this.guild(), memberId, (await this.roleNamed(roleName)).id);
2039
+ }
2040
+ async removeRoleMember(roleName, memberId) {
2041
+ await this.bot().guilds.removeMemberRole(this.guild(), memberId, (await this.roleNamed(roleName)).id);
2042
+ }
2043
+ /** Finds the role with this name, or creates it with the given mentionable, color, hoist and permissions settings; reports whether it was created. */
2044
+ async ensureRole(input) {
2045
+ const bot = this.bot();
2046
+ const color = input.color !== void 0 ? colorToInt(input.color) : void 0;
2047
+ const wanted = input.permissions !== void 0 ? permissions(input.permissions) : void 0;
2048
+ const matches = (await bot.guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, input.name));
2049
+ if (matches.length > 1) throw new Error(`${matches.length} roles are named \`${input.name}\` (ids ${matches.map((r) => r.id).join(", ")}) — delete or rename the extras so setup knows which one to manage`);
2050
+ const existing = matches[0];
2051
+ if (existing) {
2052
+ const patch = {};
2053
+ const updated = [];
2054
+ if (input.mentionable !== void 0 && existing.mentionable !== input.mentionable) {
2055
+ patch.mentionable = input.mentionable;
2056
+ updated.push("mentionable");
2057
+ }
2058
+ if (color !== void 0 && existing.color !== color) {
2059
+ patch.color = color;
2060
+ updated.push("colour");
2061
+ }
2062
+ if (input.hoist !== void 0 && (existing.hoist ?? false) !== input.hoist) {
2063
+ patch.hoist = input.hoist;
2064
+ updated.push("hoist");
2065
+ }
2066
+ if (wanted !== void 0 && existing.permissions !== wanted) {
2067
+ patch.permissions = wanted;
2068
+ updated.push("permissions");
2069
+ }
2070
+ if (updated.length > 0) {
2071
+ this.roleLoad = void 0;
2072
+ const after = await bot.guilds.modifyRole(this.guild(), existing.id, patch).catch(async (err) => {
2073
+ throw patch.permissions === void 0 ? err : await this.rolePermissionsHint(input.name, err);
2074
+ });
2075
+ const stuck = [
2076
+ [
2077
+ "mentionable",
2078
+ patch.mentionable,
2079
+ after.mentionable
2080
+ ],
2081
+ [
2082
+ "colour",
2083
+ patch.color,
2084
+ after.color
2085
+ ],
2086
+ [
2087
+ "hoist",
2088
+ patch.hoist,
2089
+ after.hoist
2090
+ ],
2091
+ [
2092
+ "permissions",
2093
+ patch.permissions,
2094
+ after.permissions
2095
+ ]
2096
+ ].filter(([, sent, now]) => sent !== void 0 && sent !== now).map(([name]) => name);
2097
+ if (stuck.length > 0) throw new Error(`role \`${input.name}\`: sent ${stuck.join(", ")} but the role came back different -- another setup run may be changing it at the same time; re-run once it has finished`);
2098
+ }
2099
+ return {
2100
+ id: existing.id,
2101
+ created: false,
2102
+ ...updated.length > 0 ? { updated } : {}
2103
+ };
2104
+ }
2105
+ this.roleLoad = void 0;
2106
+ const made = await bot.guilds.createRole(this.guild(), {
2107
+ name: input.name,
2108
+ ...input.mentionable !== void 0 ? { mentionable: input.mentionable } : {},
2109
+ ...color !== void 0 ? { color } : {},
2110
+ ...input.hoist !== void 0 ? { hoist: input.hoist } : {},
2111
+ ...wanted !== void 0 ? { permissions: wanted } : {}
2112
+ });
2113
+ const twins = (await bot.guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, input.name));
2114
+ if (twins.length > 1) throw new Error(`created role \`${input.name}\` (id ${made.id}) but ${twins.length} roles now have that name (ids ${twins.map((r) => r.id).join(", ")}) -- another setup run probably created it at the same time; delete the extra one in Discord and re-run`);
2115
+ return {
2116
+ id: made.id,
2117
+ created: true
2118
+ };
2119
+ }
56
2120
  resolve(channel) {
57
2121
  const alias = this.opts.webhooks?.[channel];
58
2122
  if (alias) return alias;
@@ -62,8 +2126,8 @@ var DiscordNotifications = class {
62
2126
  return this.defaultWebhookUrl();
63
2127
  }
64
2128
  };
65
- //#endregion
66
- //#region src/verify-token.ts
2129
+ // src/verify-token.ts
2130
+ /** Checks a Discord webhook URL by fetching the webhook; resolves to its name and id, or the failure message. */
67
2131
  async function verifyToken(webhookUrl, opts = {}) {
68
2132
  try {
69
2133
  const { id, token } = parseWebhookUrl(webhookUrl);
@@ -78,33 +2142,99 @@ async function verifyToken(webhookUrl, opts = {}) {
78
2142
  } catch (err) {
79
2143
  return {
80
2144
  ok: false,
81
- message: err instanceof Error ? err.message : String(err)
2145
+ message: errorMessage(err)
82
2146
  };
83
2147
  }
84
2148
  }
85
- //#endregion
86
- //#region src/index.ts
2149
+ // src/index.ts
2150
+ /** Builds the plugin context from its options; the webhook URL, bot token and client secret are each resolved on first use. */
87
2151
  function createContext(options = {}) {
88
2152
  let url;
2153
+ let bot;
2154
+ let applicationId;
2155
+ const botClient = () => bot ??= createDiscordBotClient({
2156
+ botToken: resolveBotToken({
2157
+ env: options.env,
2158
+ keyring: options.keyring,
2159
+ org: options.org
2160
+ }),
2161
+ ...options.unsafeBotBaseUrl && options.baseUrl ? { baseUrl: options.baseUrl } : {},
2162
+ ...options.fetch ? { fetch: options.fetch } : {}
2163
+ });
89
2164
  return {
90
2165
  options,
91
2166
  client: createDiscordClient({
92
2167
  baseUrl: options.baseUrl,
93
2168
  fetch: options.fetch
94
2169
  }),
95
- defaultWebhookUrl: () => url ??= resolveToken(options)
2170
+ defaultWebhookUrl: () => url ??= resolveToken(options),
2171
+ bot: botClient,
2172
+ oauth: async (redirectUri) => {
2173
+ applicationId ??= botClient().application.get().then((app) => app.id).catch((err) => {
2174
+ applicationId = void 0;
2175
+ throw err;
2176
+ });
2177
+ return createDiscordOAuthClient({
2178
+ clientId: await applicationId,
2179
+ clientSecret: resolveClientSecret({
2180
+ env: options.env,
2181
+ keyring: options.keyring,
2182
+ org: options.org
2183
+ }),
2184
+ redirectUri,
2185
+ ...options.unsafeBotBaseUrl && options.baseUrl ? { baseUrl: options.baseUrl } : {},
2186
+ ...options.fetch ? { fetch: options.fetch } : {}
2187
+ });
2188
+ }
96
2189
  };
97
2190
  }
2191
+ /** Builds the `notifications` capability for a context. */
98
2192
  function notifications(ctx) {
99
- return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl);
2193
+ return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl, ctx.bot, ctx.oauth);
100
2194
  }
2195
+ /**
2196
+ * Creates the Discord plugin: its `notifications` capability and its `connection` probe. The probe checks the webhook
2197
+ * when there is one, and the bot token when there is not: the webhook is only a last resort for a post that names no
2198
+ * channel, so a missing one is not a failed connection when the bot can be reached.
2199
+ */
101
2200
  function createPlugin(options = {}) {
102
2201
  const ctx = createContext(options);
2202
+ let found = "webhook";
103
2203
  return {
104
2204
  name: "@theholocron/holocron-plugin-discord",
2205
+ probes: { connection: connectionProbe({
2206
+ provider: "Discord",
2207
+ url: options.baseUrl ?? "https://discord.com",
2208
+ fetch: options.fetch,
2209
+ token: () => {
2210
+ try {
2211
+ found = "webhook";
2212
+ return resolveToken(options);
2213
+ } catch (noWebhook) {
2214
+ found = "bot";
2215
+ try {
2216
+ return resolveBotToken({
2217
+ env: options.env,
2218
+ keyring: options.keyring,
2219
+ org: options.org
2220
+ });
2221
+ } catch {
2222
+ throw noWebhook;
2223
+ }
2224
+ }
2225
+ },
2226
+ verify: (token) => found === "webhook" ? verifyToken(token, {
2227
+ baseUrl: options.baseUrl,
2228
+ fetch: options.fetch
2229
+ }) : verifyBotToken(token, {
2230
+ baseUrl: options.baseUrl,
2231
+ fetch: options.fetch,
2232
+ unsafeBotBaseUrl: options.unsafeBotBaseUrl
2233
+ })
2234
+ }) },
105
2235
  capabilities: { notifications: () => notifications(ctx) }
106
2236
  };
107
2237
  }
2238
+ /** One-line hint printed by `holocron auth set discord` when no webhook URL is supplied or the supplied one is rejected. */
108
2239
  const AUTH_HINT = "create a webhook in Discord: open your server → channel settings → Integrations → Webhooks → New Webhook, copy the webhook URL, then run: holocron auth set discord <https://discord.com/api/webhooks/...>";
109
- //#endregion
110
- export { AUTH_HINT, AuthError, DiscordNotifications, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveToken, verifyToken };
2240
+ export { AUTH_HINT, AuthError, DiscordNotifications, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveBotToken, resolveClientSecret, resolveToken, tokens, verifyToken };