@theholocron/cli 5.0.0-alpha.202 → 5.0.0-alpha.204

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/README.md CHANGED
@@ -538,18 +538,20 @@ A `notifications` provider can declare a whole server in `holocron.config.ts`
538
538
  onboarding, the bot application) and the CLI applies and checks it. The
539
539
  commands and the config are provider-neutral; Discord is the first provider.
540
540
 
541
- | Command | What it does |
542
- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
543
- | `holocron notifications setup` | Applies the layout; looks everything up by name first, so a re-run changes nothing that matches |
544
- | `holocron notifications channel add <name>` | Creates one channel (optionally with a webhook whose URL is stored as a secret) |
545
- | `holocron notifications link` | Links your account on the provider to your GitHub account by signing in with the provider (OAuth, nothing secret kept) |
546
- | `holocron notifications sync-roles` | Makes who holds a role match a GitHub team, through the links file (`--keep` only adds; `--provider` picks one) |
547
- | `holocron doctor notifications [--built-only] [--deliver]` | Read-only, step by step: does the server match the layout, and do the secrets exist (`--deliver` also posts a test message through each webhook and removes it) |
541
+ | Command | What it does |
542
+ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
543
+ | `holocron notifications setup` | Applies the layout; looks everything up by name first, so a re-run changes nothing that matches |
544
+ | `holocron notifications channel add <name>` | Creates one channel (optionally with a webhook whose URL is stored as a secret) |
545
+ | `holocron notifications create-server --name <n> --owner <id>` | Creates the server the layout describes, writes its id into the config, applies the layout, invites the owner, waits for them to join and hands the server over (`--resume` finishes an interrupted hand-over; `--force` allows a second server) |
546
+ | `holocron notifications link` | Links your account on the provider to your GitHub account by signing in with the provider (OAuth, nothing secret kept) |
547
+ | `holocron notifications sync-roles` | Makes who holds a role match a GitHub team, through the links file (`--keep` only adds; `--provider` picks one) |
548
+ | `holocron doctor notifications [--built-only] [--deliver]` | Step by step: does the server match the layout, do the secrets exist, and does a person (not the bot) own it. A full run also leaves one `🧪 test:` post in the layout's `testChannel`; `--built-only` posts nothing; `--deliver` posts to every channel and removes each post |
548
549
 
549
550
  Config shape added for role sync and sign-in (all under the provider's `layout`):
550
551
 
551
552
  | Field | Meaning |
552
553
  | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
554
+ | `testChannel` | The channel (it must declare a webhook) the doctor posts its one self-removing test message to. |
553
555
  | `roles[].team` | A GitHub team slug. The role follows that team: given to linked members, taken from linked people who left. Never touches holders nobody has linked. |
554
556
  | `links.hostedUrl` | A hosted sign-in service (Sentinel). `link` asks `<hostedUrl>/api/link` and uses it when it answers `{ "service": "link" }`; otherwise it signs in locally. |
555
557
  | `links.localPort` | The port of the local sign-in listener (default `53682`, bound to `127.0.0.1` only). |
@@ -565,6 +567,7 @@ Capability surface behind it (all optional, so providers without the concept omi
565
567
 
566
568
  - `Source.teamMembers(teamSlug, org?)`, `Source.readFile(path, repo?)` (returns the `version` a later write must present),
567
569
  `Source.writeFile(path, content, { message, version?, repo? })` (a changed `version` is refused: a real conflict check).
570
+ - `Notifications.createServer({ name, force? })`, `inviteLink(channel)`, `hasMember(id)`, `transferServer(id)` and `serverOwner()`: create a server, invite its owner, check they joined, hand it over, and say who owns it.
568
571
  - `Notifications.roleMembers(role)`, `addRoleMember(role, memberId)`, `removeRoleMember(role, memberId)`.
569
572
  - `Notifications.checkDelivery({ channel, name, category?, text })`: posts through a channel's webhook, reads the post back and removes it, and says which step failed.
570
573
  - `Notifications.signIn()` returning `{ authorizeUrl, complete }`: the provider-neutral shape of "prove which account you own".
package/dist/cli.mjs CHANGED
@@ -24,7 +24,7 @@ import search from "@inquirer/search";
24
24
  import { execFileSync, spawn, spawnSync } from "node:child_process";
25
25
  import ora from "ora";
26
26
  import { findRootSync, isWorkspaceRoot, walkFilesSync } from "@theholocron/fs-utils";
27
- import { access, copyFile, mkdir, readFile, readdir, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
27
+ import { access, copyFile, mkdir, open, readFile, readdir, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
28
28
  import { createHash, randomBytes, randomUUID } from "node:crypto";
29
29
  import { createServer } from "node:http";
30
30
  import { stringifyJson } from "@theholocron/json-utils";
@@ -411,6 +411,7 @@ const COMMAND_CONTEXTS = {
411
411
  "notifications channel add": "workspace",
412
412
  "notifications setup": "workspace",
413
413
  "notifications link": "workspace",
414
+ "notifications create-server": "workspace",
414
415
  "notifications sync-roles": "workspace",
415
416
  "doctor notifications": "workspace",
416
417
  deploy: "workspace",
@@ -3515,22 +3516,13 @@ async function runNotificationsLink(input) {
3515
3516
  //#endregion
3516
3517
  //#region src/commands/doctor-notifications/doctor-notifications.ts
3517
3518
  /**
3518
- * `holocron doctor notifications` -- read-only: compare the layout a provider
3519
+ * `holocron doctor notifications` -- compare the layout a provider
3519
3520
  * declares in `holocron.config.ts` with what is actually on the server and in the
3520
3521
  * secrets store, step by step.
3521
3522
  *
3522
3523
  * It is the end-to-end check for `notifications setup`, and stays useful after
3523
- * as a drift check. Everything the layout and `setup` cannot do yet is listed
3524
- * too, as plain failing steps, so the command is red until the last feature
3525
- * lands and each feature built turns exactly one step green. The list
3526
- * is {@link PLANNED_CHECKS}; the numbers match the table in holocron#1098.
3527
- */
3528
- /** Features not built yet, in the order of the table in holocron#1098. Move an entry into a real check when it lands. */
3529
- const PLANNED_CHECKS = [{
3530
- step: 16,
3531
- id: "server-creation",
3532
- title: "server created from config"
3533
- }];
3524
+ * as a drift check. The step numbers match the table in holocron#1098.
3525
+ */
3534
3526
  const same = (a, b) => a.toLowerCase() === b.toLowerCase();
3535
3527
  /** `everyone`, or the roles sorted and lower-cased, so order and case do not matter when comparing. */
3536
3528
  const accessKey = (v) => v === "everyone" ? "everyone" : JSON.stringify([...new Set(v.map((r) => r.toLowerCase()))].sort());
@@ -3551,7 +3543,8 @@ const shown = (s) => sanitizeDetail(s);
3551
3543
  const WELCOME_TITLE = "welcome screen and onboarding set";
3552
3544
  const APP_TITLE = "bot description, tags, install link and URLs set";
3553
3545
  const AVATAR_TITLE = "webhook names and avatars set";
3554
- const DELIVERY_TITLE = "test message delivered through every webhook";
3546
+ const DELIVERY_TITLE = "test message delivered through a webhook";
3547
+ const OWNER_TITLE = "server owned by a person, not the bot";
3555
3548
  const SERVER_TITLE = "server verification, notifications and community set";
3556
3549
  const ACCESS_TITLE = "channel and category access set";
3557
3550
  const ROLE_APPEARANCE_TITLE = "role colour, hoist and permissions set";
@@ -3584,11 +3577,10 @@ async function runDoctorNotifications(input) {
3584
3577
  problems: []
3585
3578
  });
3586
3579
  };
3587
- let deliverSkipped = false;
3588
3580
  const summarise = () => ({
3589
3581
  pass: checks.filter((c) => c.status === "pass").length,
3590
3582
  fail: checks.filter((c) => c.status === "fail").length,
3591
- skip: (input.builtOnly ? PLANNED_CHECKS.length : 0) + (deliverSkipped ? 1 : 0)
3583
+ skip: 0
3592
3584
  });
3593
3585
  const finish = () => {
3594
3586
  const summary = summarise();
@@ -3985,8 +3977,12 @@ async function runDoctorNotifications(input) {
3985
3977
  cat,
3986
3978
  channel
3987
3979
  })));
3988
- if (!input.deliver) deliverSkipped = true;
3989
- else if (withHook.length === 0) checks.push({
3980
+ const testName = layout.testChannel;
3981
+ const mode = input.deliver ? "all" : !input.builtOnly && testName !== void 0 ? "test" : "none";
3982
+ const targets = mode === "all" ? withHook : mode === "test" ? withHook.filter(({ channel }) => same(channel.name, testName)).slice(0, 1) : [];
3983
+ let deliveryNote;
3984
+ if (mode === "none") deliveryNote = !input.builtOnly && testName === void 0 ? "the delivery check needs a test channel: name one in the layout's `testChannel` (a channel with a webhook)" : "the delivery check posts test messages, so --built-only skips it; add --deliver to post to every channel";
3985
+ else if (targets.length === 0) checks.push({
3990
3986
  id: "post-works",
3991
3987
  title: DELIVERY_TITLE,
3992
3988
  status: "pass",
@@ -3997,37 +3993,40 @@ async function runDoctorNotifications(input) {
3997
3993
  else if (!notifications.checkDelivery) failed("post-works", DELIVERY_TITLE, `the \`${notifications.providerName}\` provider cannot check delivery`);
3998
3994
  else {
3999
3995
  const problems = [];
4000
- for (const { cat, channel } of withHook) {
3996
+ for (const { cat, channel } of targets) {
4001
3997
  const cfg = channel.webhook === true ? {} : channel.webhook;
3998
+ const keep = mode === "test";
4002
3999
  try {
4003
4000
  const result = await notifications.checkDelivery({
4004
4001
  channel: channel.name,
4005
4002
  name: cfg.name ?? channel.name,
4006
4003
  category: cat.name,
4007
- text: `holocron doctor delivery check for #${channel.name}: safe to ignore, this message removes itself`
4004
+ text: keep ? "🧪 test: `holocron doctor notifications` check for {channel}. This post was a test of the delivery system; it is safe to delete." : "🧪 test: `holocron doctor notifications --deliver` check for {channel}. This post was a test of the delivery system; it removes itself.",
4005
+ ...keep ? { keep: true } : {}
4008
4006
  });
4009
4007
  for (const problem of result.problems) problems.push(`#${shown(channel.name)}: ${shown(problem)}`);
4010
- if (result.problems.length === 0 && !(result.posted && result.readBack && result.removed)) problems.push(`#${shown(channel.name)}: the check did not complete`);
4008
+ if (result.problems.length === 0 && !(result.posted && result.readBack && (keep ? result.kept : result.removed))) problems.push(`#${shown(channel.name)}: the check did not complete`);
4011
4009
  } catch (err) {
4012
4010
  problems.push(`#${shown(channel.name)}: ${shown(describeProviderError(err))}`);
4013
4011
  }
4014
4012
  }
4015
- add("post-works", DELIVERY_TITLE, problems, `${withHook.length} of ${withHook.length} delivered`);
4013
+ add("post-works", DELIVERY_TITLE, problems, mode === "all" ? `${targets.length} of ${targets.length} delivered` : `delivered through #${shown(targets[0].channel.name)} (left there)`);
4014
+ }
4015
+ if (notifications.serverOwner) try {
4016
+ const owner = await notifications.serverOwner();
4017
+ add("server-owner", OWNER_TITLE, owner.isBot ? ["the bot owns the server; hand it to a person with `holocron notifications create-server --resume --owner <member id>`"] : [], `owned by member ${shown(owner.id)}`);
4018
+ } catch (err) {
4019
+ failed("server-owner", OWNER_TITLE, shown(describeProviderError(err)));
4016
4020
  }
4017
- if (!input.builtOnly) for (const planned of PLANNED_CHECKS) checks.push({
4018
- id: planned.id,
4019
- title: planned.title,
4020
- status: "fail",
4021
- detail: `not built yet (#1098, step ${planned.step})`,
4022
- problems: [],
4023
- step: planned.step
4024
- });
4025
4021
  const width = Math.max(...checks.map((c) => c.title.length));
4026
4022
  for (const check of checks) {
4027
4023
  print(statusRow(check.status === "pass" ? "ok" : "fail", [check.title.padEnd(width), check.detail]));
4028
4024
  for (const problem of check.problems) print(` - ${problem}`);
4029
4025
  }
4030
- if (deliverSkipped) print(` ${style.skip(`${DELIVERY_TITLE}: not run; add --deliver to post a test message to each channel`)}`);
4026
+ if (deliveryNote) {
4027
+ print("");
4028
+ print(` ${style.skip(`note: ${deliveryNote}`)}`);
4029
+ }
4031
4030
  const summary = summarise();
4032
4031
  print("");
4033
4032
  print(style.header(`${summary.pass} ok, ${summary.fail} fail, ${summary.skip} skipped`));
@@ -4637,6 +4636,93 @@ async function runNew(input) {
4637
4636
  };
4638
4637
  }
4639
4638
  //#endregion
4639
+ //#region src/commands/notifications-create-server/find-guild-id.ts
4640
+ /**
4641
+ * Every `guildId: "<digits>"` property in the source, found by reading it as code: comments are skipped and a
4642
+ * string is one piece, so a `guildId` inside a comment or inside another string is not a property. The key may be
4643
+ * bare or quoted. It reads tokens, not a full syntax tree, which is enough to tell a property from text.
4644
+ */
4645
+ function findGuildId(source) {
4646
+ const tokens = [];
4647
+ let i = 0;
4648
+ while (i < source.length) {
4649
+ const ch = source[i];
4650
+ if (/\s/.test(ch)) i++;
4651
+ else if (source.startsWith("//", i)) {
4652
+ const nl = source.indexOf("\n", i);
4653
+ i = nl === -1 ? source.length : nl + 1;
4654
+ } else if (source.startsWith("/*", i)) {
4655
+ const close = source.indexOf("*/", i + 2);
4656
+ i = close === -1 ? source.length : close + 2;
4657
+ } else if (ch === "\"" || ch === "'" || ch === "`") {
4658
+ let j = i + 1;
4659
+ while (j < source.length && source[j] !== ch) j += source[j] === "\\" ? 2 : 1;
4660
+ tokens.push({
4661
+ kind: "string",
4662
+ text: source.slice(i + 1, j),
4663
+ start: i + 1,
4664
+ end: j
4665
+ });
4666
+ i = j + 1;
4667
+ } else if (/[\w$]/.test(ch)) {
4668
+ let j = i + 1;
4669
+ while (j < source.length && /[\w$]/.test(source[j])) j++;
4670
+ tokens.push({
4671
+ kind: "word",
4672
+ text: source.slice(i, j),
4673
+ start: i,
4674
+ end: j
4675
+ });
4676
+ i = j;
4677
+ } else {
4678
+ tokens.push({
4679
+ kind: "punct",
4680
+ text: ch,
4681
+ start: i,
4682
+ end: i + 1
4683
+ });
4684
+ i++;
4685
+ }
4686
+ }
4687
+ const found = [];
4688
+ for (let t = 0; t + 2 < tokens.length; t++) {
4689
+ const [key, colon, value] = [
4690
+ tokens[t],
4691
+ tokens[t + 1],
4692
+ tokens[t + 2]
4693
+ ];
4694
+ if (key.kind === "punct" || key.text !== "guildId") continue;
4695
+ if (colon.text !== ":" || colon.kind !== "punct") continue;
4696
+ if (value.kind === "string" && /^\d{1,20}$/.test(value.text)) found.push({
4697
+ start: value.start,
4698
+ end: value.end
4699
+ });
4700
+ }
4701
+ return found;
4702
+ }
4703
+ //#endregion
4704
+ //#region src/commands/notifications-create-server/lock-config.ts
4705
+ /**
4706
+ * Takes a lock next to the config so two runs cannot create and hand over different servers and then overwrite
4707
+ * each other's `guildId`. Returns a function that releases it, or undefined when another run holds it. The lock
4708
+ * is a file made only if absent; one left behind by a crashed run has to be deleted by hand, and the caller says so.
4709
+ */
4710
+ async function lockConfig(filepath) {
4711
+ const path = `${filepath}.create-server.lock`;
4712
+ try {
4713
+ const handle = await open(path, "wx");
4714
+ await handle.writeFile(`${process.pid}\n`);
4715
+ await handle.close();
4716
+ } catch (err) {
4717
+ if (err.code === "EEXIST") return void 0;
4718
+ throw err;
4719
+ }
4720
+ return {
4721
+ path,
4722
+ release: () => unlink(path).catch(() => void 0)
4723
+ };
4724
+ }
4725
+ //#endregion
4640
4726
  //#region src/commands/notifications-setup/notifications-setup.ts
4641
4727
  /**
4642
4728
  * `holocron notifications setup` — apply the server layout a `notifications`
@@ -4700,12 +4786,18 @@ function accessRoleProblem(layout) {
4700
4786
  function serverLayoutProblem(layout) {
4701
4787
  const counts = /* @__PURE__ */ new Map();
4702
4788
  for (const name of (layout.categories ?? []).flatMap((c) => (c.channels ?? []).map((ch) => ch.name.toLowerCase()))) counts.set(name, (counts.get(name) ?? 0) + 1);
4789
+ const declared = (layout.categories ?? []).flatMap((c) => c.channels ?? []);
4703
4790
  const roles = new Set((layout.roles ?? []).map((r) => r.name.toLowerCase()));
4704
4791
  const channel = (where, name) => {
4705
4792
  const count = counts.get(name.toLowerCase()) ?? 0;
4706
4793
  if (count === 0) return `${where} names the channel \`${name}\`, which is not in the layout's channels`;
4707
4794
  if (count > 1) return `${where} names \`${name}\`, but more than one channel in the layout has that name`;
4708
4795
  };
4796
+ if (layout.testChannel !== void 0) {
4797
+ const problem = channel("`testChannel`", layout.testChannel);
4798
+ if (problem) return problem;
4799
+ if (!declared.some((ch) => ch.name.toLowerCase() === layout.testChannel.toLowerCase() && ch.webhook)) return `\`testChannel\` names \`${layout.testChannel}\`, which declares no webhook`;
4800
+ }
4709
4801
  const roleTeams = roleTeamProblem(layout);
4710
4802
  if (roleTeams) return roleTeams;
4711
4803
  const emptyTeam = (layout.roles ?? []).find((r) => r.team !== void 0 && r.team.trim() === "");
@@ -4748,7 +4840,7 @@ async function runNotificationsSetup(input) {
4748
4840
  const logger = input.logger ?? getLogger();
4749
4841
  /* v8 ignore next -- the real loader is only built outside tests, which always inject one */
4750
4842
  const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
4751
- await loader.load();
4843
+ if (!input.preloaded) await loader.load();
4752
4844
  assertPluginsResolvable(loader, "notifications setup");
4753
4845
  const dryRun = input.context.dryRun ?? false;
4754
4846
  const report = {
@@ -4976,6 +5068,184 @@ async function runNotificationsSetup(input) {
4976
5068
  return report;
4977
5069
  }
4978
5070
  //#endregion
5071
+ //#region src/commands/notifications-create-server/pick-server-creator.ts
5072
+ /** The provider that can create a server and hand it over. */
5073
+ function pickServerCreator(providers, wanted) {
5074
+ return pickProvider(providers, wanted, (p) => typeof p.createServer === "function" && typeof p.inviteLink === "function" && typeof p.hasMember === "function" && typeof p.transferServer === "function", {
5075
+ infinitive: "create a server",
5076
+ gerund: "creating a server"
5077
+ });
5078
+ }
5079
+ //#endregion
5080
+ //#region src/commands/notifications-create-server/write-guild-id.ts
5081
+ /**
5082
+ * Puts a new server id where the config names the old one. It changes a file the person wrote, so it only does
5083
+ * so when there is exactly one `guildId: "<digits>"` property to replace (a comment or string that mentions one is not); otherwise it says why and leaves the file alone.
5084
+ */
5085
+ async function writeGuildId(filepath, id) {
5086
+ if (!/^\d{1,20}$/.test(id)) return {
5087
+ written: false,
5088
+ reason: `\`${id}\` is not a server id`
5089
+ };
5090
+ let text;
5091
+ try {
5092
+ text = await readFile(filepath, "utf8");
5093
+ } catch (err) {
5094
+ return {
5095
+ written: false,
5096
+ reason: `could not read ${filepath} (${errorMessage(err)})`
5097
+ };
5098
+ }
5099
+ const spans = findGuildId(text);
5100
+ const count = spans.length;
5101
+ if (count !== 1) return {
5102
+ written: false,
5103
+ reason: count === 0 ? "the config has no `guildId: \"...\"` to replace" : "the config has more than one `guildId` to choose from"
5104
+ };
5105
+ const { start, end } = spans[0];
5106
+ try {
5107
+ await writeFile(filepath, `${text.slice(0, start)}${id}${text.slice(end)}`, "utf8");
5108
+ } catch (err) {
5109
+ return {
5110
+ written: false,
5111
+ reason: `could not write ${filepath} (${errorMessage(err)})`
5112
+ };
5113
+ }
5114
+ return { written: true };
5115
+ }
5116
+ //#endregion
5117
+ //#region src/commands/notifications-create-server/notifications-create-server.ts
5118
+ /**
5119
+ * `holocron notifications create-server` — makes the server a layout describes, from nothing.
5120
+ *
5121
+ * A bot can create a server (while it is in few of them), and a server it creates already has it as a member,
5122
+ * so there is no invite step for the bot. The bot owns it at first, applies the whole layout (it can, as owner),
5123
+ * then invites the person who should own it, waits for them to join, and hands the server over. The new server
5124
+ * id is written into the config so every other command finds it.
5125
+ */
5126
+ async function runNotificationsCreateServer(input) {
5127
+ /* v8 ignore next -- the real console is only used outside tests, which inject a printer */
5128
+ const print = input.print ?? ((line) => console.log(line));
5129
+ /* v8 ignore next -- the real logger is only used outside tests */
5130
+ const logger = input.logger ?? getLogger();
5131
+ /* v8 ignore next -- the real loader is only built outside tests, which always inject one */
5132
+ const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
5133
+ await loader.load();
5134
+ assertPluginsResolvable(loader, "notifications create-server");
5135
+ const dryRun = input.context.dryRun ?? false;
5136
+ const sleep = input.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
5137
+ const refuse = (message, reason = message) => {
5138
+ print(` ${style.fail(message)}`);
5139
+ print("");
5140
+ print(style.header("0 ok, 1 fail, 0 skipped"));
5141
+ logger.warn({ reason }, "notifications create-server");
5142
+ return {
5143
+ status: "fail",
5144
+ message
5145
+ };
5146
+ };
5147
+ let notifications;
5148
+ try {
5149
+ notifications = pickServerCreator(notificationProviders(loader), input.provider);
5150
+ } catch (err) {
5151
+ return refuse(errorMessage(err));
5152
+ }
5153
+ if (!input.resume && !input.name?.trim()) return refuse("the server needs a name: pass --name");
5154
+ if (!/^\S{1,100}$/.test(input.owner)) return refuse("--owner is the new owner's member id on the provider (no spaces)");
5155
+ const layout = notifications.layout;
5156
+ const inviteChannel = layout?.server?.systemChannel ?? layout?.server?.rulesChannel ?? layout?.categories?.flatMap((c) => c.channels ?? [])[0]?.name;
5157
+ if (!inviteChannel) return refuse("the layout has no channel to invite the owner through");
5158
+ if (!input.resume) {
5159
+ if (((layout.categories ?? []).some((c) => (c.channels ?? []).some((ch) => ch.webhook)) || (layout.roles ?? []).some((r) => r.secret)) && !loader.has("secrets")) return refuse("no server was created: the layout stores webhook URLs or role ids, which need a `secrets` capability — add a `secrets` provider");
5160
+ /* v8 ignore next -- tests inject setup */
5161
+ const preview = await (input.runSetup ?? runNotificationsSetup)({
5162
+ loaded: input.loaded,
5163
+ context: {
5164
+ ...input.context,
5165
+ dryRun: true
5166
+ },
5167
+ loader,
5168
+ preloaded: true,
5169
+ print: () => {},
5170
+ logger,
5171
+ provider: notifications.providerName
5172
+ });
5173
+ if (preview.status === "fail") return refuse(`no server was created: the layout cannot be applied (${preview.message ?? preview.failures[0]?.message ?? "see `holocron notifications setup --dry-run`"})`);
5174
+ }
5175
+ if (dryRun) {
5176
+ const plan = input.resume ? `would check the layout is applied to the server in the config, invite member ${input.owner} through #${inviteChannel}, wait for them to join, and hand the server over` : `would create the server "${input.name}", apply the layout, invite member ${input.owner} through #${inviteChannel}, wait for them to join, hand the server over, and write its id into ${input.loaded.filepath}`;
5177
+ print(` ${style.skip(plan)}`);
5178
+ print("");
5179
+ print(style.header("0 ok, 0 fail, 1 skipped"));
5180
+ return { status: "dry-run" };
5181
+ }
5182
+ const lock = await lockConfig(input.loaded.filepath);
5183
+ if (!lock) return refuse(`another create-server run holds ${input.loaded.filepath}.create-server.lock; wait for it, or delete that file if no run is in progress`);
5184
+ const report = { status: "ok" };
5185
+ let ok = 0;
5186
+ const step = (line) => {
5187
+ print(` ${style.success(line)}`);
5188
+ ok++;
5189
+ };
5190
+ try {
5191
+ let serverId = "the server in the config";
5192
+ if (!input.resume) {
5193
+ const made = await notifications.createServer({
5194
+ name: input.name,
5195
+ ...input.force ? { force: true } : {}
5196
+ });
5197
+ serverId = made.id;
5198
+ report.serverId = made.id;
5199
+ step(`created the server "${made.name}" (${made.id})`);
5200
+ const written = await writeGuildId(input.loaded.filepath, made.id);
5201
+ report.configUpdated = written.written;
5202
+ if (written.written) step(`wrote the server id into ${input.loaded.filepath}`);
5203
+ else print(` ${style.fail(`could not update the config: ${written.reason}. Set guildId to ${made.id} by hand.`)}`);
5204
+ } else if (notifications.serverOwner) {
5205
+ const owner = await notifications.serverOwner();
5206
+ if (!owner.isBot) return refuse("the server in the config is not owned by the bot, so there is nothing to hand over; check `guildId` names the server this run created");
5207
+ if (input.name && owner.name !== void 0 && owner.name !== input.name) return refuse(`the server in the config is called "${owner.name}", not "${input.name}"; set \`guildId\` to the server this run created`);
5208
+ }
5209
+ if ((await (input.runSetup ?? runNotificationsSetup)({
5210
+ loaded: input.loaded,
5211
+ context: input.context,
5212
+ loader,
5213
+ preloaded: true,
5214
+ print,
5215
+ logger,
5216
+ provider: notifications.providerName
5217
+ })).status === "fail") return refuse(`applying the layout to ${serverId} failed; fix it and run \`holocron notifications setup\`, then \`create-server --resume\` (the bot still owns the server)`);
5218
+ ok++;
5219
+ const invite = await notifications.inviteLink(inviteChannel);
5220
+ report.invite = invite;
5221
+ step(`invite for member ${input.owner} (one use, valid for a day): ${invite}`);
5222
+ const waitMs = input.waitMs ?? 9e5;
5223
+ const pollMs = input.pollMs ?? 5e3;
5224
+ print(` ${style.skip(`waiting for member ${input.owner} to join (up to ${Math.round(waitMs / 6e4)} minutes)…`)}`);
5225
+ let waited = 0;
5226
+ while (!await notifications.hasMember(input.owner)) {
5227
+ if (waited >= waitMs) return refuse(`member ${input.owner} did not join in time; the server is ready and still owned by the bot. Open the invite, then run \`holocron notifications create-server --resume --owner ${input.owner}\``);
5228
+ await sleep(pollMs);
5229
+ waited += pollMs;
5230
+ }
5231
+ step(`member ${input.owner} joined`);
5232
+ try {
5233
+ await notifications.transferServer(input.owner);
5234
+ } catch (err) {
5235
+ if ((await notifications.serverOwner?.().catch(() => void 0))?.id !== input.owner) throw err;
5236
+ }
5237
+ step(`handed the server to member ${input.owner}`);
5238
+ } catch (err) {
5239
+ return refuse(describeProviderError(err), logReason(err));
5240
+ } finally {
5241
+ await lock.release();
5242
+ }
5243
+ print("");
5244
+ print(style.header(`${ok} ok, 0 fail, 0 skipped`));
5245
+ logger.info({ serverId: report.serverId }, "notifications create-server");
5246
+ return report;
5247
+ }
5248
+ //#endregion
4979
5249
  //#region src/commands/npm-bump-versions/npm-bump-versions.ts
4980
5250
  async function runNpmBumpVersions(input) {
4981
5251
  const print = input.print ?? ((line) => console.log(line));
@@ -11114,14 +11384,14 @@ const COMMAND_REGISTRY = [
11114
11384
  },
11115
11385
  {
11116
11386
  name: "doctor notifications",
11117
- description: "Check the layout against the server and the secrets store, step by step (read-only unless --deliver posts test messages)",
11387
+ description: "Check the layout against the server and the secrets store, step by step (a full run leaves one test post in the test channel; --built-only posts nothing unless --deliver)",
11118
11388
  positionals: [],
11119
11389
  options: [{
11120
11390
  key: "deliver",
11121
11391
  flag: "--deliver",
11122
11392
  type: "confirm",
11123
11393
  default: false,
11124
- message: "Also post a test message through every channel's webhook (it removes itself)?"
11394
+ message: "Post a test message through every channel's webhook (each removes itself)?"
11125
11395
  }],
11126
11396
  supportsDryRun: false
11127
11397
  },
@@ -11131,6 +11401,41 @@ const COMMAND_REGISTRY = [
11131
11401
  positionals: [],
11132
11402
  supportsDryRun: true
11133
11403
  },
11404
+ {
11405
+ name: "notifications create-server",
11406
+ description: "Create the server the layout describes, apply it, invite its owner and hand it over",
11407
+ positionals: [],
11408
+ options: [
11409
+ {
11410
+ key: "name",
11411
+ flag: "--name",
11412
+ type: "input",
11413
+ message: "What the new server is called (blank when resuming):"
11414
+ },
11415
+ {
11416
+ key: "owner",
11417
+ flag: "--owner",
11418
+ type: "input",
11419
+ required: true,
11420
+ message: "Member id of the person who will own it:"
11421
+ },
11422
+ {
11423
+ key: "force",
11424
+ flag: "--force",
11425
+ type: "confirm",
11426
+ default: false,
11427
+ message: "The config already names a server: create another and replace its id?"
11428
+ },
11429
+ {
11430
+ key: "resume",
11431
+ flag: "--resume",
11432
+ type: "confirm",
11433
+ default: false,
11434
+ message: "Finish an earlier run (the server exists): invite the owner and hand it over?"
11435
+ }
11436
+ ],
11437
+ supportsDryRun: true
11438
+ },
11134
11439
  {
11135
11440
  name: "notifications link",
11136
11441
  description: "Link your server account to your GitHub account by signing in with the provider",
@@ -11982,7 +12287,7 @@ try {
11982
12287
  }).command("doctor", "Load the config and run a smoke check against every provider", (y) => y.option("repo", {
11983
12288
  type: "string",
11984
12289
  describe: "Repo coords (\"owner/name\"). Defaults to plugin-specific resolution."
11985
- }).command("notifications", "Check the layout against the server and the secrets store, step by step (read-only unless --deliver posts test messages)", (y) => y.option("scope", {
12290
+ }).command("notifications", "Check the layout against the server and the secrets store, step by step (a full run leaves one test post in the test channel; --built-only posts nothing unless --deliver)", (y) => y.option("scope", {
11986
12291
  type: "string",
11987
12292
  describe: "Where the layout's secrets live: \"repo\", \"env=<name>\" or \"org=<name>\" (default: the org)"
11988
12293
  }).option("provider", {
@@ -11995,7 +12300,7 @@ try {
11995
12300
  }).option("deliver", {
11996
12301
  type: "boolean",
11997
12302
  default: false,
11998
- describe: "Also post a test message through every channel's webhook, read it back and remove it"
12303
+ describe: "Post a test message through every channel's webhook, read it back and remove it (works with --built-only)"
11999
12304
  }), async (argv) => {
12000
12305
  const tokens = tokenContext(argv.token);
12001
12306
  if (!tokens) return;
@@ -12744,6 +13049,43 @@ try {
12744
13049
  ...argv.scope ? { scope: parseScope(argv.scope) } : {},
12745
13050
  ...argv.provider ? { provider: argv.provider } : {}
12746
13051
  })).status === "fail") process.exitCode = 1;
13052
+ }).command("create-server", "Create the server the layout describes, apply it, invite its owner and hand it over", (y) => y.option("name", {
13053
+ type: "string",
13054
+ describe: "What the new server is called (not needed with --resume)"
13055
+ }).option("owner", {
13056
+ type: "string",
13057
+ demandOption: true,
13058
+ describe: "The member id (on the provider) who will own the server once they have joined"
13059
+ }).option("provider", {
13060
+ type: "string",
13061
+ describe: "Which notifications provider, when several can create a server"
13062
+ }).option("force", {
13063
+ type: "boolean",
13064
+ default: false,
13065
+ describe: "Create another server although the config already names one, and replace its id"
13066
+ }).option("resume", {
13067
+ type: "boolean",
13068
+ default: false,
13069
+ describe: "The server exists: skip creating and applying, and finish the hand-over"
13070
+ }), async (argv) => {
13071
+ const tokens = tokenContext(argv.token);
13072
+ if (!tokens) return;
13073
+ const loaded = await loadConfig(argv.cwd);
13074
+ applyResolvedConfig(argv, loaded.resolved);
13075
+ if ((await runNotificationsCreateServer({
13076
+ loaded,
13077
+ context: {
13078
+ repoRoot: argv.cwd,
13079
+ dryRun: argv.dryRun,
13080
+ ...tokens,
13081
+ org: resolveOrg(argv, loaded.resolved)
13082
+ },
13083
+ owner: argv.owner,
13084
+ ...argv.name ? { name: argv.name } : {},
13085
+ ...argv.provider ? { provider: argv.provider } : {},
13086
+ ...argv.force ? { force: true } : {},
13087
+ ...argv.resume ? { resume: true } : {}
13088
+ })).status === "fail") process.exitCode = 1;
12747
13089
  }).command("link", "Link your server account to your GitHub account by signing in with the provider", (y) => y.option("provider", {
12748
13090
  type: "string",
12749
13091
  describe: "Which notifications provider, when several can sign members in"