@venizia/vulcan 0.4.8 → 0.4.9-1

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 (179) hide show
  1. package/base/extensions/vulcan-guards.ts +48 -41
  2. package/base/hooks/antigravity-guards.ts +4 -3
  3. package/base/hooks/codex-guards.ts +17 -6
  4. package/base/hooks/guard-git.ts +8 -8
  5. package/base/hooks/guard-manifest.ts +5 -5
  6. package/base/hooks/guard-outside.ts +8 -8
  7. package/base/hooks/guard-package.ts +6 -6
  8. package/base/hooks/guard-remote-hosts.ts +14 -9
  9. package/base/hooks/guard-scripting.ts +6 -6
  10. package/base/hooks/guard-writes.ts +20 -11
  11. package/base/hooks/post-tool.ts +4 -3
  12. package/base/hooks/prompt-submit.ts +4 -3
  13. package/base/hooks/session-start.ts +5 -3
  14. package/base/hooks/stop.ts +4 -3
  15. package/base/hooks/subagent-start.ts +2 -2
  16. package/base/make/vulcan.mk +1 -4
  17. package/base/skills/build-a-feature/SKILL.md +1 -1
  18. package/base/skills/docs-update/SKILL.md +11 -5
  19. package/base/skills/docs-update/evals/evals.json +1 -1
  20. package/base/skills/docs-writing/SKILL.md +1 -1
  21. package/base/skills/plan-a-change/references/spec-card.md +1 -1
  22. package/base/skills/ship/SKILL.md +1 -1
  23. package/base/skills/visualize-work/SKILL.md +29 -6
  24. package/base/skills/visualize-work/references/spec.md +16 -5
  25. package/package.json +5 -6
  26. package/src/agents/atlas-block.ts +43 -43
  27. package/src/agents/codex-hooks.ts +55 -52
  28. package/src/agents/common/types.ts +1 -1
  29. package/src/agents/detect.ts +19 -16
  30. package/src/agents/exclude.ts +97 -98
  31. package/src/agents/hooks-json.ts +41 -43
  32. package/src/agents/local.ts +46 -43
  33. package/src/agents/prompt.ts +45 -42
  34. package/src/agents/render.ts +203 -201
  35. package/src/agents/resolve.ts +133 -134
  36. package/src/agents/table.ts +12 -8
  37. package/src/cli.ts +3 -1
  38. package/src/commands/add.command.ts +2 -2
  39. package/src/commands/agents.command.ts +11 -17
  40. package/src/commands/clean.command.ts +6 -6
  41. package/src/commands/doctor.command.ts +6 -4
  42. package/src/commands/help.command.ts +11 -9
  43. package/src/commands/init.command.ts +14 -8
  44. package/src/commands/preset.command.ts +2 -2
  45. package/src/commands/profile.command.ts +43 -50
  46. package/src/commands/sync.command.ts +109 -111
  47. package/src/commands/upgrade.command.ts +85 -78
  48. package/src/commands/visualize.command.ts +20 -5
  49. package/src/commands/x.command.ts +55 -50
  50. package/src/common/format.ts +23 -21
  51. package/src/common/index.ts +2 -0
  52. package/src/common/json.ts +8 -5
  53. package/src/common/layout-folder.ts +96 -111
  54. package/src/common/paths.ts +14 -12
  55. package/src/common/record.ts +7 -0
  56. package/src/common/text.ts +7 -0
  57. package/src/config/common/constants.ts +13 -1
  58. package/src/config/common/types.ts +8 -1
  59. package/src/config/loader.ts +53 -48
  60. package/src/config/packages.ts +17 -11
  61. package/src/config/schema.ts +54 -7
  62. package/src/create/add-app.ts +604 -493
  63. package/src/create/add-lib.ts +249 -242
  64. package/src/create/bunfig.ts +26 -23
  65. package/src/create/checks.ts +36 -34
  66. package/src/create/common/constants.ts +1 -0
  67. package/src/create/common/failure.ts +10 -0
  68. package/src/create/common/index.ts +2 -0
  69. package/src/create/common/preset-path.ts +11 -0
  70. package/src/create/common/types.ts +7 -2
  71. package/src/create/diff.ts +21 -23
  72. package/src/create/dockerignore.ts +26 -24
  73. package/src/create/files.ts +7 -5
  74. package/src/create/init-monorepo.ts +78 -80
  75. package/src/create/lib-preset.ts +62 -61
  76. package/src/create/manifest-json.ts +10 -4
  77. package/src/create/names.ts +217 -210
  78. package/src/create/next.ts +27 -24
  79. package/src/create/plan.ts +15 -12
  80. package/src/create/preset-diff.ts +415 -240
  81. package/src/create/preset-menu.ts +40 -34
  82. package/src/create/preset.ts +207 -194
  83. package/src/create/process.ts +80 -71
  84. package/src/create/scratch.ts +49 -48
  85. package/src/create/workspace.ts +423 -398
  86. package/src/doctor/checks.ts +1069 -998
  87. package/src/doctor/makefile.ts +17 -13
  88. package/src/doctor/runner.ts +88 -116
  89. package/src/doctor/skills.ts +97 -95
  90. package/src/doctor/tags.ts +44 -41
  91. package/src/hooks/codex-patch.ts +27 -24
  92. package/src/hooks/command-view.ts +44 -39
  93. package/src/hooks/common/constants.ts +0 -3
  94. package/src/hooks/common/types.ts +15 -1
  95. package/src/hooks/decision.ts +38 -42
  96. package/src/hooks/guard-git.ts +52 -50
  97. package/src/hooks/guard-manifest.ts +58 -55
  98. package/src/hooks/guard-outside.ts +109 -88
  99. package/src/hooks/guard-package.ts +86 -77
  100. package/src/hooks/guard-scripting.ts +20 -15
  101. package/src/hooks/guard-writes.ts +169 -111
  102. package/src/hooks/owner-reply.ts +128 -128
  103. package/src/hooks/post-tool.ts +94 -93
  104. package/src/hooks/project-guards.ts +93 -55
  105. package/src/hooks/project-tmp.ts +27 -24
  106. package/src/hooks/remote-hosts.ts +157 -149
  107. package/src/hooks/session-digest.ts +99 -95
  108. package/src/hooks/shell.ts +519 -500
  109. package/src/hooks/subagent-card.ts +11 -7
  110. package/src/hooks/trusted-scripts.ts +158 -80
  111. package/src/init/common/types.ts +1 -1
  112. package/src/init/scaffold.ts +137 -134
  113. package/src/local/clean.ts +39 -37
  114. package/src/local/format.ts +21 -17
  115. package/src/local/scan.ts +146 -140
  116. package/src/manifest/render.ts +127 -112
  117. package/src/owner/card.ts +51 -46
  118. package/src/owner/profile.ts +100 -96
  119. package/src/owner/reply-switch.ts +9 -6
  120. package/src/owner/shape.ts +72 -70
  121. package/src/owner/survey.ts +175 -164
  122. package/src/owner/view.ts +62 -59
  123. package/src/owner/violations.ts +119 -123
  124. package/src/router.ts +4 -1
  125. package/src/rules/base.ts +15 -11
  126. package/src/rules/common/types.ts +1 -1
  127. package/src/rules/parser.ts +39 -32
  128. package/src/rules/slots.ts +8 -6
  129. package/src/signals/claims.ts +30 -28
  130. package/src/signals/classify.ts +36 -33
  131. package/src/signals/loop.ts +39 -37
  132. package/src/signals/state.ts +80 -85
  133. package/src/skills/frontmatter.ts +28 -28
  134. package/src/sync/agent-files.ts +217 -199
  135. package/src/sync/agent-removal.ts +62 -68
  136. package/src/sync/atlas-block.ts +45 -43
  137. package/src/sync/base-rules.ts +32 -30
  138. package/src/sync/claude-launch.ts +74 -37
  139. package/src/sync/common/constants.ts +4 -0
  140. package/src/sync/common/index.ts +1 -0
  141. package/src/sync/common/symlink.ts +9 -0
  142. package/src/sync/common/types.ts +2 -2
  143. package/src/sync/exclude.ts +77 -69
  144. package/src/sync/local-choice.ts +50 -47
  145. package/src/sync/planner.ts +64 -68
  146. package/src/sync/prune.ts +52 -48
  147. package/src/sync/settings.ts +167 -168
  148. package/src/ui/capability.ts +12 -7
  149. package/src/ui/keyboard.ts +35 -33
  150. package/src/ui/prompt.ts +81 -77
  151. package/src/visualize/assets.ts +379 -195
  152. package/src/visualize/charts.ts +188 -176
  153. package/src/visualize/compare-css.ts +31 -0
  154. package/src/visualize/compare-render.ts +196 -0
  155. package/src/visualize/compare-schema.ts +81 -0
  156. package/src/visualize/compare-validate.ts +126 -0
  157. package/src/visualize/constants.ts +29 -3
  158. package/src/visualize/diagrams.ts +189 -174
  159. package/src/visualize/gate.ts +136 -0
  160. package/src/visualize/grid-span.ts +34 -0
  161. package/src/visualize/icons.ts +9 -4
  162. package/src/visualize/index.ts +2 -0
  163. package/src/visualize/kinds-css.ts +54 -0
  164. package/src/visualize/kinds-render.ts +698 -0
  165. package/src/visualize/kinds-schema.ts +148 -0
  166. package/src/visualize/kinds-validate.ts +186 -0
  167. package/src/visualize/labels-vi.ts +109 -0
  168. package/src/visualize/labels.ts +53 -0
  169. package/src/visualize/layout.ts +112 -92
  170. package/src/visualize/page.ts +140 -114
  171. package/src/visualize/render.ts +158 -114
  172. package/src/visualize/schema.ts +21 -1
  173. package/src/visualize/sections.ts +401 -309
  174. package/src/visualize/sources.ts +270 -0
  175. package/src/visualize/theme.ts +474 -0
  176. package/src/visualize/validate.ts +15 -5
  177. package/src/wiki/anchors.ts +39 -37
  178. package/src/wiki/command.ts +4 -4
  179. package/src/wiki/source-links.ts +49 -49
@@ -1,57 +1,34 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join, relative } from 'node:path';
3
3
  import { ExitCodes } from '../common/index.ts';
4
- import {
5
- describeFolders,
6
- LayoutKeys,
7
- layoutFoldersOf,
8
- layoutOverlapProblems,
9
- listedFoldersNote,
10
- withLayoutFolder,
11
- } from '../common/layout-folder.ts';
4
+ import { LayoutFolder, LayoutKeys } from '../common/layout-folder.ts';
12
5
  import type { ILayout } from '../common/layout-folder.ts';
13
- import { loadConfig, resolvePackages } from '../config/index.ts';
14
- import type { IProjectPackage, TResolvedConfig } from '../config/index.ts';
15
- import { readWorkspaceGlobs } from '../init/index.ts';
16
- import { addLibrary } from './add-lib.ts';
17
- import { runAppChecks } from './checks.ts';
18
- import { AppSides, AppsBlockProblems, CreateFlags } from './common/index.ts';
6
+ import { OFFICIAL_PRESETS, OfficialPresets } from '@venizia/vulcan-atlas';
7
+ import type { IOfficialPreset } from '@venizia/vulcan-atlas';
8
+ import { ConfigLoader, LibraryKinds, PackageKinds, ProjectPackages } from '../config/index.ts';
9
+ import type { IProjectPackage, TLibraryKind, TResolvedConfig } from '../config/index.ts';
10
+ import { ProjectScaffold } from '../init/index.ts';
11
+ import { LibraryScaffold } from './add-lib.ts';
12
+ import { AppChecks } from './checks.ts';
13
+ import { AddFailure, AppSides, AppsBlockProblems, CreateFlags } from './common/index.ts';
19
14
  import type { IAppsBlock, ILocatedPreset, IPresetSpec, TAppSide } from './common/index.ts';
20
- import { writeFile } from './files.ts';
21
- import { recordedPresetOf } from './lib-preset.ts';
22
- import { renderManifestJson } from './manifest-json.ts';
23
- import { menusAvailable, promptSelect } from '../ui/index.ts';
24
- import { askPresetSpec } from './preset-menu.ts';
25
- import { ABORTED, confirmWrite, planLines } from './plan.ts';
26
- import {
27
- askInTerminal,
28
- askScope,
29
- askWithPrompt,
30
- nameProblem,
31
- readFlag,
32
- readScope,
33
- resolveNames,
34
- SIDE_FIELDS,
35
- } from './names.ts';
36
- import { readExistingApps, renderNext } from './next.ts';
37
- import { copyPresetFiles, locatePreset, parsePresetSpec } from './preset.ts';
38
- import { isInstallSkipped, runBun } from './process.ts';
39
- import { installNpmPreset, withScratch } from './scratch.ts';
15
+ import { ProjectFile } from './files.ts';
16
+ import { LibPreset } from './lib-preset.ts';
17
+ import { ManifestJson } from './manifest-json.ts';
18
+ import { TerminalCapability, TerminalPrompt } from '../ui/index.ts';
19
+ import { PresetMenu } from './preset-menu.ts';
20
+ import { ABORTED, WritePlan } from './plan.ts';
21
+ import { askInTerminal, ProjectNames, SIDE_FIELDS } from './names.ts';
22
+ import { NextStep } from './next.ts';
23
+ import { Preset } from './preset.ts';
24
+ import { SubProcess } from './process.ts';
25
+ import { PresetScratch } from './scratch.ts';
40
26
  import {
41
- addAppBullet,
42
- checkPeers,
43
- filePresetWarning,
44
- parseAppsBlock,
45
- pickPort,
46
- planRootManifest,
47
- presetSpecOf,
48
- readCatalog,
49
- readPort,
50
- recordPreset,
51
- renderAppConcept,
52
- renderAppManifest,
53
- renderKnowledgeIndex,
54
- replaceAppsBlock,
27
+ AppsBlock,
28
+ PortRegistry,
29
+ PresetRecord,
30
+ WorkspaceDocs,
31
+ WorkspaceManifest,
55
32
  } from './workspace.ts';
56
33
 
57
34
  type TRootManifest = Record<string, unknown>;
@@ -62,12 +39,6 @@ const ROOT_HINT =
62
39
 
63
40
  const MISSING_API = `missing ${CreateFlags.API} <app> or ${CreateFlags.NO_API}`;
64
41
 
65
- const fail = (opts: { message: string }): number => {
66
- process.stderr.write(`vulcan add: ${opts.message}\n`);
67
-
68
- return ExitCodes.FAILURE;
69
- };
70
-
71
42
  /** The side the flags give away: a frontend flag, or only the backend folder; undefined when they do not say. */
72
43
  const sideNamedBy = (opts: { args: string[] }): TAppSide | undefined => {
73
44
  const frontend = [CreateFlags.FRONTEND_DIR, CreateFlags.API, CreateFlags.NO_API].some((flag) =>
@@ -91,7 +62,7 @@ const sideNamedBy = (opts: { args: string[] }): TAppSide | undefined => {
91
62
  const missingFlag = (opts: { args: string[]; layout: ILayout }): string | undefined => {
92
63
  const side = sideNamedBy({ args: opts.args });
93
64
 
94
- if (readFlag({ args: opts.args, flag: CreateFlags.APP }) === undefined) {
65
+ if (ProjectNames.readFlag({ args: opts.args, flag: CreateFlags.APP }) === undefined) {
95
66
  const kind = side === undefined ? '' : `${side} `;
96
67
 
97
68
  return `missing ${CreateFlags.APP} (Name of this ${kind}app) - names are never chosen for you`;
@@ -103,11 +74,14 @@ const missingFlag = (opts: { args: string[]; layout: ILayout }): string | undefi
103
74
 
104
75
  const folder = SIDE_FIELDS[side];
105
76
 
106
- const listed = layoutFoldersOf({ value: opts.layout[side] });
77
+ const listed = LayoutFolder.layoutFoldersOf({ value: opts.layout[side] });
107
78
 
108
79
  // One listed folder is the answer; none, or several, is for the flag to say.
109
- if (readFlag({ args: opts.args, flag: folder.flag }) === undefined && listed.length !== 1) {
110
- return `missing ${folder.flag} (${folder.question}${listed.length > 1 ? `; ${listedFoldersNote({ folders: listed })}` : ''}) - names are never chosen for you`;
80
+ if (
81
+ ProjectNames.readFlag({ args: opts.args, flag: folder.flag }) === undefined &&
82
+ listed.length !== 1
83
+ ) {
84
+ return `missing ${folder.flag} (${folder.question}${listed.length > 1 ? `; ${LayoutFolder.listedNote({ folders: listed })}` : ''}) - names are never chosen for you`;
111
85
  }
112
86
 
113
87
  const hasApi = opts.args.includes(CreateFlags.API) || opts.args.includes(CreateFlags.NO_API);
@@ -115,30 +89,97 @@ const missingFlag = (opts: { args: string[]; layout: ILayout }): string | undefi
115
89
  return side === AppSides.FRONTEND && !hasApi ? MISSING_API : undefined;
116
90
  };
117
91
 
118
- /** The two commands a project can run for this preset: what `add` prints when it is not told what to create. */
119
- const kindCommands = (opts: { presetValue: string }): string[] => [
120
- `bun x --no-install vulcan add --preset ${opts.presetValue} ${CreateFlags.APP} <name>`,
121
- `bun x --no-install vulcan add --preset ${opts.presetValue} ${CreateFlags.LIB} <name>`,
122
- ];
92
+ /** What `add` makes: an app, or one of the library kinds. */
93
+ type TAddKind = typeof PackageKinds.APP | TLibraryKind;
94
+
95
+ /** Per kind: the flag that names it and the words a menu and a message describe it with. */
96
+ const ADD_KINDS: Record<TAddKind, { flag: string; hint: string }> = {
97
+ [PackageKinds.APP]: { flag: CreateFlags.APP, hint: 'a runnable app' },
98
+ [LibraryKinds.LIB]: { flag: CreateFlags.LIB, hint: 'a library other apps import' },
99
+ [LibraryKinds.SHARED]: {
100
+ flag: CreateFlags.SHARED,
101
+ hint: 'a side-neutral package other apps import',
102
+ },
103
+ };
104
+
105
+ const ADD_KIND_ORDER: TAddKind[] = [PackageKinds.APP, LibraryKinds.LIB, LibraryKinds.SHARED];
106
+
107
+ /** The commands a project can run for this preset: what `add` prints when it is not told what to create. */
108
+ const kindCommands = (opts: { presetValue: string }): string[] =>
109
+ ADD_KIND_ORDER.map(
110
+ (kind) =>
111
+ `bun x --no-install vulcan add --preset ${opts.presetValue} ${ADD_KINDS[kind].flag} <name>`,
112
+ );
123
113
 
124
114
  const NO_BACKEND = ':none';
125
- const KIND_HINTS: Record<string, string> = { app: 'a runnable app', lib: 'a shared package' };
126
115
 
127
- const SAY_WHAT = `say what to create - \`${CreateFlags.APP} <name>\` (a runnable app) or \`${CreateFlags.LIB} <name>\` (a shared package)`;
116
+ const DESCRIBED_KINDS = ADD_KIND_ORDER.map(
117
+ (kind) => `\`${ADD_KINDS[kind].flag} <name>\` (${ADD_KINDS[kind].hint})`,
118
+ );
119
+
120
+ const SAY_WHAT = `say what to create - ${DESCRIBED_KINDS.slice(0, -1).join(', ')} or ${DESCRIBED_KINDS.at(-1)}`;
121
+
122
+ /** The kinds a located preset makes: always an app, a library kind only when its file is there. */
123
+ const kindsOffered = (opts: { located: ILocatedPreset }): TAddKind[] => {
124
+ const hasFile: Record<TAddKind, boolean> = {
125
+ [PackageKinds.APP]: true,
126
+ [LibraryKinds.LIB]: opts.located.libFile !== undefined,
127
+ [LibraryKinds.SHARED]: opts.located.sharedFile !== undefined,
128
+ };
129
+
130
+ return ADD_KIND_ORDER.filter((kind) => hasFile[kind]);
131
+ };
132
+
133
+ /**
134
+ * Why a preset cannot make a shared package, and where one can be had: the presets this project recorded with a
135
+ * shared kind, then the official ones that have it. Nothing is invented: with none known it says so.
136
+ */
137
+ const noSharedKindMessage = (opts: {
138
+ located: ILocatedPreset;
139
+ recorded: TResolvedConfig['presets'];
140
+ name: string;
141
+ official?: IOfficialPreset[];
142
+ }): string => {
143
+ const { official = OFFICIAL_PRESETS } = opts;
144
+ const recorded = (opts.recorded ?? []).filter((preset) => preset.shared !== undefined);
145
+ const known = [
146
+ ...recorded.map((preset) => preset.spec),
147
+ ...official
148
+ .filter((preset) => preset.shared !== undefined)
149
+ .map((preset) => preset.id)
150
+ .filter(
151
+ (id) => !recorded.some((preset) => OfficialPresets.idOf({ spec: preset.spec }) === id),
152
+ ),
153
+ ];
154
+ const commands = known.map(
155
+ (spec) =>
156
+ `bun x --no-install vulcan add --preset ${spec} ${ADD_KINDS[LibraryKinds.SHARED].flag} ${opts.name}`,
157
+ );
158
+
159
+ return `preset ${opts.located.packageName} has no shared kind (it makes: ${kindsOffered({ located: opts.located }).join(' and ')}); ${
160
+ commands.length === 0
161
+ ? 'no preset known to this project or to the official list has one'
162
+ : `a preset with one: run ${commands.join(' or ')}`
163
+ }`;
164
+ };
128
165
 
129
166
  /** The terminal asks which kind, listing only what the preset offers; end of input stops the command. */
130
- const askKind = async (opts: { offered: string[] }): Promise<string | undefined> => {
131
- if (menusAvailable()) {
132
- const picked = await promptSelect({
167
+ const askKind = async (opts: { offered: TAddKind[] }): Promise<TAddKind | undefined> => {
168
+ if (TerminalCapability.menusAvailable()) {
169
+ const picked = await TerminalPrompt.promptSelect({
133
170
  message: 'What do you want to create?',
134
- choices: opts.offered.map((kind) => ({ value: kind, label: kind, hint: KIND_HINTS[kind] })),
171
+ choices: opts.offered.map((kind) => ({
172
+ value: kind,
173
+ label: kind,
174
+ hint: ADD_KINDS[kind].hint,
175
+ })),
135
176
  });
136
177
 
137
- return picked ?? undefined;
178
+ return opts.offered.find((kind) => kind === picked);
138
179
  }
139
180
 
140
181
  for (;;) {
141
- const answer = askWithPrompt({
182
+ const answer = ProjectNames.askWithPrompt({
142
183
  question: `What do you want to create? (${opts.offered.join(', ')})`,
143
184
  });
144
185
 
@@ -146,10 +187,10 @@ const askKind = async (opts: { offered: string[] }): Promise<string | undefined>
146
187
  return undefined;
147
188
  }
148
189
 
149
- const kind = answer.trim();
190
+ const chosen = opts.offered.find((kind) => kind === answer.trim());
150
191
 
151
- if (opts.offered.includes(kind)) {
152
- return kind;
192
+ if (chosen !== undefined) {
193
+ return chosen;
153
194
  }
154
195
  }
155
196
  };
@@ -186,510 +227,580 @@ const literal = (opts: {
186
227
  ),
187
228
  ];
188
229
 
189
- /** A frontend's proxy target: the chosen backend app's port, or nothing when it has no backend. */
190
- export const resolveApiUrl = async (opts: {
191
- root: string;
192
- args: string[];
193
- interactive: boolean;
194
- backendFolders: string[];
195
- packages: IProjectPackage[];
196
- }): Promise<{ ok: true; apiUrl: string } | { ok: false; error: string }> => {
197
- if (opts.args.includes(CreateFlags.NO_API)) {
198
- return { ok: true, apiUrl: '' };
199
- }
200
-
201
- let chosen = readFlag({ args: opts.args, flag: CreateFlags.API });
202
-
203
- if (chosen === undefined) {
204
- if (!opts.interactive) {
205
- return { ok: false, error: MISSING_API };
206
- }
230
+ const usedPorts = (opts: { root: string; packages: IProjectPackage[] }): number[] =>
231
+ NextStep.readExistingApps({
232
+ root: opts.root,
233
+ paths: opts.packages.map((entry) => entry.path),
234
+ }).map((app) => app.port);
207
235
 
208
- if (menusAvailable()) {
209
- const backends = opts.packages.filter((entry) =>
210
- opts.backendFolders.some((folder) => entry.path.startsWith(`${folder}/`)),
211
- );
236
+ /** A terminal picks one of the presets the project recorded or an official one, or types another; null when cancelled. */
237
+ const askPreset = async (opts: { cwd: string }): Promise<string | null> => {
238
+ const loaded = await ConfigLoader.load({ root: opts.cwd });
212
239
 
213
- // Nothing to pick from: a frontend of a project without a backend has nothing to proxy to.
214
- if (backends.length === 0) {
215
- return { ok: true, apiUrl: '' };
216
- }
240
+ return PresetMenu.askSpec({ recorded: loaded.ok ? (loaded.config.presets ?? []) : [] });
241
+ };
217
242
 
218
- const picked = await promptSelect({
219
- message: 'Backend app to proxy /api to',
220
- choices: [
221
- ...backends.map((entry) => ({ value: entry.dir, label: entry.dir, hint: entry.path })),
222
- { value: NO_BACKEND, label: 'none', hint: 'no proxy' },
223
- ],
243
+ export class AppScaffold {
244
+ private static async runAdd(opts: {
245
+ cwd: string;
246
+ args: string[];
247
+ scratch: string;
248
+ official?: IOfficialPreset[];
249
+ }): Promise<number> {
250
+ const { cwd } = opts;
251
+ const flagged = ProjectNames.readFlag({ args: opts.args, flag: CreateFlags.PRESET });
252
+
253
+ if (flagged === undefined && !TerminalCapability.menusAvailable()) {
254
+ return AddFailure.fail({
255
+ message: '--preset needs a value (a package name, or file:<path>)',
224
256
  });
257
+ }
225
258
 
226
- if (picked === null) {
227
- return { ok: false, error: 'aborted' };
228
- }
259
+ const askingPreset = flagged === undefined ? askPreset({ cwd }) : undefined;
260
+ const typedPreset = await askingPreset;
261
+ const presetValue = flagged ?? typedPreset?.trim();
229
262
 
230
- chosen = picked === NO_BACKEND ? '' : picked;
231
- } else {
232
- chosen =
233
- askWithPrompt({ question: 'Backend app to proxy /api to (empty for none)' })?.trim() ?? '';
263
+ if (presetValue === undefined || presetValue === '') {
264
+ return AddFailure.fail({
265
+ message: '--preset needs a value (a package name, or file:<path>)',
266
+ });
234
267
  }
235
268
 
236
- if (chosen === '') {
237
- return { ok: true, apiUrl: '' };
269
+ const loaded = await ConfigLoader.load({ root: cwd });
270
+
271
+ if (!loaded.ok) {
272
+ return AddFailure.fail({ message: loaded.file === undefined ? ROOT_HINT : loaded.error });
238
273
  }
239
- }
240
274
 
241
- const backend = opts.packages.find(
242
- (entry) =>
243
- entry.dir === chosen &&
244
- opts.backendFolders.some((folder) => entry.path.startsWith(`${folder}/`)),
245
- );
275
+ const config: TResolvedConfig = loaded.config;
276
+ const configPath = relative(cwd, loaded.file);
277
+ const manifestPath = join(cwd, 'package.json');
278
+ const manifest = readRootManifest({ path: manifestPath });
246
279
 
247
- if (backend === undefined) {
248
- return {
249
- ok: false,
250
- error: `${CreateFlags.API} '${chosen}' is not a backend app of this monorepo`,
251
- };
252
- }
280
+ if (config.layout === undefined || manifest === undefined) {
281
+ return AddFailure.fail({ message: ROOT_HINT });
282
+ }
253
283
 
254
- const envFile = join(opts.root, backend.path, '.env.example');
255
- const port = existsSync(envFile)
256
- ? readPort({ envExample: readFileSync(envFile, 'utf8') })
257
- : undefined;
284
+ const interactive = process.stdin.isTTY === true;
285
+ const flaggedKinds = ADD_KIND_ORDER.filter((candidate) =>
286
+ opts.args.includes(ADD_KINDS[candidate].flag),
287
+ );
258
288
 
259
- if (port === undefined) {
260
- return {
261
- ok: false,
262
- error: `no *PORT=<number> line in ${backend.path}/.env.example to proxy to`,
263
- };
264
- }
289
+ if (flaggedKinds.length > 1) {
290
+ return AddFailure.fail({
291
+ message: `${CreateFlags.APP}, ${CreateFlags.LIB} and ${CreateFlags.SHARED} cannot be used together`,
292
+ });
293
+ }
265
294
 
266
- return { ok: true, apiUrl: `http://localhost:${port}` };
267
- };
295
+ const [flaggedKind] = flaggedKinds;
296
+ const flagsLibrary = flaggedKind !== undefined && flaggedKind !== PackageKinds.APP;
297
+ const flaggedScope = ProjectNames.readScope({ args: opts.args });
268
298
 
269
- const usedPorts = (opts: { root: string; packages: IProjectPackage[] }): number[] =>
270
- readExistingApps({ root: opts.root, paths: opts.packages.map((entry) => entry.path) }).map(
271
- (app) => app.port,
272
- );
299
+ if (!flaggedScope.ok) {
300
+ return AddFailure.fail({ message: flaggedScope.error });
301
+ }
273
302
 
274
- export const locate = async (opts: {
275
- cwd: string;
276
- scratch: string;
277
- spec: IPresetSpec;
278
- }): Promise<{ ok: true; located: ILocatedPreset } | { ok: false; error: string }> => {
279
- if (opts.spec.packageName === undefined) {
280
- return locatePreset({ spec: opts.spec, root: opts.cwd });
281
- }
303
+ if (
304
+ flagsLibrary &&
305
+ ProjectNames.readFlag({ args: opts.args, flag: ADD_KINDS[flaggedKind].flag }) === undefined
306
+ ) {
307
+ return AddFailure.fail({ message: `${ADD_KINDS[flaggedKind].flag} needs a name` });
308
+ }
282
309
 
283
- if (isInstallSkipped()) {
284
- return { ok: false, error: 'an npm preset needs an install - use file: in tests' };
285
- }
310
+ // Never a default kind: without a terminal to ask, nothing is fetched or written until the flag says which.
311
+ if (!interactive && flaggedKind === undefined) {
312
+ return AddFailure.fail({
313
+ message: `${SAY_WHAT}\n ${kindCommands({ presetValue }).join('\n ')}`,
314
+ });
315
+ }
286
316
 
287
- const installed = await installNpmPreset({ scratch: opts.scratch, spec: opts.spec });
317
+ const early =
318
+ interactive || flagsLibrary
319
+ ? undefined
320
+ : missingFlag({ args: opts.args, layout: config.layout });
288
321
 
289
- return installed === ExitCodes.OK
290
- ? locatePreset({ spec: opts.spec, root: opts.scratch })
291
- : { ok: false, error: `could not install ${opts.spec.packageName}@${opts.spec.range}` };
292
- };
322
+ if (early !== undefined) {
323
+ return AddFailure.fail({ message: early });
324
+ }
293
325
 
294
- /** A terminal picks one of the presets the project recorded or an official one, or types another; null when cancelled. */
295
- const askPreset = async (opts: { cwd: string }): Promise<string | null> => {
296
- const loaded = await loadConfig({ root: opts.cwd });
326
+ const spec = Preset.parseSpec({ value: presetValue, cwd });
327
+ const located = await AppScaffold.locate({ cwd, scratch: opts.scratch, spec });
297
328
 
298
- return askPresetSpec({ recorded: loaded.ok ? (loaded.config.presets ?? []) : [] });
299
- };
329
+ if (!located.ok) {
330
+ return AddFailure.fail({ message: located.error });
331
+ }
300
332
 
301
- const runAdd = async (opts: { cwd: string; args: string[]; scratch: string }): Promise<number> => {
302
- const { cwd } = opts;
303
- const flagged = readFlag({ args: opts.args, flag: CreateFlags.PRESET });
333
+ const { preset, packageName, packageVersion } = located.located;
334
+ const recordedSpec = PresetRecord.presetSpecOf({ value: presetValue, root: cwd, cwd });
335
+ let kind: TAddKind = flaggedKind ?? PackageKinds.APP;
336
+
337
+ if (flaggedKind === LibraryKinds.SHARED && located.located.sharedFile === undefined) {
338
+ return AddFailure.fail({
339
+ message: noSharedKindMessage({
340
+ located: located.located,
341
+ recorded: config.presets,
342
+ name:
343
+ ProjectNames.readFlag({ args: opts.args, flag: ADD_KINDS[flaggedKind].flag }) ??
344
+ '<name>',
345
+ official: opts.official,
346
+ }),
347
+ });
348
+ }
304
349
 
305
- if (flagged === undefined && !menusAvailable()) {
306
- return fail({ message: '--preset needs a value (a package name, or file:<path>)' });
307
- }
350
+ if (flaggedKind === undefined) {
351
+ const offered = kindsOffered({ located: located.located });
352
+ const askingKind = offered.length === 1 ? PackageKinds.APP : askKind({ offered });
353
+ const chosen = await askingKind;
308
354
 
309
- const presetValue = flagged ?? (await askPreset({ cwd }))?.trim();
355
+ if (chosen === undefined) {
356
+ return AddFailure.fail({ message: SAY_WHAT });
357
+ }
310
358
 
311
- if (presetValue === undefined || presetValue === '') {
312
- return fail({ message: '--preset needs a value (a package name, or file:<path>)' });
313
- }
359
+ kind = chosen;
360
+ }
314
361
 
315
- const loaded = await loadConfig({ root: cwd });
362
+ if (kind !== PackageKinds.APP) {
363
+ const flaggedName = ProjectNames.readFlag({ args: opts.args, flag: ADD_KINDS[kind].flag });
364
+ const askingName =
365
+ flaggedName === undefined
366
+ ? askInTerminal({
367
+ question: 'Name of this library',
368
+ validate: (value) =>
369
+ value.trim() === '' ? undefined : ProjectNames.nameProblem({ name: value.trim() }),
370
+ })
371
+ : undefined;
372
+ const typedName = await askingName;
373
+ const name = flaggedName ?? typedName?.trim();
374
+
375
+ if (name === undefined || name === '') {
376
+ return AddFailure.fail({ message: `${ADD_KINDS[kind].flag} needs a name` });
377
+ }
316
378
 
317
- if (!loaded.ok) {
318
- return fail({ message: loaded.file === undefined ? ROOT_HINT : loaded.error });
319
- }
379
+ return LibraryScaffold.add({
380
+ cwd,
381
+ args: opts.args,
382
+ interactive,
383
+ presetValue,
384
+ spec,
385
+ located: located.located,
386
+ config,
387
+ configFile: loaded.file,
388
+ configPath,
389
+ manifest,
390
+ packages: ProjectPackages.resolve({ config }),
391
+ libName: name,
392
+ kind,
393
+ recorded: ({ block }) =>
394
+ PresetRecord.record({
395
+ block,
396
+ preset: LibPreset.recordedOf({ spec: recordedSpec, located: located.located }),
397
+ }),
398
+ });
399
+ }
320
400
 
321
- const config: TResolvedConfig = loaded.config;
322
- const configPath = relative(cwd, loaded.file);
323
- const manifestPath = join(cwd, 'package.json');
324
- const manifest = readRootManifest({ path: manifestPath });
401
+ // Before any question: a catalog the preset cannot live in is no reason to ask for names.
402
+ const peerProblem = WorkspaceManifest.checkPeers({
403
+ catalog: WorkspaceManifest.readCatalog({ manifest }),
404
+ peers: preset.peers,
405
+ presetVersions: preset,
406
+ });
325
407
 
326
- if (config.layout === undefined || manifest === undefined) {
327
- return fail({ message: ROOT_HINT });
328
- }
408
+ if (peerProblem !== undefined) {
409
+ return AddFailure.fail({ message: peerProblem });
410
+ }
329
411
 
330
- const interactive = process.stdin.isTTY === true;
331
- const libFlag = opts.args.includes(CreateFlags.LIB);
332
- const libName = readFlag({ args: opts.args, flag: CreateFlags.LIB });
333
- const appFlag = opts.args.includes(CreateFlags.APP);
412
+ const side = preset.side;
413
+ const listed = LayoutFolder.layoutFoldersOf({ value: config.layout[side] });
414
+ const [only] = listed;
415
+ const names = await ProjectNames.resolve({
416
+ fields: [
417
+ // One listed folder is the answer and a menu does not ask; several are picked from; a new one is a flag.
418
+ {
419
+ ...SIDE_FIELDS[side],
420
+ previous: listed.length === 1 ? only : undefined,
421
+ choices: listed.length > 1 ? listed : undefined,
422
+ fixed: TerminalCapability.menusAvailable() && listed.length === 1,
423
+ },
424
+ { key: 'app', flag: CreateFlags.APP, question: `Name of this ${side} app` },
425
+ ],
426
+ args: opts.args,
427
+ interactive,
428
+ ask: askInTerminal,
429
+ });
334
430
 
335
- if (libFlag && appFlag) {
336
- return fail({ message: `${CreateFlags.APP} and ${CreateFlags.LIB} cannot be used together` });
337
- }
431
+ if (!names.ok) {
432
+ return AddFailure.fail({ message: names.error });
433
+ }
338
434
 
339
- const flaggedScope = readScope({ args: opts.args });
435
+ const { folder, app } = names.names;
340
436
 
341
- if (!flaggedScope.ok) {
342
- return fail({ message: flaggedScope.error });
343
- }
437
+ const otherSide = Object.entries(config.layout).find(
438
+ ([key, value]) => key !== side && LayoutFolder.layoutFoldersOf({ value }).includes(folder),
439
+ );
344
440
 
345
- if (libFlag && libName === undefined) {
346
- return fail({ message: `${CreateFlags.LIB} needs a name` });
347
- }
441
+ // One folder holds one kind of code: a folder another key already owns would mix them.
442
+ if (otherSide !== undefined) {
443
+ return AddFailure.fail({
444
+ message:
445
+ otherSide[0] === LayoutKeys.OTHER
446
+ ? `the ${side} folder '${folder}' is listed under layout.other in ${configPath}: folders the layout leaves alone are not app targets`
447
+ : `the ${side} folder '${folder}' is the ${otherSide[0]} folder in ${configPath}; each kind of code needs its own folder`,
448
+ });
449
+ }
348
450
 
349
- // Never a default kind: without a terminal to ask, nothing is fetched or written until the flag says which.
350
- if (!interactive && !libFlag && !appFlag) {
351
- return fail({
352
- message: `${SAY_WHAT}\n ${kindCommands({ presetValue }).join('\n ')}`,
451
+ const grown = LayoutFolder.withLayoutFolder({ value: config.layout[side], folder });
452
+ const overlaps = LayoutFolder.layoutOverlapProblems({
453
+ layout: { ...config.layout, [side]: grown },
353
454
  });
354
- }
355
455
 
356
- const early =
357
- interactive || libFlag ? undefined : missingFlag({ args: opts.args, layout: config.layout });
456
+ // A folder inside another (or around one) would give a package path two owners.
457
+ if (overlaps.length > 0) {
458
+ return AddFailure.fail({
459
+ message: `the ${side} folder '${folder}' does not fit the layout of ${configPath}: ${overlaps.join('; ')}`,
460
+ });
461
+ }
358
462
 
359
- if (early !== undefined) {
360
- return fail({ message: early });
361
- }
463
+ const isNewFolder = !listed.includes(folder);
362
464
 
363
- const spec = parsePresetSpec({ value: presetValue, cwd });
364
- const located = await locate({ cwd, scratch: opts.scratch, spec });
465
+ // Optional, asked only where menus are drawn; a plain terminal and a script give --scope.
466
+ const askingScope =
467
+ flaggedScope.scope ??
468
+ (TerminalCapability.menusAvailable() ? ProjectNames.askScope() : undefined);
469
+ const scope = await askingScope;
365
470
 
366
- if (!located.ok) {
367
- return fail({ message: located.error });
368
- }
369
-
370
- const { preset, packageName, packageVersion } = located.located;
371
- const recordedSpec = presetSpecOf({ value: presetValue, root: cwd, cwd });
372
- let kind = libFlag ? 'lib' : 'app';
471
+ if (scope === null) {
472
+ return AddFailure.fail({ message: ABORTED });
473
+ }
373
474
 
374
- if (!libFlag && !appFlag) {
375
- const offered = ['app', ...(located.located.libFile === undefined ? [] : ['lib'])];
376
- const chosen = offered.length === 1 ? 'app' : await askKind({ offered });
475
+ const packageOfApp = scope === undefined ? app : `${scope}/${app}`;
476
+ const packages = ProjectPackages.resolve({ config });
377
477
 
378
- if (chosen === undefined) {
379
- return fail({ message: SAY_WHAT });
478
+ if (
479
+ existsSync(join(cwd, folder, app)) ||
480
+ packages.some((entry) => entry.dir === app || entry.name === packageOfApp)
481
+ ) {
482
+ return AddFailure.fail({ message: `${folder}/${app} already exists` });
380
483
  }
381
484
 
382
- kind = chosen;
383
- }
485
+ const devPort = PortRegistry.pick({
486
+ preferred: preset.devPort,
487
+ used: usedPorts({ root: cwd, packages }),
488
+ });
489
+ let apiUrl = '';
490
+
491
+ if (side === AppSides.FRONTEND) {
492
+ const api = await AppScaffold.resolveApiUrl({
493
+ root: cwd,
494
+ args: opts.args,
495
+ interactive,
496
+ backendFolders: LayoutFolder.layoutFoldersOf({ value: config.layout.backend }),
497
+ packages,
498
+ });
384
499
 
385
- if (kind === 'lib') {
386
- const name =
387
- libName ??
388
- (
389
- await askInTerminal({
390
- question: 'Name of this library',
391
- validate: (value) =>
392
- value.trim() === '' ? undefined : nameProblem({ name: value.trim() }),
393
- })
394
- )?.trim();
500
+ if (!api.ok) {
501
+ return AddFailure.fail({ message: api.error });
502
+ }
395
503
 
396
- if (name === undefined || name === '') {
397
- return fail({ message: `${CreateFlags.LIB} needs a name` });
504
+ apiUrl = api.apiUrl;
398
505
  }
399
506
 
400
- return addLibrary({
401
- cwd,
402
- args: opts.args,
403
- interactive,
404
- presetValue,
405
- spec,
406
- located: located.located,
407
- config,
408
- configFile: loaded.file,
409
- configPath,
410
- manifest,
411
- packages: resolvePackages({ config }),
412
- libName: name,
413
- recorded: ({ block }) =>
414
- recordPreset({
415
- block,
416
- preset: recordedPresetOf({ spec: recordedSpec, located: located.located }),
417
- }),
418
- });
419
- }
507
+ const source = readFileSync(loaded.file, 'utf8');
508
+ const entry = { dir: app, name: packageOfApp, path: `${folder}/${app}` };
509
+ const knownSources = new Set(config.atlas.sources.map((known) => known.name));
510
+ const newSources = preset.atlas.filter((candidate) => !knownSources.has(candidate.name));
511
+ const parsed = AppsBlock.parse({ source });
512
+
513
+ // The user's config is theirs: with the block gone or no longer JSON it is never rewritten, only described.
514
+ if (!parsed.ok) {
515
+ return AddFailure.fail({
516
+ message: [
517
+ parsed.reason === AppsBlockProblems.MISSING
518
+ ? `the vulcan:apps block is gone from ${configPath} - add by hand:`
519
+ : `the vulcan:apps block in ${configPath} is not the JSON vulcan wrote - add by hand:`,
520
+ ...literal({ side, folders: grown, app: entry, sources: newSources }),
521
+ ].join('\n'),
522
+ });
523
+ }
420
524
 
421
- // Before any question: a catalog the preset cannot live in is no reason to ask for names.
422
- const peerProblem = checkPeers({
423
- catalog: readCatalog({ manifest }),
424
- peers: preset.peers,
425
- });
525
+ // Extend what the markers hold: the resolved config also carries what the user added outside them.
526
+ const extended: IAppsBlock = {
527
+ layout: {
528
+ ...parsed.block.layout,
529
+ [side]: LayoutFolder.withLayoutFolder({ value: parsed.block.layout[side], folder }),
530
+ },
531
+ packages: [...parsed.block.packages, entry],
532
+ ...(parsed.block.presets === undefined ? {} : { presets: parsed.block.presets }),
533
+ sources: [
534
+ ...parsed.block.sources,
535
+ ...newSources.filter(
536
+ (candidate) => !parsed.block.sources.some((existing) => existing.name === candidate.name),
537
+ ),
538
+ ],
539
+ };
540
+ const block = PresetRecord.record({
541
+ block: extended,
542
+ preset: LibPreset.recordedOf({ spec: recordedSpec, located: located.located }),
543
+ });
544
+ const replaced = AppsBlock.replace({ source, block });
545
+ // A config written before presets were recorded does not read them yet: the line that does goes in.
546
+ const nextConfig =
547
+ replaced === undefined || replaced.includes('apps.presets')
548
+ ? replaced
549
+ : replaced.replace(
550
+ ' packages: apps.packages,\n',
551
+ ' packages: apps.packages,\n presets: apps.presets,\n',
552
+ );
553
+
554
+ if (nextConfig === undefined) {
555
+ return AddFailure.fail({ message: ROOT_HINT });
556
+ }
426
557
 
427
- if (peerProblem !== undefined) {
428
- return fail({ message: peerProblem });
429
- }
558
+ const project = config.name ?? (typeof manifest.name === 'string' ? manifest.name : app);
430
559
 
431
- const side = preset.side;
432
- const listed = layoutFoldersOf({ value: config.layout[side] });
433
- const [only] = listed;
434
- const names = await resolveNames({
435
- fields: [
436
- // One listed folder is the answer and a menu does not ask; several are picked from; a new one is a flag.
437
- {
438
- ...SIDE_FIELDS[side],
439
- previous: listed.length === 1 ? only : undefined,
440
- choices: listed.length > 1 ? listed : undefined,
441
- fixed: menusAvailable() && listed.length === 1,
442
- },
443
- { key: 'app', flag: CreateFlags.APP, question: `Name of this ${side} app` },
444
- ],
445
- args: opts.args,
446
- interactive,
447
- ask: askInTerminal,
448
- });
449
-
450
- if (!names.ok) {
451
- return fail({ message: names.error });
452
- }
560
+ const warning = WorkspaceDocs.filePresetWarning({ spec, packageName });
453
561
 
454
- const { folder, app } = names.names;
562
+ if (warning !== undefined) {
563
+ process.stderr.write(`${warning}\n`);
564
+ }
455
565
 
456
- const otherSide = Object.entries(config.layout).find(
457
- ([key, value]) => key !== side && layoutFoldersOf({ value }).includes(folder),
458
- );
566
+ const rows: [string, string][] = [['app', `${folder}/${app}`]];
459
567
 
460
- // One folder holds one kind of code: a folder another key already owns would mix them.
461
- if (otherSide !== undefined) {
462
- return fail({
463
- message:
464
- otherSide[0] === LayoutKeys.OTHER
465
- ? `the ${side} folder '${folder}' is listed under layout.other in ${configPath}: folders the layout leaves alone are not app targets`
466
- : `the ${side} folder '${folder}' is the ${otherSide[0]} folder in ${configPath}; each kind of code needs its own folder`,
467
- });
468
- }
568
+ if (isNewFolder) {
569
+ rows.push([
570
+ 'layout',
571
+ `adds '${folder}' to layout.${side} (now ${LayoutFolder.describe({ folders: LayoutFolder.layoutFoldersOf({ value: grown }) })})`,
572
+ ]);
573
+ }
469
574
 
470
- const grown = withLayoutFolder({ value: config.layout[side], folder });
471
- const overlaps = layoutOverlapProblems({ layout: { ...config.layout, [side]: grown } });
575
+ if (scope !== undefined) {
576
+ rows.push(['package', packageOfApp]);
577
+ }
472
578
 
473
- // A folder inside another (or around one) would give a package path two owners.
474
- if (overlaps.length > 0) {
475
- return fail({
476
- message: `the ${side} folder '${folder}' does not fit the layout of ${configPath}: ${overlaps.join('; ')}`,
477
- });
478
- }
579
+ rows.push(
580
+ ['side', side],
581
+ ['preset', `${packageName} ${packageVersion}`],
582
+ ['port', String(devPort)],
583
+ );
479
584
 
480
- const isNewFolder = !listed.includes(folder);
585
+ if (side === AppSides.FRONTEND) {
586
+ rows.push(['proxy', apiUrl === '' ? '(none)' : apiUrl]);
587
+ }
481
588
 
482
- // Optional, asked only where menus are drawn; a plain terminal and a script give --scope.
483
- const scope = flaggedScope.scope ?? (menusAvailable() ? await askScope() : undefined);
589
+ const confirmed = await WritePlan.confirm({
590
+ title: `Add ${app}`,
591
+ lines: WritePlan.planLines({ rows }),
592
+ });
484
593
 
485
- if (scope === null) {
486
- return fail({ message: ABORTED });
487
- }
594
+ if (!confirmed) {
595
+ return AddFailure.fail({ message: ABORTED });
596
+ }
488
597
 
489
- const packageOfApp = scope === undefined ? app : `${scope}/${app}`;
490
- const packages = resolvePackages({ config });
598
+ Preset.copyFiles({
599
+ located: located.located,
600
+ target: join(cwd, folder, app),
601
+ tokens: { project, app, appPath: `${folder}/${app}`, devPort: String(devPort), apiUrl },
602
+ });
603
+ ProjectFile.write({
604
+ root: cwd,
605
+ path: `${folder}/${app}/package.json`,
606
+ content: WorkspaceManifest.renderApp({
607
+ app,
608
+ name: packageOfApp,
609
+ preset,
610
+ presetPackage: { name: packageName, version: packageVersion },
611
+ }),
612
+ });
491
613
 
492
- if (
493
- existsSync(join(cwd, folder, app)) ||
494
- packages.some((entry) => entry.dir === app || entry.name === packageOfApp)
495
- ) {
496
- return fail({ message: `${folder}/${app} already exists` });
497
- }
614
+ const nextManifest = WorkspaceManifest.planRoot({
615
+ manifest,
616
+ globs: ProjectScaffold.readWorkspaceGlobs({ root: cwd }),
617
+ folder,
618
+ additions: {
619
+ ...preset.dependencies,
620
+ ...preset.devDependencies,
621
+ [packageName]: spec.packageName === undefined ? spec.range : packageVersion,
622
+ },
623
+ });
498
624
 
499
- const devPort = pickPort({ preferred: preset.devPort, used: usedPorts({ root: cwd, packages }) });
500
- let apiUrl = '';
625
+ ProjectFile.write({
626
+ root: cwd,
627
+ path: 'package.json',
628
+ content: ManifestJson.render({ value: nextManifest }),
629
+ });
630
+ ProjectFile.write({ root: cwd, path: configPath, content: nextConfig });
631
+ ProjectFile.write({
632
+ root: cwd,
633
+ path: `${KNOWLEDGE_DIRECTORY}/packages/${app}.md`,
634
+ content: WorkspaceDocs.renderAppConcept({
635
+ app: { name: app, side, folder },
636
+ summary: preset.summary,
637
+ presetPackage: packageName,
638
+ }),
639
+ });
640
+ const indexPath = join(cwd, KNOWLEDGE_DIRECTORY, 'index.md');
501
641
 
502
- if (side === AppSides.FRONTEND) {
503
- const api = await resolveApiUrl({
642
+ ProjectFile.write({
504
643
  root: cwd,
505
- args: opts.args,
506
- interactive,
507
- backendFolders: layoutFoldersOf({ value: config.layout.backend }),
508
- packages,
644
+ path: `${KNOWLEDGE_DIRECTORY}/index.md`,
645
+ content: existsSync(indexPath)
646
+ ? AppsBlock.addBullet({
647
+ source: readFileSync(indexPath, 'utf8'),
648
+ app: { name: app, summary: preset.summary },
649
+ })
650
+ : WorkspaceDocs.renderKnowledgeIndex({
651
+ project,
652
+ apps: [{ name: app, summary: preset.summary }],
653
+ }),
509
654
  });
510
655
 
511
- if (!api.ok) {
512
- return fail({ message: api.error });
656
+ for (const step of [
657
+ () => SubProcess.runBun({ cwd, args: ['install'], label: 'bun install' }),
658
+ // The installed CLI syncs, so the project is wired to the version it pins.
659
+ () =>
660
+ SubProcess.runBun({
661
+ cwd,
662
+ args: [join(cwd, 'node_modules', '.bin', 'vulcan'), 'sync'],
663
+ label: 'vulcan sync',
664
+ }),
665
+ () =>
666
+ AppChecks.run({ root: cwd, appDirectory: join(cwd, folder, app), checks: preset.checks }),
667
+ ]) {
668
+ const code = await step();
669
+
670
+ if (code !== ExitCodes.OK) {
671
+ return code;
672
+ }
513
673
  }
514
674
 
515
- apiUrl = api.apiUrl;
516
- }
675
+ // Every app `make dev` serves: those that were here, then the new one at the port it was given.
676
+ process.stderr.write(
677
+ NextStep.render({
678
+ done: `Done. ${folder}/${app} is added.`,
679
+ command: 'make dev',
680
+ apps: [
681
+ ...NextStep.readExistingApps({
682
+ root: cwd,
683
+ paths: packages.map((existing) => existing.path),
684
+ }),
685
+ { port: devPort, urls: preset.urls },
686
+ ],
687
+ }),
688
+ );
517
689
 
518
- const source = readFileSync(loaded.file, 'utf8');
519
- const entry = { dir: app, name: packageOfApp, path: `${folder}/${app}` };
520
- const knownSources = new Set(config.atlas.sources.map((known) => known.name));
521
- const newSources = preset.atlas.filter((candidate) => !knownSources.has(candidate.name));
522
- const parsed = parseAppsBlock({ source });
523
-
524
- // The user's config is theirs: with the block gone or no longer JSON it is never rewritten, only described.
525
- if (!parsed.ok) {
526
- return fail({
527
- message: [
528
- parsed.reason === AppsBlockProblems.MISSING
529
- ? `the vulcan:apps block is gone from ${configPath} - add by hand:`
530
- : `the vulcan:apps block in ${configPath} is not the JSON vulcan wrote - add by hand:`,
531
- ...literal({ side, folders: grown, app: entry, sources: newSources }),
532
- ].join('\n'),
533
- });
690
+ return ExitCodes.OK;
534
691
  }
535
692
 
536
- // Extend what the markers hold: the resolved config also carries what the user added outside them.
537
- const extended: IAppsBlock = {
538
- layout: {
539
- ...parsed.block.layout,
540
- [side]: withLayoutFolder({ value: parsed.block.layout[side], folder }),
541
- },
542
- packages: [...parsed.block.packages, entry],
543
- ...(parsed.block.presets === undefined ? {} : { presets: parsed.block.presets }),
544
- sources: [
545
- ...parsed.block.sources,
546
- ...newSources.filter(
547
- (candidate) => !parsed.block.sources.some((existing) => existing.name === candidate.name),
548
- ),
549
- ],
550
- };
551
- const block = recordPreset({
552
- block: extended,
553
- preset: recordedPresetOf({ spec: recordedSpec, located: located.located }),
554
- });
555
- const replaced = replaceAppsBlock({ source, block });
556
- // A config written before presets were recorded does not read them yet: the line that does goes in.
557
- const nextConfig =
558
- replaced === undefined || replaced.includes('apps.presets')
559
- ? replaced
560
- : replaced.replace(
561
- ' packages: apps.packages,\n',
562
- ' packages: apps.packages,\n presets: apps.presets,\n',
563
- );
564
-
565
- if (nextConfig === undefined) {
566
- return fail({ message: ROOT_HINT });
567
- }
693
+ /** A frontend's proxy target: the chosen backend app's port, or nothing when it has no backend. */
694
+ static async resolveApiUrl(opts: {
695
+ root: string;
696
+ args: string[];
697
+ interactive: boolean;
698
+ backendFolders: string[];
699
+ packages: IProjectPackage[];
700
+ }): Promise<{ ok: true; apiUrl: string } | { ok: false; error: string }> {
701
+ if (opts.args.includes(CreateFlags.NO_API)) {
702
+ return { ok: true, apiUrl: '' };
703
+ }
568
704
 
569
- const project = config.name ?? (typeof manifest.name === 'string' ? manifest.name : app);
705
+ let chosen = ProjectNames.readFlag({ args: opts.args, flag: CreateFlags.API });
570
706
 
571
- const warning = filePresetWarning({ spec, packageName });
707
+ if (chosen === undefined) {
708
+ if (!opts.interactive) {
709
+ return { ok: false, error: MISSING_API };
710
+ }
572
711
 
573
- if (warning !== undefined) {
574
- process.stderr.write(`${warning}\n`);
575
- }
712
+ if (TerminalCapability.menusAvailable()) {
713
+ const backends = opts.packages.filter((entry) =>
714
+ opts.backendFolders.some((folder) => entry.path.startsWith(`${folder}/`)),
715
+ );
576
716
 
577
- const rows: [string, string][] = [['app', `${folder}/${app}`]];
717
+ // Nothing to pick from: a frontend of a project without a backend has nothing to proxy to.
718
+ if (backends.length === 0) {
719
+ return { ok: true, apiUrl: '' };
720
+ }
721
+
722
+ const picked = await TerminalPrompt.promptSelect({
723
+ message: 'Backend app to proxy /api to',
724
+ choices: [
725
+ ...backends.map((entry) => ({ value: entry.dir, label: entry.dir, hint: entry.path })),
726
+ { value: NO_BACKEND, label: 'none', hint: 'no proxy' },
727
+ ],
728
+ });
729
+
730
+ if (picked === null) {
731
+ return { ok: false, error: 'aborted' };
732
+ }
733
+
734
+ chosen = picked === NO_BACKEND ? '' : picked;
735
+ } else {
736
+ chosen =
737
+ ProjectNames.askWithPrompt({
738
+ question: 'Backend app to proxy /api to (empty for none)',
739
+ })?.trim() ?? '';
740
+ }
578
741
 
579
- if (isNewFolder) {
580
- rows.push([
581
- 'layout',
582
- `adds '${folder}' to layout.${side} (now ${describeFolders({ folders: layoutFoldersOf({ value: grown }) })})`,
583
- ]);
584
- }
742
+ if (chosen === '') {
743
+ return { ok: true, apiUrl: '' };
744
+ }
745
+ }
585
746
 
586
- if (scope !== undefined) {
587
- rows.push(['package', packageOfApp]);
588
- }
747
+ const backend = opts.packages.find(
748
+ (entry) =>
749
+ entry.dir === chosen &&
750
+ opts.backendFolders.some((folder) => entry.path.startsWith(`${folder}/`)),
751
+ );
589
752
 
590
- rows.push(
591
- ['side', side],
592
- ['preset', `${packageName} ${packageVersion}`],
593
- ['port', String(devPort)],
594
- );
753
+ if (backend === undefined) {
754
+ return {
755
+ ok: false,
756
+ error: `${CreateFlags.API} '${chosen}' is not a backend app of this monorepo`,
757
+ };
758
+ }
595
759
 
596
- if (side === AppSides.FRONTEND) {
597
- rows.push(['proxy', apiUrl === '' ? '(none)' : apiUrl]);
598
- }
760
+ const envFile = join(opts.root, backend.path, '.env.example');
761
+ const port = existsSync(envFile)
762
+ ? PortRegistry.read({ envExample: readFileSync(envFile, 'utf8') })
763
+ : undefined;
599
764
 
600
- const confirmed = await confirmWrite({ title: `Add ${app}`, lines: planLines({ rows }) });
765
+ if (port === undefined) {
766
+ return {
767
+ ok: false,
768
+ error: `no *PORT=<number> line in ${backend.path}/.env.example to proxy to`,
769
+ };
770
+ }
601
771
 
602
- if (!confirmed) {
603
- return fail({ message: ABORTED });
772
+ return { ok: true, apiUrl: `http://localhost:${port}` };
604
773
  }
605
774
 
606
- copyPresetFiles({
607
- located: located.located,
608
- target: join(cwd, folder, app),
609
- tokens: { project, app, appPath: `${folder}/${app}`, devPort: String(devPort), apiUrl },
610
- });
611
- writeFile({
612
- root: cwd,
613
- path: `${folder}/${app}/package.json`,
614
- content: renderAppManifest({
615
- app,
616
- name: packageOfApp,
617
- preset,
618
- presetPackage: { name: packageName, version: packageVersion },
619
- }),
620
- });
621
-
622
- const nextManifest = planRootManifest({
623
- manifest,
624
- globs: readWorkspaceGlobs({ root: cwd }),
625
- folder,
626
- additions: {
627
- ...preset.dependencies,
628
- ...preset.devDependencies,
629
- [packageName]: spec.packageName === undefined ? spec.range : packageVersion,
630
- },
631
- });
632
-
633
- writeFile({
634
- root: cwd,
635
- path: 'package.json',
636
- content: renderManifestJson({ value: nextManifest }),
637
- });
638
- writeFile({ root: cwd, path: configPath, content: nextConfig });
639
- writeFile({
640
- root: cwd,
641
- path: `${KNOWLEDGE_DIRECTORY}/packages/${app}.md`,
642
- content: renderAppConcept({
643
- app: { name: app, side, folder },
644
- summary: preset.summary,
645
- presetPackage: packageName,
646
- }),
647
- });
648
- const indexPath = join(cwd, KNOWLEDGE_DIRECTORY, 'index.md');
649
-
650
- writeFile({
651
- root: cwd,
652
- path: `${KNOWLEDGE_DIRECTORY}/index.md`,
653
- content: existsSync(indexPath)
654
- ? addAppBullet({
655
- source: readFileSync(indexPath, 'utf8'),
656
- app: { name: app, summary: preset.summary },
657
- })
658
- : renderKnowledgeIndex({ project, apps: [{ name: app, summary: preset.summary }] }),
659
- });
660
-
661
- for (const step of [
662
- () => runBun({ cwd, args: ['install'], label: 'bun install' }),
663
- // The installed CLI syncs, so the project is wired to the version it pins.
664
- () =>
665
- runBun({
666
- cwd,
667
- args: [join(cwd, 'node_modules', '.bin', 'vulcan'), 'sync'],
668
- label: 'vulcan sync',
669
- }),
670
- () => runAppChecks({ root: cwd, appDirectory: join(cwd, folder, app), checks: preset.checks }),
671
- ]) {
672
- const code = await step();
775
+ static async locate(opts: {
776
+ cwd: string;
777
+ scratch: string;
778
+ spec: IPresetSpec;
779
+ }): Promise<{ ok: true; located: ILocatedPreset } | { ok: false; error: string }> {
780
+ if (opts.spec.packageName === undefined) {
781
+ return Preset.locate({ spec: opts.spec, root: opts.cwd });
782
+ }
673
783
 
674
- if (code !== ExitCodes.OK) {
675
- return code;
784
+ if (SubProcess.isInstallSkipped()) {
785
+ return { ok: false, error: 'an npm preset needs an install - use file: in tests' };
676
786
  }
677
- }
678
787
 
679
- // Every app `make dev` serves: those that were here, then the new one at the port it was given.
680
- process.stderr.write(
681
- renderNext({
682
- done: `Done. ${folder}/${app} is added.`,
683
- command: 'make dev',
684
- apps: [
685
- ...readExistingApps({ root: cwd, paths: packages.map((existing) => existing.path) }),
686
- { port: devPort, urls: preset.urls },
687
- ],
688
- }),
689
- );
788
+ const installed = await PresetScratch.installNpm({ scratch: opts.scratch, spec: opts.spec });
690
789
 
691
- return ExitCodes.OK;
692
- };
790
+ return installed === ExitCodes.OK
791
+ ? Preset.locate({ spec: opts.spec, root: opts.scratch })
792
+ : { ok: false, error: `could not install ${opts.spec.packageName}@${opts.spec.range}` };
793
+ }
693
794
 
694
- export const addApp = async (opts: { cwd: string; args: string[] }): Promise<number> =>
695
- withScratch({ root: opts.cwd, run: (scratch) => runAdd({ ...opts, scratch }) });
795
+ static async add(opts: {
796
+ cwd: string;
797
+ args: string[];
798
+ /** The official presets a refusal names; the published list by default. */
799
+ official?: IOfficialPreset[];
800
+ }): Promise<number> {
801
+ return PresetScratch.withScratch({
802
+ root: opts.cwd,
803
+ run: (scratch) => AppScaffold.runAdd({ ...opts, scratch }),
804
+ });
805
+ }
806
+ }