@davidbyoung/software-factory 0.1.7 → 0.1.9

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.
Files changed (63) hide show
  1. package/README.md +2 -0
  2. package/dist/agent/claude-code.mjs +15 -21
  3. package/dist/board.d.mts +20 -3
  4. package/dist/board.mjs +126 -38
  5. package/dist/cli.mjs +75 -9
  6. package/dist/code-host/github-setup.mjs +2 -2
  7. package/dist/code-host/github.mjs +4 -0
  8. package/dist/code-host/types.d.mts +2 -0
  9. package/dist/columns-suggest.d.mts +0 -1
  10. package/dist/columns-suggest.mjs +2 -8
  11. package/dist/commands.d.mts +2 -0
  12. package/dist/commands.mjs +22 -11
  13. package/dist/config.d.mts +12 -0
  14. package/dist/config.mjs +62 -11
  15. package/dist/doctor.d.mts +9 -1
  16. package/dist/doctor.mjs +209 -20
  17. package/dist/explain.d.mts +5 -0
  18. package/dist/explain.mjs +29 -0
  19. package/dist/init.d.mts +2 -0
  20. package/dist/init.mjs +143 -13
  21. package/dist/lib/color.d.mts +11 -0
  22. package/dist/lib/color.mjs +15 -0
  23. package/dist/npmrc.d.mts +29 -0
  24. package/dist/npmrc.mjs +98 -0
  25. package/dist/preset-commands.d.mts +2 -2
  26. package/dist/preset-commands.mjs +20 -24
  27. package/dist/preset.d.mts +4 -0
  28. package/dist/preset.mjs +13 -2
  29. package/dist/runner/github-actions.mjs +47 -10
  30. package/dist/runner/types.d.mts +13 -0
  31. package/dist/setup.d.mts +6 -1
  32. package/dist/site.d.mts +3 -0
  33. package/dist/site.mjs +8 -1
  34. package/dist/status.d.mts +5 -2
  35. package/dist/status.mjs +13 -22
  36. package/dist/sync.d.mts +14 -1
  37. package/dist/sync.mjs +83 -7
  38. package/dist/ticket-fields.d.mts +84 -0
  39. package/dist/ticket-fields.mjs +374 -0
  40. package/dist/ticket.mjs +8 -7
  41. package/dist/tickets/github-setup.mjs +1 -1
  42. package/dist/tickets/github.mjs +69 -0
  43. package/dist/tickets/index.d.mts +8 -1
  44. package/dist/tickets/index.mjs +67 -7
  45. package/dist/tickets/types.d.mts +27 -1
  46. package/dist/tickets/types.mjs +4 -0
  47. package/dist/tools.d.mts +1 -1
  48. package/docs/cli.md +44 -10
  49. package/docs/configuration.md +78 -25
  50. package/docs/design.md +10 -0
  51. package/docs/developing.md +49 -18
  52. package/docs/existing-repo.md +137 -8
  53. package/docs/github/by-hand.md +4 -0
  54. package/docs/github/reference.md +5 -0
  55. package/docs/github/setup.md +146 -8
  56. package/docs/limitations.md +0 -3
  57. package/docs/presets.md +5 -9
  58. package/docs/quick-start.md +3 -3
  59. package/docs/skills.md +3 -1
  60. package/docs/updating.md +3 -3
  61. package/package.json +4 -2
  62. package/settings.schema.json +68 -11
  63. package/skills/factory-deps/SKILL.md +4 -0
package/dist/init.mjs CHANGED
@@ -14,10 +14,12 @@ import { isMap, parseDocument } from "yaml";
14
14
  import { builtOf, secretSteps, TOOLS, } from "./tools.mjs";
15
15
  import { NeedsScopeError } from "./code-host/types.mjs";
16
16
  import { columnsOf, fieldNamesOf, filesDeps, parseSettings, resolveFiles, POLL_MINUTES, repoRoot, SETTINGS_FILE, SettingsError, } from "./config.mjs";
17
- import { checks as doctorChecks, doctorDeps, line } from "./doctor.mjs";
17
+ import { colorOn, painter } from "./lib/color.mjs";
18
+ import { checks as doctorChecks, doctorDeps, printChecks } from "./doctor.mjs";
18
19
  import { branchDeps, needDefaultBranch, NoDefaultBranch, } from "./lib/default-branch.mjs";
19
20
  import { hasCommand, noTerminal } from "./lib/has-command.mjs";
20
21
  import { DEFAULT_RUNNER } from "./runner/index.mjs";
22
+ import { addressOf, firstRefusal, NPMRC, npmrcAt, } from "./npmrc.mjs";
21
23
  import { listed } from "./lib/listed.mjs";
22
24
  import { neededSecrets, PART_TEXT, PARTS, partsOn, resolveParts, SIGNING_KEY, } from "./parts.mjs";
23
25
  import { CONTEXT as REVIEW_VERDICT } from "./review-verdict.mjs";
@@ -25,12 +27,13 @@ import { RULE } from "./setup.mjs";
25
27
  import { differences, PACKAGE, plan as syncPlan } from "./sync.mjs";
26
28
  import { DEFAULT_COLUMNS, STATE_KEYS, sameName } from "./lib/work-status.mjs";
27
29
  import { askReady, suggestColumns } from "./columns-suggest.mjs";
30
+ import { FACTORY_FIELDS, suggestFields } from "./ticket-fields.mjs";
28
31
  const SIGNING_TITLE = "software factory builds";
29
32
  /** Where each release's poller image is published. */
30
33
  const POLLER_IMAGE = "ghcr.io/davidbyoung/software-factory-poller";
31
34
  /** A month of runs at each interval the scheduled poller allows. */
32
35
  const RUNS_A_MONTH = (minutes) => (30 * 24 * 60) / minutes;
33
- const AGAIN = "Run npx --no-install factory init again to add it.";
36
+ const AGAIN = "Run factory init again to add it.";
34
37
  /** The columns and fields the board sync uses: the settings' names where
35
38
  * they rename one, and none for one they set to none. */
36
39
  function boardShape(s) {
@@ -138,8 +141,15 @@ export async function main(_argv, d) {
138
141
  ? `${tools[choice[kind]].label}, from your settings`
139
142
  : "chosen below";
140
143
  };
144
+ const npmrc = npmrcAt(d.root);
141
145
  d.out(`Setting up the software factory for ${repository}`);
142
146
  d.out("");
147
+ if (!agent.agent.installed(d.hasCommand)) {
148
+ d.out(`The factory runs in a coding agent, and ${agent.label} is not installed.`);
149
+ d.out("Install it and run factory init again.");
150
+ d.out("Nothing changed.");
151
+ return 1;
152
+ }
143
153
  d.out("Found");
144
154
  const row = (label, text) => d.out(` ${label.padEnd(14)} ${text}`);
145
155
  row("Code host", `${d.tools.codeHost[found.codeHost].label} (from your git remote)`);
@@ -147,11 +157,18 @@ export async function main(_argv, d) {
147
157
  row("Coding agent", agent.setup.found?.({ hasCommand: d.hasCommand }) ?? agent.label);
148
158
  row("Cloud builds", shown("runner"));
149
159
  row("package.json", hasPackage ? "yes" : "none, so a private one will be created");
160
+ if (npmrc.names.length)
161
+ row(NPMRC, `reads ${npmrc.names.join(", ")}`);
150
162
  row("Settings", settingsText === null ? "none yet" : SETTINGS_FILE);
151
163
  row("Board", settings?.tickets.board != null
152
164
  ? `${settings.tickets.board}, from your settings`
153
165
  : "none yet");
154
166
  d.out("");
167
+ const refused = firstRefusal(npmrc);
168
+ if (refused) {
169
+ d.out(refused);
170
+ return 1;
171
+ }
155
172
  const pick = async (kind, question) => {
156
173
  const tools = d.tools[kind];
157
174
  if (only(tools))
@@ -178,14 +195,22 @@ export async function main(_argv, d) {
178
195
  hasCommand: d.hasCommand,
179
196
  opened: { codeHost, runner, tickets },
180
197
  });
181
- let secrets;
198
+ let own;
199
+ let npm;
200
+ // A secret the organization shares with the repository counts as set.
201
+ const isOrganization = await codeHost.ownerIsOrganization().catch(() => true);
202
+ let shared = [];
182
203
  try {
183
- secrets = await runner.secretNames();
204
+ own = await runner.secretNames();
205
+ if (isOrganization)
206
+ shared = await runner.organizationSecretNames().catch(() => []);
207
+ npm = await npmSecrets(npmrc, runner, codeHost, isOrganization);
184
208
  }
185
209
  catch (e) {
186
210
  d.out(`Could not reach the code host: ${message(e)}`);
187
211
  return 1;
188
212
  }
213
+ const secrets = [...own, ...shared];
189
214
  const isSet = (n) => secrets.includes(n);
190
215
  const cloudNeeds = secretSteps(d.tools, context(["cloud"])).flatMap((s) => s.step.needs.filter((n) => n.part === "cloud"));
191
216
  const before = partsOn(settings, secrets, cloudNeeds);
@@ -211,7 +236,7 @@ export async function main(_argv, d) {
211
236
  const chooseBoard = async (offerNew) => {
212
237
  const existing = boardOps ? await boardOps.list() : [];
213
238
  if (!offerNew && existing.length === 0) {
214
- d.out("No board to use instead: create one on the code host, then run npx --no-install factory init again.");
239
+ d.out("No board to use instead: create one on the code host, then run factory init again.");
215
240
  return null;
216
241
  }
217
242
  const choice = await d.ask.select("Which board?", [
@@ -287,7 +312,6 @@ export async function main(_argv, d) {
287
312
  out: d.out,
288
313
  agent: agent.agent,
289
314
  label: agent.label,
290
- hasCommand: d.hasCommand,
291
315
  }, {
292
316
  board,
293
317
  columns: names,
@@ -301,6 +325,34 @@ export async function main(_argv, d) {
301
325
  else if (asksReady && settings)
302
326
  readyColumn = await askReady({ ask: d.ask, out: d.out }, { columns: names, current: columnsOf(settings) });
303
327
  }
328
+ // The factory fields a refined ticket has: the coding agent suggests
329
+ // which of the tickets' text fields holds each, when the settings name
330
+ // none of the four.
331
+ let fieldLines = [];
332
+ if (tickets.fields &&
333
+ !FACTORY_FIELDS.some((f) => doc.hasIn(["tickets", "fields", f.key]))) {
334
+ let text;
335
+ try {
336
+ text = (await tickets.fields.list()).filter((f) => f.text);
337
+ }
338
+ catch (e) {
339
+ d.out(`Could not read ${repository}'s ticket fields: ${message(e)}`);
340
+ d.out("Nothing changed.");
341
+ return 1;
342
+ }
343
+ if (text.length) {
344
+ const got = await suggestFields({ ask: d.ask, out: d.out, agent: agent.agent, label: agent.label }, {
345
+ repository,
346
+ fields: text,
347
+ plainText: tickets.fields.plainText
348
+ ? d.tools.tickets[chosen.tickets].label
349
+ : null,
350
+ });
351
+ if (got === 1)
352
+ return 1;
353
+ fieldLines = got;
354
+ }
355
+ }
304
356
  // The settings as they will stand, keeping every other key and comment.
305
357
  if (!doc.has("version"))
306
358
  doc.set("version", 2);
@@ -315,13 +367,18 @@ export async function main(_argv, d) {
315
367
  doc.setIn(["tickets", "board"], board);
316
368
  for (const [key, name] of columnLines)
317
369
  doc.setIn(["tickets", "columns", key], name);
370
+ for (const [key, name] of fieldLines)
371
+ doc.setIn(["tickets", "fields", key], name);
318
372
  if (readyColumn === null)
319
373
  remove(doc, ["tickets", "columns", "ready"]);
320
374
  else if (readyColumn !== undefined)
321
375
  doc.setIn(["tickets", "columns", "ready"], readyColumn);
322
- if (!parts.has("board"))
323
- for (const key of ["board", "columns", "fields"])
376
+ if (!parts.has("board")) {
377
+ for (const key of ["board", "columns"])
324
378
  remove(doc, ["tickets", key]);
379
+ for (const key of ["session", "runs-in", "cost"])
380
+ remove(doc, ["tickets", "fields", key]);
381
+ }
325
382
  if (parts.has("from-board"))
326
383
  doc.setIn(["builds", "trigger"], trigger);
327
384
  else if (before.has("from-board"))
@@ -357,7 +414,13 @@ export async function main(_argv, d) {
357
414
  // you choose to replace them.
358
415
  const steps = secretSteps(d.tools, context(parts));
359
416
  const needed = neededSecrets(parts, steps);
360
- const alreadySet = [...new Set(needed.flatMap((n) => n.anyOf.filter(isSet)))];
417
+ const npmBothSet = npm.tokens.filter((n) => isSet(n) && npm.dependabot(n) === "set");
418
+ const alreadySet = [
419
+ ...new Set([
420
+ ...needed.flatMap((n) => n.anyOf.filter(isSet)),
421
+ ...npmBothSet,
422
+ ]),
423
+ ];
361
424
  let replace = false;
362
425
  if (alreadySet.length)
363
426
  replace = await d.ask.confirm(alreadySet.length === 1
@@ -372,11 +435,22 @@ export async function main(_argv, d) {
372
435
  }))
373
436
  .filter((a) => a.names.length > 0);
374
437
  const wantsKey = parts.has("signing") && (replace || !isSet(SIGNING_KEY));
438
+ const npmAsked = npm.tokens
439
+ .map((name) => {
440
+ const again = replace && npmBothSet.includes(name);
441
+ return {
442
+ name,
443
+ actions: again || !isSet(name),
444
+ dependabot: again || npm.dependabot(name) !== "set",
445
+ unseen: !again && npm.dependabot(name) === "unknown",
446
+ };
447
+ })
448
+ .filter((a) => a.actions || a.dependabot);
375
449
  const stillRead = new Set(needed.flatMap((n) => n.anyOf));
376
450
  const deletable = [
377
451
  ...new Set(neededSecrets(new Set(removed), secretSteps(d.tools, context(removed)))
378
452
  .flatMap((n) => n.anyOf)
379
- .filter((n) => isSet(n) && !stillRead.has(n))),
453
+ .filter((n) => own.includes(n) && !stillRead.has(n))),
380
454
  ];
381
455
  // The plan.
382
456
  const newText = String(doc);
@@ -412,6 +486,8 @@ export async function main(_argv, d) {
412
486
  planRow("Board", `give board ${board} any of the factory's columns and fields it lacks`);
413
487
  if (toStore.length)
414
488
  planRow("Secrets", toStore.join(", "));
489
+ for (const a of npmAsked)
490
+ planRow("Secrets", `${a.name} ${forWhich(a)}`);
415
491
  if (parts.has("auto-merge"))
416
492
  planRow("Settings", "allow auto-merge on the repository");
417
493
  if (parts.has("review"))
@@ -496,6 +572,32 @@ export async function main(_argv, d) {
496
572
  break;
497
573
  }
498
574
  }
575
+ // The tokens .npmrc reads, each stored where it is missing.
576
+ for (const a of npmAsked) {
577
+ d.out("");
578
+ let prompt = "Paste the same token again (leave empty to do this later):";
579
+ if (a.actions && a.dependabot) {
580
+ d.out(`${NPMRC} reads ${a.name} for ${addressOf(npmrc, a.name)}.`);
581
+ d.out("The factory's workflows install with it. Use a token that can only read.");
582
+ prompt = "Paste it (leave empty to do this later):";
583
+ }
584
+ else if (!a.unseen)
585
+ d.out(a.actions
586
+ ? `${a.name} is set for Dependabot but not for Actions, and GitHub never shows a secret's value.`
587
+ : `${a.name} is set for Actions but not for Dependabot, and GitHub never shows a secret's value.`);
588
+ if (a.unseen)
589
+ d.out(`${a.name} isn't set for Dependabot on this repository, and only an organization admin can see whether your organization sets it. If it does, leave this empty.`);
590
+ const value = await d.ask.secret(prompt);
591
+ if (!value) {
592
+ d.out(`No ${a.name} stored. The factory's workflows fail at npm ci until it is. ${AGAIN}`);
593
+ continue;
594
+ }
595
+ if (a.actions)
596
+ await runner.setSecret(a.name, value);
597
+ if (a.dependabot)
598
+ await runner.setDependabotSecret(a.name, value);
599
+ d.out(`Stored ${a.name} ${forWhich(a)}.`);
600
+ }
499
601
  // The signing key.
500
602
  if (wantsKey) {
501
603
  const key = await d.keygen();
@@ -565,8 +667,8 @@ export async function main(_argv, d) {
565
667
  d.out("");
566
668
  d.out("Checks");
567
669
  const found2 = await d.checks();
568
- for (const c of found2)
569
- d.out(` ${line(c)}`);
670
+ for (const l of printChecks(found2, d.paint, 2))
671
+ d.out(l);
570
672
  return found2.some((c) => c.state === "fail") ? 1 : 0;
571
673
  }
572
674
  /** The questions, asked at the terminal. */
@@ -612,7 +714,7 @@ export async function run(argv) {
612
714
  }
613
715
  },
614
716
  tools: TOOLS,
615
- sync: async () => (await import("./sync.mjs")).run([]),
717
+ sync: async () => (await import("./sync.mjs")).run([], false),
616
718
  // The settings are not written yet, so the code host asked is the one
617
719
  // setup has just opened, not the one a settings file names.
618
720
  syncChanges: async (text, host) => {
@@ -655,6 +757,7 @@ export async function run(argv) {
655
757
  }
656
758
  },
657
759
  checks: () => doctorChecks(doctorDeps(root)),
760
+ paint: painter(colorOn()),
658
761
  packageName: manifest.name,
659
762
  packageVersion: manifest.version,
660
763
  };
@@ -673,3 +776,30 @@ export async function run(argv) {
673
776
  throw e;
674
777
  }
675
778
  }
779
+ /** The tokens `.npmrc` reads, and whether each is set for Dependabot. */
780
+ async function npmSecrets(npmrc, runner, codeHost, isOrganization) {
781
+ const tokens = npmrc.names.filter((n) => n !== "GITHUB_TOKEN");
782
+ if (!tokens.length)
783
+ return { tokens, dependabot: () => "set" };
784
+ const own = await runner.dependabotSecretNames();
785
+ const organization = isOrganization && tokens.some((n) => !own.includes(n))
786
+ ? await runner.organizationDependabotSecretNames(await codeHost.isPrivate())
787
+ : [];
788
+ return {
789
+ tokens,
790
+ dependabot: (name) => own.includes(name)
791
+ ? "set"
792
+ : organization === null
793
+ ? isOrganization
794
+ ? "unknown"
795
+ : "missing"
796
+ : organization.includes(name)
797
+ ? "set"
798
+ : "missing",
799
+ };
800
+ }
801
+ const forWhich = (a) => a.actions && a.dependabot
802
+ ? "for Actions and for Dependabot"
803
+ : a.actions
804
+ ? "for Actions"
805
+ : "for Dependabot";
@@ -0,0 +1,11 @@
1
+ import { styleText } from "node:util";
2
+ export type StyleFormat = Parameters<typeof styleText>[0];
3
+ export type Paint = (format: StyleFormat, text: string) => string;
4
+ export declare const plain: Paint;
5
+ /** Whether output to `stream` is colored, by Node's own rule: a terminal
6
+ * unless NO_COLOR, NODE_DISABLE_COLORS, or TERM=dumb, or wherever
7
+ * FORCE_COLOR says. */
8
+ export declare function colorOn(stream?: NodeJS.WritableStream): boolean;
9
+ /** Paints when `on`. The decision is made once, by `colorOn`, so painting
10
+ * skips Node's stream check: with it, a test's piped output stays plain. */
11
+ export declare function painter(on: boolean): Paint;
@@ -0,0 +1,15 @@
1
+ import { styleText } from "node:util";
2
+ export const plain = (_format, text) => text;
3
+ /** Whether output to `stream` is colored, by Node's own rule: a terminal
4
+ * unless NO_COLOR, NODE_DISABLE_COLORS, or TERM=dumb, or wherever
5
+ * FORCE_COLOR says. */
6
+ export function colorOn(stream = process.stdout) {
7
+ return styleText("red", "x", { stream }) !== "x";
8
+ }
9
+ /** Paints when `on`. The decision is made once, by `colorOn`, so painting
10
+ * skips Node's stream check: with it, a test's piped output stays plain. */
11
+ export function painter(on) {
12
+ return on
13
+ ? (format, text) => styleText(format, text, { validateStream: false })
14
+ : plain;
15
+ }
@@ -0,0 +1,29 @@
1
+ export declare const NPMRC = ".npmrc";
2
+ export type SignIn = {
3
+ name: string;
4
+ key: string;
5
+ };
6
+ export type Npmrc = {
7
+ /** Each variable a sign-in line reads, once, in the order first read. */
8
+ names: string[];
9
+ signIns: SignIn[];
10
+ /** Each registry URL a `registry=` or `@scope:registry=` line names. */
11
+ registries: string[];
12
+ };
13
+ export declare function readNpmrc(text: string | null): Npmrc;
14
+ /** The `.npmrc` at the root, read; nothing when there is none. */
15
+ export declare function npmrcAt(root: string): Npmrc;
16
+ /** Why a name can't be set from a secret, or null when it can. */
17
+ export declare function refusal(name: string): string | null;
18
+ /** The first refusal among the names, or null. */
19
+ export declare const firstRefusal: (n: Npmrc) => string | null;
20
+ declare const bare: (url: string) => string;
21
+ /** The registry a sign-in line is for: the registry URL whose host and
22
+ * path its key starts with, the longest when several do, or else the
23
+ * key's own `//host/path/`. */
24
+ export declare function addressOf(n: Npmrc, name: string): string;
25
+ /** The registries Dependabot has to be told, the public one aside. */
26
+ export declare const privateRegistries: (n: Npmrc) => string[];
27
+ /** The registry `.npmrc` sends a package's scope to, or null. */
28
+ export declare function npmrcRegistry(text: string | null, pkg: string): string | null;
29
+ export { bare as bareRegistry };
package/dist/npmrc.mjs ADDED
@@ -0,0 +1,98 @@
1
+ // What the factory reads from the repository's own `.npmrc`: the variables
2
+ // its sign-in lines read, which the workflows set from secrets of the same
3
+ // names, and the registries it names, which Dependabot has to know.
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ export const NPMRC = ".npmrc";
7
+ const SYNC = "npx --no-install factory sync";
8
+ const PUBLIC_REGISTRY = "https://registry.npmjs.org/";
9
+ const SIGN_IN = /:(_authToken|_auth|_password|username)$/;
10
+ /** npm's own pattern (`@npmcli/config`'s `env-replace.js`): an odd run of
11
+ * backslashes before `${` makes it text. */
12
+ const VARIABLE = /(?<!\\)(\\*)\$\{([^${}?]+)(\?)?\}/g;
13
+ /** The key and value of each setting line, as npm's `ini` reads them. */
14
+ function entries(text) {
15
+ const out = [];
16
+ for (const raw of text.split(/\r?\n/)) {
17
+ const line = raw.trim();
18
+ if (!line || line.startsWith("#") || line.startsWith(";"))
19
+ continue;
20
+ const at = line.indexOf("=");
21
+ if (at < 0)
22
+ continue;
23
+ const key = line.slice(0, at).trim();
24
+ let value = line.slice(at + 1).trim();
25
+ if (/^(".*"|'.*')$/.test(value))
26
+ value = value.slice(1, -1);
27
+ out.push({ key, value });
28
+ }
29
+ return out;
30
+ }
31
+ /** The variables a value reads. */
32
+ function variables(value) {
33
+ const out = [];
34
+ for (const m of value.matchAll(VARIABLE))
35
+ if (m[1].length % 2 === 0)
36
+ out.push(m[2]);
37
+ return out;
38
+ }
39
+ export function readNpmrc(text) {
40
+ const found = { names: [], signIns: [], registries: [] };
41
+ if (!text)
42
+ return found;
43
+ for (const { key, value } of entries(text)) {
44
+ if (key === "registry" || /^@[^:]+:registry$/.test(key)) {
45
+ if (!found.registries.includes(value))
46
+ found.registries.push(value);
47
+ continue;
48
+ }
49
+ if (!SIGN_IN.test(key))
50
+ continue;
51
+ for (const name of variables(value)) {
52
+ found.signIns.push({ name, key });
53
+ if (!found.names.includes(name))
54
+ found.names.push(name);
55
+ }
56
+ }
57
+ return found;
58
+ }
59
+ /** The `.npmrc` at the root, read; nothing when there is none. */
60
+ export function npmrcAt(root) {
61
+ const path = join(root, NPMRC);
62
+ return readNpmrc(existsSync(path) ? readFileSync(path, "utf8") : null);
63
+ }
64
+ /** Why a name can't be set from a secret, or null when it can. */
65
+ export function refusal(name) {
66
+ if (name === "GITHUB_TOKEN")
67
+ return null;
68
+ if (name.startsWith("GITHUB_"))
69
+ return `${NPMRC} reads \${${name}} to sign in, and GitHub refuses a secret whose name starts with GITHUB_. Rename it in ${NPMRC}, then run: ${SYNC}`;
70
+ if (["HOME", "PATH", "CI"].includes(name) || /^(RUNNER|ACTIONS)_/.test(name))
71
+ return `${NPMRC} reads \${${name}} to sign in, and the runner sets ${name} for itself. Rename it in ${NPMRC}, then run: ${SYNC}`;
72
+ return null;
73
+ }
74
+ /** The first refusal among the names, or null. */
75
+ export const firstRefusal = (n) => n.names.map(refusal).find((r) => r !== null) ?? null;
76
+ const bare = (url) => url.replace(/^[a-z]+:/i, "").replace(/\/+$/, "");
77
+ /** The registry a sign-in line is for: the registry URL whose host and
78
+ * path its key starts with, the longest when several do, or else the
79
+ * key's own `//host/path/`. */
80
+ export function addressOf(n, name) {
81
+ const key = n.signIns.find((s) => s.name === name)?.key ?? "";
82
+ const at = key.replace(SIGN_IN, "");
83
+ const match = n.registries
84
+ .filter((r) => at === bare(r) || at.startsWith(`${bare(r)}/`))
85
+ .sort((a, b) => bare(b).length - bare(a).length)[0];
86
+ return match ?? at;
87
+ }
88
+ /** The registries Dependabot has to be told, the public one aside. */
89
+ export const privateRegistries = (n) => n.registries.filter((r) => bare(r) !== bare(PUBLIC_REGISTRY));
90
+ /** The registry `.npmrc` sends a package's scope to, or null. */
91
+ export function npmrcRegistry(text, pkg) {
92
+ if (!text || !pkg.startsWith("@"))
93
+ return null;
94
+ const scope = pkg.split("/")[0];
95
+ const found = entries(text).find((e) => e.key === `${scope}:registry`);
96
+ return found ? found.value : null;
97
+ }
98
+ export { bare as bareRegistry };
@@ -1,3 +1,4 @@
1
+ import { type Paint } from "./lib/color.mts";
1
2
  import { type Resolved } from "./config.mts";
2
3
  import type { Check } from "./setup.mts";
3
4
  export type PresetDeps = {
@@ -25,6 +26,7 @@ export type PresetDeps = {
25
26
  resolve: (own: string, choices: string | null) => Promise<Resolved>;
26
27
  write: (path: string, text: string | null) => void;
27
28
  read: (path: string) => string | null;
29
+ paint?: Paint;
28
30
  };
29
31
  /** A value as the summaries show it: a list's items joined, a plugin by its
30
32
  * name. */
@@ -34,8 +36,6 @@ export declare function installError(name: string, stderr: string, registry: str
34
36
  /** Whether a group in `.github/dependabot.yml` has the package as its only
35
37
  * pattern. */
36
38
  export declare function hasOwnGroup(text: string | null, pkg: string): Promise<boolean>;
37
- /** The registry `.npmrc` sends a package's scope to, or null. */
38
- export declare function npmrcRegistry(text: string | null, pkg: string): string | null;
39
39
  /** The lines `preset add` ends with for what Dependabot still needs. */
40
40
  export declare function nextLines(dependabot: string | null, npmrc: string | null, pkg: string): Promise<string[]>;
41
41
  export declare function add(argv: string[], d: PresetDeps): Promise<number>;
@@ -8,12 +8,14 @@
8
8
  // factory preset choose KEY PRESET
9
9
  // factory preset check
10
10
  // factory preset changes REF
11
+ import { colorOn, painter, plain } from "./lib/color.mjs";
11
12
  import { execFileSync, spawnSync } from "node:child_process";
12
13
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, } from "node:fs";
13
14
  import { STATUS_CODES } from "node:http";
14
15
  import { dirname, join, relative, sep } from "node:path";
15
16
  import { filesDeps, parseChoices, repoRoot, resolveFiles, SETTINGS_FILE, SettingsError, } from "./config.mjs";
16
17
  import { CHOICES_FILE, choicesText, findPackage, LOCK_FILE, OWN, PLUGIN_LISTS, presetFaults, PRESET_FILE, readLock, shipped, shipsText, splitName, stable, staleMessages, } from "./preset.mjs";
18
+ import { npmrcRegistry } from "./npmrc.mjs";
17
19
  const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
18
20
  const DEPENDABOT = ".github/dependabot.yml";
19
21
  // ---------------------------------------------------------------- Values
@@ -81,19 +83,21 @@ function valueInEffect(r, key) {
81
83
  return r.resolution.files.get(key)?.source;
82
84
  return getPath(r.resolution.raw, key.split("."));
83
85
  }
84
- function summary(head, groups, files) {
86
+ function summary(head, groups, files, paint) {
85
87
  const shown = groups.filter((g) => g.rows.length);
86
88
  const width = Math.max(0, ...shown.flatMap((g) => g.rows.map((r) => r.key.length))) + 3;
87
89
  return [
88
90
  head,
89
91
  "",
90
92
  ...shown.flatMap((g) => [
91
- ` ${g.title}`,
93
+ ` ${paint("bold", g.title)}`,
92
94
  ...g.rows.map((r) => ` ${r.key.padEnd(width)}${r.text}`),
93
95
  ]),
94
96
  ...(files.length ? ["", ...files.map((f) => ` ${f}`)] : []),
95
97
  ];
96
98
  }
99
+ /** An `OLD → NEW` row: the old value dim, the new one bold. */
100
+ const change = (paint, was, now) => `${paint("dim", was)} → ${paint("bold", now)}`;
97
101
  /** A question asked until the answer is one of `options`. */
98
102
  async function choose(d, question, options) {
99
103
  for (;;) {
@@ -246,18 +250,6 @@ export async function hasOwnGroup(text, pkg) {
246
250
  g.patterns.length === 1 &&
247
251
  g.patterns[0] === pkg));
248
252
  }
249
- /** The registry `.npmrc` sends a package's scope to, or null. */
250
- export function npmrcRegistry(text, pkg) {
251
- if (!text || !pkg.startsWith("@"))
252
- return null;
253
- const scope = pkg.split("/")[0];
254
- for (const line of text.split("\n")) {
255
- const m = /^\s*(@[^:\s]+):registry\s*=\s*(\S+)\s*$/.exec(line);
256
- if (m && m[1] === scope)
257
- return m[2];
258
- }
259
- return null;
260
- }
261
253
  const bare = (url) => url.replace(/\/+$/, "");
262
254
  /** The lines `preset add` ends with for what Dependabot still needs. */
263
255
  export async function nextLines(dependabot, npmrc, pkg) {
@@ -293,6 +285,7 @@ async function syncing(d, wroteChoices) {
293
285
  // ---------------------------------------------------------------- add
294
286
  const PAREN = "this preset";
295
287
  export async function add(argv, d) {
288
+ const paint = d.paint ?? plain;
296
289
  const name = argv.find((a) => !a.startsWith("--"));
297
290
  const yes = argv.includes("--yes");
298
291
  const dry = argv.includes("--dry-run");
@@ -302,7 +295,7 @@ export async function add(argv, d) {
302
295
  }
303
296
  const ownText = d.read(SETTINGS_FILE);
304
297
  if (ownText === null) {
305
- d.err(`${SETTINGS_FILE} is missing. Run: npx --no-install factory init`);
298
+ d.err(`${SETTINGS_FILE} is missing. Run: factory init`);
306
299
  return 1;
307
300
  }
308
301
  const own = (await loadYaml(ownText));
@@ -391,13 +384,13 @@ export async function add(argv, d) {
391
384
  continue;
392
385
  }
393
386
  if (list) {
394
- added.push({ key: list, text: `+ ${show(mine)}` });
387
+ added.push({ key: list, text: paint("green", `+ ${show(mine)}`) });
395
388
  continue;
396
389
  }
397
390
  const was = getPath(effNow, key.split("."));
398
391
  if (stable(was) === stable(mine))
399
392
  continue;
400
- replacesDefault.push({ key, text: `${show(was)} → ${show(mine)}` });
393
+ replacesDefault.push({ key, text: change(paint, show(was), show(mine)) });
401
394
  }
402
395
  for (const path of VALUE_LISTS) {
403
396
  const was = getPath(effNow, path.split("."));
@@ -408,7 +401,7 @@ export async function add(argv, d) {
408
401
  for (const item of is)
409
402
  if (!had.has(stable(item)) &&
410
403
  after.resolution.sources.get(`${path}[${stable(item)}]`)?.from === name)
411
- added.push({ key: path, text: `+ ${show(item)}` });
404
+ added.push({ key: path, text: paint("green", `+ ${show(item)}`) });
412
405
  }
413
406
  const locked = await lockFiles(d);
414
407
  const writes = [...after.resolution.files]
@@ -423,7 +416,7 @@ export async function add(argv, d) {
423
416
  rows,
424
417
  })),
425
418
  { title: `replaced by your ${SETTINGS_FILE}`, rows: yours },
426
- ], writes))
419
+ ], writes, paint))
427
420
  d.out(line);
428
421
  if (dry) {
429
422
  undo();
@@ -482,6 +475,7 @@ async function lockFiles(d) {
482
475
  }
483
476
  // ---------------------------------------------------------------- remove
484
477
  export async function remove(argv, d) {
478
+ const paint = d.paint ?? plain;
485
479
  const name = argv.find((a) => !a.startsWith("--"));
486
480
  const yes = argv.includes("--yes");
487
481
  const dry = argv.includes("--dry-run");
@@ -532,17 +526,17 @@ export async function remove(argv, d) {
532
526
  if (!after.resolution.sources.has(key))
533
527
  removed.push({
534
528
  key: path,
535
- text: `− ${show(JSON.parse(key.slice(path.length + 1, -1)))}`,
529
+ text: paint("red", `− ${show(JSON.parse(key.slice(path.length + 1, -1)))}`),
536
530
  });
537
531
  continue;
538
532
  }
539
533
  if (!nextSrc) {
540
534
  if (list)
541
- removed.push({ key: list, text: `− ${show(old)}` });
535
+ removed.push({ key: list, text: paint("red", `− ${show(old)}`) });
542
536
  else
543
537
  toDefault.push({
544
538
  key,
545
- text: `${show(old)} → ${show(getPath(effAfter, key.split(".")))}`,
539
+ text: change(paint, show(old), show(getPath(effAfter, key.split(".")))),
546
540
  });
547
541
  continue;
548
542
  }
@@ -551,7 +545,7 @@ export async function remove(argv, d) {
551
545
  continue;
552
546
  const row = {
553
547
  key: list ?? key,
554
- text: `${show(old)} → ${show(next)}, from ${nextSrc.from}`,
548
+ text: `${change(paint, show(old), show(next))}, from ${nextSrc.from}`,
555
549
  };
556
550
  if (src.state === "chosen") {
557
551
  chosenAgainst.push(row);
@@ -570,7 +564,7 @@ export async function remove(argv, d) {
570
564
  { title: "back to the default", rows: toDefault },
571
565
  { title: "back to another preset's value", rows: toOther },
572
566
  { title: "back to a value you chose against", rows: chosenAgainst },
573
- ], deletes))
567
+ ], deletes, paint))
574
568
  d.out(line);
575
569
  if (dry)
576
570
  return 0;
@@ -856,6 +850,7 @@ export async function changes(argv, d) {
856
850
  version: "",
857
851
  presets: [],
858
852
  hash: null,
853
+ npmrcVariables: [],
859
854
  settings: {},
860
855
  overridden: {},
861
856
  files: [],
@@ -1085,6 +1080,7 @@ export function presetDeps(root = repoRoot()) {
1085
1080
  out: (l) => console.log(l),
1086
1081
  err: (l) => console.error(l),
1087
1082
  terminal: Boolean(process.stdin.isTTY && process.stdout.isTTY),
1083
+ paint: painter(colorOn()),
1088
1084
  ask: async (question) => {
1089
1085
  const { createInterface } = await import("node:readline/promises");
1090
1086
  const rl = createInterface({
package/dist/preset.d.mts CHANGED
@@ -143,6 +143,8 @@ export type Lock = {
143
143
  version: string;
144
144
  }[];
145
145
  hash: string | null;
146
+ /** The variables `.npmrc`'s sign-in lines read at the last sync. */
147
+ npmrcVariables: string[];
146
148
  settings: Obj | null;
147
149
  overridden: Record<string, Replaced[]>;
148
150
  files: string[];
@@ -161,6 +163,8 @@ export type StaleDeps = {
161
163
  * undefined when there is no node_modules to look in. */
162
164
  installed: (pkg: string) => string | null | undefined;
163
165
  load: (t: string) => unknown;
166
+ /** The variables `.npmrc`'s sign-in lines read now. */
167
+ npmrcNames?: string[];
164
168
  };
165
169
  /** Why the lock is stale, the first of: missing, from an earlier release,
166
170
  * a settings file changed, a preset not installed, a preset at another