@theholocron/holocron-plugin-discord 5.0.0-alpha.187 → 5.0.0-alpha.189

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.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { AuthError, EnsureWebhookResult, EnsuredResource, Notifications, NotificationsLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
1
+ import { AuthError, EnsureWebhookResult, EnsuredResource, Notifications, NotificationsAccess, NotificationsLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
2
2
  import { DiscordBotClient, DiscordClient, DiscordClientOptions, DiscordWebhookInfo, createDiscordClient, parseWebhookUrl } from "@theholocron/discord-client";
3
3
  //#region src/auth.d.ts
4
4
  declare const resolveToken: (input?: ResolveTokenInput) => string;
@@ -52,6 +52,25 @@ declare class DiscordNotifications implements Notifications {
52
52
  * the layout, not with the server.
53
53
  */
54
54
  inspect(layout: NotificationsLayout): Promise<ServerInspection>;
55
+ validateLayout(layout: NotificationsLayout): string | undefined;
56
+ private botUser?;
57
+ private botId;
58
+ /**
59
+ * The overwrites that make a channel look like `access`. The list is exact: it replaces
60
+ * whatever was set by hand. `[]` (public) when nothing is restricted.
61
+ */
62
+ private overwritesFor;
63
+ /**
64
+ * Read an access back out of a channel's overwrites, naming roles as the layout does. Only
65
+ * overwrites of the shape {@link overwritesFor} writes can be read back; anything else
66
+ * (a role-specific deny, a member overwrite, only some of the posting bits) means the
67
+ * channel's real access is not something the layout can state, and is reported as `"custom"`
68
+ * rather than guessed at.
69
+ */
70
+ private accessOf;
71
+ /** The server's roles, fetched once and forgotten whenever setup changes a role. */
72
+ private roleLoad?;
73
+ private roleList;
55
74
  private guild;
56
75
  /**
57
76
  * The server's channel list, fetched once per instance. Every ensure* call used
@@ -73,7 +92,15 @@ declare class DiscordNotifications implements Notifications {
73
92
  */
74
93
  private createChannel;
75
94
  private static same;
76
- ensureCategory(name: string): Promise<EnsuredResource>;
95
+ ensureCategory(name: string, opts?: {
96
+ access?: NotificationsAccess;
97
+ }): Promise<EnsuredResource>;
98
+ /**
99
+ * Edit a channel and keep the shared list in step; forget the list if the edit may have half-applied.
100
+ * Discord answers with the channel as it now is: if the overwrites that come back are not the ones we
101
+ * sent, something else changed it at the same time, so say so instead of reporting success.
102
+ */
103
+ private modifyChannel;
77
104
  /**
78
105
  * Find a channel by name. A name can exist in several categories, so with a
79
106
  * parent: prefer the one already there, then an uncategorised one (moved in);
@@ -85,6 +112,7 @@ declare class DiscordNotifications implements Notifications {
85
112
  name: string;
86
113
  category?: string;
87
114
  topic?: string;
115
+ access?: NotificationsAccess;
88
116
  }): Promise<EnsuredResource>;
89
117
  ensureWebhook(input: {
90
118
  channel: string;
@@ -94,6 +122,9 @@ declare class DiscordNotifications implements Notifications {
94
122
  ensureRole(input: {
95
123
  name: string;
96
124
  mentionable?: boolean;
125
+ color?: string;
126
+ hoist?: boolean;
127
+ permissions?: string[];
97
128
  }): Promise<EnsuredResource>;
98
129
  private resolve;
99
130
  }
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
2
2
  import { errorMessage } from "@theholocron/misc-utils";
3
- import { ChannelType, createDiscordBotClient, createDiscordClient, parseWebhookUrl } from "@theholocron/discord-client";
3
+ import { ChannelType, createDiscordBotClient, createDiscordClient, parseWebhookUrl, permissionNames, permissions } from "@theholocron/discord-client";
4
4
  //#region src/auth.ts
5
5
  const resolveToken = createResolveToken({
6
6
  envName: "HOLOCRON_DISCORD_WEBHOOK",
@@ -16,10 +16,38 @@ const resolveBotToken = createResolveToken({
16
16
  });
17
17
  //#endregion
18
18
  //#region src/capabilities/notifications.ts
19
+ /** `#rrggbb` to Discord's integer colour. */
20
+ function colorToInt(hex) {
21
+ if (!/^#[0-9a-fA-F]{6}$/.test(hex)) throw new Error(`invalid colour ${JSON.stringify(hex)}: use #rrggbb`);
22
+ return Number.parseInt(hex.slice(1), 16);
23
+ }
24
+ /** Discord's integer colour to `#rrggbb`. 0 is Discord's "no colour", and is what `#000000` means too. */
25
+ function colorToHex(color) {
26
+ return `#${color.toString(16).padStart(6, "0")}`;
27
+ }
19
28
  /** An error as one line: the message, plus Discord's own response body when there is one. */
20
29
  function reason(err) {
21
30
  return err instanceof ProviderApiError && err.details ? `${errorMessage(err)}: ${String(err.details).slice(0, 200)}` : errorMessage(err);
22
31
  }
32
+ /** What @everyone loses when a channel is read-only: sending, and starting or posting in threads. */
33
+ const POST = [
34
+ "SendMessages",
35
+ "SendMessagesInThreads",
36
+ "CreatePublicThreads",
37
+ "CreatePrivateThreads"
38
+ ];
39
+ /** What the bot keeps in a channel it has locked down, so it can still manage it and post. */
40
+ const BOT_KEEPS = [
41
+ "ViewChannel",
42
+ "SendMessages",
43
+ "ReadMessageHistory",
44
+ "ManageChannels",
45
+ "ManageWebhooks"
46
+ ];
47
+ /** Overwrites as a comparable set: order and the shape of the array do not matter. */
48
+ function overwriteKey(list) {
49
+ return (list ?? []).map((o) => `${o.id}:${o.type}:${o.allow}:${o.deny}`).sort().join("|");
50
+ }
23
51
  var DiscordNotifications = class DiscordNotifications {
24
52
  client;
25
53
  opts;
@@ -90,21 +118,131 @@ var DiscordNotifications = class DiscordNotifications {
90
118
  let roles = [];
91
119
  let rolesError;
92
120
  if ((layout.roles ?? []).length > 0) try {
93
- roles = (await bot.guilds.roles(this.guild())).map((r) => ({
94
- name: r.name,
95
- id: r.id,
96
- mentionable: r.mentionable
97
- }));
121
+ roles = (await bot.guilds.roles(this.guild())).map((r) => {
122
+ return {
123
+ name: r.name,
124
+ id: r.id,
125
+ mentionable: r.mentionable,
126
+ color: colorToHex(r.color),
127
+ ...r.hoist !== void 0 ? { hoist: r.hoist } : {},
128
+ ...r.permissions !== void 0 ? { permissions: permissionNames(r.permissions) } : {}
129
+ };
130
+ });
98
131
  } catch (err) {
99
132
  rolesError = reason(err);
100
133
  }
134
+ const roleName = (id) => roles.find((r) => r.id === id)?.name ?? id;
135
+ found.forEach((entry, i) => {
136
+ entry.access = this.accessOf(text[i].permission_overwrites, roleName);
137
+ });
138
+ const categoryAccess = {};
139
+ for (const c of channels.filter((c) => c.type === ChannelType.Category)) categoryAccess[c.name] = this.accessOf(c.permission_overwrites, roleName);
101
140
  return {
102
141
  categories: [...categoryName.values()],
142
+ categoryAccess,
103
143
  channels: found,
104
144
  roles,
105
145
  ...rolesError ? { rolesError } : {}
106
146
  };
107
147
  }
148
+ validateLayout(layout) {
149
+ for (const role of layout.roles ?? []) try {
150
+ if (role.color !== void 0) colorToInt(role.color);
151
+ if (role.permissions !== void 0) permissions(role.permissions);
152
+ } catch (err) {
153
+ return `role \`${role.name}\`: ${errorMessage(err)}`;
154
+ }
155
+ }
156
+ botUser;
157
+ botId() {
158
+ return this.botUser ??= this.bot().users.me().then((u) => u.id).catch((err) => {
159
+ this.botUser = void 0;
160
+ throw err;
161
+ });
162
+ }
163
+ /**
164
+ * The overwrites that make a channel look like `access`. The list is exact: it replaces
165
+ * whatever was set by hand. `[]` (public) when nothing is restricted.
166
+ */
167
+ async overwritesFor(access) {
168
+ const view = access.view ?? "everyone";
169
+ const post = access.post ?? "everyone";
170
+ const everyoneDeny = [...view === "everyone" ? [] : ["ViewChannel"], ...post === "everyone" ? [] : POST];
171
+ if (everyoneDeny.length === 0) return [];
172
+ const roles = [...view === "everyone" ? [] : view, ...post === "everyone" ? [] : post].length > 0 ? await this.roleList() : [];
173
+ const idOf = (name) => {
174
+ const found = roles.filter((r) => DiscordNotifications.same(r.name, name));
175
+ if (found.length === 0) throw new Error(`access names the role \`${name}\`, which does not exist on the server yet`);
176
+ if (found.length > 1) throw new Error(`access names the role \`${name}\`, but ${found.length} roles have that name (ids ${found.map((r) => r.id).join(", ")}) -- delete or rename the extras`);
177
+ return found[0].id;
178
+ };
179
+ const allow = /* @__PURE__ */ new Map();
180
+ const grant = (roleName, names) => {
181
+ const id = idOf(roleName);
182
+ allow.set(id, [.../* @__PURE__ */ new Set([...allow.get(id) ?? [], ...names])]);
183
+ };
184
+ if (view !== "everyone") for (const r of view) grant(r, ["ViewChannel"]);
185
+ if (post !== "everyone") for (const r of post) grant(r, POST);
186
+ return [
187
+ {
188
+ id: this.guild(),
189
+ type: 0,
190
+ allow: "0",
191
+ deny: permissions(everyoneDeny)
192
+ },
193
+ ...[...allow].map(([id, names]) => ({
194
+ id,
195
+ type: 0,
196
+ allow: permissions(names),
197
+ deny: "0"
198
+ })),
199
+ {
200
+ id: await this.botId(),
201
+ type: 1,
202
+ allow: permissions(BOT_KEEPS),
203
+ deny: "0"
204
+ }
205
+ ];
206
+ }
207
+ /**
208
+ * Read an access back out of a channel's overwrites, naming roles as the layout does. Only
209
+ * overwrites of the shape {@link overwritesFor} writes can be read back; anything else
210
+ * (a role-specific deny, a member overwrite, only some of the posting bits) means the
211
+ * channel's real access is not something the layout can state, and is reported as `"custom"`
212
+ * rather than guessed at.
213
+ */
214
+ accessOf(overwrites, roleName) {
215
+ const list = overwrites ?? [];
216
+ const managed = permissions(["ViewChannel", ...POST]);
217
+ const within = (bits) => (BigInt(bits) & ~BigInt(managed)) === 0n;
218
+ const postOf = (bits) => {
219
+ const have = POST.filter((b) => permissionNames(bits).includes(b)).length;
220
+ return have === 0 ? "none" : have === POST.length ? "all" : "some";
221
+ };
222
+ const botSignature = permissions(BOT_KEEPS);
223
+ let everyone;
224
+ const roles = [];
225
+ for (const o of list) if (o.type === 1) {
226
+ if (o.allow !== botSignature || o.deny !== "0") return "custom";
227
+ } else if (o.id === this.guild()) everyone = o;
228
+ else roles.push(o);
229
+ if (everyone && (everyone.allow !== "0" || !within(everyone.deny) || postOf(everyone.deny) === "some")) return "custom";
230
+ for (const o of roles) if (o.deny !== "0" || !within(o.allow) || postOf(o.allow) === "some") return "custom";
231
+ const denied = (bit) => everyone !== void 0 && permissionNames(everyone.deny).includes(bit);
232
+ const names = (bit) => roles.filter((o) => permissionNames(o.allow).includes(bit)).map((o) => roleName(o.id));
233
+ return {
234
+ view: denied("ViewChannel") ? names("ViewChannel") : "everyone",
235
+ post: denied("SendMessages") ? names("SendMessages") : "everyone"
236
+ };
237
+ }
238
+ /** The server's roles, fetched once and forgotten whenever setup changes a role. */
239
+ roleLoad;
240
+ roleList() {
241
+ return this.roleLoad ??= this.bot().guilds.roles(this.guild()).catch((err) => {
242
+ this.roleLoad = void 0;
243
+ throw err;
244
+ });
245
+ }
108
246
  guild() {
109
247
  if (!this.opts.guildId) throw new Error("no Discord server id — set `guildId` in the discord provider options in holocron.config.ts");
110
248
  return this.opts.guildId;
@@ -145,21 +283,52 @@ var DiscordNotifications = class DiscordNotifications {
145
283
  static same(a, b) {
146
284
  return a.toLowerCase() === b.toLowerCase();
147
285
  }
148
- async ensureCategory(name) {
286
+ async ensureCategory(name, opts = {}) {
149
287
  const existing = (await this.channelList()).find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, name));
150
- if (existing) return {
151
- id: existing.id,
152
- created: false
153
- };
288
+ const overwrites = opts.access ? await this.overwritesFor(opts.access) : void 0;
289
+ if (existing) {
290
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
291
+ await this.modifyChannel(existing, { permission_overwrites: overwrites });
292
+ return {
293
+ id: existing.id,
294
+ created: false,
295
+ updated: ["access"]
296
+ };
297
+ }
298
+ return {
299
+ id: existing.id,
300
+ created: false
301
+ };
302
+ }
154
303
  return {
155
304
  id: (await this.createChannel({
156
305
  name,
157
- type: ChannelType.Category
306
+ type: ChannelType.Category,
307
+ ...overwrites ? { permission_overwrites: overwrites } : {}
158
308
  })).id,
159
309
  created: true
160
310
  };
161
311
  }
162
312
  /**
313
+ * Edit a channel and keep the shared list in step; forget the list if the edit may have half-applied.
314
+ * Discord answers with the channel as it now is: if the overwrites that come back are not the ones we
315
+ * sent, something else changed it at the same time, so say so instead of reporting success.
316
+ */
317
+ async modifyChannel(channel, patch) {
318
+ let after;
319
+ try {
320
+ after = await this.bot().channels.modify(channel.id, patch);
321
+ } catch (err) {
322
+ this.channelLoad = void 0;
323
+ throw err;
324
+ }
325
+ if (patch.permission_overwrites && overwriteKey(after.permission_overwrites) !== overwriteKey(patch.permission_overwrites)) {
326
+ this.channelLoad = void 0;
327
+ 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`);
328
+ }
329
+ Object.assign(channel, patch);
330
+ }
331
+ /**
163
332
  * Find a channel by name. A name can exist in several categories, so with a
164
333
  * parent: prefer the one already there, then an uncategorised one (moved in);
165
334
  * never grab a channel that lives under a different category. Announcement
@@ -171,26 +340,29 @@ var DiscordNotifications = class DiscordNotifications {
171
340
  return named.find((c) => c.parent_id === parentId) ?? named.find((c) => !c.parent_id);
172
341
  }
173
342
  async ensureChannel(input) {
174
- const bot = this.bot();
175
343
  const parent = input.category ? (await this.ensureCategory(input.category)).id : void 0;
176
344
  const existing = DiscordNotifications.findChannel(await this.channelList(), input.name, parent);
345
+ const overwrites = input.access ? await this.overwritesFor(input.access) : void 0;
177
346
  if (existing) {
178
- const patch = {
179
- ...parent && existing.parent_id !== parent ? { parent_id: parent } : {},
180
- ...input.topic !== void 0 && (existing.topic ?? "") !== input.topic ? { topic: input.topic } : {}
181
- };
182
- if (Object.keys(patch).length > 0) {
183
- try {
184
- await bot.channels.modify(existing.id, patch);
185
- } catch (err) {
186
- this.channelLoad = void 0;
187
- throw err;
188
- }
189
- Object.assign(existing, patch);
347
+ const updated = [];
348
+ const patch = {};
349
+ if (parent && existing.parent_id !== parent) {
350
+ patch.parent_id = parent;
351
+ updated.push("category");
352
+ }
353
+ if (input.topic !== void 0 && (existing.topic ?? "") !== input.topic) {
354
+ patch.topic = input.topic;
355
+ updated.push("topic");
356
+ }
357
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
358
+ patch.permission_overwrites = overwrites;
359
+ updated.push("access");
190
360
  }
361
+ if (updated.length > 0) await this.modifyChannel(existing, patch);
191
362
  return {
192
363
  id: existing.id,
193
- created: false
364
+ created: false,
365
+ ...updated.length > 0 ? { updated } : {}
194
366
  };
195
367
  }
196
368
  return {
@@ -198,7 +370,8 @@ var DiscordNotifications = class DiscordNotifications {
198
370
  name: input.name,
199
371
  type: ChannelType.Text,
200
372
  ...input.topic ? { topic: input.topic } : {},
201
- ...parent ? { parent_id: parent } : {}
373
+ ...parent ? { parent_id: parent } : {},
374
+ ...overwrites ? { permission_overwrites: overwrites } : {}
202
375
  })).id,
203
376
  created: true
204
377
  };
@@ -221,19 +394,75 @@ var DiscordNotifications = class DiscordNotifications {
221
394
  }
222
395
  async ensureRole(input) {
223
396
  const bot = this.bot();
224
- const existing = (await bot.guilds.roles(this.guild())).find((r) => DiscordNotifications.same(r.name, input.name));
397
+ const color = input.color !== void 0 ? colorToInt(input.color) : void 0;
398
+ const wanted = input.permissions !== void 0 ? permissions(input.permissions) : void 0;
399
+ const matches = (await bot.guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, input.name));
400
+ 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`);
401
+ const existing = matches[0];
225
402
  if (existing) {
226
- if (input.mentionable !== void 0 && existing.mentionable !== input.mentionable) throw new Error(`role \`${input.name}\` exists with mentionable=${existing.mentionable} but the layout wants ${input.mentionable}; updating an existing role is not supported yet — change it in Discord (Role → Allow anyone to @mention this role)`);
403
+ const patch = {};
404
+ const updated = [];
405
+ if (input.mentionable !== void 0 && existing.mentionable !== input.mentionable) {
406
+ patch.mentionable = input.mentionable;
407
+ updated.push("mentionable");
408
+ }
409
+ if (color !== void 0 && existing.color !== color) {
410
+ patch.color = color;
411
+ updated.push("colour");
412
+ }
413
+ if (input.hoist !== void 0 && (existing.hoist ?? false) !== input.hoist) {
414
+ patch.hoist = input.hoist;
415
+ updated.push("hoist");
416
+ }
417
+ if (wanted !== void 0 && existing.permissions !== wanted) {
418
+ patch.permissions = wanted;
419
+ updated.push("permissions");
420
+ }
421
+ if (updated.length > 0) {
422
+ this.roleLoad = void 0;
423
+ const after = await bot.guilds.modifyRole(this.guild(), existing.id, patch);
424
+ const stuck = [
425
+ [
426
+ "mentionable",
427
+ patch.mentionable,
428
+ after.mentionable
429
+ ],
430
+ [
431
+ "colour",
432
+ patch.color,
433
+ after.color
434
+ ],
435
+ [
436
+ "hoist",
437
+ patch.hoist,
438
+ after.hoist
439
+ ],
440
+ [
441
+ "permissions",
442
+ patch.permissions,
443
+ after.permissions
444
+ ]
445
+ ].filter(([, sent, now]) => sent !== void 0 && sent !== now).map(([name]) => name);
446
+ 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`);
447
+ }
227
448
  return {
228
449
  id: existing.id,
229
- created: false
450
+ created: false,
451
+ ...updated.length > 0 ? { updated } : {}
230
452
  };
231
453
  }
454
+ this.roleLoad = void 0;
455
+ const made = await bot.guilds.createRole(this.guild(), {
456
+ name: input.name,
457
+ ...input.mentionable !== void 0 ? { mentionable: input.mentionable } : {},
458
+ ...color !== void 0 ? { color } : {},
459
+ ...input.hoist !== void 0 ? { hoist: input.hoist } : {},
460
+ ...wanted !== void 0 ? { permissions: wanted } : {}
461
+ });
462
+ const twins = (await bot.guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, input.name));
463
+ 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`);
232
464
  return {
233
- id: (await bot.guilds.createRole(this.guild(), {
234
- name: input.name,
235
- ...input.mentionable !== void 0 ? { mentionable: input.mentionable } : {}
236
- })).id,
465
+ id: made.id,
237
466
  created: true
238
467
  };
239
468
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-discord",
3
- "version": "5.0.0-alpha.187",
3
+ "version": "5.0.0-alpha.189",
4
4
  "description": "Holocron plugin for Discord. Implements the notifications capability via Discord incoming webhooks.",
5
5
  "keywords": [
6
6
  "discord",
@@ -30,7 +30,7 @@
30
30
  "dist"
31
31
  ],
32
32
  "devDependencies": {
33
- "@theholocron/discord-client": "^1.43.1",
33
+ "@theholocron/discord-client": "^1.44.0",
34
34
  "@theholocron/eslint-config": "^8.8.2",
35
35
  "@theholocron/http-client": "^1.43.1",
36
36
  "@theholocron/misc-utils": "^1.16.0",
@@ -48,12 +48,12 @@
48
48
  "tsx": "4.23.15",
49
49
  "typescript": "^5.9.3",
50
50
  "vitest": "^4.1.11",
51
- "@theholocron/cli": "5.0.0-alpha.187"
51
+ "@theholocron/cli": "5.0.0-alpha.189"
52
52
  },
53
53
  "peerDependencies": {
54
- "@theholocron/discord-client": "^1.43.1",
54
+ "@theholocron/discord-client": "^1.44.0",
55
55
  "@theholocron/misc-utils": "^1.16.0",
56
- "@theholocron/cli": "5.0.0-alpha.187"
56
+ "@theholocron/cli": "5.0.0-alpha.189"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">=22"