@theholocron/holocron-plugin-discord 5.0.0-alpha.27 → 5.0.0-alpha.270

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,1541 @@
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, createDiscordBotClient, createDiscordClient, createDiscordOAuthClient, findVerifiedConnection, parseWebhookUrl, permissionNames, permissions } from "@theholocron/discord-client";
4
+ // src/auth.ts
3
5
  const resolveToken = createResolveToken({
4
6
  envName: "HOLOCRON_DISCORD_WEBHOOK",
5
7
  vendorEnvName: "DISCORD_WEBHOOK_URL",
6
8
  keyringService: "discord",
7
9
  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
10
  });
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 })
25
- });
26
- if (!res.ok) throw new ProviderApiError(`Discord webhook POST failed (${res.status})`, res.status, void 0);
27
- }
28
- } };
11
+ const resolveBotToken = createResolveToken({
12
+ envName: "HOLOCRON_DISCORD_BOT_TOKEN",
13
+ vendorEnvName: "DISCORD_BOT_TOKEN",
14
+ keyringService: "discord.holonet",
15
+ 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."
16
+ });
17
+ const resolveClientSecret = createResolveToken({
18
+ envName: "HOLOCRON_DISCORD_CLIENT_SECRET",
19
+ vendorEnvName: "DISCORD_CLIENT_SECRET",
20
+ keyringService: "discord.holonet.oauth",
21
+ 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."
22
+ });
23
+ // src/capabilities/notifications.ts
24
+ /** Discord's numeric settings, by the names the layout uses. */
25
+ const VERIFICATION = {
26
+ none: 0,
27
+ low: 1,
28
+ medium: 2,
29
+ high: 3,
30
+ highest: 4
31
+ };
32
+ const NOTIFICATIONS = {
33
+ all: 0,
34
+ mentions: 1
35
+ };
36
+ const FILTER = {
37
+ off: 0,
38
+ noRoles: 1,
39
+ all: 2
40
+ };
41
+ const nameOf = (map, value) => Object.keys(map).find((k) => map[k] === value);
42
+ /** What the bot needs in the server to do everything `setup` does. The invite link asks for exactly these. */
43
+ const BOT_NEEDS = [
44
+ "ViewChannel",
45
+ "SendMessages",
46
+ "ReadMessageHistory",
47
+ "ManageChannels",
48
+ "ManageRoles",
49
+ "ManageWebhooks",
50
+ "ManageGuild",
51
+ "CreatePublicThreads",
52
+ "CreatePrivateThreads",
53
+ "SendMessagesInThreads"
54
+ ];
55
+ /** The OAuth2 scopes Discord offers an application, as its own application page lists them. Exact, lower-case. */
56
+ const SCOPES = /* @__PURE__ */ new Set([
57
+ "applications.builds.read",
58
+ "applications.commands",
59
+ "applications.commands.permissions.update",
60
+ "applications.entitlements",
61
+ "applications.store.update",
62
+ "bot",
63
+ "connections",
64
+ "email",
65
+ "gdm.join",
66
+ "guilds",
67
+ "guilds.join",
68
+ "guilds.members.read",
69
+ "identify",
70
+ "messages.read",
71
+ "openid",
72
+ "role_connections.write",
73
+ "rpc",
74
+ "rpc.activities.write",
75
+ "rpc.notifications.read",
76
+ "rpc.screenshare.read",
77
+ "rpc.screenshare.write",
78
+ "rpc.video.read",
79
+ "rpc.video.write",
80
+ "rpc.voice.read",
81
+ "rpc.voice.write",
82
+ "webhook.incoming"
83
+ ]);
84
+ /** The locales Discord accepts for a server's preferred language. */
85
+ const LOCALES = /* @__PURE__ */ new Set([
86
+ "id",
87
+ "da",
88
+ "de",
89
+ "en-GB",
90
+ "en-US",
91
+ "es-ES",
92
+ "es-419",
93
+ "fr",
94
+ "hr",
95
+ "it",
96
+ "lt",
97
+ "hu",
98
+ "nl",
99
+ "no",
100
+ "pl",
101
+ "pt-BR",
102
+ "ro",
103
+ "fi",
104
+ "sv-SE",
105
+ "vi",
106
+ "tr",
107
+ "cs",
108
+ "el",
109
+ "bg",
110
+ "ru",
111
+ "uk",
112
+ "hi",
113
+ "th",
114
+ "zh-CN",
115
+ "ja",
116
+ "zh-TW",
117
+ "ko"
118
+ ]);
119
+ /** "applied a, b; " for the start of a message about a step that stopped part-way, or nothing. */
120
+ function appliedPrefix(applied) {
121
+ return applied.length > 0 ? `applied ${applied.join(", ")}; but ` : "";
29
122
  }
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
- };
123
+ /** A layout name to Discord's number, undefined when the layout leaves it out; an unknown name is an error, not an omission. */
124
+ function s_(name, map) {
125
+ if (name === void 0) return void 0;
126
+ if (!Object.hasOwn(map, name)) throw new Error(`unknown value ${JSON.stringify(name)}; use one of ${Object.keys(map).join(", ")}`);
127
+ return map[name];
128
+ }
129
+ /** `#rrggbb` to Discord's integer colour. */
130
+ function colorToInt(hex) {
131
+ if (!/^#[0-9a-fA-F]{6}$/.test(hex)) throw new Error(`invalid colour ${JSON.stringify(hex)}: use #rrggbb`);
132
+ return Number.parseInt(hex.slice(1), 16);
133
+ }
134
+ /** Discord's integer colour to `#rrggbb`. 0 is Discord's "no colour", and is what `#000000` means too. */
135
+ function colorToHex(color) {
136
+ return `#${color.toString(16).padStart(6, "0")}`;
38
137
  }
39
- //#endregion
40
- //#region src/capabilities/notifications.ts
41
- var DiscordNotifications = class {
138
+ /** An error as one line: the message, plus Discord's own response body when there is one. */
139
+ function reason(err) {
140
+ return err instanceof ProviderApiError && err.details ? `${errorMessage(err)}: ${String(err.details).slice(0, 200)}` : errorMessage(err);
141
+ }
142
+ /**
143
+ * What @everyone loses when a channel is read-only. Only sending: Discord refuses (403) any change to the
144
+ * thread permissions on an existing text channel from a bot whose own role lacks them, and Holonet's
145
+ * does. Members can therefore still start threads in a read-only channel until the bot is given those
146
+ * permissions; see {@link THREAD_BITS} for how channels that already carry them are read.
147
+ */
148
+ const POST = ["SendMessages"];
149
+ const THREAD_MASK = ~BigInt(permissions([
150
+ "SendMessagesInThreads",
151
+ "CreatePublicThreads",
152
+ "CreatePrivateThreads"
153
+ ]));
154
+ /** What the bot keeps in a channel it has locked down, so it can still manage it and post. */
155
+ const BOT_KEEPS = [
156
+ "ViewChannel",
157
+ "SendMessages",
158
+ "ReadMessageHistory",
159
+ "ManageChannels",
160
+ "ManageWebhooks"
161
+ ];
162
+ /**
163
+ * Overwrites as a comparable set: order and the shape of the array do not matter, and the thread
164
+ * permissions are left out (setup does not manage them, so their presence is not a difference).
165
+ */
166
+ function overwriteKey(list) {
167
+ return (list ?? []).map((o) => ({
168
+ ...o,
169
+ allow: BigInt(o.allow) & THREAD_MASK,
170
+ deny: BigInt(o.deny) & THREAD_MASK
171
+ })).filter((o) => o.allow !== 0n || o.deny !== 0n).map((o) => `${o.id}:${o.type}:${o.allow}:${o.deny}`).sort().join("|");
172
+ }
173
+ /**
174
+ * Desired overwrites with the thread permissions of the existing ones laid back in. Discord refuses
175
+ * any change to those from this bot, so a replacement list must carry them over untouched or the
176
+ * whole edit is rejected, even when it changes nothing but what we do manage.
177
+ */
178
+ function keepThreadBits(desired, existing) {
179
+ const threads = ~THREAD_MASK;
180
+ const merged = desired.map((o) => ({ ...o }));
181
+ for (const old of existing ?? []) {
182
+ const allow = BigInt(old.allow) & threads;
183
+ const deny = BigInt(old.deny) & threads;
184
+ if (allow === 0n && deny === 0n) continue;
185
+ const same = merged.find((o) => o.id === old.id && o.type === old.type);
186
+ if (same) {
187
+ same.allow = (BigInt(same.allow) | allow).toString();
188
+ same.deny = (BigInt(same.deny) | deny).toString();
189
+ } else merged.push({
190
+ id: old.id,
191
+ type: old.type,
192
+ allow: allow.toString(),
193
+ deny: deny.toString()
194
+ });
195
+ }
196
+ return merged;
197
+ }
198
+ let idCounter = 0;
199
+ /** A snowflake-shaped id for a new onboarding question or answer, which Discord asks the sender to make. */
200
+ const newId = () => String((BigInt(Date.now()) - 1420070400000n << 22n) + BigInt(idCounter++ % 4096));
201
+ var DiscordNotifications = class DiscordNotifications {
42
202
  client;
43
203
  opts;
44
204
  defaultWebhookUrl;
205
+ bot;
206
+ oauth;
45
207
  key = "notifications";
46
208
  providerName = "discord";
47
- constructor(client, opts, defaultWebhookUrl) {
209
+ constructor(client, opts, defaultWebhookUrl, bot = () => {
210
+ throw new Error("no Discord bot client configured");
211
+ }, oauth = () => {
212
+ throw new Error("no Discord OAuth client configured");
213
+ }) {
48
214
  this.client = client;
49
215
  this.opts = opts;
50
216
  this.defaultWebhookUrl = defaultWebhookUrl;
217
+ this.bot = bot;
218
+ this.oauth = oauth;
219
+ }
220
+ /**
221
+ * Sign a member in with Discord to learn which GitHub account they own. Asks only for `identify` and
222
+ * `connections`, reads the account Discord has verified, and revokes the token before returning: nothing
223
+ * about the sign-in is kept.
224
+ */
225
+ signIn() {
226
+ return {
227
+ authorizeUrl: async ({ redirectUri, state }) => (await this.oauth(redirectUri)).authorizeUrl({ state }),
228
+ complete: async ({ redirectUri, code }) => {
229
+ const client = await this.oauth(redirectUri);
230
+ const token = await client.exchangeCode(code);
231
+ try {
232
+ const [user, connections] = await Promise.all([client.user(token.access_token), client.connections(token.access_token)]);
233
+ const github = findVerifiedConnection(connections, "github");
234
+ return {
235
+ member: user.id,
236
+ name: user.global_name ?? user.username,
237
+ ...github ? { github: {
238
+ id: github.id,
239
+ login: github.name
240
+ } } : {}
241
+ };
242
+ } finally {
243
+ await client.revoke(token.access_token).catch(() => {});
244
+ }
245
+ }
246
+ };
247
+ }
248
+ get layout() {
249
+ return this.opts.layout;
51
250
  }
52
251
  async send(channel, message) {
53
- const { id, token } = parseWebhookUrl(this.resolve(channel || this.opts.defaultChannel || ""));
252
+ const webhookUrl = this.resolve(channel || this.opts.defaultChannel || "");
253
+ const { id, token } = parseWebhookUrl(webhookUrl);
54
254
  await this.client.webhooks.execute(id, token, message);
55
255
  }
256
+ /**
257
+ * `holocron doctor`: the bot token is valid and can see the configured server.
258
+ * Null when no `guildId` is set -- a post-only config has no bot to check. A
259
+ * `layout` without a `guildId` is a half-written provisioning config, so that
260
+ * fails instead of passing as post-only.
261
+ */
262
+ async whoami() {
263
+ if (!this.opts.guildId) {
264
+ if (this.opts.layout) throw new Error("`layout` is set but `guildId` is not — add the server id to the discord provider options");
265
+ return null;
266
+ }
267
+ const bot = this.bot();
268
+ const me = await bot.users.me();
269
+ return { target: `${(await bot.guilds.get(this.opts.guildId)).name} (as ${me.username})` };
270
+ }
271
+ /**
272
+ * Read-only: what is on the server, for the parts of `layout` we will compare. Webhooks are
273
+ * listed only for channels the layout gives one (one request each), so the cost scales with
274
+ * the layout, not with the server.
275
+ */
276
+ async inspect(layout) {
277
+ const bot = this.bot();
278
+ const channels = await this.channelList();
279
+ const categoryName = new Map(channels.filter((c) => c.type === ChannelType.Category).map((c) => [c.id, c.name]));
280
+ const wantsWebhook = new Set((layout.categories ?? []).flatMap((c) => (c.channels ?? []).filter((ch) => ch.webhook).map((ch) => ch.name.toLowerCase())));
281
+ const text = channels.filter((c) => c.type === ChannelType.Text || c.type === ChannelType.Announcement);
282
+ const found = [];
283
+ for (const c of text) {
284
+ let webhooks = [];
285
+ let webhookAvatars = [];
286
+ let webhooksError;
287
+ if (wantsWebhook.has(c.name.toLowerCase())) try {
288
+ const hooks = await bot.channels.webhooks(c.id);
289
+ webhooks = hooks.map((w) => w.name ?? "");
290
+ webhookAvatars = hooks.filter((w) => w.avatar).map((w) => w.name ?? "");
291
+ } catch (err) {
292
+ webhooksError = reason(err);
293
+ }
294
+ const category = c.parent_id ? categoryName.get(c.parent_id) : void 0;
295
+ found.push({
296
+ name: c.name,
297
+ ...category ? { category } : {},
298
+ ...c.topic ? { topic: c.topic } : {},
299
+ webhooks,
300
+ webhookAvatars,
301
+ ...webhooksError ? { webhooksError } : {}
302
+ });
303
+ }
304
+ let roles = [];
305
+ let rolesError;
306
+ if ((layout.roles ?? []).length > 0) try {
307
+ roles = (await bot.guilds.roles(this.guild())).map((r) => {
308
+ return {
309
+ name: r.name,
310
+ id: r.id,
311
+ mentionable: r.mentionable,
312
+ color: colorToHex(r.color),
313
+ ...r.hoist !== void 0 ? { hoist: r.hoist } : {},
314
+ ...r.permissions !== void 0 ? { permissions: permissionNames(r.permissions) } : {}
315
+ };
316
+ });
317
+ } catch (err) {
318
+ rolesError = reason(err);
319
+ }
320
+ const nameOfChannel = (id) => channels.find((c) => c.id === id)?.name ?? id;
321
+ const channelName = (id) => id ? nameOfChannel(id) : void 0;
322
+ let server;
323
+ let serverError;
324
+ if (layout.server) try {
325
+ const guild = await bot.guilds.get(this.guild());
326
+ const verification = nameOf(VERIFICATION, guild.verification_level);
327
+ const defaultNotifications = nameOf(NOTIFICATIONS, guild.default_message_notifications);
328
+ const contentFilter = nameOf(FILTER, guild.explicit_content_filter);
329
+ const systemChannel = channelName(guild.system_channel_id);
330
+ const rulesChannel = channelName(guild.rules_channel_id);
331
+ const updatesChannel = channelName(guild.public_updates_channel_id);
332
+ server = {
333
+ ...verification ? { verification } : {},
334
+ ...defaultNotifications ? { defaultNotifications } : {},
335
+ ...contentFilter ? { contentFilter } : {},
336
+ ...systemChannel ? { systemChannel } : {},
337
+ ...rulesChannel ? { rulesChannel } : {},
338
+ ...updatesChannel ? { updatesChannel } : {},
339
+ community: (guild.features ?? []).includes("COMMUNITY"),
340
+ ...guild.description !== void 0 && guild.description !== null ? { description: guild.description } : {},
341
+ ...guild.preferred_locale ? { locale: guild.preferred_locale } : {}
342
+ };
343
+ } catch (err) {
344
+ serverError = reason(err);
345
+ }
346
+ let pinned;
347
+ let pinnedError;
348
+ if (layout.pinned) try {
349
+ pinned = await this.pinnedStates(layout.pinned);
350
+ } catch (err) {
351
+ pinnedError = reason(err);
352
+ }
353
+ let welcome;
354
+ let welcomeError;
355
+ if (layout.welcome) try {
356
+ const guild = await bot.guilds.get(this.guild());
357
+ const screen = await this.welcomeScreenOf();
358
+ welcome = {
359
+ enabled: (guild.features ?? []).includes("WELCOME_SCREEN_ENABLED"),
360
+ description: screen.description ?? "",
361
+ channels: (screen.welcome_channels ?? []).map((c) => ({
362
+ channel: nameOfChannel(c.channel_id),
363
+ description: c.description,
364
+ ...c.emoji_name ? { emoji: c.emoji_name } : {}
365
+ }))
366
+ };
367
+ } catch (err) {
368
+ welcomeError = reason(err);
369
+ }
370
+ let onboarding;
371
+ let onboardingError;
372
+ if (layout.onboarding) try {
373
+ const found = await bot.guilds.onboarding(this.guild());
374
+ const roleOf = (id) => roles.find((r) => r.id === id)?.name ?? id;
375
+ onboarding = {
376
+ enabled: found.enabled,
377
+ defaultChannels: found.default_channel_ids.map(nameOfChannel),
378
+ prompts: found.prompts.map((p) => ({
379
+ title: p.title,
380
+ singleSelect: p.single_select,
381
+ required: p.required,
382
+ options: p.options.map((o) => ({
383
+ title: o.title,
384
+ ...o.description ? { description: o.description } : {},
385
+ ...o.emoji?.name ?? o.emoji_name ? { emoji: o.emoji?.name ?? o.emoji_name } : {},
386
+ channels: (o.channel_ids ?? []).map(nameOfChannel),
387
+ roles: (o.role_ids ?? []).map(roleOf)
388
+ }))
389
+ }))
390
+ };
391
+ } catch (err) {
392
+ onboardingError = reason(err);
393
+ }
394
+ let application;
395
+ let applicationError;
396
+ if (layout.application) try {
397
+ const app = await bot.application.get();
398
+ const install = app.install_params;
399
+ application = {
400
+ ...app.description ? { description: app.description } : {},
401
+ tags: app.tags ?? [],
402
+ ...install ? { install: {
403
+ scopes: install.scopes,
404
+ permissions: permissionNames(install.permissions)
405
+ } } : {},
406
+ ...app.terms_of_service_url ? { termsUrl: app.terms_of_service_url } : {},
407
+ ...app.privacy_policy_url ? { privacyUrl: app.privacy_policy_url } : {},
408
+ ...app.role_connections_verification_url ? { roleConnectionsUrl: app.role_connections_verification_url } : {},
409
+ intents: { members: DiscordNotifications.membersIntentOn(app.flags ?? 0) },
410
+ redirectUris: app.redirect_uris ?? []
411
+ };
412
+ } catch (err) {
413
+ applicationError = reason(err);
414
+ }
415
+ let everyone;
416
+ let everyoneError;
417
+ if (layout.everyone) try {
418
+ const role = (await bot.guilds.roles(this.guild())).find((r) => r.id === this.guild());
419
+ if (role?.permissions === void 0) throw new Error("the server has no @everyone role to read");
420
+ everyone = { permissions: permissionNames(role.permissions) };
421
+ } catch (err) {
422
+ everyoneError = reason(err);
423
+ }
424
+ const roleName = (id) => roles.find((r) => r.id === id)?.name ?? id;
425
+ found.forEach((entry, i) => {
426
+ entry.access = this.accessOf(text[i].permission_overwrites, roleName);
427
+ });
428
+ const categoryAccess = {};
429
+ for (const c of channels.filter((c) => c.type === ChannelType.Category)) categoryAccess[c.name] = this.accessOf(c.permission_overwrites, roleName);
430
+ return {
431
+ categories: [...categoryName.values()],
432
+ categoryAccess,
433
+ ...server ? { server } : {},
434
+ ...serverError ? { serverError } : {},
435
+ ...welcome ? { welcome } : {},
436
+ ...welcomeError ? { welcomeError } : {},
437
+ ...pinned ? { pinned } : {},
438
+ ...pinnedError ? { pinnedError } : {},
439
+ ...onboarding ? { onboarding } : {},
440
+ ...onboardingError ? { onboardingError } : {},
441
+ ...application ? { application } : {},
442
+ ...applicationError ? { applicationError } : {},
443
+ ...everyone ? { everyone } : {},
444
+ ...everyoneError ? { everyoneError } : {},
445
+ channels: found,
446
+ roles,
447
+ ...rolesError ? { rolesError } : {}
448
+ };
449
+ }
450
+ /** What the bot keeps: the usual set, and Pin Messages when the layout pins messages. */
451
+ needs() {
452
+ return this.opts.layout?.pinned?.length ? [...BOT_NEEDS, "PinMessages"] : BOT_NEEDS;
453
+ }
454
+ /** Where to re-invite the bot so its role holds what `setup` needs. Re-authorising updates the role in place. */
455
+ async inviteUrl(names = this.needs()) {
456
+ const url = new URL("https://discord.com/oauth2/authorize");
457
+ url.searchParams.set("client_id", await this.botId());
458
+ url.searchParams.set("scope", "bot");
459
+ url.searchParams.set("permissions", permissions(names));
460
+ url.searchParams.set("guild_id", this.guild());
461
+ return url.toString();
462
+ }
463
+ /** Changing server settings needs Manage Server; an empty edit proves the bot has it without changing anything. */
464
+ async preflight(layout) {
465
+ if (!layout.server) return;
466
+ try {
467
+ await this.bot().guilds.modify(this.guild(), {});
468
+ } catch (err) {
469
+ throw await this.manageServerHint(err);
470
+ }
471
+ }
472
+ /** The one role with this name, or an error saying why not: two would mean granting something to the wrong members. */
473
+ static pickRole(roles, name, who) {
474
+ const found = roles.filter((r) => DiscordNotifications.same(r.name, name));
475
+ if (found.length === 0) throw new Error(`${who} names the role \`${name}\`, which does not exist on the server yet`);
476
+ 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`);
477
+ return found[0].id;
478
+ }
479
+ /** The one text or announcement channel with this name, or an error saying why not. */
480
+ static pickChannelId(channels, name, who) {
481
+ const named = channels.filter((c) => (c.type === ChannelType.Text || c.type === ChannelType.Announcement) && DiscordNotifications.same(c.name, name));
482
+ if (named.length === 0) throw new Error(`${who} name the channel \`${name}\`, which does not exist on the server yet`);
483
+ 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`);
484
+ return named[0].id;
485
+ }
486
+ /** True for a 403 that is about permissions, not about the bot being unable to see the server at all. */
487
+ static missingPermissions(err) {
488
+ return err instanceof ProviderApiError && err.status === 403 && !/Missing Access|\b50001\b/.test(String(err.details));
489
+ }
490
+ /** An invite link, or nothing when building it needs a request that fails: the advice must not depend on one. */
491
+ async inviteOrNothing(names) {
492
+ try {
493
+ return await this.inviteUrl(names);
494
+ } catch {
495
+ return;
496
+ }
497
+ }
498
+ /** Turning community on or off needs Administrator, which is more than the bot should keep. */
499
+ async communityHint(err, applied, turningOn) {
500
+ if (!(err instanceof ProviderApiError && err.status === 403)) return err;
501
+ const link = await this.inviteOrNothing(["Administrator"]);
502
+ 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)";
503
+ 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";
504
+ const revoke = await this.inviteOrNothing();
505
+ 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`, {
506
+ permission: "Administrator",
507
+ ...link ? { grantUrl: link } : {},
508
+ ...revoke ? { revokeUrl: revoke } : {},
509
+ ...applied.length > 0 ? { applied } : {}
510
+ }, { cause: err });
511
+ }
512
+ /** A 403 on a server edit becomes the explanation and the invite link; anything else is passed on as it is. */
513
+ async manageServerHint(err) {
514
+ if (!DiscordNotifications.missingPermissions(err)) return err;
515
+ const link = await this.inviteOrNothing();
516
+ 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 });
517
+ }
518
+ async ensureServer(settings) {
519
+ const bot = this.bot();
520
+ const guild = await bot.guilds.get(this.guild());
521
+ const channels = await this.channelList();
522
+ const idOf = (name) => DiscordNotifications.pickChannelId(channels, name, "server settings");
523
+ const patch = {};
524
+ const updated = [];
525
+ const set = (label, key, want, have) => {
526
+ if (want !== void 0 && want !== have) {
527
+ patch[key] = want;
528
+ updated.push(label);
529
+ }
530
+ };
531
+ set("verification", "verification_level", s_(settings.verification, VERIFICATION), guild.verification_level);
532
+ set("defaultNotifications", "default_message_notifications", s_(settings.defaultNotifications, NOTIFICATIONS), guild.default_message_notifications);
533
+ set("contentFilter", "explicit_content_filter", s_(settings.contentFilter, FILTER), guild.explicit_content_filter);
534
+ set("systemChannel", "system_channel_id", settings.systemChannel && idOf(settings.systemChannel), guild.system_channel_id);
535
+ set("rulesChannel", "rules_channel_id", settings.rulesChannel && idOf(settings.rulesChannel), guild.rules_channel_id);
536
+ const updatesId = settings.updatesChannel ? idOf(settings.updatesChannel) : void 0;
537
+ const updatesChanged = updatesId !== void 0 && updatesId !== guild.public_updates_channel_id;
538
+ set("description", "description", settings.description, guild.description ?? "");
539
+ set("locale", "preferred_locale", settings.locale, guild.preferred_locale);
540
+ const community = (guild.features ?? []).includes("COMMUNITY");
541
+ const toggleCommunity = settings.community !== void 0 && settings.community !== community;
542
+ const updatesWithCommunity = updatesId !== void 0 && toggleCommunity && settings.community === true;
543
+ const communityAfter = toggleCommunity ? settings.community === true : community;
544
+ if (updatesChanged && !updatesWithCommunity) {
545
+ 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\``);
546
+ patch.public_updates_channel_id = updatesId;
547
+ updated.push("updatesChannel");
548
+ }
549
+ const ordinary = async () => {
550
+ if (Object.keys(patch).length === 0) return;
551
+ let after;
552
+ try {
553
+ after = await bot.guilds.modify(this.guild(), patch);
554
+ } catch (err) {
555
+ throw await this.manageServerHint(err);
556
+ }
557
+ const stuck = Object.keys(patch).filter((k) => {
558
+ const got = after[k];
559
+ return patch[k] !== (k === "description" ? got ?? "" : got);
560
+ });
561
+ if (stuck.length > 0) throw new Error(`sent ${stuck.join(", ")} but the server came back different -- Discord may have refused a part of it`);
562
+ };
563
+ const toggle = async () => {
564
+ if (!toggleCommunity) return;
565
+ const freshGuild = await bot.guilds.get(this.guild());
566
+ const fresh = freshGuild.features ?? [];
567
+ const wanted = settings.community ? [.../* @__PURE__ */ new Set([...fresh, "COMMUNITY"])] : fresh.filter((f) => f !== "COMMUNITY");
568
+ const turningOn = settings.community === true;
569
+ const rulesSent = turningOn ? (settings.rulesChannel ? idOf(settings.rulesChannel) : freshGuild.rules_channel_id) || void 0 : void 0;
570
+ const updatesSent = turningOn ? (updatesWithCommunity ? updatesId : freshGuild.public_updates_channel_id) || void 0 : void 0;
571
+ let after;
572
+ try {
573
+ after = await bot.guilds.modify(this.guild(), {
574
+ features: wanted,
575
+ ...rulesSent ? { rules_channel_id: rulesSent } : {},
576
+ ...updatesSent ? { public_updates_channel_id: updatesSent } : {}
577
+ });
578
+ } catch (err) {
579
+ throw await this.communityHint(err, updated, settings.community === true);
580
+ }
581
+ const nowFeatures = after.features ?? [];
582
+ 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`);
583
+ if (settings.community) {
584
+ const lost = fresh.filter((f) => f !== "COMMUNITY" && !nowFeatures.includes(f));
585
+ 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`);
586
+ }
587
+ 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`);
588
+ 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`);
589
+ if (updatesWithCommunity && updatesChanged) updated.push("updatesChannel");
590
+ updated.push("community");
591
+ };
592
+ if (toggleCommunity && settings.community === false) {
593
+ await toggle();
594
+ await ordinary();
595
+ } else {
596
+ await ordinary();
597
+ await toggle();
598
+ }
599
+ return { updated };
600
+ }
601
+ /** What the bot's roles give it server-wide (the owner holds every permission), before any channel overwrite. */
602
+ async serverPermissions() {
603
+ const bot = this.bot();
604
+ const me = await this.botId();
605
+ if ((await this.serverOwner()).isBot) return {
606
+ owner: true,
607
+ bits: 0n,
608
+ held: /* @__PURE__ */ new Set(),
609
+ me
610
+ };
611
+ const [member, roles] = await Promise.all([bot.guilds.member(this.guild(), me), bot.guilds.roles(this.guild())]);
612
+ const held = /* @__PURE__ */ new Set([this.guild(), ...member.roles]);
613
+ return {
614
+ owner: false,
615
+ bits: roles.filter((r) => held.has(r.id)).reduce((all, r) => all | BigInt(r.permissions ?? "0"), 0n),
616
+ held,
617
+ me
618
+ };
619
+ }
620
+ async holdsPermission(permission) {
621
+ const { owner, bits } = await this.serverPermissions();
622
+ if (owner) return true;
623
+ const has = (name) => {
624
+ const bit = BigInt(permissions([name]));
625
+ return (bits & bit) === bit;
626
+ };
627
+ return has("Administrator") || has(permission);
628
+ }
629
+ /**
630
+ * Whether a channel's own overwrites take a permission away from a bot whose roles grant it, in the order Discord
631
+ * applies them: @everyone, then the bot's roles, then the bot itself. Read fresh, since a person may have just edited them.
632
+ */
633
+ async channelDenies(permission, channelId) {
634
+ const { owner, bits, held, me } = await this.serverPermissions();
635
+ const bit = BigInt(permissions([permission]));
636
+ if (owner || (bits & BigInt(permissions(["Administrator"]))) !== 0n || (bits & bit) !== bit) return false;
637
+ const list = (await this.bot().guilds.channels(this.guild())).find((c) => c.id === channelId)?.permission_overwrites ?? [];
638
+ const apply = (now, found) => {
639
+ const deny = found.reduce((all, o) => all | BigInt(o.deny), 0n);
640
+ const allow = found.reduce((all, o) => all | BigInt(o.allow), 0n);
641
+ return now & ~deny | allow;
642
+ };
643
+ let now = apply(bits, list.filter((o) => o.id === this.guild()));
644
+ now = apply(now, list.filter((o) => o.type === 0 && o.id !== this.guild() && held.has(o.id)));
645
+ now = apply(now, list.filter((o) => o.type === 1 && o.id === me));
646
+ return (now & bit) !== bit;
647
+ }
648
+ /** The messages this bot posted in a channel, pinned or not, among the channel's last hundred. */
649
+ async ownMessages(channelId) {
650
+ const me = await this.botId();
651
+ return (await this.bot().channels.messages(channelId, 100)).filter((m) => m.author?.id === me).map((m) => ({
652
+ id: m.id,
653
+ content: m.content,
654
+ pinned: m.pinned === true
655
+ }));
656
+ }
657
+ /**
658
+ * The layout's text with each `#name` that is one of the server's channels turned into Discord's own link to it
659
+ * (`<#id>`), so the message shows clickable channels. A name that matches no channel, or more than one, is left as written.
660
+ */
661
+ static linkChannels(content, channels) {
662
+ const idsByName = /* @__PURE__ */ new Map();
663
+ for (const c of channels) {
664
+ if (c.type === ChannelType.Category) continue;
665
+ idsByName.set(c.name.toLowerCase(), [...idsByName.get(c.name.toLowerCase()) ?? [], c.id]);
666
+ }
667
+ return content.split(/(https?:\/\/\S+)/).map((part, i) => i % 2 === 1 ? part : part.replace(/(?<=^|[\s([{"'*_~>])#([\p{L}\p{N}_-]+)/giu, (whole, name) => {
668
+ const ids = idsByName.get(name.toLowerCase());
669
+ return ids?.length === 1 ? `<#${ids[0]}>` : whole;
670
+ })).join("");
671
+ }
672
+ /** The layout's messages grouped by channel, in the order the channels first appear, with channel names linked. */
673
+ static pinsByChannel(pinned, channels) {
674
+ const byChannel = /* @__PURE__ */ new Map();
675
+ for (const pin of pinned) {
676
+ const key = pin.channel.toLowerCase();
677
+ const content = DiscordNotifications.linkChannels(pin.content, channels);
678
+ byChannel.set(key, [.../* @__PURE__ */ new Set([...byChannel.get(key) ?? [], content])]);
679
+ }
680
+ return byChannel;
681
+ }
682
+ /**
683
+ * What differs in one channel: the declared messages that are not pinned yet, and the bot's pinned messages the
684
+ * layout does not declare (or declares once and the bot pinned twice). The layout is the whole set of the bot's
685
+ * pins in a channel it names.
686
+ */
687
+ static pinDrift(own, wanted) {
688
+ const pinned = own.filter((m) => m.pinned).sort((a, b) => BigInt(a.id) < BigInt(b.id) ? -1 : 1);
689
+ const kept = /* @__PURE__ */ new Set();
690
+ const extras = pinned.filter((m) => {
691
+ if (!wanted.includes(m.content) || kept.has(m.content)) return true;
692
+ kept.add(m.content);
693
+ return false;
694
+ });
695
+ return {
696
+ missing: wanted.filter((c) => !kept.has(c)),
697
+ extras
698
+ };
699
+ }
700
+ /** 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. */
701
+ async pinnedStates(pinned) {
702
+ const channels = await this.channelList();
703
+ const verdicts = /* @__PURE__ */ new Map();
704
+ for (const [channel, wanted] of DiscordNotifications.pinsByChannel(pinned, channels)) {
705
+ const own = await this.ownMessages(DiscordNotifications.pickChannelId(channels, channel, "pinned messages"));
706
+ const drift = DiscordNotifications.pinDrift(own, wanted);
707
+ verdicts.set(channel, {
708
+ missing: new Set(drift.missing),
709
+ extras: drift.extras.length,
710
+ anyPinned: own.some((m) => m.pinned)
711
+ });
712
+ }
713
+ return pinned.map((pin) => {
714
+ const v = verdicts.get(pin.channel.toLowerCase());
715
+ const state = v.missing.has(DiscordNotifications.linkChannels(pin.content, channels)) ? v.anyPinned ? "different" : "missing" : v.extras > 0 ? "different" : "ok";
716
+ return {
717
+ channel: pin.channel,
718
+ state
719
+ };
720
+ });
721
+ }
722
+ async ensurePinned(pinned) {
723
+ const bot = this.bot();
724
+ const channels = await this.channelList();
725
+ const updated = [];
726
+ const byChannel = DiscordNotifications.pinsByChannel(pinned, channels);
727
+ for (const [channel, wanted] of byChannel) {
728
+ const long = wanted.find((content) => content.length > 2e3);
729
+ 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`);
730
+ }
731
+ for (const [channel, wanted] of byChannel) {
732
+ const channelId = DiscordNotifications.pickChannelId(channels, channel, "pinned messages");
733
+ const own = await this.ownMessages(channelId);
734
+ const drift = DiscordNotifications.pinDrift(own, wanted);
735
+ if (drift.missing.length === 0 && drift.extras.length === 0) continue;
736
+ let extras = drift.extras;
737
+ for (const content of drift.missing) {
738
+ const orphan = own.find((m) => !m.pinned && m.content === content);
739
+ const posted = orphan ?? await bot.channels.createMessage(channelId, { content });
740
+ try {
741
+ try {
742
+ await bot.channels.pin(channelId, posted.id);
743
+ } catch (err) {
744
+ if (!(err instanceof ProviderApiError && /\b30003\b/.test(String(err.details))) || extras.length === 0) throw err;
745
+ for (const old of extras) await bot.channels.deleteMessage(channelId, old.id);
746
+ extras = [];
747
+ await bot.channels.pin(channelId, posted.id);
748
+ }
749
+ } catch (err) {
750
+ if (!orphan) await bot.channels.deleteMessage(channelId, posted.id).catch(() => void 0);
751
+ throw await this.pinHint(err, channel);
752
+ }
753
+ }
754
+ for (const old of extras) await bot.channels.deleteMessage(channelId, old.id);
755
+ if (drift.missing.length > 0) {
756
+ const after = DiscordNotifications.pinDrift(await this.ownMessages(channelId), wanted);
757
+ for (const dup of after.extras) await bot.channels.deleteMessage(channelId, dup.id);
758
+ }
759
+ updated.push(`#${channel}`);
760
+ }
761
+ return { updated };
762
+ }
763
+ /** A 403 on pinning becomes the missing permission and a link that grants it, which `setup` can walk a person through. */
764
+ async pinHint(err, channel) {
765
+ if (!DiscordNotifications.missingPermissions(err)) return err;
766
+ 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 });
767
+ const link = await this.inviteOrNothing([...BOT_NEEDS, "PinMessages"]);
768
+ 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}` : ""}`, {
769
+ permission: "PinMessages",
770
+ label: "Pin Messages",
771
+ keep: true,
772
+ ...link ? { grantUrl: link } : {}
773
+ }, { cause: err });
774
+ }
775
+ /** A 403 on the welcome screen or onboarding becomes the likely reason; anything else is passed on. */
776
+ static communityFeatureHint(err, what) {
777
+ if (!(err instanceof ProviderApiError && err.status === 403)) return err;
778
+ 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 });
779
+ }
780
+ /** The numeric code Discord puts in the JSON body of an error, or undefined when the body is not that. */
781
+ static codeOf(err) {
782
+ try {
783
+ return JSON.parse(String(err.details)).code;
784
+ } catch {
785
+ return;
786
+ }
787
+ }
788
+ /** The welcome screen; a server that never had one answers 404 (10069), which is an empty screen. */
789
+ async welcomeScreenOf() {
790
+ try {
791
+ return await this.bot().guilds.welcomeScreen(this.guild());
792
+ } catch (err) {
793
+ if (err instanceof ProviderApiError && err.status === 404 && DiscordNotifications.codeOf(err) === 10069) return {
794
+ description: null,
795
+ welcome_channels: []
796
+ };
797
+ throw err;
798
+ }
799
+ }
800
+ async ensureWelcome(welcome) {
801
+ const bot = this.bot();
802
+ const channels = await this.channelList();
803
+ const idOf = (name) => DiscordNotifications.pickChannelId(channels, name, "the welcome screen");
804
+ const wanted = {
805
+ enabled: welcome.enabled ?? true,
806
+ description: welcome.description,
807
+ welcome_channels: welcome.channels.map((c) => ({
808
+ channel_id: idOf(c.channel),
809
+ description: c.description,
810
+ emoji_name: c.emoji ?? null,
811
+ emoji_id: null
812
+ }))
813
+ };
814
+ const normalise = (list) => JSON.stringify(list.map((c) => [
815
+ c.channel_id,
816
+ c.description,
817
+ c.emoji_name ?? null,
818
+ c.emoji_id ?? null
819
+ ]));
820
+ let guild;
821
+ let screen;
822
+ try {
823
+ guild = await bot.guilds.get(this.guild());
824
+ screen = await this.welcomeScreenOf();
825
+ } catch (err) {
826
+ throw DiscordNotifications.communityFeatureHint(err, "the welcome screen");
827
+ }
828
+ const updated = [];
829
+ if ((guild.features ?? []).includes("WELCOME_SCREEN_ENABLED") !== wanted.enabled) updated.push("enabled");
830
+ if ((screen.description ?? "") !== wanted.description) updated.push("description");
831
+ if (normalise(screen.welcome_channels ?? []) !== normalise(wanted.welcome_channels)) updated.push("channels");
832
+ if (updated.length === 0) return { updated };
833
+ let after;
834
+ try {
835
+ after = await bot.guilds.modifyWelcomeScreen(this.guild(), wanted);
836
+ } catch (err) {
837
+ throw DiscordNotifications.communityFeatureHint(err, "the welcome screen");
838
+ }
839
+ 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");
840
+ 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`);
841
+ return { updated };
842
+ }
843
+ /** An onboarding prompt reduced to what the layout can state, so the server's and the layout's can be compared. */
844
+ static onboardingKey(prompts) {
845
+ return JSON.stringify(prompts.map((p) => [
846
+ p.type,
847
+ p.in_onboarding,
848
+ p.title,
849
+ p.single_select,
850
+ p.required,
851
+ p.options.map((o) => [
852
+ o.title,
853
+ o.description ?? "",
854
+ [...o.channel_ids ?? []].sort(),
855
+ [...o.role_ids ?? []].sort(),
856
+ o.emoji?.name ?? o.emoji_name ?? null
857
+ ])
858
+ ]));
859
+ }
860
+ async ensureOnboarding(onboarding) {
861
+ const bot = this.bot();
862
+ const channels = await this.channelList();
863
+ const channelId = (name) => DiscordNotifications.pickChannelId(channels, name, "onboarding");
864
+ const roles = (onboarding.prompts ?? []).some((p) => p.options.some((o) => (o.roles ?? []).length > 0)) ? await this.roleList() : [];
865
+ const roleId = (name) => DiscordNotifications.pickRole(roles, name, "onboarding");
866
+ let current;
867
+ try {
868
+ current = await bot.guilds.onboarding(this.guild());
869
+ } catch (err) {
870
+ throw DiscordNotifications.communityFeatureHint(err, "onboarding");
871
+ }
872
+ const usedIds = /* @__PURE__ */ new Set();
873
+ const prompts = onboarding.prompts === void 0 ? current.prompts : onboarding.prompts.map((p) => {
874
+ const had = current.prompts.find((c) => c.title === p.title && !usedIds.has(c.id));
875
+ if (had) usedIds.add(had.id);
876
+ const hadOptions = /* @__PURE__ */ new Set();
877
+ return {
878
+ id: had?.id ?? newId(),
879
+ type: 0,
880
+ title: p.title,
881
+ single_select: p.singleSelect ?? false,
882
+ required: p.required ?? false,
883
+ in_onboarding: true,
884
+ options: p.options.map((o) => ({
885
+ id: (() => {
886
+ const old = had?.options.find((c) => c.title === o.title && !hadOptions.has(c.id));
887
+ if (old) hadOptions.add(old.id);
888
+ return old?.id ?? newId();
889
+ })(),
890
+ title: o.title,
891
+ description: o.description ?? null,
892
+ channel_ids: (o.channels ?? []).map(channelId),
893
+ role_ids: (o.roles ?? []).map(roleId),
894
+ emoji_name: o.emoji ?? null
895
+ }))
896
+ };
897
+ });
898
+ const defaultChannels = onboarding.defaultChannels === void 0 ? current.default_channel_ids : onboarding.defaultChannels.map(channelId);
899
+ const enabled = onboarding.enabled ?? current.enabled;
900
+ const updated = [];
901
+ if (enabled !== current.enabled) updated.push("enabled");
902
+ if (JSON.stringify([...defaultChannels].sort()) !== JSON.stringify([...current.default_channel_ids].sort())) updated.push("defaultChannels");
903
+ if (DiscordNotifications.onboardingKey(prompts) !== DiscordNotifications.onboardingKey(current.prompts)) updated.push("prompts");
904
+ if (updated.length === 0) return { updated };
905
+ const body = {
906
+ prompts,
907
+ default_channel_ids: defaultChannels,
908
+ enabled,
909
+ mode: current.mode ?? 0
910
+ };
911
+ let after;
912
+ try {
913
+ after = await bot.guilds.modifyOnboarding(this.guild(), body);
914
+ } catch (err) {
915
+ throw DiscordNotifications.communityFeatureHint(err, "onboarding");
916
+ }
917
+ 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");
918
+ return { updated };
919
+ }
920
+ async ensureEveryone(everyone) {
921
+ const bot = this.bot();
922
+ const role = (await bot.guilds.roles(this.guild())).find((r) => r.id === this.guild());
923
+ if (role?.permissions === void 0) throw new Error("the server has no @everyone role to change");
924
+ const bit = (name) => BigInt(permissions([name]));
925
+ const have = BigInt(role.permissions);
926
+ const allow = everyone.allow ?? [];
927
+ const deny = everyone.deny ?? [];
928
+ const want = allow.reduce((acc, n) => acc | bit(n), have);
929
+ const final = deny.reduce((acc, n) => acc & ~bit(n), want);
930
+ if (final === have) return { updated: [] };
931
+ const updated = [...allow.filter((n) => (have & bit(n)) === 0n), ...deny.filter((n) => (have & bit(n)) !== 0n)];
932
+ this.roleLoad = void 0;
933
+ 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");
934
+ return { updated };
935
+ }
936
+ async ensureApplication(app) {
937
+ const bot = this.bot();
938
+ const current = await bot.application.get();
939
+ const set = (list) => JSON.stringify([...new Set(list.map((n) => n.toLowerCase()))].sort());
940
+ const exact = (list) => JSON.stringify([...new Set(list)].sort());
941
+ const urls = [
942
+ ["termsUrl", "terms_of_service_url"],
943
+ ["privacyUrl", "privacy_policy_url"],
944
+ ["roleConnectionsUrl", "role_connections_verification_url"]
945
+ ];
946
+ const body = {};
947
+ const updated = [];
948
+ if (app.description !== void 0 && (current.description ?? "") !== app.description) {
949
+ body.description = app.description;
950
+ updated.push("description");
951
+ }
952
+ if (app.tags !== void 0 && set(current.tags ?? []) !== set(app.tags)) {
953
+ body.tags = app.tags;
954
+ updated.push("tags");
955
+ }
956
+ const install = app.install && {
957
+ scopes: app.install.scopes,
958
+ permissions: permissions(app.install.permissions)
959
+ };
960
+ const haveInstall = current.install_params;
961
+ if (install && (!haveInstall || exact(haveInstall.scopes) !== exact(install.scopes) || haveInstall.permissions !== install.permissions)) {
962
+ body.install_params = install;
963
+ updated.push("install");
964
+ }
965
+ for (const [field, key] of urls) if (app[field] !== void 0 && (current[key] ?? "") !== app[field]) {
966
+ body[key] = app[field];
967
+ updated.push(field);
968
+ }
969
+ const flagsNow = current.flags ?? 0;
970
+ const membersWanted = app.intents?.members;
971
+ if (membersWanted !== void 0 && membersWanted !== DiscordNotifications.membersIntentOn(flagsNow)) {
972
+ body.flags = membersWanted ? flagsNow | ApplicationFlag.GatewayGuildMembersLimited : flagsNow & ~ApplicationFlag.GatewayGuildMembersLimited;
973
+ updated.push("intents");
974
+ }
975
+ 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)`);
976
+ if (updated.length === 0) return {
977
+ updated,
978
+ ...todo.length ? { todo } : {}
979
+ };
980
+ let after;
981
+ try {
982
+ after = await bot.application.modify(body);
983
+ } catch (err) {
984
+ 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 });
985
+ throw err;
986
+ }
987
+ const stuck = updated.filter((name) => {
988
+ if (name === "description") return (after.description ?? "") !== app.description;
989
+ if (name === "tags") return set(after.tags ?? []) !== set(app.tags);
990
+ if (name === "intents") return DiscordNotifications.membersIntentOn(after.flags ?? 0) !== app.intents.members;
991
+ if (name === "install") return !after.install_params || exact(after.install_params.scopes) !== exact(install.scopes) || after.install_params.permissions !== install.permissions;
992
+ const key = urls.find(([f]) => f === name)[1];
993
+ return (after[key] ?? "") !== app[name];
994
+ });
995
+ 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`);
996
+ return {
997
+ updated,
998
+ ...todo.length ? { todo } : {}
999
+ };
1000
+ }
1001
+ /** Whether the Server Members Intent is on: the unverified app's toggle, or the verified app's own bit. */
1002
+ static membersIntentOn(flags) {
1003
+ return (flags & (ApplicationFlag.GatewayGuildMembers | ApplicationFlag.GatewayGuildMembersLimited)) !== 0;
1004
+ }
1005
+ validateLayout(layout) {
1006
+ const app = layout.application;
1007
+ if (app) {
1008
+ if (app.description !== void 0 && app.description.length > 400) return `application: \`description\` is ${app.description.length} characters; Discord allows up to 400`;
1009
+ if (app.tags !== void 0) {
1010
+ if (app.tags.length > 5) return `application: ${app.tags.length} tags; Discord allows up to 5`;
1011
+ const long = app.tags.find((t) => t.length > 20);
1012
+ if (long !== void 0) return `application: the tag ${JSON.stringify(long)} is over 20 characters`;
1013
+ }
1014
+ const badRedirect = (app.redirectUris ?? []).find((u) => !/^https:\/\/|^http:\/\/localhost(:\d+)?\//.test(u));
1015
+ if (badRedirect !== void 0) return `application: \`redirectUris\` ${JSON.stringify(badRedirect)} must start with https:// (or http://localhost for a local sign-in)`;
1016
+ for (const [field, url] of [
1017
+ ["termsUrl", app.termsUrl],
1018
+ ["privacyUrl", app.privacyUrl],
1019
+ ["roleConnectionsUrl", app.roleConnectionsUrl]
1020
+ ]) if (url !== void 0 && !/^https:\/\//.test(url)) return `application: \`${field}\` ${JSON.stringify(url)} must start with https://`;
1021
+ if (app.install) {
1022
+ if (app.install.scopes.length === 0) return "application: `install.scopes` is empty; the link needs at least `bot`";
1023
+ const unknown = app.install.scopes.find((s) => !SCOPES.has(s));
1024
+ 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)`;
1025
+ try {
1026
+ permissions(app.install.permissions);
1027
+ } catch (err) {
1028
+ return `application: \`install.permissions\`: ${errorMessage(err)}`;
1029
+ }
1030
+ }
1031
+ }
1032
+ if (layout.everyone) try {
1033
+ permissions([...layout.everyone.allow ?? [], ...layout.everyone.deny ?? []]);
1034
+ } catch (err) {
1035
+ return `everyone: ${errorMessage(err)}`;
1036
+ }
1037
+ const questions = layout.onboarding?.prompts?.length ?? 0;
1038
+ if (questions > 5) return `onboarding: ${questions} questions; Discord allows up to 5`;
1039
+ const welcome = layout.welcome;
1040
+ if (welcome) {
1041
+ if (welcome.description.length > 140) return `welcome: \`description\` is ${welcome.description.length} characters; Discord allows up to 140`;
1042
+ if (welcome.channels.length > 5) return `welcome: ${welcome.channels.length} channels; Discord allows up to 5`;
1043
+ const long = welcome.channels.find((c) => c.description.length > 50);
1044
+ if (long) return `welcome: the description of \`${long.channel}\` is ${long.description.length} characters; Discord allows up to 50`;
1045
+ }
1046
+ const long2000 = layout.pinned?.find((p) => p.content.length > 2e3);
1047
+ if (long2000) return `pinned: the message for \`${long2000.channel}\` is ${long2000.content.length} characters; Discord allows up to 2000`;
1048
+ const server = layout.server;
1049
+ for (const [field, map] of [
1050
+ ["verification", VERIFICATION],
1051
+ ["defaultNotifications", NOTIFICATIONS],
1052
+ ["contentFilter", FILTER]
1053
+ ]) {
1054
+ const value = server?.[field];
1055
+ if (value !== void 0 && !Object.hasOwn(map, value)) return `server: \`${field}\` is ${JSON.stringify(value)}; use one of ${Object.keys(map).join(", ")}`;
1056
+ }
1057
+ 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`";
1058
+ 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)`;
1059
+ if (server?.community === true && (server.verification === void 0 || server.verification === "none")) return "server: community features need `verification` of at least `low`";
1060
+ if (server?.community === true && server.contentFilter !== "all") return "server: community features need `contentFilter: \"all\"`";
1061
+ for (const role of layout.roles ?? []) try {
1062
+ if (role.color !== void 0) colorToInt(role.color);
1063
+ if (role.permissions !== void 0) permissions(role.permissions);
1064
+ } catch (err) {
1065
+ return `role \`${role.name}\`: ${errorMessage(err)}`;
1066
+ }
1067
+ }
1068
+ botUser;
1069
+ botId() {
1070
+ return this.botUser ??= this.bot().users.me().then((u) => u.id).catch((err) => {
1071
+ this.botUser = void 0;
1072
+ throw err;
1073
+ });
1074
+ }
1075
+ /**
1076
+ * The overwrites that make a channel look like `access`. The list is exact: it replaces
1077
+ * whatever was set by hand. `[]` (public) when nothing is restricted.
1078
+ */
1079
+ async overwritesFor(access) {
1080
+ const view = access.view ?? "everyone";
1081
+ const post = access.post ?? "everyone";
1082
+ const everyoneDeny = [...view === "everyone" ? [] : ["ViewChannel"], ...post === "everyone" ? [] : POST];
1083
+ if (everyoneDeny.length === 0) return [];
1084
+ const roles = [...view === "everyone" ? [] : view, ...post === "everyone" ? [] : post].length > 0 ? await this.roleList() : [];
1085
+ const idOf = (name) => DiscordNotifications.pickRole(roles, name, "access");
1086
+ const allow = /* @__PURE__ */ new Map();
1087
+ const grant = (roleName, names) => {
1088
+ const id = idOf(roleName);
1089
+ allow.set(id, [.../* @__PURE__ */ new Set([...allow.get(id) ?? [], ...names])]);
1090
+ };
1091
+ if (view !== "everyone") for (const r of view) grant(r, ["ViewChannel"]);
1092
+ if (post !== "everyone") for (const r of post) grant(r, POST);
1093
+ return [
1094
+ {
1095
+ id: this.guild(),
1096
+ type: 0,
1097
+ allow: "0",
1098
+ deny: permissions(everyoneDeny)
1099
+ },
1100
+ ...[...allow].map(([id, names]) => ({
1101
+ id,
1102
+ type: 0,
1103
+ allow: permissions(names),
1104
+ deny: "0"
1105
+ })),
1106
+ {
1107
+ id: await this.botId(),
1108
+ type: 1,
1109
+ allow: permissions(BOT_KEEPS),
1110
+ deny: "0"
1111
+ }
1112
+ ];
1113
+ }
1114
+ /**
1115
+ * Read an access back out of a channel's overwrites, naming roles as the layout does. Only
1116
+ * overwrites of the shape {@link overwritesFor} writes can be read back; anything else
1117
+ * (a role-specific deny, a member overwrite, only some of the posting bits) means the
1118
+ * channel's real access is not something the layout can state, and is reported as `"custom"`
1119
+ * rather than guessed at.
1120
+ */
1121
+ accessOf(overwrites, roleName) {
1122
+ const list = overwrites ?? [];
1123
+ const managed = permissions(["ViewChannel", ...POST]);
1124
+ const unthreaded = (bits) => BigInt(bits) & THREAD_MASK;
1125
+ const within = (bits) => (unthreaded(bits) & ~BigInt(managed)) === 0n;
1126
+ const botSignature = permissions(BOT_KEEPS);
1127
+ let everyone;
1128
+ const roles = [];
1129
+ for (const o of list) if (o.type === 1) {
1130
+ if (o.allow !== botSignature || o.deny !== "0") return "custom";
1131
+ } else if (o.id === this.guild()) everyone = o;
1132
+ else roles.push(o);
1133
+ if (everyone && (unthreaded(everyone.allow) !== 0n || !within(everyone.deny))) return "custom";
1134
+ for (const o of roles) if (unthreaded(o.deny) !== 0n || !within(o.allow)) return "custom";
1135
+ const denied = (bit) => everyone !== void 0 && permissionNames(everyone.deny).includes(bit);
1136
+ const names = (bit) => roles.filter((o) => permissionNames(o.allow).includes(bit)).map((o) => roleName(o.id));
1137
+ return {
1138
+ view: denied("ViewChannel") ? names("ViewChannel") : "everyone",
1139
+ post: denied("SendMessages") ? names("SendMessages") : "everyone"
1140
+ };
1141
+ }
1142
+ /** The server's roles, fetched once and forgotten whenever setup changes a role. */
1143
+ roleLoad;
1144
+ roleList() {
1145
+ return this.roleLoad ??= this.bot().guilds.roles(this.guild()).catch((err) => {
1146
+ this.roleLoad = void 0;
1147
+ throw err;
1148
+ });
1149
+ }
1150
+ /** The server this run created, which takes over from `guildId` for the rest of the run. */
1151
+ createdGuild;
1152
+ guild() {
1153
+ if (this.createdGuild) return this.createdGuild;
1154
+ if (!this.opts.guildId) throw new Error("no Discord server id — set `guildId` in the discord provider options in holocron.config.ts");
1155
+ 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)`);
1156
+ return this.opts.guildId;
1157
+ }
1158
+ /**
1159
+ * The server's channel list, fetched once per instance. Every ensure* call used
1160
+ * to refetch it -- about 40 identical GETs in one setup run -- and Discord
1161
+ * rate-limited the route. Our own creates and edits update the copy, so it
1162
+ * stays accurate for the run; a new run builds a new instance.
1163
+ *
1164
+ * It is the in-flight promise that is shared, not the array: callers that start
1165
+ * while the first fetch is pending all get the same snapshot, so a later
1166
+ * response can never overwrite what an earlier caller added.
1167
+ */
1168
+ channelLoad;
1169
+ channelList() {
1170
+ return this.channelLoad ??= this.bot().guilds.channels(this.guild()).catch((err) => {
1171
+ this.channelLoad = void 0;
1172
+ throw err;
1173
+ });
1174
+ }
1175
+ /**
1176
+ * Create a channel and add it to the shared list. If the create fails, Discord
1177
+ * may still have applied it (a timeout looks the same as a refusal), so forget the
1178
+ * list: the next ensure refetches the server's real state instead of creating a
1179
+ * duplicate.
1180
+ */
1181
+ async createChannel(body) {
1182
+ try {
1183
+ const made = await this.bot().guilds.createChannel(this.guild(), body);
1184
+ (await this.channelList()).push(made);
1185
+ return made;
1186
+ } catch (err) {
1187
+ this.channelLoad = void 0;
1188
+ throw err;
1189
+ }
1190
+ }
1191
+ static same(a, b) {
1192
+ return a.toLowerCase() === b.toLowerCase();
1193
+ }
1194
+ async ensureCategory(name, opts = {}) {
1195
+ const existing = (await this.channelList()).find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, name));
1196
+ const overwrites = opts.access ? await this.overwritesFor(opts.access) : void 0;
1197
+ if (existing) {
1198
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
1199
+ await this.modifyChannel(existing, { permission_overwrites: keepThreadBits(overwrites, existing.permission_overwrites) });
1200
+ return {
1201
+ id: existing.id,
1202
+ created: false,
1203
+ updated: ["access"]
1204
+ };
1205
+ }
1206
+ return {
1207
+ id: existing.id,
1208
+ created: false
1209
+ };
1210
+ }
1211
+ return {
1212
+ id: (await this.createChannel({
1213
+ name,
1214
+ type: ChannelType.Category,
1215
+ ...overwrites ? { permission_overwrites: overwrites } : {}
1216
+ })).id,
1217
+ created: true
1218
+ };
1219
+ }
1220
+ /**
1221
+ * Edit a channel and keep the shared list in step; forget the list if the edit may have half-applied.
1222
+ * Discord answers with the channel as it now is: if the overwrites that come back are not the ones we
1223
+ * sent, something else changed it at the same time, so say so instead of reporting success.
1224
+ */
1225
+ async modifyChannel(channel, patch) {
1226
+ let after;
1227
+ try {
1228
+ after = await this.bot().channels.modify(channel.id, patch);
1229
+ } catch (err) {
1230
+ this.channelLoad = void 0;
1231
+ throw err;
1232
+ }
1233
+ if (patch.permission_overwrites && overwriteKey(after.permission_overwrites) !== overwriteKey(patch.permission_overwrites)) {
1234
+ this.channelLoad = void 0;
1235
+ 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`);
1236
+ }
1237
+ Object.assign(channel, patch);
1238
+ }
1239
+ /**
1240
+ * Find a channel by name. A name can exist in several categories, so with a
1241
+ * parent: prefer the one already there, then an uncategorised one (moved in);
1242
+ * never grab a channel that lives under a different category. Announcement
1243
+ * channels count: reusing one beats creating a same-named text channel.
1244
+ */
1245
+ static findChannel(channels, name, parentId) {
1246
+ const named = channels.filter((c) => (c.type === ChannelType.Text || c.type === ChannelType.Announcement) && DiscordNotifications.same(c.name, name));
1247
+ if (!parentId) return named[0];
1248
+ return named.find((c) => c.parent_id === parentId) ?? named.find((c) => !c.parent_id);
1249
+ }
1250
+ async ensureChannel(input) {
1251
+ const parent = input.category ? (await this.ensureCategory(input.category)).id : void 0;
1252
+ const existing = DiscordNotifications.findChannel(await this.channelList(), input.name, parent);
1253
+ const overwrites = input.access ? await this.overwritesFor(input.access) : void 0;
1254
+ if (existing) {
1255
+ const updated = [];
1256
+ const patch = {};
1257
+ if (parent && existing.parent_id !== parent) {
1258
+ patch.parent_id = parent;
1259
+ updated.push("category");
1260
+ }
1261
+ if (input.topic !== void 0 && (existing.topic ?? "") !== input.topic) {
1262
+ patch.topic = input.topic;
1263
+ updated.push("topic");
1264
+ }
1265
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
1266
+ patch.permission_overwrites = keepThreadBits(overwrites, existing.permission_overwrites);
1267
+ updated.push("access");
1268
+ }
1269
+ if (updated.length > 0) await this.modifyChannel(existing, patch);
1270
+ return {
1271
+ id: existing.id,
1272
+ created: false,
1273
+ ...updated.length > 0 ? { updated } : {}
1274
+ };
1275
+ }
1276
+ return {
1277
+ id: (await this.createChannel({
1278
+ name: input.name,
1279
+ type: ChannelType.Text,
1280
+ ...input.topic ? { topic: input.topic } : {},
1281
+ ...parent ? { parent_id: parent } : {},
1282
+ ...overwrites ? { permission_overwrites: overwrites } : {}
1283
+ })).id,
1284
+ created: true
1285
+ };
1286
+ }
1287
+ async ensureWebhook(input) {
1288
+ const bot = this.bot();
1289
+ const parent = input.category ? (await this.channelList()).find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, input.category))?.id : void 0;
1290
+ const channel = DiscordNotifications.findChannel(await this.channelList(), input.channel, parent);
1291
+ if (!channel) throw new Error(`no channel named \`${input.channel}\` — create it first`);
1292
+ const existing = (await bot.channels.webhooks(channel.id)).find((w) => DiscordNotifications.same(w.name ?? "", input.name));
1293
+ const hook = existing ?? await bot.channels.createWebhook(channel.id, { name: input.name });
1294
+ const result = {
1295
+ created: !existing,
1296
+ ...hook.url ? { url: hook.url } : {}
1297
+ };
1298
+ if (input.avatar !== void 0 && !hook.avatar) try {
1299
+ await bot.webhooks.modify(hook.id, { avatar: input.avatar });
1300
+ result.updated = ["avatar"];
1301
+ } catch (err) {
1302
+ result.avatarError = reason(err);
1303
+ }
1304
+ return result;
1305
+ }
1306
+ async checkDelivery(input) {
1307
+ const result = {
1308
+ posted: false,
1309
+ readBack: false,
1310
+ removed: false,
1311
+ problems: []
1312
+ };
1313
+ const fail = (problem) => ({
1314
+ ...result,
1315
+ problems: [problem]
1316
+ });
1317
+ 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");
1318
+ let bot;
1319
+ let hook;
1320
+ let text = input.text;
1321
+ try {
1322
+ bot = this.bot();
1323
+ const channels = await this.channelList();
1324
+ let parent;
1325
+ if (input.category) {
1326
+ parent = channels.find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, input.category))?.id;
1327
+ if (!parent) return fail(`no category named \`${input.category}\``);
1328
+ }
1329
+ const channel = DiscordNotifications.findChannel(channels, input.channel, parent);
1330
+ if (!channel || parent && channel.parent_id !== parent) return fail(`no channel named \`${input.channel}\`${input.category ? ` under \`${input.category}\`` : ""}`);
1331
+ const named = (await bot.channels.webhooks(channel.id)).filter((w) => DiscordNotifications.same(w.name ?? "", input.name));
1332
+ if (named.length === 0) return fail(`no webhook named \`${input.name}\``);
1333
+ const usable = named.find((w) => w.token);
1334
+ if (!usable?.token) return fail(`webhook \`${input.name}\` was not created by this bot, so its token is hidden`);
1335
+ hook = {
1336
+ id: usable.id,
1337
+ token: usable.token,
1338
+ channelId: channel.id
1339
+ };
1340
+ text = input.text.replaceAll("{channel}", `<#${channel.id}>`);
1341
+ } catch (err) {
1342
+ return fail(reason(err));
1343
+ }
1344
+ let messageId;
1345
+ try {
1346
+ messageId = (await this.client.webhooks.executeAndWait(hook.id, hook.token, text)).id;
1347
+ result.posted = true;
1348
+ } catch (err) {
1349
+ result.problems.push(`the post was refused (${reason(err)})`);
1350
+ try {
1351
+ const stray = (await bot.channels.messages(hook.channelId, 100)).find((m) => m.webhook_id === hook.id && m.content === text);
1352
+ if (stray && input.keep) {
1353
+ result.posted = true;
1354
+ result.kept = true;
1355
+ result.problems.push(`the test message ${stray.id} arrived but its response was lost; it was left in place`);
1356
+ } else if (stray) {
1357
+ await bot.channels.deleteMessage(hook.channelId, stray.id);
1358
+ result.problems.push(`the test message ${stray.id} had been posted, and was removed`);
1359
+ }
1360
+ } catch {}
1361
+ return result;
1362
+ }
1363
+ try {
1364
+ result.readBack = (await bot.channels.messages(hook.channelId, 100)).some((m) => m.id === messageId);
1365
+ if (!result.readBack) result.problems.push("the post was accepted but is not in the channel");
1366
+ } catch (err) {
1367
+ result.problems.push(`could not read the channel back (${reason(err)})`);
1368
+ }
1369
+ if (input.keep) {
1370
+ result.kept = true;
1371
+ return result;
1372
+ }
1373
+ try {
1374
+ await this.client.webhooks.deleteMessage(hook.id, hook.token, messageId);
1375
+ result.removed = true;
1376
+ } catch (err) {
1377
+ result.problems.push(`could not remove the test message ${messageId} (${reason(err)})`);
1378
+ }
1379
+ return result;
1380
+ }
1381
+ async createServer(input) {
1382
+ if (this.createdGuild) {
1383
+ const existing = await this.bot().guilds.get(this.createdGuild);
1384
+ return {
1385
+ id: existing.id,
1386
+ name: existing.name
1387
+ };
1388
+ }
1389
+ 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`);
1390
+ const guild = await this.botOwnedServer(input.name) ?? await this.bot().guilds.create({ name: input.name });
1391
+ this.createdGuild = guild.id;
1392
+ this.channelLoad = void 0;
1393
+ return {
1394
+ id: guild.id,
1395
+ name: guild.name
1396
+ };
1397
+ }
1398
+ /** A server this bot owns (not one it only belongs to) with exactly this name, read across every page. */
1399
+ async botOwnedServer(name) {
1400
+ let after;
1401
+ for (;;) {
1402
+ const page = await this.bot().users.guilds(after ? { after } : {});
1403
+ const hit = page.find((g) => g.owner && g.name === name);
1404
+ if (hit) return hit;
1405
+ const last = page[page.length - 1];
1406
+ if (page.length < 200 || !last) return void 0;
1407
+ after = last.id;
1408
+ }
1409
+ }
1410
+ async inviteLink(channelName) {
1411
+ const channel = DiscordNotifications.findChannel(await this.channelList(), channelName);
1412
+ if (!channel) throw new Error(`no channel named \`${channelName}\` to invite into`);
1413
+ return `https://discord.gg/${(await this.bot().channels.createInvite(channel.id, {
1414
+ max_age: 86400,
1415
+ max_uses: 1,
1416
+ unique: true
1417
+ })).code}`;
1418
+ }
1419
+ async hasMember(memberId) {
1420
+ try {
1421
+ await this.bot().guilds.member(this.guild(), memberId);
1422
+ return true;
1423
+ } catch (err) {
1424
+ if (err instanceof ProviderApiError && err.status === 404) return false;
1425
+ throw err;
1426
+ }
1427
+ }
1428
+ async transferServer(memberId) {
1429
+ await this.bot().guilds.modify(this.guild(), { owner_id: memberId });
1430
+ }
1431
+ async serverOwner() {
1432
+ const guild = await this.bot().guilds.get(this.guild());
1433
+ if (!guild.owner_id) throw new Error("Discord did not say who owns the server");
1434
+ return {
1435
+ id: guild.owner_id,
1436
+ isBot: guild.owner_id === await this.botId(),
1437
+ ...guild.name ? { name: guild.name } : {}
1438
+ };
1439
+ }
1440
+ /** The one role with this name, or an error that says what to fix: none, or more than one. */
1441
+ async roleNamed(name) {
1442
+ const matches = (await this.bot().guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, name));
1443
+ if (matches.length === 0) throw new Error(`no role named \`${name}\` — run \`holocron notifications setup\` to create it`);
1444
+ 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`);
1445
+ return matches[0];
1446
+ }
1447
+ async roleMembers(roleName) {
1448
+ const role = await this.roleNamed(roleName);
1449
+ try {
1450
+ return (await this.bot().guilds.membersWithRole(this.guild(), role.id)).flatMap((m) => m.user ? [{
1451
+ id: m.user.id,
1452
+ ...m.user.username ? { name: m.user.username } : {}
1453
+ }] : []);
1454
+ } catch (err) {
1455
+ 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 });
1456
+ throw err;
1457
+ }
1458
+ }
1459
+ async addRoleMember(roleName, memberId) {
1460
+ await this.bot().guilds.addMemberRole(this.guild(), memberId, (await this.roleNamed(roleName)).id);
1461
+ }
1462
+ async removeRoleMember(roleName, memberId) {
1463
+ await this.bot().guilds.removeMemberRole(this.guild(), memberId, (await this.roleNamed(roleName)).id);
1464
+ }
1465
+ async ensureRole(input) {
1466
+ const bot = this.bot();
1467
+ const color = input.color !== void 0 ? colorToInt(input.color) : void 0;
1468
+ const wanted = input.permissions !== void 0 ? permissions(input.permissions) : void 0;
1469
+ const matches = (await bot.guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, input.name));
1470
+ 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`);
1471
+ const existing = matches[0];
1472
+ if (existing) {
1473
+ const patch = {};
1474
+ const updated = [];
1475
+ if (input.mentionable !== void 0 && existing.mentionable !== input.mentionable) {
1476
+ patch.mentionable = input.mentionable;
1477
+ updated.push("mentionable");
1478
+ }
1479
+ if (color !== void 0 && existing.color !== color) {
1480
+ patch.color = color;
1481
+ updated.push("colour");
1482
+ }
1483
+ if (input.hoist !== void 0 && (existing.hoist ?? false) !== input.hoist) {
1484
+ patch.hoist = input.hoist;
1485
+ updated.push("hoist");
1486
+ }
1487
+ if (wanted !== void 0 && existing.permissions !== wanted) {
1488
+ patch.permissions = wanted;
1489
+ updated.push("permissions");
1490
+ }
1491
+ if (updated.length > 0) {
1492
+ this.roleLoad = void 0;
1493
+ const after = await bot.guilds.modifyRole(this.guild(), existing.id, patch);
1494
+ const stuck = [
1495
+ [
1496
+ "mentionable",
1497
+ patch.mentionable,
1498
+ after.mentionable
1499
+ ],
1500
+ [
1501
+ "colour",
1502
+ patch.color,
1503
+ after.color
1504
+ ],
1505
+ [
1506
+ "hoist",
1507
+ patch.hoist,
1508
+ after.hoist
1509
+ ],
1510
+ [
1511
+ "permissions",
1512
+ patch.permissions,
1513
+ after.permissions
1514
+ ]
1515
+ ].filter(([, sent, now]) => sent !== void 0 && sent !== now).map(([name]) => name);
1516
+ 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`);
1517
+ }
1518
+ return {
1519
+ id: existing.id,
1520
+ created: false,
1521
+ ...updated.length > 0 ? { updated } : {}
1522
+ };
1523
+ }
1524
+ this.roleLoad = void 0;
1525
+ const made = await bot.guilds.createRole(this.guild(), {
1526
+ name: input.name,
1527
+ ...input.mentionable !== void 0 ? { mentionable: input.mentionable } : {},
1528
+ ...color !== void 0 ? { color } : {},
1529
+ ...input.hoist !== void 0 ? { hoist: input.hoist } : {},
1530
+ ...wanted !== void 0 ? { permissions: wanted } : {}
1531
+ });
1532
+ const twins = (await bot.guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, input.name));
1533
+ 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`);
1534
+ return {
1535
+ id: made.id,
1536
+ created: true
1537
+ };
1538
+ }
56
1539
  resolve(channel) {
57
1540
  const alias = this.opts.webhooks?.[channel];
58
1541
  if (alias) return alias;
@@ -62,8 +1545,7 @@ var DiscordNotifications = class {
62
1545
  return this.defaultWebhookUrl();
63
1546
  }
64
1547
  };
65
- //#endregion
66
- //#region src/verify-token.ts
1548
+ // src/verify-token.ts
67
1549
  async function verifyToken(webhookUrl, opts = {}) {
68
1550
  try {
69
1551
  const { id, token } = parseWebhookUrl(webhookUrl);
@@ -78,33 +1560,70 @@ async function verifyToken(webhookUrl, opts = {}) {
78
1560
  } catch (err) {
79
1561
  return {
80
1562
  ok: false,
81
- message: err instanceof Error ? err.message : String(err)
1563
+ message: errorMessage(err)
82
1564
  };
83
1565
  }
84
1566
  }
85
- //#endregion
86
- //#region src/index.ts
1567
+ // src/index.ts
87
1568
  function createContext(options = {}) {
88
1569
  let url;
1570
+ let bot;
1571
+ let applicationId;
1572
+ const botClient = () => bot ??= createDiscordBotClient({
1573
+ botToken: resolveBotToken({
1574
+ env: options.env,
1575
+ keyring: options.keyring,
1576
+ org: options.org
1577
+ }),
1578
+ ...options.unsafeBotBaseUrl && options.baseUrl ? { baseUrl: options.baseUrl } : {},
1579
+ ...options.fetch ? { fetch: options.fetch } : {}
1580
+ });
89
1581
  return {
90
1582
  options,
91
1583
  client: createDiscordClient({
92
1584
  baseUrl: options.baseUrl,
93
1585
  fetch: options.fetch
94
1586
  }),
95
- defaultWebhookUrl: () => url ??= resolveToken(options)
1587
+ defaultWebhookUrl: () => url ??= resolveToken(options),
1588
+ bot: botClient,
1589
+ oauth: async (redirectUri) => {
1590
+ applicationId ??= botClient().application.get().then((app) => app.id).catch((err) => {
1591
+ applicationId = void 0;
1592
+ throw err;
1593
+ });
1594
+ return createDiscordOAuthClient({
1595
+ clientId: await applicationId,
1596
+ clientSecret: resolveClientSecret({
1597
+ env: options.env,
1598
+ keyring: options.keyring,
1599
+ org: options.org
1600
+ }),
1601
+ redirectUri,
1602
+ ...options.unsafeBotBaseUrl && options.baseUrl ? { baseUrl: options.baseUrl } : {},
1603
+ ...options.fetch ? { fetch: options.fetch } : {}
1604
+ });
1605
+ }
96
1606
  };
97
1607
  }
98
1608
  function notifications(ctx) {
99
- return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl);
1609
+ return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl, ctx.bot, ctx.oauth);
100
1610
  }
101
1611
  function createPlugin(options = {}) {
102
1612
  const ctx = createContext(options);
103
1613
  return {
104
1614
  name: "@theholocron/holocron-plugin-discord",
1615
+ probes: { connection: connectionProbe({
1616
+ provider: "Discord",
1617
+ url: options.baseUrl ?? "https://discord.com",
1618
+ fetch: options.fetch,
1619
+ token: () => resolveToken(options),
1620
+ verify: (token) => verifyToken(token, {
1621
+ baseUrl: options.baseUrl,
1622
+ fetch: options.fetch
1623
+ })
1624
+ }) },
105
1625
  capabilities: { notifications: () => notifications(ctx) }
106
1626
  };
107
1627
  }
108
1628
  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 };
1629
+ export { AUTH_HINT, AuthError, DiscordNotifications, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveBotToken, resolveClientSecret, resolveToken, verifyToken };