@venizia/vulcan 0.2.0 → 0.3.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.
@@ -0,0 +1,234 @@
1
+ import { Glob } from 'bun';
2
+ import {
3
+ chmodSync,
4
+ existsSync,
5
+ lstatSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ realpathSync,
9
+ statSync,
10
+ writeFileSync,
11
+ } from 'node:fs';
12
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
13
+ import { z } from 'zod';
14
+ import { readProperty } from '../common/index.ts';
15
+ import { AppSides, CreateConstants } from './common/index.ts';
16
+ import type { ILocatedPreset, IPresetSpec, TAppSide, TPresetResult } from './common/index.ts';
17
+
18
+ const PRESET_SCHEMA = z
19
+ .object({
20
+ presetVersion: z.number(),
21
+ side: z.string().refine((value): value is TAppSide => AppSides.isValid(value), {
22
+ message: `one of: ${[...AppSides.SCHEME_SET].join(', ')}`,
23
+ }),
24
+ summary: z.string(),
25
+ devPort: z.number().int().positive(),
26
+ dependencies: z.record(z.string(), z.string()).default({}),
27
+ devDependencies: z.record(z.string(), z.string()).default({}),
28
+ peers: z.record(z.string(), z.string()).default({}),
29
+ scripts: z.record(z.string(), z.string()).default({}),
30
+ checks: z.array(z.string()).default([]),
31
+ urls: z.array(z.string().startsWith('/')).default([]),
32
+ files: z.string(),
33
+ atlas: z.array(z.object({ name: z.string(), repo: z.string(), ref: z.string() })).default([]),
34
+ })
35
+ // A check is run as `bun run <check>`; an entry that is not a script could be a bun flag.
36
+ .superRefine((value, context) => {
37
+ value.checks.forEach((check, index) => {
38
+ if (!Object.hasOwn(value.scripts, check)) {
39
+ context.addIssue({
40
+ code: 'custom',
41
+ path: ['checks', index],
42
+ message: `"${check}" is not a key of scripts`,
43
+ });
44
+ }
45
+ });
46
+ });
47
+
48
+ const TOKEN = /\{\{(\w+)\}\}/g;
49
+ const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
50
+ const EXECUTABLE_BITS = 0o111;
51
+ const PERMISSION_BITS = 0o777;
52
+
53
+ const escapes = (opts: { root: string; path: string }): boolean => {
54
+ const relativePath = relative(opts.root, opts.path);
55
+
56
+ return isAbsolute(relativePath) || relativePath === '..' || relativePath.startsWith(`..${sep}`);
57
+ };
58
+
59
+ /** A path a preset names must stay inside its own package, with symlinks resolved. */
60
+ const resolveInside = (opts: { root: string; from: string; path: string }): string | undefined => {
61
+ const resolved = resolve(opts.from, opts.path);
62
+
63
+ if (escapes({ root: opts.root, path: resolved })) {
64
+ return undefined;
65
+ }
66
+
67
+ if (
68
+ existsSync(resolved) &&
69
+ escapes({ root: realpathSync(opts.root), path: realpathSync(resolved) })
70
+ ) {
71
+ return undefined;
72
+ }
73
+
74
+ return resolved;
75
+ };
76
+
77
+ /** Text gets its tokens replaced; anything with a NUL byte or invalid UTF-8 is copied as it is. */
78
+ const substituteTokens = (opts: { content: Buffer; tokens: Record<string, string> }): Buffer => {
79
+ if (opts.content.includes(0)) {
80
+ return opts.content;
81
+ }
82
+
83
+ try {
84
+ const text = UTF8.decode(opts.content);
85
+
86
+ return Buffer.from(text.replace(TOKEN, (match, key: string) => opts.tokens[key] ?? match));
87
+ } catch {
88
+ return opts.content;
89
+ }
90
+ };
91
+
92
+ export const parsePresetSpec = (opts: { value: string; cwd: string }): IPresetSpec => {
93
+ if (opts.value.startsWith(CreateConstants.PRESET_FILE_PREFIX)) {
94
+ const path = opts.value.slice(CreateConstants.PRESET_FILE_PREFIX.length);
95
+
96
+ return { range: `${CreateConstants.PRESET_FILE_PREFIX}${resolve(opts.cwd, path)}` };
97
+ }
98
+
99
+ // The version separator is the last '@' that is not the scope's leading one.
100
+ const at = opts.value.lastIndexOf('@');
101
+ const [name, range] =
102
+ at > 0 ? [opts.value.slice(0, at), opts.value.slice(at + 1)] : [opts.value, 'latest'];
103
+ const packageName = name.startsWith('@') ? name : `${CreateConstants.PRESET_SCOPE}${name}`;
104
+
105
+ return { packageName, range };
106
+ };
107
+
108
+ const readJson = (opts: { file: string }): Record<string, unknown> | undefined => {
109
+ if (!existsSync(opts.file)) {
110
+ return undefined;
111
+ }
112
+
113
+ try {
114
+ return JSON.parse(readFileSync(opts.file, 'utf8'));
115
+ } catch (error) {
116
+ console.error(
117
+ `[readJson] ${opts.file} | ${error instanceof Error ? error.message : String(error)}`,
118
+ );
119
+
120
+ return undefined;
121
+ }
122
+ };
123
+
124
+ export const locatePreset = (opts: { spec: IPresetSpec; root: string }): TPresetResult => {
125
+ const packageRoot =
126
+ opts.spec.packageName === undefined
127
+ ? opts.spec.range.slice(CreateConstants.PRESET_FILE_PREFIX.length)
128
+ : join(opts.root, 'node_modules', opts.spec.packageName);
129
+ const manifest = readJson({ file: join(packageRoot, 'package.json') });
130
+
131
+ if (manifest === undefined) {
132
+ return { ok: false, error: `no package at ${packageRoot} - was it installed?` };
133
+ }
134
+
135
+ const packageName = String(manifest.name);
136
+ const packageVersion = String(manifest.version);
137
+ const shown = `${packageName}@${packageVersion}`;
138
+ const field = readProperty({ value: manifest[CreateConstants.PRESET_FIELD], key: 'preset' });
139
+
140
+ if (typeof field !== 'string') {
141
+ return {
142
+ ok: false,
143
+ error: `${shown} ships no VULCAN preset (no "vulcan": { "preset" } in its package.json)`,
144
+ };
145
+ }
146
+
147
+ const presetFile = resolveInside({ root: packageRoot, from: packageRoot, path: field });
148
+
149
+ if (presetFile === undefined) {
150
+ return {
151
+ ok: false,
152
+ error: `${shown}: vulcan.preset ${field} points outside the package`,
153
+ };
154
+ }
155
+
156
+ const raw = readJson({ file: presetFile });
157
+
158
+ if (raw === undefined) {
159
+ return { ok: false, error: `${shown}: ${field} is missing or not JSON` };
160
+ }
161
+
162
+ if (raw.presetVersion !== CreateConstants.PRESET_VERSION) {
163
+ return {
164
+ ok: false,
165
+ error: `${shown} has preset version ${String(raw.presetVersion)}; this VULCAN reads version ${CreateConstants.PRESET_VERSION} - upgrade @venizia/vulcan`,
166
+ };
167
+ }
168
+
169
+ const parsed = PRESET_SCHEMA.safeParse(raw);
170
+
171
+ if (!parsed.success) {
172
+ const issues = parsed.error.issues
173
+ .map(issue => `${issue.path.join('.')} ${issue.message}`)
174
+ .join('; ');
175
+
176
+ return { ok: false, error: `${shown}: ${field}: ${issues}` };
177
+ }
178
+
179
+ const filesFolder = resolveInside({
180
+ root: packageRoot,
181
+ from: dirname(presetFile),
182
+ path: parsed.data.files,
183
+ });
184
+
185
+ if (filesFolder === undefined) {
186
+ return {
187
+ ok: false,
188
+ error: `${shown}: ${field}: files ${parsed.data.files} points outside the package`,
189
+ };
190
+ }
191
+
192
+ const preset = { ...parsed.data, files: filesFolder };
193
+ const located: ILocatedPreset = { preset, packageRoot, packageName, packageVersion };
194
+
195
+ return { ok: true, located };
196
+ };
197
+
198
+ export const copyPresetFiles = (opts: {
199
+ located: ILocatedPreset;
200
+ target: string;
201
+ tokens: Record<string, string>;
202
+ }): string[] => {
203
+ const written: string[] = [];
204
+
205
+ for (const path of new Glob('**/*').scanSync({ cwd: opts.located.preset.files, dot: true })) {
206
+ const source = join(opts.located.preset.files, path);
207
+
208
+ // A link could point at any file on the machine; only real files belong to the preset.
209
+ if (lstatSync(source).isSymbolicLink()) {
210
+ continue;
211
+ }
212
+
213
+ const name = basename(path);
214
+ const relativePath = CreateConstants.PRESET_DOTFILE_NAMES.includes(name)
215
+ ? join(dirname(path), `.${name.slice(1)}`)
216
+ : path;
217
+ const destination = join(opts.target, relativePath);
218
+ const { mode } = statSync(source);
219
+
220
+ mkdirSync(dirname(destination), { recursive: true });
221
+ writeFileSync(
222
+ destination,
223
+ substituteTokens({ content: readFileSync(source), tokens: opts.tokens }),
224
+ );
225
+
226
+ if (mode & EXECUTABLE_BITS) {
227
+ chmodSync(destination, mode & PERMISSION_BITS);
228
+ }
229
+
230
+ written.push(relativePath);
231
+ }
232
+
233
+ return written;
234
+ };
@@ -0,0 +1,62 @@
1
+ import { ExitCodes } from '../common/index.ts';
2
+ import { CreateConstants } from './common/index.ts';
3
+
4
+ /** `bun` commands init and add run; VULCAN_NO_INSTALL=1 (tests) prints them instead. */
5
+ export const isInstallSkipped = (): boolean => process.env[CreateConstants.NO_INSTALL_ENV] === '1';
6
+
7
+ /** The `bun` this process runs, unless a test replaced it. */
8
+ export const bunExecutable = (): string => process.env[CreateConstants.BUN_ENV] ?? process.execPath;
9
+
10
+ /** Any command, under the same skip rule as `runBun`; a skipped one counts as done. */
11
+ export const runCommand = async (opts: {
12
+ cwd: string;
13
+ command: string[];
14
+ label: string;
15
+ }): Promise<number> => {
16
+ if (isInstallSkipped()) {
17
+ process.stderr.write(` skipped ${opts.label} (VULCAN_NO_INSTALL)\n`);
18
+
19
+ return ExitCodes.OK;
20
+ }
21
+
22
+ const child = Bun.spawn(opts.command, {
23
+ cwd: opts.cwd,
24
+ stdio: ['inherit', 'inherit', 'inherit'],
25
+ });
26
+
27
+ return child.exited;
28
+ };
29
+
30
+ export const runBun = async (opts: {
31
+ cwd: string;
32
+ args: string[];
33
+ label: string;
34
+ }): Promise<number> =>
35
+ runCommand({ cwd: opts.cwd, command: [bunExecutable(), ...opts.args], label: opts.label });
36
+
37
+ /**
38
+ * `git init` on the new project. A machine without git (or with one too old for `-b`) still gets a
39
+ * working project: the missing step is printed for the user to run, and the flow goes on.
40
+ */
41
+ export const runGitInit = async (opts: { cwd: string }): Promise<number> => {
42
+ const git = process.env[CreateConstants.GIT_ENV] ?? 'git';
43
+ let code: number = ExitCodes.FAILURE;
44
+
45
+ try {
46
+ code = await runCommand({
47
+ cwd: opts.cwd,
48
+ command: [git, 'init', '-q', '-b', 'develop'],
49
+ label: 'git init',
50
+ });
51
+ } catch {
52
+ // Bun.spawn throws when the executable is not there; the message below says what to do.
53
+ }
54
+
55
+ if (code !== ExitCodes.OK) {
56
+ process.stderr.write(
57
+ `vulcan init: git init did not run - install git, then run: git init -b develop (in ${opts.cwd})\n`,
58
+ );
59
+ }
60
+
61
+ return ExitCodes.OK;
62
+ };
@@ -0,0 +1,38 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import type { IPresetSpec } from './common/index.ts';
5
+ import { runBun } from './process.ts';
6
+
7
+ /**
8
+ * An npm preset is read from node_modules, so it is installed into a scratch folder outside the
9
+ * project: every refusal that depends on what the package says happens before anything is written.
10
+ */
11
+ export const installNpmPreset = async (opts: {
12
+ scratch: string;
13
+ spec: IPresetSpec;
14
+ }): Promise<number> => {
15
+ writeFileSync(
16
+ join(opts.scratch, 'package.json'),
17
+ `${JSON.stringify({ name: 'vulcan-preset-scratch', private: true })}\n`,
18
+ );
19
+
20
+ return runBun({
21
+ cwd: opts.scratch,
22
+ args: ['add', `${opts.spec.packageName}@${opts.spec.range}`],
23
+ label: `bun add ${opts.spec.packageName}@${opts.spec.range}`,
24
+ });
25
+ };
26
+
27
+ /** The scratch folder lives as long as the flow: the located preset's files are copied from it. */
28
+ export const withScratch = async <TResult>(opts: {
29
+ run: (scratch: string) => Promise<TResult>;
30
+ }): Promise<TResult> => {
31
+ const scratch = mkdtempSync(join(tmpdir(), 'vulcan-preset-'));
32
+
33
+ try {
34
+ return await opts.run(scratch);
35
+ } finally {
36
+ rmSync(scratch, { recursive: true, force: true });
37
+ }
38
+ };
@@ -0,0 +1,374 @@
1
+ import { coversFolder } from '../init/index.ts';
2
+ import { CreateConstants } from './common/index.ts';
3
+ import type { IApp, IAppsBlock, IPreset, IPresetSpec } from './common/index.ts';
4
+
5
+ const ENV_PORT = /^[A-Z0-9_]*PORT=(\d+)\s*$/m;
6
+
7
+ /** A newline inside a list item or a paragraph would split it. */
8
+ const oneLine = (opts: { text: string }): string => opts.text.replace(/\s+/g, ' ').trim();
9
+
10
+ const json = (opts: { value: unknown }): string => `${JSON.stringify(opts.value, null, 2)}\n`;
11
+
12
+ export const renderRootManifest = (opts: {
13
+ project: string;
14
+ workspaces: string[];
15
+ catalog: Record<string, string>;
16
+ vulcanVersion: string;
17
+ }): string =>
18
+ json({
19
+ value: {
20
+ name: opts.project,
21
+ private: true,
22
+ workspaces: { packages: opts.workspaces, catalog: opts.catalog },
23
+ scripts: { dev: "bun run --filter '*' dev" },
24
+ devDependencies: { '@venizia/vulcan': opts.vulcanVersion },
25
+ },
26
+ });
27
+
28
+ /** A version the monorepo already pins wins, so every app shares one copy. */
29
+ export const mergeCatalog = (opts: {
30
+ catalog: Record<string, string>;
31
+ additions: Record<string, string>;
32
+ }): Record<string, string> => ({ ...opts.additions, ...opts.catalog });
33
+
34
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
35
+ typeof value === 'object' && value !== null && !Array.isArray(value);
36
+
37
+ const toStringRecord = (opts: { value: unknown }): Record<string, string> =>
38
+ isRecord(opts.value)
39
+ ? Object.fromEntries(
40
+ Object.entries(opts.value).filter(
41
+ (entry): entry is [string, string] => typeof entry[1] === 'string',
42
+ ),
43
+ )
44
+ : {};
45
+
46
+ /** The catalog of a root manifest wherever it lives: top level, or inside object-form workspaces. */
47
+ export const readCatalog = (opts: {
48
+ manifest: Record<string, unknown>;
49
+ }): Record<string, string> => ({
50
+ ...(isRecord(opts.manifest.workspaces)
51
+ ? toStringRecord({ value: opts.manifest.workspaces.catalog })
52
+ : {}),
53
+ ...toStringRecord({ value: opts.manifest.catalog }),
54
+ });
55
+
56
+ /**
57
+ * The root manifest with the new folder and the preset's catalog entries added, and nothing else
58
+ * changed: an array of workspaces stays an array, and the catalog stays where the project keeps it
59
+ * (top level, or inside object-form workspaces; an array has no room for one, so top level).
60
+ */
61
+ export const planRootManifest = (opts: {
62
+ manifest: Record<string, unknown>;
63
+ globs: string[];
64
+ folder: string;
65
+ additions: Record<string, string>;
66
+ }): Record<string, unknown> => {
67
+ const { manifest, folder } = opts;
68
+ const { workspaces } = manifest;
69
+ const globs = coversFolder({ globs: opts.globs, folder })
70
+ ? opts.globs
71
+ : [...opts.globs, `${folder}/*`];
72
+ const existing = readCatalog({ manifest });
73
+ const fresh = Object.fromEntries(
74
+ Object.entries(opts.additions).filter(([name]) => existing[name] === undefined),
75
+ );
76
+ const isTopLevel = isRecord(manifest.catalog) || Array.isArray(workspaces);
77
+
78
+ if (isTopLevel) {
79
+ return {
80
+ ...manifest,
81
+ workspaces: Array.isArray(workspaces)
82
+ ? globs
83
+ : { ...(isRecord(workspaces) ? workspaces : {}), packages: globs },
84
+ catalog: mergeCatalog({
85
+ catalog: toStringRecord({ value: manifest.catalog }),
86
+ additions: fresh,
87
+ }),
88
+ };
89
+ }
90
+
91
+ const inside = isRecord(workspaces) ? workspaces : {};
92
+
93
+ return {
94
+ ...manifest,
95
+ workspaces: {
96
+ ...inside,
97
+ packages: globs,
98
+ catalog: mergeCatalog({
99
+ catalog: toStringRecord({ value: inside.catalog }),
100
+ additions: fresh,
101
+ }),
102
+ },
103
+ };
104
+ };
105
+
106
+ /**
107
+ * The catalog value is read as the version the install resolves to, compared with the preset's
108
+ * range by semver order (what Bun.semver implements). A prerelease sorts before its release, so
109
+ * `^0.2.2-5` does not meet `^0.2.2`: it is refused, never rounded up. A value that is not a plain
110
+ * version (`workspace:*`, a git URL, a range) cannot be compared, so it is refused as well.
111
+ */
112
+ export const checkPeers = (opts: {
113
+ catalog: Record<string, string>;
114
+ peers: Record<string, string>;
115
+ }): string | undefined => {
116
+ for (const [name, range] of Object.entries(opts.peers)) {
117
+ const pinned = opts.catalog[name];
118
+
119
+ if (pinned === undefined) {
120
+ continue;
121
+ }
122
+
123
+ const version = pinned.replace(/^[\^~]/, '');
124
+
125
+ if (!CreateConstants.VERSION_PATTERN.test(version)) {
126
+ return `the monorepo pins ${name} ${pinned}, which is not a version vulcan can compare with the preset's ${range} - pin a version in the catalog first`;
127
+ }
128
+
129
+ if (!Bun.semver.satisfies(version, range)) {
130
+ return CreateConstants.PRERELEASE_PATTERN.test(version)
131
+ ? `the monorepo pins ${name} ${pinned}, a prerelease, which does not meet the preset's ${range} (a prerelease sorts before its release) - pin a release in the catalog first`
132
+ : `the monorepo pins ${name} ${pinned}, but the preset needs ${range} - move the catalog first`;
133
+ }
134
+ }
135
+
136
+ return undefined;
137
+ };
138
+
139
+ const toCatalog = (opts: { dependencies: Record<string, string> }): Record<string, string> =>
140
+ Object.fromEntries(
141
+ Object.keys(opts.dependencies)
142
+ .sort()
143
+ .map(name => [name, 'catalog:']),
144
+ );
145
+
146
+ export const renderAppManifest = (opts: {
147
+ app: string;
148
+ preset: IPreset;
149
+ presetPackage: { name: string; version: string };
150
+ }): string =>
151
+ json({
152
+ value: {
153
+ name: opts.app,
154
+ version: '0.0.0',
155
+ private: true,
156
+ scripts: opts.preset.scripts,
157
+ dependencies: toCatalog({
158
+ dependencies: {
159
+ ...opts.preset.dependencies,
160
+ [opts.presetPackage.name]: opts.presetPackage.version,
161
+ },
162
+ }),
163
+ devDependencies: toCatalog({ dependencies: opts.preset.devDependencies }),
164
+ // What `add` prints later: this app's urls, since the preset is not at hand then.
165
+ ...(opts.preset.urls.length === 0 ? {} : { vulcan: { urls: opts.preset.urls } }),
166
+ },
167
+ });
168
+
169
+ export const renderAppsBlock = (opts: { block: IAppsBlock }): string =>
170
+ [
171
+ CreateConstants.APPS_BLOCK_START,
172
+ `const apps = ${JSON.stringify(opts.block, null, 2)};`,
173
+ CreateConstants.APPS_BLOCK_END,
174
+ ].join('\n');
175
+
176
+ export const renderVulcanConfig = (opts: { project: string; block: IAppsBlock }): string =>
177
+ [
178
+ "import type { VulcanConfig } from '@venizia/vulcan';",
179
+ '',
180
+ renderAppsBlock({ block: opts.block }),
181
+ '',
182
+ 'export default {',
183
+ ` name: '${opts.project}',`,
184
+ " agents: ['claude'],",
185
+ " rules: { 'V-W-01': 'on-user-word' },",
186
+ ' layout: apps.layout,',
187
+ ' packages: apps.packages,',
188
+ ' atlas: { sources: apps.sources },',
189
+ '} satisfies VulcanConfig;',
190
+ '',
191
+ ].join('\n');
192
+
193
+ /** Only the text between the markers is rewritten; undefined when the user edited them away. */
194
+ export const replaceAppsBlock = (opts: {
195
+ source: string;
196
+ block: IAppsBlock;
197
+ }): string | undefined => {
198
+ const start = opts.source.indexOf(CreateConstants.APPS_BLOCK_START);
199
+ const end = opts.source.indexOf(CreateConstants.APPS_BLOCK_END);
200
+
201
+ if (start === -1 || end === -1 || end < start) {
202
+ return undefined;
203
+ }
204
+
205
+ const before = opts.source.slice(0, start);
206
+ const after = opts.source.slice(end + CreateConstants.APPS_BLOCK_END.length);
207
+
208
+ return `${before}${renderAppsBlock({ block: opts.block })}${after}`;
209
+ };
210
+
211
+ const hasStrings = (opts: { value: unknown; keys: string[] }): boolean => {
212
+ const { value } = opts;
213
+
214
+ return isRecord(value) && opts.keys.every(key => typeof value[key] === 'string');
215
+ };
216
+
217
+ const isAppsBlock = (value: unknown): value is IAppsBlock =>
218
+ isRecord(value) &&
219
+ isRecord(value.layout) &&
220
+ Object.values(value.layout).every(folder => typeof folder === 'string') &&
221
+ Array.isArray(value.packages) &&
222
+ value.packages.every(entry => hasStrings({ value: entry, keys: ['dir', 'name', 'path'] })) &&
223
+ Array.isArray(value.sources) &&
224
+ value.sources.every(entry => hasStrings({ value: entry, keys: ['name', 'repo', 'ref'] }));
225
+
226
+ export type TAppsBlockResult =
227
+ | { ok: true; block: IAppsBlock }
228
+ | { ok: false; reason: 'missing' | 'invalid' };
229
+
230
+ const APPS_DECLARATION = 'const apps = ';
231
+
232
+ /** What the markers hold now, so `add` extends it instead of rebuilding it from the resolved config. */
233
+ export const parseAppsBlock = (opts: { source: string }): TAppsBlockResult => {
234
+ const start = opts.source.indexOf(CreateConstants.APPS_BLOCK_START);
235
+ const end = opts.source.indexOf(CreateConstants.APPS_BLOCK_END);
236
+
237
+ if (start === -1 || end === -1 || end < start) {
238
+ return { ok: false, reason: 'missing' };
239
+ }
240
+
241
+ const body = opts.source.slice(start + CreateConstants.APPS_BLOCK_START.length, end);
242
+ const declaration = body.indexOf(APPS_DECLARATION);
243
+
244
+ if (declaration === -1) {
245
+ return { ok: false, reason: 'invalid' };
246
+ }
247
+
248
+ try {
249
+ const parsed: unknown = JSON.parse(
250
+ body
251
+ .slice(declaration + APPS_DECLARATION.length)
252
+ .trim()
253
+ .replace(/;$/, ''),
254
+ );
255
+
256
+ return isAppsBlock(parsed) ? { ok: true, block: parsed } : { ok: false, reason: 'invalid' };
257
+ } catch (error) {
258
+ console.error(
259
+ `[parseAppsBlock] the vulcan:apps block is not JSON | ${error instanceof Error ? error.message : String(error)}`,
260
+ );
261
+
262
+ return { ok: false, reason: 'invalid' };
263
+ }
264
+ };
265
+
266
+ const APPS_HEADING = /^## Apps\s*$/;
267
+ const ANY_HEADING = /^#{1,2}\s/;
268
+
269
+ const renderAppBullet = (opts: { app: { name: string; summary: string } }): string =>
270
+ `- [${opts.app.name}](packages/${opts.app.name}.md) - ${oneLine({ text: opts.app.summary })}`;
271
+
272
+ /**
273
+ * One bullet for one app, after the last bullet under `## Apps` (a section is added when the index
274
+ * has none). Every other byte of the index is the user's and is returned as it was.
275
+ */
276
+ export const addAppBullet = (opts: {
277
+ source: string;
278
+ app: { name: string; summary: string };
279
+ }): string => {
280
+ if (opts.source.includes(`](packages/${opts.app.name}.md)`)) {
281
+ return opts.source;
282
+ }
283
+
284
+ const eol = opts.source.includes('\r\n') ? '\r\n' : '\n';
285
+ const bullet = renderAppBullet({ app: opts.app });
286
+ const lines = opts.source.split(eol);
287
+ const heading = lines.findIndex(line => APPS_HEADING.test(line));
288
+
289
+ if (heading === -1) {
290
+ const kept = opts.source.trimEnd();
291
+
292
+ return `${kept === '' ? '' : `${kept}${eol}${eol}`}## Apps${eol}${eol}${bullet}${eol}`;
293
+ }
294
+
295
+ const next = lines.findIndex((line, index) => index > heading && ANY_HEADING.test(line));
296
+ const section = lines.slice(heading + 1, next === -1 ? lines.length : next);
297
+ const last = section.findLastIndex(line => line.startsWith('- ['));
298
+
299
+ if (last === -1) {
300
+ lines.splice(heading, 1, lines[heading] ?? '', '', bullet);
301
+ } else {
302
+ lines.splice(heading + 1 + last + 1, 0, bullet);
303
+ }
304
+
305
+ return lines.join(eol);
306
+ };
307
+
308
+ /** The catalog entry a `file:` preset writes only works on this machine; say so. */
309
+ export const filePresetWarning = (opts: {
310
+ spec: IPresetSpec;
311
+ packageName: string;
312
+ }): string | undefined =>
313
+ opts.spec.packageName === undefined
314
+ ? `warning: the catalog gets ${opts.packageName} as ${opts.spec.range} - a file: entry is not portable, so a clone elsewhere or CI cannot install it until it names a published version`
315
+ : undefined;
316
+
317
+ export const renderKnowledgeIndex = (opts: {
318
+ project: string;
319
+ apps: { name: string; summary: string }[];
320
+ }): string =>
321
+ [
322
+ '---',
323
+ 'okf_version: "0.2"',
324
+ '---',
325
+ '',
326
+ `# ${opts.project} knowledge`,
327
+ '',
328
+ `Facts about ${opts.project}, in the Open Knowledge Format. Rules live in \`../rules.md\`.`,
329
+ '',
330
+ '## Apps',
331
+ '',
332
+ ...opts.apps.map(app => renderAppBullet({ app })),
333
+ '',
334
+ ].join('\n');
335
+
336
+ export const renderAppConcept = (opts: {
337
+ app: IApp;
338
+ summary: string;
339
+ presetPackage: string;
340
+ }): string =>
341
+ [
342
+ '---',
343
+ 'type: Package',
344
+ `title: ${opts.app.name}`,
345
+ // JSON string syntax is valid YAML, so a colon, quote or newline in the summary stays one scalar.
346
+ `description: ${JSON.stringify(opts.summary)}`,
347
+ `resource: ${opts.app.folder}/${opts.app.name}`,
348
+ `tags: [packages, ${opts.app.side}]`,
349
+ '---',
350
+ '',
351
+ `# ${opts.app.name}`,
352
+ '',
353
+ `The ${opts.app.side} app at \`${opts.app.folder}/${opts.app.name}\`, created from the ${opts.presetPackage} preset. ${oneLine({ text: opts.summary })}`,
354
+ '',
355
+ ].join('\n');
356
+
357
+ export const renderLogEntry = (opts: { date: string; text: string }): string =>
358
+ `## ${opts.date}\n\n- ${opts.text}\n`;
359
+
360
+ export const pickPort = (opts: { preferred: number; used: number[] }): number => {
361
+ let port = opts.preferred;
362
+
363
+ while (opts.used.includes(port)) {
364
+ port++;
365
+ }
366
+
367
+ return port;
368
+ };
369
+
370
+ export const readPort = (opts: { envExample: string }): number | undefined => {
371
+ const match = ENV_PORT.exec(opts.envExample);
372
+
373
+ return match === null ? undefined : Number(match[1]);
374
+ };