@sontoriyama/mcp-code-mode 0.0.0-stage → 0.4.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,454 @@
1
+ // Shared execution core: own the console capture, spill envelope and optional
2
+ // timeout/abort so the CLI front-end (run.mjs) and the MCP front-end
3
+ // (mcp-server.mjs) run exactly the same program semantics.
4
+ import { randomBytes } from 'node:crypto';
5
+ import { closeSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, writeFileSync } from 'node:fs';
6
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { StringDecoder } from 'node:string_decoder';
9
+ import { inspect } from 'node:util';
10
+ import { execJson, execTool, mapBounded, ToolCallError } from './tools.mjs';
11
+
12
+ export const DEFAULT_MAX_CHARS = 32000;
13
+
14
+ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
15
+ const MODULE_SYNTAX_RE = /cannot use import statement outside a module|unexpected token 'export'|cannot use 'import\.meta' outside a module/i;
16
+
17
+ export function parseMaxChars(raw = process.env.CODEMODE_MAX_OUTPUT_CHARS) {
18
+ if (raw === undefined || raw === null || String(raw).trim() === '') {
19
+ return DEFAULT_MAX_CHARS;
20
+ }
21
+ const n = Number(raw);
22
+ return Number.isFinite(n) && n >= 1 ? Math.floor(n) : DEFAULT_MAX_CHARS;
23
+ }
24
+
25
+ export function safeJsonStringify(value, space = 0) {
26
+ const ancestors = [];
27
+ return JSON.stringify(
28
+ value,
29
+ function (_key, v) {
30
+ if (typeof v === 'bigint') return `${v.toString()}n`;
31
+ if (typeof v !== 'object' || v === null) return v;
32
+ while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();
33
+ if (ancestors.includes(v)) return '[Circular]';
34
+ ancestors.push(v);
35
+ return v;
36
+ },
37
+ space,
38
+ );
39
+ }
40
+
41
+ export function boundOutput(text, maxChars = parseMaxChars()) {
42
+ const limit = parseMaxChars(maxChars);
43
+ if (text.length <= limit) return { text, truncated: false };
44
+ const marker = '\n… code mode output truncated …\n';
45
+ if (limit <= marker.length) {
46
+ return { text: text.slice(0, limit), truncated: true };
47
+ }
48
+ const head = Math.ceil((limit - marker.length) / 2);
49
+ const tail = limit - marker.length - head;
50
+ return {
51
+ text: text.slice(0, head) + marker + (tail > 0 ? text.slice(-tail) : ''),
52
+ truncated: true,
53
+ };
54
+ }
55
+
56
+ function formatLogPart(part) {
57
+ if (typeof part === 'string') return part;
58
+ try {
59
+ return safeJsonStringify(part) ?? String(part);
60
+ } catch {
61
+ return inspect(part, { depth: 4, breakLength: Infinity });
62
+ }
63
+ }
64
+
65
+ export function normalizeError(err) {
66
+ if (err instanceof ToolCallError) {
67
+ return { kind: 'tool-call', toolName: err.toolName, message: err.message };
68
+ }
69
+ if (err instanceof Error) {
70
+ return { kind: 'exception', message: err.message };
71
+ }
72
+ return { kind: 'exception', message: formatLogPart(err) };
73
+ }
74
+
75
+ function isInsideDir(baseReal, candidateReal) {
76
+ const rel = relative(baseReal, candidateReal);
77
+ return rel !== ''
78
+ && rel !== '.'
79
+ && rel !== '..'
80
+ && !rel.startsWith(`..${sep}`)
81
+ && !isAbsolute(rel);
82
+ }
83
+
84
+ function isFailedSpillHeader(filePath) {
85
+ let fd;
86
+ try {
87
+ fd = openSync(filePath, 'r');
88
+ if (!fstatSync(fd).isFile()) return true;
89
+ const buf = Buffer.allocUnsafe(1024);
90
+ const bytes = readSync(fd, buf, 0, buf.length, 0);
91
+ const head = buf.subarray(0, bytes).toString('utf8');
92
+ return /"ok"\s*:\s*false\b/.test(head);
93
+ } catch {
94
+ return true;
95
+ } finally {
96
+ if (fd !== undefined) {
97
+ try { closeSync(fd); } catch {}
98
+ }
99
+ }
100
+ }
101
+
102
+ function resolveSpillTarget(baseDir, nameOrPath) {
103
+ let baseReal;
104
+ try {
105
+ baseReal = realpathSync(baseDir);
106
+ } catch (err) {
107
+ if ((err?.code === 'ENOENT' || err?.code === 'ENOTDIR') && !nameOrPath) {
108
+ throw new Error('no spill files found in output directory');
109
+ }
110
+ throw err;
111
+ }
112
+
113
+ if (!nameOrPath) {
114
+ let entries;
115
+ try {
116
+ entries = readdirSync(baseReal);
117
+ } catch (err) {
118
+ if (err?.code === 'ENOENT') {
119
+ throw new Error('no spill files found in output directory');
120
+ }
121
+ throw err;
122
+ }
123
+ const files = [];
124
+ for (const entry of entries) {
125
+ if (!entry.endsWith('.json')) continue;
126
+ try {
127
+ const real = realpathSync(resolve(baseReal, entry));
128
+ if (!isInsideDir(baseReal, real)) continue;
129
+ const st = lstatSync(real);
130
+ if (!st.isFile()) continue;
131
+ files.push({ path: real, mtime: st.mtimeMs });
132
+ } catch {
133
+ continue;
134
+ }
135
+ }
136
+ files.sort((a, b) => b.mtime - a.mtime);
137
+ if (files.length === 0) throw new Error('no spill files found in output directory');
138
+ for (const file of files) {
139
+ if (!isFailedSpillHeader(file.path)) return file.path;
140
+ }
141
+ return files[0].path;
142
+ }
143
+
144
+ // Reject lexical escapes (`..`, bare `.`) before touching the filesystem so
145
+ // the error message stays stable, then resolve symlinks and re-check.
146
+ //
147
+ // Both the configured base and its realpath are accepted lexically, because a
148
+ // spill path written into an envelope keeps the base as configured while
149
+ // `realpathSync` can rewrite it (macOS: `os.tmpdir()` lives under `/var`, a
150
+ // symlink to `/private/var`). The symlink-traversal guard below still checks
151
+ // the resolved target against the single real base, so this loosens nothing.
152
+ const baseLexical = resolve(baseDir);
153
+ const lexical = resolve(baseLexical, String(nameOrPath));
154
+ if (!isInsideDir(baseLexical, lexical) && !isInsideDir(baseReal, lexical)) {
155
+ throw new Error('spill.read path must stay inside CODEMODE_OUT_DIR');
156
+ }
157
+ const real = realpathSync(lexical);
158
+ if (!isInsideDir(baseReal, real)) {
159
+ throw new Error('spill.read path must stay inside CODEMODE_OUT_DIR');
160
+ }
161
+ if (!lstatSync(real).isFile()) {
162
+ throw new Error('spill.read target must be a regular file');
163
+ }
164
+ return real;
165
+ }
166
+
167
+ export function createSpillHelper(outDir = resolve(process.env.CODEMODE_OUT_DIR ?? '.agent/out')) {
168
+ const baseDir = resolve(outDir);
169
+ return Object.freeze({
170
+ dir: baseDir,
171
+ read(nameOrPath) {
172
+ return JSON.parse(readFileSync(resolveSpillTarget(baseDir, nameOrPath), 'utf8'));
173
+ },
174
+ });
175
+ }
176
+
177
+ const SPILL_READ_CHUNK_BYTES = 64 * 1024;
178
+ const DEFAULT_SPILL_PAGE_CHARS = 20000;
179
+ const MAX_SPILL_PAGE_CHARS = 1000000;
180
+
181
+ export function readSpillPage(outDir, { name, path, offset = 0, maxChars = DEFAULT_SPILL_PAGE_CHARS } = {}) {
182
+ const target = resolveSpillTarget(resolve(outDir), name ?? path);
183
+ const requested = Number(offset);
184
+ const start = Number.isInteger(requested) && requested > 0 ? requested : 0;
185
+ const limit = Number.isInteger(maxChars) && maxChars > 0
186
+ ? Math.max(2, Math.min(Math.floor(maxChars), MAX_SPILL_PAGE_CHARS))
187
+ : DEFAULT_SPILL_PAGE_CHARS;
188
+
189
+ const fd = openSync(target, 'r');
190
+ const decoder = new StringDecoder('utf8');
191
+ const buffer = Buffer.allocUnsafe(SPILL_READ_CHUNK_BYTES);
192
+ let position = 0;
193
+ let charCount = 0;
194
+ let text = '';
195
+ try {
196
+ if (!fstatSync(fd).isFile()) {
197
+ throw new Error('spill.read target must be a regular file');
198
+ }
199
+ for (;;) {
200
+ const bytes = readSync(fd, buffer, 0, buffer.length, position);
201
+ position += bytes;
202
+ const chunk = bytes === 0 ? decoder.end() : decoder.write(buffer.subarray(0, bytes));
203
+ if (chunk.length > 0) {
204
+ const chunkStart = charCount;
205
+ const chunkEnd = charCount + chunk.length;
206
+ if (text.length < limit) {
207
+ const from = Math.max(start, chunkStart);
208
+ const to = Math.min(start + limit, chunkEnd);
209
+ if (to > from) text += chunk.slice(from - chunkStart, to - chunkStart);
210
+ }
211
+ charCount = chunkEnd;
212
+ }
213
+ if (bytes === 0) break;
214
+ }
215
+ } finally {
216
+ closeSync(fd);
217
+ }
218
+
219
+ // Never end a page on a lone high surrogate: it would be mangled when the
220
+ // host re-encodes it. Drop it so the next page starts on a clean code point.
221
+ if (text.length > 0) {
222
+ const last = text.charCodeAt(text.length - 1);
223
+ if (last >= 0xd800 && last <= 0xdbff) text = text.slice(0, -1);
224
+ }
225
+
226
+ const pageOffset = Math.min(start, charCount);
227
+ const nextOffset = pageOffset + text.length < charCount ? pageOffset + text.length : null;
228
+ return {
229
+ text,
230
+ totalChars: charCount,
231
+ offset: pageOffset,
232
+ truncated: nextOffset !== null,
233
+ nextOffset,
234
+ };
235
+ }
236
+
237
+ async function importModuleSource(code, scope) {
238
+ const dataUrl = `data:text/javascript;base64,${Buffer.from(code, 'utf8').toString('base64')}`;
239
+ const mod = await import(dataUrl);
240
+ const run = mod.run ?? mod.default;
241
+ if (typeof run !== 'function') {
242
+ throw new Error('program must export run({ tools, args }) or a default function');
243
+ }
244
+ return run(scope);
245
+ }
246
+
247
+ async function executeSourceCode(code, scope) {
248
+ let fn;
249
+ try {
250
+ fn = new AsyncFunction(
251
+ 'tools',
252
+ 'args',
253
+ 'mapBounded',
254
+ 'execTool',
255
+ 'execJson',
256
+ 'spill',
257
+ 'listTools',
258
+ 'callTool',
259
+ code,
260
+ );
261
+ } catch (err) {
262
+ if (!(err instanceof SyntaxError) || !MODULE_SYNTAX_RE.test(err.message)) throw err;
263
+ return importModuleSource(code, scope);
264
+ }
265
+ return fn(
266
+ scope.tools,
267
+ scope.args,
268
+ mapBounded,
269
+ execTool,
270
+ execJson,
271
+ scope.spill,
272
+ scope.listTools,
273
+ scope.callTool,
274
+ );
275
+ }
276
+
277
+ export async function executeProgram({
278
+ mode,
279
+ source,
280
+ programPath,
281
+ args = {},
282
+ registry,
283
+ spill,
284
+ outDir = resolve(process.env.CODEMODE_OUT_DIR ?? '.agent/out'),
285
+ label = 'inline',
286
+ spillStem = label,
287
+ version,
288
+ maxChars = parseMaxChars(),
289
+ timeoutMs,
290
+ signal,
291
+ listTools,
292
+ callTool,
293
+ isolateProcess = false,
294
+ emptySourceMessage,
295
+ sourceError,
296
+ log = (line) => console.error(line),
297
+ } = {}) {
298
+ const logs = [];
299
+ const startedAt = new Date().toISOString();
300
+ let result;
301
+ let failed = false;
302
+ let errorPayload;
303
+
304
+ const originalLog = console.log;
305
+ const originalWrite = process.stdout.write;
306
+ const originalExit = process.exit;
307
+
308
+ console.log = (...parts) => logs.push(parts.map(formatLogPart).join(' '));
309
+ if (isolateProcess) {
310
+ process.stdout.write = (chunk, encoding, callback) => {
311
+ logs.push(Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk));
312
+ if (typeof encoding === 'function') encoding();
313
+ else if (typeof callback === 'function') callback();
314
+ return true;
315
+ };
316
+ process.exit = (code) => {
317
+ throw new Error(`process.exit(${code ?? 0}) is not allowed inside run_code`);
318
+ };
319
+ }
320
+
321
+ const controller = new AbortController();
322
+ let timer = null;
323
+ const abortFromOutside = () => controller.abort(signal.reason);
324
+ if (signal) {
325
+ if (signal.aborted) controller.abort(signal.reason);
326
+ else signal.addEventListener('abort', abortFromOutside, { once: true });
327
+ }
328
+ if (Number.isInteger(timeoutMs) && timeoutMs > 0) {
329
+ timer = setTimeout(() => {
330
+ controller.abort(new Error(`run_code timed out after ${timeoutMs}ms`));
331
+ }, timeoutMs);
332
+ timer.unref?.();
333
+ }
334
+
335
+ const scope = {
336
+ tools: registry,
337
+ args,
338
+ spill,
339
+ listTools,
340
+ callTool,
341
+ };
342
+
343
+ try {
344
+ const programPromise = (async () => {
345
+ if (sourceError) throw sourceError;
346
+ if (emptySourceMessage && String(source ?? '').trim().length === 0) {
347
+ throw new Error(emptySourceMessage);
348
+ }
349
+ if (mode === 'file') {
350
+ const url = `${pathToFileURL(resolve(programPath)).href}?t=${Date.now()}`;
351
+ const mod = await import(url);
352
+ const run = mod.run ?? mod.default;
353
+ if (typeof run !== 'function') {
354
+ throw new Error('program must export run({ tools, args }) or a default function');
355
+ }
356
+ return run(scope);
357
+ }
358
+ return executeSourceCode(source, scope);
359
+ })();
360
+
361
+ const aborted = new Promise((_resolve, reject) => {
362
+ if (controller.signal.aborted) {
363
+ reject(controller.signal.reason ?? new Error('aborted'));
364
+ return;
365
+ }
366
+ controller.signal.addEventListener(
367
+ 'abort',
368
+ () => reject(controller.signal.reason ?? new Error('aborted')),
369
+ { once: true },
370
+ );
371
+ });
372
+ programPromise.catch(() => {});
373
+ result = await Promise.race([programPromise, aborted]);
374
+ } catch (e) {
375
+ failed = true;
376
+ errorPayload = normalizeError(e);
377
+ } finally {
378
+ if (timer) clearTimeout(timer);
379
+ if (signal) signal.removeEventListener('abort', abortFromOutside);
380
+ console.log = originalLog;
381
+ if (isolateProcess) {
382
+ process.stdout.write = originalWrite;
383
+ process.exit = originalExit;
384
+ }
385
+ }
386
+
387
+ const finishedAt = new Date().toISOString();
388
+ const stamp = startedAt.replace(/[:.]/g, '-');
389
+ const suffix = `${process.pid}-${randomBytes(4).toString('hex')}`;
390
+
391
+ let outPath = null;
392
+ try {
393
+ mkdirSync(outDir, { recursive: true, mode: 0o700 });
394
+ outPath = resolve(outDir, `${spillStem}-${stamp}-${suffix}.json`);
395
+ } catch (e) {
396
+ log(`[codemode] spill-dir-failed: ${e instanceof Error ? e.message : String(e)}`);
397
+ }
398
+
399
+ const serialize = (spillPath) => {
400
+ const envelope = {
401
+ ok: !failed,
402
+ version,
403
+ program: label,
404
+ startedAt,
405
+ finishedAt,
406
+ logs,
407
+ ...(failed ? { error: errorPayload } : { result: result ?? null }),
408
+ ...(spillPath ? { spill: { path: spillPath } } : {}),
409
+ };
410
+ try {
411
+ return { envelope, text: safeJsonStringify(envelope, 2) };
412
+ } catch (e) {
413
+ failed = true;
414
+ const fallback = {
415
+ ok: false,
416
+ version,
417
+ program: label,
418
+ startedAt,
419
+ finishedAt,
420
+ logs,
421
+ error: { kind: 'serialization', message: e instanceof Error ? e.message : String(e) },
422
+ ...(spillPath ? { spill: { path: spillPath } } : {}),
423
+ };
424
+ return { envelope: fallback, text: safeJsonStringify(fallback, 2) };
425
+ }
426
+ };
427
+
428
+ let serialized = serialize(null);
429
+ if (outPath && serialized.text.length > maxChars) {
430
+ serialized = serialize(outPath);
431
+ }
432
+
433
+ if (outPath) {
434
+ try {
435
+ writeFileSync(outPath, serialized.text, { mode: 0o600, flag: 'wx' });
436
+ } catch (e) {
437
+ log(`[codemode] spill-write-failed: ${e instanceof Error ? e.message : String(e)}`);
438
+ outPath = null;
439
+ serialized = serialize(null);
440
+ }
441
+ }
442
+
443
+ return {
444
+ ok: !failed,
445
+ envelope: serialized.envelope,
446
+ text: serialized.text,
447
+ logs,
448
+ spillPath: outPath,
449
+ truncated: Boolean(outPath) && serialized.text.length > maxChars,
450
+ maxChars,
451
+ startedAt,
452
+ finishedAt,
453
+ };
454
+ }
@@ -0,0 +1,154 @@
1
+ // Generic declarative CLI manifest adapter with anti-flag-injection validation
2
+ // and progressive tool discovery.
3
+ import { readFileSync } from 'node:fs';
4
+ import { basename, resolve } from 'node:path';
5
+ import {
6
+ assertPositiveInt,
7
+ assertRepo,
8
+ execJson,
9
+ execTool,
10
+ SAFE_TOKEN_RE,
11
+ ToolCallError,
12
+ } from './core.mjs';
13
+
14
+ const TOOL_NAME_RE = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)*$/;
15
+ const PLACEHOLDER_RE = /\{\{([A-Za-z0-9_]+)\}\}/g;
16
+ const RESERVED_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor', 'describe', 'call']);
17
+
18
+ function validateParam(toolName, paramName, spec = {}, rawValue) {
19
+ const value = rawValue === undefined ? spec.default : rawValue;
20
+ if (value === undefined || value === null || value === '') {
21
+ if (spec.required) {
22
+ throw new ToolCallError(toolName, `missing required parameter: ${paramName}`);
23
+ }
24
+ return undefined;
25
+ }
26
+
27
+ const type = spec.type ?? 'string';
28
+ if (type === 'int') {
29
+ return String(assertPositiveInt(toolName, paramName, value));
30
+ }
31
+ if (type === 'repo') {
32
+ return assertRepo(toolName, value);
33
+ }
34
+ if (type === 'safeToken') {
35
+ if (typeof value !== 'string' || !SAFE_TOKEN_RE.test(value)) {
36
+ throw new ToolCallError(toolName, `${paramName} must be a safe non-flag token`);
37
+ }
38
+ return value;
39
+ }
40
+ if (type === 'enum') {
41
+ const allowed = Array.isArray(spec.values) ? spec.values : [];
42
+ if (typeof value !== 'string' || !allowed.includes(value)) {
43
+ throw new ToolCallError(toolName, `${paramName} must be one of: ${allowed.join(', ')}`);
44
+ }
45
+ return value;
46
+ }
47
+
48
+ // Default: string (rejects leading '-' unless spec.allowFlag === true)
49
+ const str = String(value);
50
+ if (str.length === 0) {
51
+ if (spec.required) throw new ToolCallError(toolName, `${paramName} must be non-empty`);
52
+ return undefined;
53
+ }
54
+ if (spec.allowFlag !== true && str.startsWith('-')) {
55
+ throw new ToolCallError(toolName, `${paramName} must not start with '-' (flag injection blocked)`);
56
+ }
57
+ return str;
58
+ }
59
+
60
+ function resolveArgv(toolName, argTemplates, paramsSpec, input = {}) {
61
+ const validated = {};
62
+ for (const [paramName, spec] of Object.entries(paramsSpec ?? {})) {
63
+ validated[paramName] = validateParam(toolName, paramName, spec, input?.[paramName]);
64
+ }
65
+
66
+ const argv = [];
67
+ for (const template of argTemplates) {
68
+ if (typeof template !== 'string') {
69
+ throw new ToolCallError(toolName, 'manifest args must be strings');
70
+ }
71
+ // Whole-argument placeholder: omit arg if optional param is undefined
72
+ const exactMatch = /^\{\{([A-Za-z0-9_]+)\}\}$/.exec(template);
73
+ if (exactMatch) {
74
+ const key = exactMatch[1];
75
+ if (!(key in validated)) {
76
+ validated[key] = validateParam(toolName, key, { type: 'string', required: true }, input?.[key]);
77
+ }
78
+ if (validated[key] !== undefined) argv.push(validated[key]);
79
+ continue;
80
+ }
81
+
82
+ let missingOptional = false;
83
+ const expanded = template.replace(PLACEHOLDER_RE, (_m, key) => {
84
+ if (!(key in validated)) {
85
+ validated[key] = validateParam(toolName, key, { type: 'string', required: true }, input?.[key]);
86
+ }
87
+ if (validated[key] === undefined) {
88
+ missingOptional = true;
89
+ return '';
90
+ }
91
+ return validated[key];
92
+ });
93
+ if (!missingOptional) argv.push(expanded);
94
+ }
95
+ return argv;
96
+ }
97
+
98
+ export function createManifestTools(manifest, sourceLabel = 'manifest') {
99
+ if (!manifest || typeof manifest !== 'object' || !manifest.tools || typeof manifest.tools !== 'object') {
100
+ throw new Error('manifest must be an object with a "tools" map');
101
+ }
102
+
103
+ const flat = new Map();
104
+ const catalog = [];
105
+
106
+ for (const [name, def] of Object.entries(manifest.tools)) {
107
+ if (!TOOL_NAME_RE.test(name)) {
108
+ throw new Error(`invalid manifest tool name: ${name}`);
109
+ }
110
+ const segments = name.split('.');
111
+ if (segments.some((s) => RESERVED_SEGMENTS.has(s))) {
112
+ throw new Error(`reserved segment in manifest tool name: ${name}`);
113
+ }
114
+ if (!def || typeof def.cmd !== 'string' || def.cmd.trim().length === 0) {
115
+ throw new Error(`manifest tool "${name}" must specify a non-empty "cmd"`);
116
+ }
117
+ const argTemplates = Array.isArray(def.args) ? def.args : [];
118
+ const parse = def.parse === 'json' ? 'json' : 'text';
119
+ const timeout = Number.isInteger(def.timeout) && def.timeout > 0 ? def.timeout : 180000;
120
+ const paramsSpec = def.params && typeof def.params === 'object' ? def.params : {};
121
+
122
+ const fn = async (input = {}, opts) => {
123
+ const signal = opts?.signal;
124
+ const argv = resolveArgv(name, argTemplates, paramsSpec, input);
125
+ if (parse === 'json') {
126
+ return execJson(name, def.cmd, argv, { timeout, signal });
127
+ }
128
+ return (await execTool(name, def.cmd, argv, { timeout, signal })).trim();
129
+ };
130
+
131
+ flat.set(name, fn);
132
+ catalog.push({
133
+ name,
134
+ source: sourceLabel,
135
+ description: typeof def.description === 'string' ? def.description : `Run ${def.cmd}`,
136
+ params: Object.fromEntries(
137
+ Object.entries(paramsSpec).map(([k, spec]) => [
138
+ k,
139
+ `${spec.type ?? 'string'}${spec.required ? ' (required)' : spec.default !== undefined ? ` (default: ${spec.default})` : ' (optional)'}`,
140
+ ]),
141
+ ),
142
+ parse,
143
+ });
144
+ }
145
+
146
+ return { flat, catalog };
147
+ }
148
+
149
+ export function loadManifest(manifestPath) {
150
+ const fullPath = resolve(manifestPath);
151
+ const raw = readFileSync(fullPath, 'utf8');
152
+ const parsed = JSON.parse(raw);
153
+ return createManifestTools(parsed, `manifest:${basename(fullPath)}`);
154
+ }