jsmind 0.9.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +2 -2
- package/README.md +78 -67
- package/README.zh.md +81 -0
- package/dist/cli.js +4482 -0
- package/dist/cli.js.map +1 -0
- package/dist/jsmind.cjs +4101 -0
- package/dist/jsmind.cjs.map +1 -0
- package/dist/jsmind.d.ts +1269 -0
- package/dist/jsmind.js +4099 -0
- package/dist/jsmind.js.map +1 -0
- package/dist/jsmind.umd.js +4107 -0
- package/dist/jsmind.umd.js.map +1 -0
- package/package.json +65 -51
- package/es6/README-en.md +0 -37
- package/es6/README.md +0 -34
- package/es6/jsmind.draggable-node.js +0 -9
- package/es6/jsmind.draggable-node.js.map +0 -1
- package/es6/jsmind.js +0 -9
- package/es6/jsmind.js.map +0 -1
- package/es6/jsmind.screenshot.js +0 -9
- package/es6/jsmind.screenshot.js.map +0 -1
- package/style/jsmind.css +0 -408
- package/types/generated/index.d.ts +0 -8
- package/types/generated/jsmind.common.d.ts +0 -66
- package/types/generated/jsmind.d.ts +0 -366
- package/types/generated/jsmind.data_provider.d.ts +0 -56
- package/types/generated/jsmind.dom.d.ts +0 -59
- package/types/generated/jsmind.format.d.ts +0 -100
- package/types/generated/jsmind.graph.d.ts +0 -180
- package/types/generated/jsmind.layout_provider.d.ts +0 -182
- package/types/generated/jsmind.mind.d.ts +0 -121
- package/types/generated/jsmind.node.d.ts +0 -62
- package/types/generated/jsmind.option.d.ts +0 -64
- package/types/generated/jsmind.plugin.d.ts +0 -21
- package/types/generated/jsmind.shortcut_provider.d.ts +0 -52
- package/types/generated/jsmind.util.d.ts +0 -26
- package/types/generated/jsmind.view_provider.d.ts +0 -347
- package/types/generated/plugins/jsmind.draggable-node.d.ts +0 -229
- package/types/generated/plugins/jsmind.screenshot.d.ts +0 -83
- package/types/tsconfig.declaration.json +0 -19
package/dist/cli.js
ADDED
|
@@ -0,0 +1,4482 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* @license BSD-3-Clause
|
|
4
|
+
* @copyright 2014-2025 hizzgdev@163.com
|
|
5
|
+
*
|
|
6
|
+
* Project Home:
|
|
7
|
+
* https://github.com/hizzgdev/jsmind-v2/
|
|
8
|
+
*/
|
|
9
|
+
import { parseArgs } from 'node:util';
|
|
10
|
+
import { readFileSync, existsSync, copyFileSync, writeFileSync, mkdtempSync, rmSync, mkdirSync } from 'node:fs';
|
|
11
|
+
import { join, dirname, resolve } from 'node:path';
|
|
12
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
13
|
+
import { tmpdir } from 'node:os';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Exit codes and the error type the CLI commands throw.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* The three failure classes are kept apart on purpose. An agent that gets `1`
|
|
21
|
+
* will go and fix the data; one that gets `2` will fix its command line; one
|
|
22
|
+
* that gets `3` will stop and ask a human. Collapsing them into a single code
|
|
23
|
+
* leaves the caller guessing which of those to do.
|
|
24
|
+
*
|
|
25
|
+
* @packageDocumentation
|
|
26
|
+
*/
|
|
27
|
+
/**
|
|
28
|
+
* Process exit codes.
|
|
29
|
+
*
|
|
30
|
+
* @public
|
|
31
|
+
*/
|
|
32
|
+
const CliExit = {
|
|
33
|
+
/** Everything worked. */
|
|
34
|
+
Ok: 0,
|
|
35
|
+
/** The data is invalid: validation failed, or a referenced id is absent. */
|
|
36
|
+
InvalidData: 1,
|
|
37
|
+
/** The command line is wrong: missing argument, unknown command, conflicts. */
|
|
38
|
+
Usage: 2,
|
|
39
|
+
/** IO or runtime failure: file missing, no write permission, crash. */
|
|
40
|
+
IoError: 3,
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* An error that already knows which exit code it deserves.
|
|
44
|
+
*
|
|
45
|
+
* @public
|
|
46
|
+
*/
|
|
47
|
+
class CliError extends Error {
|
|
48
|
+
/** Exit code this failure maps to. */
|
|
49
|
+
exit;
|
|
50
|
+
/**
|
|
51
|
+
* @param message - Human-readable description, written to stderr.
|
|
52
|
+
* @param exit - Exit code to terminate with.
|
|
53
|
+
*/
|
|
54
|
+
constructor(message, exit) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.exit = exit;
|
|
57
|
+
this.name = 'CliError';
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Convenience constructor for a usage error.
|
|
62
|
+
*
|
|
63
|
+
* @param message - What the caller got wrong.
|
|
64
|
+
* @returns A CliError carrying `CliExit.Usage`.
|
|
65
|
+
*/
|
|
66
|
+
function usageError(message) {
|
|
67
|
+
return new CliError(message, CliExit.Usage);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Convenience constructor for an invalid-data error.
|
|
71
|
+
*
|
|
72
|
+
* @param message - What is wrong with the data.
|
|
73
|
+
* @returns A CliError carrying `CliExit.InvalidData`.
|
|
74
|
+
*/
|
|
75
|
+
function dataError(message) {
|
|
76
|
+
return new CliError(message, CliExit.InvalidData);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Convenience constructor for an IO error.
|
|
80
|
+
*
|
|
81
|
+
* @param message - What failed.
|
|
82
|
+
* @returns A CliError carrying `CliExit.IoError`.
|
|
83
|
+
*/
|
|
84
|
+
function ioError(message) {
|
|
85
|
+
return new CliError(message, CliExit.IoError);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* File and stream plumbing shared by every CLI command.
|
|
90
|
+
*
|
|
91
|
+
* @packageDocumentation
|
|
92
|
+
*/
|
|
93
|
+
/**
|
|
94
|
+
* Reads and parses a JSON file.
|
|
95
|
+
*
|
|
96
|
+
* @param path - File to read.
|
|
97
|
+
* @returns The parsed document.
|
|
98
|
+
* @throws {@link CliError} With `IoError` when the file cannot be read, or with
|
|
99
|
+
* `InvalidData` when it is not valid JSON.
|
|
100
|
+
*/
|
|
101
|
+
function readJsonFile(path) {
|
|
102
|
+
let text;
|
|
103
|
+
try {
|
|
104
|
+
text = readFileSync(path, 'utf8');
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
const code = err.code;
|
|
108
|
+
if (code === 'ENOENT') {
|
|
109
|
+
throw ioError(`File not found: ${path}`);
|
|
110
|
+
}
|
|
111
|
+
if (code === 'EACCES') {
|
|
112
|
+
throw ioError(`Permission denied: ${path}`);
|
|
113
|
+
}
|
|
114
|
+
throw ioError(`Cannot read ${path}: ${err.message}`);
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
return JSON.parse(text);
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
// Reachable file, unreadable content: that is a data problem, not a
|
|
121
|
+
// filesystem one. Exit 1 tells the caller to fix the file; exit 3 would
|
|
122
|
+
// send it to a human for something it can see for itself.
|
|
123
|
+
throw dataError(`Not valid JSON: ${path} (${err.message})`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Renders a document as the CLI writes it.
|
|
128
|
+
*
|
|
129
|
+
* @remarks
|
|
130
|
+
* Two-space indent and a trailing newline, so a file the CLI touches stays
|
|
131
|
+
* diff-friendly instead of collapsing onto one line.
|
|
132
|
+
*
|
|
133
|
+
* @param data - Document to render.
|
|
134
|
+
* @returns JSON text ready to write.
|
|
135
|
+
*/
|
|
136
|
+
function renderJson(data) {
|
|
137
|
+
return `${JSON.stringify(data, null, 2)}\n`;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Writes a document to disk.
|
|
141
|
+
*
|
|
142
|
+
* @remarks
|
|
143
|
+
* Returns the text that was written so the caller can validate exactly what
|
|
144
|
+
* landed, rather than re-deriving it and hoping the two agree.
|
|
145
|
+
*
|
|
146
|
+
* @param data - Document to write.
|
|
147
|
+
* @param target - Path to write to.
|
|
148
|
+
* @param options - Dry-run / backup behaviour.
|
|
149
|
+
* @returns The serialized text, or null in dry-run mode.
|
|
150
|
+
*/
|
|
151
|
+
function writeJsonFile(data, target, options) {
|
|
152
|
+
const text = renderJson(data);
|
|
153
|
+
if (options.dryRun) {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
if (options.backup && existsSync(target)) {
|
|
157
|
+
try {
|
|
158
|
+
copyFileSync(target, `${target}.bak`);
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
throw ioError(`Cannot create backup for ${target}: ${err.message}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
writeFileSync(target, text, 'utf8');
|
|
166
|
+
}
|
|
167
|
+
catch (err) {
|
|
168
|
+
throw ioError(`Cannot write ${target}: ${err.message}`);
|
|
169
|
+
}
|
|
170
|
+
return text;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Restores a file to a previously captured state.
|
|
174
|
+
*
|
|
175
|
+
* @remarks
|
|
176
|
+
* Used when validation fails after a write. Best effort: if even the restore
|
|
177
|
+
* fails the caller has already got a loud enough problem, so the original error
|
|
178
|
+
* is not masked by this one.
|
|
179
|
+
*
|
|
180
|
+
* @param target - Path to restore.
|
|
181
|
+
* @param previous - Exact contents to put back.
|
|
182
|
+
*/
|
|
183
|
+
function restoreFile(target, previous) {
|
|
184
|
+
try {
|
|
185
|
+
writeFileSync(target, previous, 'utf8');
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
// Nothing useful to add; the caller reports the validation failure,
|
|
189
|
+
// which is the real problem.
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Reads an integer option, falling back when it is absent.
|
|
194
|
+
*
|
|
195
|
+
* @param raw - Raw option value.
|
|
196
|
+
* @param fallback - Used when the option is absent.
|
|
197
|
+
* @param name - Option name for the error message.
|
|
198
|
+
* @returns The integer.
|
|
199
|
+
* @throws {@link CliError} With `Usage` when present but not a non-negative integer.
|
|
200
|
+
*/
|
|
201
|
+
function intOption(raw, fallback, name) {
|
|
202
|
+
if (raw === undefined) {
|
|
203
|
+
return fallback;
|
|
204
|
+
}
|
|
205
|
+
return parseIntOption(raw, name);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Reads an optional integer option, or `undefined` when absent.
|
|
209
|
+
*
|
|
210
|
+
* @param values - Parsed option values.
|
|
211
|
+
* @param name - Option name without dashes.
|
|
212
|
+
* @returns The non-negative integer, or `undefined`.
|
|
213
|
+
* @throws {@link CliError} With `Usage` when present but not a non-negative integer.
|
|
214
|
+
* @remarks
|
|
215
|
+
* The optional counterpart of {@link requireIntOption}. Together with
|
|
216
|
+
* {@link numberOption} that covers the three readers this CLI needs - required,
|
|
217
|
+
* optional, fractional - and none of them takes a flag deciding what it accepts:
|
|
218
|
+
* the name says it. A parameter that switched "allow negatives" on would have to
|
|
219
|
+
* be passed correctly at every call site, and forgetting it would not fail loudly.
|
|
220
|
+
*/
|
|
221
|
+
function optionalIntOption(values, name) {
|
|
222
|
+
if (values[name] === undefined) {
|
|
223
|
+
return undefined;
|
|
224
|
+
}
|
|
225
|
+
return parseIntOption(values[name], name);
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Reads a positive number option, falling back when it is absent.
|
|
229
|
+
*
|
|
230
|
+
* Unlike {@link intOption} this accepts fractions, which is what a rendering
|
|
231
|
+
* scale needs: 1.5 is a legitimate value, 0 is not - it would produce an
|
|
232
|
+
* image with no pixels in it.
|
|
233
|
+
*
|
|
234
|
+
* @param raw - Raw option value.
|
|
235
|
+
* @param fallback - Used when the option is absent.
|
|
236
|
+
* @param name - Option name for the error message.
|
|
237
|
+
* @returns The number.
|
|
238
|
+
* @throws {@link CliError} With `Usage` when present but not a positive number.
|
|
239
|
+
*/
|
|
240
|
+
function numberOption(raw, fallback, name) {
|
|
241
|
+
if (raw === undefined) {
|
|
242
|
+
return fallback;
|
|
243
|
+
}
|
|
244
|
+
const value = Number(raw);
|
|
245
|
+
if (!Number.isFinite(value) || value <= 0) {
|
|
246
|
+
throw usageError(`--${name} must be a positive number, got "${String(raw)}"`);
|
|
247
|
+
}
|
|
248
|
+
return value;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Reads an option restricted to a fixed set of values.
|
|
252
|
+
*
|
|
253
|
+
* The allowed list goes in the message, because "not one of image/gif" alone
|
|
254
|
+
* leaves the caller guessing what would have worked.
|
|
255
|
+
*
|
|
256
|
+
* @param raw - Raw option value.
|
|
257
|
+
* @param fallback - Used when the option is absent.
|
|
258
|
+
* @param allowed - Accepted values.
|
|
259
|
+
* @param name - Option name for the error message.
|
|
260
|
+
* @returns The chosen value.
|
|
261
|
+
* @throws {@link CliError} With `Usage` when present but not in `allowed`.
|
|
262
|
+
*/
|
|
263
|
+
function enumOption(raw, fallback, allowed, name) {
|
|
264
|
+
if (raw === undefined) {
|
|
265
|
+
return fallback;
|
|
266
|
+
}
|
|
267
|
+
const value = String(raw);
|
|
268
|
+
if (!allowed.includes(value)) {
|
|
269
|
+
throw usageError(`--${name} must be one of ${allowed.join(', ')}, got "${value}"`);
|
|
270
|
+
}
|
|
271
|
+
return value;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Converts one raw option value to a non-negative integer.
|
|
275
|
+
*
|
|
276
|
+
* @param raw - Raw value.
|
|
277
|
+
* @param name - Option name for the error message.
|
|
278
|
+
* @returns The integer.
|
|
279
|
+
* @throws {@link CliError} With `Usage` when the value is not a non-negative integer.
|
|
280
|
+
*/
|
|
281
|
+
function parseIntOption(raw, name) {
|
|
282
|
+
const value = Number(raw);
|
|
283
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
284
|
+
throw usageError(`--${name} must be a non-negative integer, got "${String(raw)}"`);
|
|
285
|
+
}
|
|
286
|
+
return value;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Reads a required string option from parsed arguments.
|
|
290
|
+
*
|
|
291
|
+
* @param values - Parsed option values.
|
|
292
|
+
* @param name - Option name without dashes.
|
|
293
|
+
* @returns The value.
|
|
294
|
+
* @throws {@link CliError} With `Usage` when absent.
|
|
295
|
+
*/
|
|
296
|
+
function requireOption(values, name) {
|
|
297
|
+
const value = values[name];
|
|
298
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
299
|
+
throw usageError(`Missing required option --${name}`);
|
|
300
|
+
}
|
|
301
|
+
return value;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Reads an optional string option.
|
|
305
|
+
*
|
|
306
|
+
* @param values - Parsed option values.
|
|
307
|
+
* @param name - Option name without dashes.
|
|
308
|
+
* @returns The value, or undefined.
|
|
309
|
+
*/
|
|
310
|
+
function optionalOption(values, name) {
|
|
311
|
+
const value = values[name];
|
|
312
|
+
return typeof value === 'string' ? value : undefined;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Plain-object helpers.
|
|
317
|
+
*
|
|
318
|
+
* @packageDocumentation
|
|
319
|
+
*/
|
|
320
|
+
/**
|
|
321
|
+
* Merges user values over default values, returning a new object.
|
|
322
|
+
*
|
|
323
|
+
* @remarks
|
|
324
|
+
* A one-level merge: nested objects are replaced, not merged field by field.
|
|
325
|
+
* Callers that need a deeper merge must merge each nested section themselves.
|
|
326
|
+
*
|
|
327
|
+
* The user values being absent returns a copy of the defaults rather than the
|
|
328
|
+
* defaults themselves, so the result can be mutated without reaching back into
|
|
329
|
+
* whatever constant was passed in.
|
|
330
|
+
*
|
|
331
|
+
* @param defaultValues - The base values.
|
|
332
|
+
* @param userValues - Values to apply on top, if any.
|
|
333
|
+
* @returns A new object; neither input is mutated.
|
|
334
|
+
*
|
|
335
|
+
* @public
|
|
336
|
+
*/
|
|
337
|
+
function mergeObjects(defaultValues, userValues) {
|
|
338
|
+
if (!userValues) {
|
|
339
|
+
return { ...defaultValues };
|
|
340
|
+
}
|
|
341
|
+
return {
|
|
342
|
+
...defaultValues,
|
|
343
|
+
...userValues
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Style and theme data structures for JsMind mind maps.
|
|
349
|
+
*
|
|
350
|
+
* @remarks
|
|
351
|
+
* This module only defines data. Nothing here draws anything — the rendering
|
|
352
|
+
* layer consumes these values but never appears in this file.
|
|
353
|
+
*
|
|
354
|
+
* @packageDocumentation
|
|
355
|
+
*/
|
|
356
|
+
/**
|
|
357
|
+
* Semantic tone. Expresses color only, never geometry.
|
|
358
|
+
*
|
|
359
|
+
* @remarks
|
|
360
|
+
* Semantic roles are about color; geometry is orthogonal (a node can be
|
|
361
|
+
* warning-colored, thick-bordered and large-font at once). Keeping them apart
|
|
362
|
+
* gives the agent fewer side effects per change, which makes generated output
|
|
363
|
+
* more controllable.
|
|
364
|
+
*
|
|
365
|
+
* @public
|
|
366
|
+
*/
|
|
367
|
+
const JmTone = {
|
|
368
|
+
/** Default tone, resolved from the theme's neutral palette. */
|
|
369
|
+
Default: 'default',
|
|
370
|
+
/** Primary or emphasis tone. */
|
|
371
|
+
Primary: 'primary',
|
|
372
|
+
/** Success or positive tone. */
|
|
373
|
+
Success: 'success',
|
|
374
|
+
/** Warning or caution tone. */
|
|
375
|
+
Warning: 'warning',
|
|
376
|
+
/** Danger or negative tone. */
|
|
377
|
+
Danger: 'danger',
|
|
378
|
+
/** Informational or neutral-accent tone. */
|
|
379
|
+
Info: 'info',
|
|
380
|
+
/**
|
|
381
|
+
* Accent tone for an element that stands out without carrying a judgement.
|
|
382
|
+
*
|
|
383
|
+
* @remarks
|
|
384
|
+
* `primary` already means "this is the important one", which is a claim
|
|
385
|
+
* about the content. `accent` is the option for "make this one visually
|
|
386
|
+
* distinct" with no claim attached — the purple that v1 exposed as
|
|
387
|
+
* `theme-wisteria` and that none of the semantic tones could absorb.
|
|
388
|
+
*/
|
|
389
|
+
Accent: 'accent',
|
|
390
|
+
};
|
|
391
|
+
/**
|
|
392
|
+
* Font weight.
|
|
393
|
+
*
|
|
394
|
+
* @remarks
|
|
395
|
+
* An enum rather than an inline union so the CLI can enumerate the accepted
|
|
396
|
+
* values instead of repeating them. `JmLinePattern` and `JmLineCurve` had this
|
|
397
|
+
* shape already; `fontWeight` was the odd one out.
|
|
398
|
+
*
|
|
399
|
+
* @public
|
|
400
|
+
*/
|
|
401
|
+
const JmFontWeight = {
|
|
402
|
+
/** Regular weight. */
|
|
403
|
+
Normal: 'normal',
|
|
404
|
+
/** Emphasised weight. */
|
|
405
|
+
Bold: 'bold',
|
|
406
|
+
};
|
|
407
|
+
/**
|
|
408
|
+
* Line dash style.
|
|
409
|
+
*
|
|
410
|
+
* @public
|
|
411
|
+
*/
|
|
412
|
+
const JmLinePattern = {
|
|
413
|
+
/** Continuous line. */
|
|
414
|
+
Solid: 'solid',
|
|
415
|
+
/** Dashed line. */
|
|
416
|
+
Dashed: 'dashed',
|
|
417
|
+
/** Dotted line. */
|
|
418
|
+
Dotted: 'dotted',
|
|
419
|
+
};
|
|
420
|
+
/**
|
|
421
|
+
* How a line travels between its two endpoints.
|
|
422
|
+
*
|
|
423
|
+
* @remarks
|
|
424
|
+
* A different axis from {@link JmLinePattern}: `pattern` says whether the
|
|
425
|
+
* stroke is dashed, `curve` says what shape it traces. They are separable on
|
|
426
|
+
* purpose - a straight dashed line and a curved dashed line both need to exist,
|
|
427
|
+
* and a single `style` string (as in v1's `line_style`) could only ever express
|
|
428
|
+
* one of the two.
|
|
429
|
+
*
|
|
430
|
+
* @public
|
|
431
|
+
*/
|
|
432
|
+
const JmLineCurve = {
|
|
433
|
+
/** Straight segment from one endpoint to the other. */
|
|
434
|
+
Straight: 'straight',
|
|
435
|
+
/**
|
|
436
|
+
* Cubic bezier leaving each endpoint horizontally.
|
|
437
|
+
*
|
|
438
|
+
* @remarks
|
|
439
|
+
* The default, and what v1 drew. Edges leaving a node always read better
|
|
440
|
+
* when they depart along the horizontal axis: siblings sit in a column, so a
|
|
441
|
+
* straight segment between two of them cuts diagonally across the layout.
|
|
442
|
+
*/
|
|
443
|
+
Bezier: 'bezier',
|
|
444
|
+
};
|
|
445
|
+
/**
|
|
446
|
+
* The only theme built into this version.
|
|
447
|
+
*
|
|
448
|
+
* @remarks
|
|
449
|
+
* Dark mode is a separate theme, not a light/dark variant pair of the same
|
|
450
|
+
* theme, because a dark palette is not a mechanical inversion of a light one.
|
|
451
|
+
*
|
|
452
|
+
* @public
|
|
453
|
+
*/
|
|
454
|
+
const JSMIND_THEME_DEFAULT = {
|
|
455
|
+
background: '#ffffff',
|
|
456
|
+
// Filled solids with white text, taken from v1 — a node carrying a tone
|
|
457
|
+
// that only tints its background barely reads as "this one is different"
|
|
458
|
+
// from across the canvas. The v1 palette names that map onto these tones
|
|
459
|
+
// (belizehole, nephrite, pumpkin, pomegranate) are the same hue a few
|
|
460
|
+
// degrees away, so they fold in rather than getting their own entry.
|
|
461
|
+
tones: {
|
|
462
|
+
default: { fillColor: '#ffffff', textColor: '#333333', borderColor: '#cccccc', lineColor: '#b0b0b0' },
|
|
463
|
+
primary: { fillColor: '#428bca', textColor: '#ffffff', borderColor: '#357ebd', lineColor: '#689ece' },
|
|
464
|
+
success: { fillColor: '#5cb85c', textColor: '#ffffff', borderColor: '#4cae4c', lineColor: '#79c279' },
|
|
465
|
+
warning: { fillColor: '#f0ad4e', textColor: '#ffffff', borderColor: '#eea236', lineColor: '#f2b968' },
|
|
466
|
+
danger: { fillColor: '#d9534f', textColor: '#ffffff', borderColor: '#d43f3a', lineColor: '#df6f6b' },
|
|
467
|
+
info: { fillColor: '#5dc0de', textColor: '#ffffff', borderColor: '#46b8da', lineColor: '#74cae3' },
|
|
468
|
+
accent: { fillColor: '#9b59b6', textColor: '#ffffff', borderColor: '#8e44ad', lineColor: '#aa73c2' },
|
|
469
|
+
},
|
|
470
|
+
node: {
|
|
471
|
+
radius: 5,
|
|
472
|
+
padding: 10,
|
|
473
|
+
fontSize: 16,
|
|
474
|
+
rootFontSize: 24,
|
|
475
|
+
fontFamily: 'Verdana, Arial, Helvetica, sans-serif',
|
|
476
|
+
lineHeight: 1.125,
|
|
477
|
+
// Zero, because the stylesheet drew no border: the depth came from the
|
|
478
|
+
// shadow below. Tone palettes still carry a borderColor for themes that
|
|
479
|
+
// do want one.
|
|
480
|
+
borderWidth: 0,
|
|
481
|
+
maxWidth: 400,
|
|
482
|
+
shadow: {
|
|
483
|
+
normal: { offsetX: 1, offsetY: 1, blur: 1, color: '#666666' },
|
|
484
|
+
hover: { offsetX: 2, offsetY: 2, blur: 8, color: '#000000' },
|
|
485
|
+
selected: { offsetX: 2, offsetY: 2, blur: 8, color: '#000000' },
|
|
486
|
+
},
|
|
487
|
+
},
|
|
488
|
+
line: {
|
|
489
|
+
width: 2,
|
|
490
|
+
pattern: JmLinePattern.Solid,
|
|
491
|
+
curve: JmLineCurve.Bezier,
|
|
492
|
+
},
|
|
493
|
+
expander: {
|
|
494
|
+
size: 13,
|
|
495
|
+
radius: 6.5,
|
|
496
|
+
fontSize: 8,
|
|
497
|
+
lineHeight: 11,
|
|
498
|
+
borderWidth: 1,
|
|
499
|
+
},
|
|
500
|
+
};
|
|
501
|
+
/**
|
|
502
|
+
* Built-in theme presets, keyed by name.
|
|
503
|
+
*
|
|
504
|
+
* @public
|
|
505
|
+
*/
|
|
506
|
+
const JSMIND_THEME_PRESETS = {
|
|
507
|
+
default: JSMIND_THEME_DEFAULT,
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* Custom error class for jsMind operations.
|
|
512
|
+
*
|
|
513
|
+
* @public
|
|
514
|
+
*/
|
|
515
|
+
class JsMindError extends Error {
|
|
516
|
+
/** The data associated with the error. */
|
|
517
|
+
data;
|
|
518
|
+
/**
|
|
519
|
+
* Stable machine-readable code, when the failure has one.
|
|
520
|
+
*
|
|
521
|
+
* @remarks
|
|
522
|
+
* Callers branch on this rather than on `message`, which is written for
|
|
523
|
+
* humans and may be reworded at any time.
|
|
524
|
+
*/
|
|
525
|
+
code;
|
|
526
|
+
/**
|
|
527
|
+
* Creates a new JsMindError instance.
|
|
528
|
+
*
|
|
529
|
+
* @param message - The error message.
|
|
530
|
+
* @param data - Extra data carried with the error.
|
|
531
|
+
* @param code - Stable machine-readable code, if any.
|
|
532
|
+
*/
|
|
533
|
+
constructor(message, data = {}, code) {
|
|
534
|
+
super(message);
|
|
535
|
+
this.data = data;
|
|
536
|
+
if (code !== undefined) {
|
|
537
|
+
this.code = code;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Represents a size with width and height.
|
|
544
|
+
*
|
|
545
|
+
* @public
|
|
546
|
+
*/
|
|
547
|
+
class JmSize {
|
|
548
|
+
/** The width value. */
|
|
549
|
+
width;
|
|
550
|
+
/** The height value. */
|
|
551
|
+
height;
|
|
552
|
+
/**
|
|
553
|
+
* Creates a new size instance.
|
|
554
|
+
*
|
|
555
|
+
* @param width - The width value.
|
|
556
|
+
* @param height - The height value.
|
|
557
|
+
*/
|
|
558
|
+
constructor(width, height) {
|
|
559
|
+
this.width = width;
|
|
560
|
+
this.height = height;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
class JmPoint {
|
|
564
|
+
x;
|
|
565
|
+
y;
|
|
566
|
+
constructor(x, y) {
|
|
567
|
+
this.x = x;
|
|
568
|
+
this.y = y;
|
|
569
|
+
}
|
|
570
|
+
offset(offset) {
|
|
571
|
+
return new JmPoint(this.x + offset.x, this.y + offset.y);
|
|
572
|
+
}
|
|
573
|
+
static Zero = new JmPoint(0, 0);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
class JmNodeViewData {
|
|
577
|
+
element = null;
|
|
578
|
+
expander = null;
|
|
579
|
+
leadingLine = null;
|
|
580
|
+
}
|
|
581
|
+
class JmNodeLayoutData {
|
|
582
|
+
side = JmNodeSide.Center;
|
|
583
|
+
visible = true;
|
|
584
|
+
size = new JmSize(0, 0);
|
|
585
|
+
withDescendantsSize = new JmSize(0, 0);
|
|
586
|
+
offsetToParent = new JmPoint(0, 0);
|
|
587
|
+
}
|
|
588
|
+
class NodeInternalData {
|
|
589
|
+
view = new JmNodeViewData();
|
|
590
|
+
layout = new JmNodeLayoutData();
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Node of mind map.
|
|
594
|
+
*
|
|
595
|
+
* @public
|
|
596
|
+
*/
|
|
597
|
+
class JmNode {
|
|
598
|
+
/** The unique identifier of the node. */
|
|
599
|
+
id;
|
|
600
|
+
/** The content of the node. */
|
|
601
|
+
content;
|
|
602
|
+
/** The parent node, or null if this is the root node. */
|
|
603
|
+
parent;
|
|
604
|
+
/** Array of child nodes. */
|
|
605
|
+
children;
|
|
606
|
+
/** Whether the node is folded (collapsed). */
|
|
607
|
+
folded;
|
|
608
|
+
/** The direction of the node. */
|
|
609
|
+
side;
|
|
610
|
+
/** Additional data associated with the node. */
|
|
611
|
+
data;
|
|
612
|
+
/**
|
|
613
|
+
* Visual overrides for this node.
|
|
614
|
+
*
|
|
615
|
+
* @remarks
|
|
616
|
+
* Unset fields fall back to the theme. Storing only the difference keeps
|
|
617
|
+
* theme changes propagating to every node that did not override anything.
|
|
618
|
+
*/
|
|
619
|
+
style;
|
|
620
|
+
/** View data associated with the node. */
|
|
621
|
+
_data;
|
|
622
|
+
/**
|
|
623
|
+
* Creates a new node.
|
|
624
|
+
*
|
|
625
|
+
* @param id - The unique identifier of the node.
|
|
626
|
+
* @param content - The content of the node.
|
|
627
|
+
* @throws {@link JsMindError} If the node ID or content is invalid.
|
|
628
|
+
*/
|
|
629
|
+
constructor(id, content) {
|
|
630
|
+
if (!id) {
|
|
631
|
+
throw new JsMindError('Invalid node id');
|
|
632
|
+
}
|
|
633
|
+
if (!content) {
|
|
634
|
+
throw new JsMindError('Content is required');
|
|
635
|
+
}
|
|
636
|
+
this.id = id;
|
|
637
|
+
this.content = content;
|
|
638
|
+
this.parent = null;
|
|
639
|
+
this.children = [];
|
|
640
|
+
this.folded = false;
|
|
641
|
+
this.side = JmNodeSide.SideA;
|
|
642
|
+
this.data = {};
|
|
643
|
+
this._data = new NodeInternalData();
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Lists all subnode IDs recursively.
|
|
647
|
+
*
|
|
648
|
+
* @returns Array of all subnode IDs including this node's children and their descendants.
|
|
649
|
+
*/
|
|
650
|
+
getAllSubnodeIds() {
|
|
651
|
+
const nodeIds = [];
|
|
652
|
+
if (this.children.length > 0) {
|
|
653
|
+
this.children.forEach((node) => {
|
|
654
|
+
nodeIds.push(node.id);
|
|
655
|
+
nodeIds.push(...node.getAllSubnodeIds());
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
return nodeIds;
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Compares this node with another node.
|
|
662
|
+
*
|
|
663
|
+
* @param other - The other node to compare with.
|
|
664
|
+
* @returns True if they are equal, false otherwise.
|
|
665
|
+
*/
|
|
666
|
+
equals(other) {
|
|
667
|
+
return this.id === other.id
|
|
668
|
+
&& this.content.type === other.content.type
|
|
669
|
+
&& this.content.value === other.content.value
|
|
670
|
+
&& this.folded === other.folded
|
|
671
|
+
&& this.side === other.side
|
|
672
|
+
&& ((this.parent === null && other.parent === null) || (this.parent.id === other.parent.id))
|
|
673
|
+
&& this.children.length === other.children.length
|
|
674
|
+
&& this.children.every((child, idx, _) => { return child.id === other.children[idx].id; });
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Checks if this node is a descendant of another node.
|
|
678
|
+
*
|
|
679
|
+
* @param potentialAncestor - The potential ancestor node.
|
|
680
|
+
* @returns True if this node is a descendant of potentialAncestor.
|
|
681
|
+
*/
|
|
682
|
+
isDescendant(potentialAncestor) {
|
|
683
|
+
if (!potentialAncestor || !potentialAncestor.children) {
|
|
684
|
+
return false;
|
|
685
|
+
}
|
|
686
|
+
for (const child of potentialAncestor.children) {
|
|
687
|
+
if (child.id === this.id) {
|
|
688
|
+
return true;
|
|
689
|
+
}
|
|
690
|
+
if (this.isDescendant(child)) {
|
|
691
|
+
return true;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
return false;
|
|
695
|
+
}
|
|
696
|
+
isRoot() {
|
|
697
|
+
return this.parent === null;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Enumeration for directions of node.
|
|
702
|
+
*
|
|
703
|
+
* @public
|
|
704
|
+
*/
|
|
705
|
+
const JmNodeSide = {
|
|
706
|
+
/** Left direction. */
|
|
707
|
+
SideB: -1,
|
|
708
|
+
/** Center direction. */
|
|
709
|
+
Center: 0,
|
|
710
|
+
/** Right direction. */
|
|
711
|
+
SideA: 1,
|
|
712
|
+
};
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* Edge of mind map.
|
|
716
|
+
*
|
|
717
|
+
* @remarks
|
|
718
|
+
* Edges represent additional relationships between nodes (not parent-child relationships).
|
|
719
|
+
*
|
|
720
|
+
* @public
|
|
721
|
+
*/
|
|
722
|
+
class JmEdge {
|
|
723
|
+
/** The unique identifier of the edge. */
|
|
724
|
+
id;
|
|
725
|
+
/** The ID of the source node. */
|
|
726
|
+
sourceNodeId;
|
|
727
|
+
/** The ID of the target node. */
|
|
728
|
+
targetNodeId;
|
|
729
|
+
/** The type of the edge. */
|
|
730
|
+
type;
|
|
731
|
+
/** The optional label of the edge. */
|
|
732
|
+
label;
|
|
733
|
+
/**
|
|
734
|
+
* Visual style of the edge line.
|
|
735
|
+
*
|
|
736
|
+
* @remarks
|
|
737
|
+
* Uses the same `JmLineStyle` as `JmNodeStyle.incoming` so that
|
|
738
|
+
* hierarchical and additional relationships share one vocabulary.
|
|
739
|
+
*/
|
|
740
|
+
style;
|
|
741
|
+
/**
|
|
742
|
+
* Creates a new edge.
|
|
743
|
+
*
|
|
744
|
+
* @param id - The unique identifier of the edge.
|
|
745
|
+
* @param sourceNodeId - The ID of the source node.
|
|
746
|
+
* @param targetNodeId - The ID of the target node.
|
|
747
|
+
* @param type - The type of the edge.
|
|
748
|
+
* @param label - Optional label for the edge.
|
|
749
|
+
* @throws {@link JsMindError} If any of the required parameters are invalid.
|
|
750
|
+
*/
|
|
751
|
+
constructor(id, sourceNodeId, targetNodeId, type, label = null) {
|
|
752
|
+
if (!id) {
|
|
753
|
+
throw new JsMindError('invalid edge id');
|
|
754
|
+
}
|
|
755
|
+
if (!sourceNodeId) {
|
|
756
|
+
throw new JsMindError('invalid source node id');
|
|
757
|
+
}
|
|
758
|
+
if (!targetNodeId) {
|
|
759
|
+
throw new JsMindError('invalid target node');
|
|
760
|
+
}
|
|
761
|
+
if (!type) {
|
|
762
|
+
throw new JsMindError('invalid edge type');
|
|
763
|
+
}
|
|
764
|
+
this.id = id;
|
|
765
|
+
this.sourceNodeId = sourceNodeId;
|
|
766
|
+
this.targetNodeId = targetNodeId;
|
|
767
|
+
this.type = type;
|
|
768
|
+
this.label = label;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Type of edge - only for additional relationships (not parent-child).
|
|
773
|
+
*
|
|
774
|
+
* @public
|
|
775
|
+
*/
|
|
776
|
+
const JmEdgeType = {
|
|
777
|
+
/** Link edge type. */
|
|
778
|
+
Link: 'link',
|
|
779
|
+
};
|
|
780
|
+
|
|
781
|
+
/**
|
|
782
|
+
* Content types and utilities for JsMind nodes.
|
|
783
|
+
*
|
|
784
|
+
* @packageDocumentation
|
|
785
|
+
*/
|
|
786
|
+
/**
|
|
787
|
+
* Enumeration for content types of node.
|
|
788
|
+
*
|
|
789
|
+
* @public
|
|
790
|
+
*/
|
|
791
|
+
const JmNodeContentType = {
|
|
792
|
+
/** Text content type. */
|
|
793
|
+
Text: 'text',
|
|
794
|
+
};
|
|
795
|
+
/**
|
|
796
|
+
* Content of mind map node.
|
|
797
|
+
*
|
|
798
|
+
* @public
|
|
799
|
+
*/
|
|
800
|
+
class JmNodeContent {
|
|
801
|
+
/** The type of the content. */
|
|
802
|
+
type;
|
|
803
|
+
/** The actual content value. */
|
|
804
|
+
value;
|
|
805
|
+
/**
|
|
806
|
+
* Creates a content object.
|
|
807
|
+
*
|
|
808
|
+
* @param type - The type of content.
|
|
809
|
+
* @param value - The actual content value.
|
|
810
|
+
* @throws {@link Error} If the content type is invalid.
|
|
811
|
+
*/
|
|
812
|
+
constructor(type, value) {
|
|
813
|
+
if (!type || !Object.values(JmNodeContentType).includes(type)) {
|
|
814
|
+
throw new Error(`Invalid content type: ${type}`);
|
|
815
|
+
}
|
|
816
|
+
this.type = type;
|
|
817
|
+
this.value = value;
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Checks if content is of specific type.
|
|
821
|
+
*
|
|
822
|
+
* @param type - The type to check.
|
|
823
|
+
* @returns True if content is of the specified type.
|
|
824
|
+
*/
|
|
825
|
+
hasType(type) {
|
|
826
|
+
return this.type === type;
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Checks if content is text type.
|
|
830
|
+
*
|
|
831
|
+
* @returns True if content is text type.
|
|
832
|
+
*/
|
|
833
|
+
isText() {
|
|
834
|
+
return this.hasType(JmNodeContentType.Text);
|
|
835
|
+
}
|
|
836
|
+
getText() {
|
|
837
|
+
if (!this.isText()) {
|
|
838
|
+
throw new Error('Content is not text type');
|
|
839
|
+
}
|
|
840
|
+
return this.value;
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Creates a text content object.
|
|
844
|
+
*
|
|
845
|
+
* @param text - The text content.
|
|
846
|
+
* @returns The content object.
|
|
847
|
+
*/
|
|
848
|
+
static createText(text) {
|
|
849
|
+
return new JmNodeContent(JmNodeContentType.Text, text);
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* Creates a content object from an object with type and value.
|
|
853
|
+
*
|
|
854
|
+
* @param obj - The object to create content from.
|
|
855
|
+
* @returns The content object.
|
|
856
|
+
*/
|
|
857
|
+
static fromObject(obj) {
|
|
858
|
+
return new JmNodeContent(obj.type, obj.value);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/**
|
|
863
|
+
* Validation for v2 mind map data.
|
|
864
|
+
*
|
|
865
|
+
* @remarks
|
|
866
|
+
* Every check returns a coded issue instead of throwing. A caller (the CLI, a
|
|
867
|
+
* host application, an agent) branches on `code`; the `message` is for humans
|
|
868
|
+
* to read and must never be parsed.
|
|
869
|
+
*
|
|
870
|
+
* @packageDocumentation
|
|
871
|
+
*/
|
|
872
|
+
/**
|
|
873
|
+
* Error codes for v2 data validation.
|
|
874
|
+
*
|
|
875
|
+
* @remarks
|
|
876
|
+
* Codes are stable identifiers. Messages may be reworded at any time; these
|
|
877
|
+
* may not.
|
|
878
|
+
*
|
|
879
|
+
* @public
|
|
880
|
+
*/
|
|
881
|
+
const JmValidationCode = {
|
|
882
|
+
/** Top-level `format` missing or not "jsmind_v2". */
|
|
883
|
+
Format: 'E_FORMAT',
|
|
884
|
+
/** `meta` missing or its fields are not strings. */
|
|
885
|
+
Meta: 'E_META',
|
|
886
|
+
/** The top-level `nodes` object is absent or not an object. */
|
|
887
|
+
NodesMissing: 'E_NODES_MISSING',
|
|
888
|
+
/** The top-level `edges` object is absent or not an object. */
|
|
889
|
+
EdgesMissing: 'E_EDGES_MISSING',
|
|
890
|
+
/** `root` does not point at an existing node. */
|
|
891
|
+
RootMissing: 'E_ROOT_MISSING',
|
|
892
|
+
/** A `nodes` key differs from the `id` of its value. */
|
|
893
|
+
NodeKeyMismatch: 'E_NODE_KEY_MISMATCH',
|
|
894
|
+
/** An `edges` key differs from the `id` of its value. */
|
|
895
|
+
EdgeKeyMismatch: 'E_EDGE_KEY_MISMATCH',
|
|
896
|
+
/** A node's `parent` points at a node that is not present. */
|
|
897
|
+
NodeParentMissing: 'E_NODE_PARENT_MISSING',
|
|
898
|
+
/** A node's `children` lists an id that is not present. */
|
|
899
|
+
NodeChildMissing: 'E_NODE_CHILD_MISSING',
|
|
900
|
+
/** An edge endpoint points at a node that is not present. */
|
|
901
|
+
EdgeNodeMissing: 'E_EDGE_NODE_MISSING',
|
|
902
|
+
/** More than one node has `parent === null`. */
|
|
903
|
+
MultipleRoots: 'E_MULTIPLE_ROOTS',
|
|
904
|
+
/** The root node has a non-null `parent`. */
|
|
905
|
+
RootParentSet: 'E_ROOT_PARENT_SET',
|
|
906
|
+
/** A non-root node uses `side: 0`, which belongs to the root alone. */
|
|
907
|
+
NonRootSideCenter: 'E_NON_ROOT_SIDE_CENTER',
|
|
908
|
+
/** `parent.children` and `child.parent` disagree. */
|
|
909
|
+
ParentChildMismatch: 'E_PARENT_CHILD_MISMATCH',
|
|
910
|
+
/** Following `parent` links returns to where it started. */
|
|
911
|
+
Cycle: 'E_CYCLE',
|
|
912
|
+
/** `content.type` is not a known content type. */
|
|
913
|
+
ContentType: 'E_CONTENT_TYPE',
|
|
914
|
+
/** `edge.type` is not a known edge type. */
|
|
915
|
+
EdgeType: 'E_EDGE_TYPE',
|
|
916
|
+
/** `side` is not a known side value. */
|
|
917
|
+
Side: 'E_SIDE',
|
|
918
|
+
/** `style.tone` is not one of the known tones. */
|
|
919
|
+
Tone: 'E_TONE',
|
|
920
|
+
/** A line pattern is not solid/dashed/dotted. */
|
|
921
|
+
LineStyle: 'E_LINE_STYLE',
|
|
922
|
+
/** A numeric style value is out of range. */
|
|
923
|
+
StyleRange: 'E_STYLE_RANGE',
|
|
924
|
+
/** `style.theme` names a preset that does not exist. */
|
|
925
|
+
ThemeUnknown: 'E_THEME_UNKNOWN',
|
|
926
|
+
};
|
|
927
|
+
/** Edge types accepted for `edge.type`. */
|
|
928
|
+
const EDGE_TYPES = new Set(Object.values(JmEdgeType));
|
|
929
|
+
/** Numeric side values accepted for a node. */
|
|
930
|
+
const SIDE_VALUES = new Set(Object.values(JmNodeSide));
|
|
931
|
+
/** Line patterns accepted for `borderStyle` and `incoming.pattern`. */
|
|
932
|
+
const LINE_PATTERNS = new Set(Object.values(JmLinePattern));
|
|
933
|
+
/** Tones accepted for `style.tone`. */
|
|
934
|
+
const TONES = new Set(Object.values(JmTone));
|
|
935
|
+
/** Content types accepted for `content.type`. */
|
|
936
|
+
const CONTENT_TYPES = new Set(Object.values(JmNodeContentType));
|
|
937
|
+
/**
|
|
938
|
+
* Narrows to a plain object.
|
|
939
|
+
*
|
|
940
|
+
* @param value - Value to test.
|
|
941
|
+
* @returns True for non-null, non-array objects.
|
|
942
|
+
*/
|
|
943
|
+
function isRecord(value) {
|
|
944
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Reads a string field, or null when absent or not a string.
|
|
948
|
+
*
|
|
949
|
+
* @param holder - Object to read from.
|
|
950
|
+
* @param key - Field name.
|
|
951
|
+
* @returns The string, or null.
|
|
952
|
+
*/
|
|
953
|
+
function str(holder, key) {
|
|
954
|
+
const value = holder[key];
|
|
955
|
+
return typeof value === 'string' ? value : null;
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* Validates v2 data against every rule in the format specification.
|
|
959
|
+
*
|
|
960
|
+
* @remarks
|
|
961
|
+
* Never throws for malformed input: anything structurally wrong becomes an
|
|
962
|
+
* issue with a code. The one thing it cannot represent is a non-object root,
|
|
963
|
+
* which it reports as `E_FORMAT` since nothing can be read from it.
|
|
964
|
+
*
|
|
965
|
+
* @param data - Candidate data, typically parsed JSON.
|
|
966
|
+
* @returns Every issue found; `valid` is true only when the list is empty.
|
|
967
|
+
*
|
|
968
|
+
* @public
|
|
969
|
+
*/
|
|
970
|
+
function validateMindData(data) {
|
|
971
|
+
const errors = [];
|
|
972
|
+
if (!isRecord(data)) {
|
|
973
|
+
errors.push({
|
|
974
|
+
code: JmValidationCode.Format,
|
|
975
|
+
path: '',
|
|
976
|
+
message: 'Data is not an object.',
|
|
977
|
+
});
|
|
978
|
+
return { valid: false, errors };
|
|
979
|
+
}
|
|
980
|
+
// ---- format ----
|
|
981
|
+
if (data.format !== 'jsmind_v2') {
|
|
982
|
+
errors.push({
|
|
983
|
+
code: JmValidationCode.Format,
|
|
984
|
+
path: 'format',
|
|
985
|
+
message: `Expected format "jsmind_v2", got ${JSON.stringify(data.format) ?? 'nothing'}.`,
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
// ---- meta ----
|
|
989
|
+
const meta = data.meta;
|
|
990
|
+
if (!isRecord(meta)) {
|
|
991
|
+
errors.push({
|
|
992
|
+
code: JmValidationCode.Meta,
|
|
993
|
+
path: 'meta',
|
|
994
|
+
message: 'Missing "meta" object.',
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
else {
|
|
998
|
+
for (const key of ['name', 'author', 'version']) {
|
|
999
|
+
if (typeof meta[key] !== 'string') {
|
|
1000
|
+
errors.push({
|
|
1001
|
+
code: JmValidationCode.Meta,
|
|
1002
|
+
path: `meta/${key}`,
|
|
1003
|
+
message: `"meta.${key}" must be a string.`,
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
// ---- nodes / edges containers ----
|
|
1009
|
+
const nodes = data.nodes;
|
|
1010
|
+
const edges = data.edges;
|
|
1011
|
+
// Both container checks run before the early return: a document missing both
|
|
1012
|
+
// should learn about both, not just whichever is checked first.
|
|
1013
|
+
if (!isRecord(nodes)) {
|
|
1014
|
+
errors.push({
|
|
1015
|
+
code: JmValidationCode.NodesMissing,
|
|
1016
|
+
path: 'nodes',
|
|
1017
|
+
message: 'Missing "nodes" object.',
|
|
1018
|
+
});
|
|
1019
|
+
}
|
|
1020
|
+
if (!isRecord(edges)) {
|
|
1021
|
+
errors.push({
|
|
1022
|
+
code: JmValidationCode.EdgesMissing,
|
|
1023
|
+
path: 'edges',
|
|
1024
|
+
message: 'Missing "edges" object.',
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
if (!isRecord(nodes)) {
|
|
1028
|
+
// Without nodes there is not a single reference in the document that can
|
|
1029
|
+
// be resolved, so every later rule would only repeat itself.
|
|
1030
|
+
return { valid: false, errors };
|
|
1031
|
+
}
|
|
1032
|
+
const nodeIds = new Set(Object.keys(nodes));
|
|
1033
|
+
// ---- root ----
|
|
1034
|
+
const rootId = str(data, 'root');
|
|
1035
|
+
if (!rootId) {
|
|
1036
|
+
errors.push({
|
|
1037
|
+
code: JmValidationCode.RootMissing,
|
|
1038
|
+
path: 'root',
|
|
1039
|
+
message: '"root" must be a non-empty string.',
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
else if (!nodeIds.has(rootId)) {
|
|
1043
|
+
errors.push({
|
|
1044
|
+
code: JmValidationCode.RootMissing,
|
|
1045
|
+
path: 'root',
|
|
1046
|
+
message: `"root" points at "${rootId}", which is not in "nodes".`,
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
// ---- node keys ----
|
|
1050
|
+
for (const [key, node] of Object.entries(nodes)) {
|
|
1051
|
+
if (!isRecord(node)) {
|
|
1052
|
+
errors.push({
|
|
1053
|
+
code: JmValidationCode.NodeKeyMismatch,
|
|
1054
|
+
path: `nodes/${key}`,
|
|
1055
|
+
message: `Node under key "${key}" is not an object.`,
|
|
1056
|
+
});
|
|
1057
|
+
continue;
|
|
1058
|
+
}
|
|
1059
|
+
if (node.id !== key) {
|
|
1060
|
+
errors.push({
|
|
1061
|
+
code: JmValidationCode.NodeKeyMismatch,
|
|
1062
|
+
path: `nodes/${key}`,
|
|
1063
|
+
message: `Key "${key}" does not match the node's own id ${JSON.stringify(node.id)}.`,
|
|
1064
|
+
});
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
// ---- edge keys ----
|
|
1068
|
+
if (isRecord(edges)) {
|
|
1069
|
+
for (const [key, edge] of Object.entries(edges)) {
|
|
1070
|
+
if (!isRecord(edge)) {
|
|
1071
|
+
errors.push({
|
|
1072
|
+
code: JmValidationCode.EdgeKeyMismatch,
|
|
1073
|
+
path: `edges/${key}`,
|
|
1074
|
+
message: `Edge under key "${key}" is not an object.`,
|
|
1075
|
+
});
|
|
1076
|
+
continue;
|
|
1077
|
+
}
|
|
1078
|
+
if (edge.id !== key) {
|
|
1079
|
+
errors.push({
|
|
1080
|
+
code: JmValidationCode.EdgeKeyMismatch,
|
|
1081
|
+
path: `edges/${key}`,
|
|
1082
|
+
message: `Key "${key}" does not match the edge's own id ${JSON.stringify(edge.id)}.`,
|
|
1083
|
+
});
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
// ---- per-node checks ----
|
|
1088
|
+
const parentOf = new Map();
|
|
1089
|
+
for (const [key, node] of Object.entries(nodes)) {
|
|
1090
|
+
if (!isRecord(node)) {
|
|
1091
|
+
continue;
|
|
1092
|
+
}
|
|
1093
|
+
const at = `nodes/${key}`;
|
|
1094
|
+
// content
|
|
1095
|
+
const content = node.content;
|
|
1096
|
+
if (!isRecord(content)) {
|
|
1097
|
+
errors.push({
|
|
1098
|
+
code: JmValidationCode.ContentType,
|
|
1099
|
+
path: `${at}/content`,
|
|
1100
|
+
message: 'Missing "content" object.',
|
|
1101
|
+
});
|
|
1102
|
+
}
|
|
1103
|
+
else {
|
|
1104
|
+
const type = content.type;
|
|
1105
|
+
if (typeof type !== 'string' || !CONTENT_TYPES.has(type)) {
|
|
1106
|
+
errors.push({
|
|
1107
|
+
code: JmValidationCode.ContentType,
|
|
1108
|
+
path: `${at}/content/type`,
|
|
1109
|
+
message: `Unknown content type ${JSON.stringify(type)}. Expected one of ${[...CONTENT_TYPES].join(', ')}.`,
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
// parent reference
|
|
1114
|
+
const parent = node.parent;
|
|
1115
|
+
if (parent === null) {
|
|
1116
|
+
parentOf.set(key, null);
|
|
1117
|
+
}
|
|
1118
|
+
else if (typeof parent === 'string') {
|
|
1119
|
+
parentOf.set(key, parent);
|
|
1120
|
+
if (!nodeIds.has(parent)) {
|
|
1121
|
+
errors.push({
|
|
1122
|
+
code: JmValidationCode.NodeParentMissing,
|
|
1123
|
+
path: `${at}/parent`,
|
|
1124
|
+
message: `Parent "${parent}" is not in "nodes".`,
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
else {
|
|
1129
|
+
errors.push({
|
|
1130
|
+
code: JmValidationCode.NodeParentMissing,
|
|
1131
|
+
path: `${at}/parent`,
|
|
1132
|
+
message: '"parent" must be a node id or null.',
|
|
1133
|
+
});
|
|
1134
|
+
// Deliberately NOT recorded as null. A malformed parent is
|
|
1135
|
+
// undetermined, not root-like: recording it as null makes the root
|
|
1136
|
+
// count below report an extra E_MULTIPLE_ROOTS for the same broken
|
|
1137
|
+
// field, which is a false positive on a different code.
|
|
1138
|
+
}
|
|
1139
|
+
// children references
|
|
1140
|
+
const children = node.children;
|
|
1141
|
+
if (!Array.isArray(children)) {
|
|
1142
|
+
errors.push({
|
|
1143
|
+
code: JmValidationCode.NodeChildMissing,
|
|
1144
|
+
path: `${at}/children`,
|
|
1145
|
+
message: '"children" must be an array.',
|
|
1146
|
+
});
|
|
1147
|
+
}
|
|
1148
|
+
else {
|
|
1149
|
+
for (const childId of children) {
|
|
1150
|
+
if (typeof childId !== 'string' || !nodeIds.has(childId)) {
|
|
1151
|
+
errors.push({
|
|
1152
|
+
code: JmValidationCode.NodeChildMissing,
|
|
1153
|
+
path: `${at}/children`,
|
|
1154
|
+
message: `Child ${JSON.stringify(childId)} is not in "nodes".`,
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
// side is a number in the JSON, per the format spec: -1 left, 0 centre,
|
|
1160
|
+
// 1 right. No name conversion happens at this layer.
|
|
1161
|
+
const side = node.side;
|
|
1162
|
+
if (typeof side !== 'number' || !SIDE_VALUES.has(side)) {
|
|
1163
|
+
errors.push({
|
|
1164
|
+
code: JmValidationCode.Side,
|
|
1165
|
+
path: `${at}/side`,
|
|
1166
|
+
message: `"side" must be -1, 0 or 1, got ${JSON.stringify(side)}.`,
|
|
1167
|
+
});
|
|
1168
|
+
}
|
|
1169
|
+
else if (side === JmNodeSide.Center && parent !== null) {
|
|
1170
|
+
// Centre is not a position, it is the absence of one: it tells the
|
|
1171
|
+
// layout to place the node relative to the root, which only the root
|
|
1172
|
+
// itself can do. A child carrying it is laid out nowhere and does
|
|
1173
|
+
// not paint at all - the data validates, the node silently vanishes
|
|
1174
|
+
// from the picture, and nothing downstream says why.
|
|
1175
|
+
errors.push({
|
|
1176
|
+
code: JmValidationCode.NonRootSideCenter,
|
|
1177
|
+
path: `${at}/side`,
|
|
1178
|
+
message: 'Only the root may use side 0 (centre); a child must be -1 (left) or 1 (right).',
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
// per-node style
|
|
1182
|
+
validateNodeStyle(node.style, `${at}/style`, errors);
|
|
1183
|
+
}
|
|
1184
|
+
// ---- parent/children agreement ----
|
|
1185
|
+
for (const [key, node] of Object.entries(nodes)) {
|
|
1186
|
+
if (!isRecord(node) || !Array.isArray(node.children)) {
|
|
1187
|
+
continue;
|
|
1188
|
+
}
|
|
1189
|
+
for (const childId of node.children) {
|
|
1190
|
+
if (typeof childId !== 'string') {
|
|
1191
|
+
continue;
|
|
1192
|
+
}
|
|
1193
|
+
const child = nodes[childId];
|
|
1194
|
+
if (!isRecord(child)) {
|
|
1195
|
+
continue;
|
|
1196
|
+
}
|
|
1197
|
+
if (child.parent !== key) {
|
|
1198
|
+
errors.push({
|
|
1199
|
+
code: JmValidationCode.ParentChildMismatch,
|
|
1200
|
+
path: `nodes/${childId}/parent`,
|
|
1201
|
+
message: `Listed as a child of "${key}", but its parent is ${JSON.stringify(child.parent)}.`,
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
// ---- exactly one root ----
|
|
1207
|
+
// Nodes with a malformed parent are absent from parentOf entirely, so a
|
|
1208
|
+
// broken field cannot masquerade as a second root.
|
|
1209
|
+
const roots = [...parentOf.entries()].filter(([, parent]) => parent === null).map(([id]) => id);
|
|
1210
|
+
if (roots.length > 1) {
|
|
1211
|
+
errors.push({
|
|
1212
|
+
code: JmValidationCode.MultipleRoots,
|
|
1213
|
+
path: 'nodes',
|
|
1214
|
+
message: `${roots.length} nodes have a null parent: ${roots.join(', ')}. Exactly one is allowed.`,
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
if (rootId && parentOf.has(rootId) && parentOf.get(rootId) !== null) {
|
|
1218
|
+
errors.push({
|
|
1219
|
+
code: JmValidationCode.RootParentSet,
|
|
1220
|
+
path: `nodes/${rootId}/parent`,
|
|
1221
|
+
message: 'The root node must have a null parent.',
|
|
1222
|
+
});
|
|
1223
|
+
}
|
|
1224
|
+
// ---- cycles ----
|
|
1225
|
+
// A node whose parent chain runs INTO a cycle but does not belong to one
|
|
1226
|
+
// must not be blamed: walking up from D (D -> A -> B -> C -> A) does revisit
|
|
1227
|
+
// a node, but it is A, not D. Report the cycle's own members instead.
|
|
1228
|
+
const reportedCycles = new Set();
|
|
1229
|
+
for (const startId of nodeIds) {
|
|
1230
|
+
const cycle = findParentCycle(startId, parentOf);
|
|
1231
|
+
if (cycle === null) {
|
|
1232
|
+
continue;
|
|
1233
|
+
}
|
|
1234
|
+
// Same cycle reached from different entry points yields the same member
|
|
1235
|
+
// set; sort it so one cycle is reported exactly once, and pick a stable
|
|
1236
|
+
// node to hang the issue on.
|
|
1237
|
+
const members = [...cycle].sort();
|
|
1238
|
+
const key = members.join(',');
|
|
1239
|
+
if (reportedCycles.has(key)) {
|
|
1240
|
+
continue;
|
|
1241
|
+
}
|
|
1242
|
+
reportedCycles.add(key);
|
|
1243
|
+
errors.push({
|
|
1244
|
+
code: JmValidationCode.Cycle,
|
|
1245
|
+
path: `nodes/${members[0]}`,
|
|
1246
|
+
message: `Following "parent" from this node returns to it (cycle: ${members.join(' -> ')} -> ${members[0]}).`,
|
|
1247
|
+
});
|
|
1248
|
+
}
|
|
1249
|
+
// ---- edges ----
|
|
1250
|
+
if (isRecord(edges)) {
|
|
1251
|
+
for (const [key, edge] of Object.entries(edges)) {
|
|
1252
|
+
if (!isRecord(edge)) {
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
const at = `edges/${key}`;
|
|
1256
|
+
const edgeType = edge.type;
|
|
1257
|
+
if (typeof edgeType !== 'string' || !EDGE_TYPES.has(edgeType)) {
|
|
1258
|
+
errors.push({
|
|
1259
|
+
code: JmValidationCode.EdgeType,
|
|
1260
|
+
path: `${at}/type`,
|
|
1261
|
+
message: `Unknown edge type ${JSON.stringify(edgeType)}. Expected one of ${[...EDGE_TYPES].join(', ')}.`,
|
|
1262
|
+
});
|
|
1263
|
+
}
|
|
1264
|
+
for (const field of ['sourceNodeId', 'targetNodeId']) {
|
|
1265
|
+
const endpoint = edge[field];
|
|
1266
|
+
if (typeof endpoint !== 'string' || !nodeIds.has(endpoint)) {
|
|
1267
|
+
errors.push({
|
|
1268
|
+
code: JmValidationCode.EdgeNodeMissing,
|
|
1269
|
+
path: `${at}/${field}`,
|
|
1270
|
+
message: `Edge endpoint ${JSON.stringify(endpoint)} is not in "nodes".`,
|
|
1271
|
+
});
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
validateLineStyle(edge.style, `${at}/style`, errors);
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
// ---- mind map style ----
|
|
1278
|
+
validateMindStyle(data.style, errors);
|
|
1279
|
+
return { valid: errors.length === 0, errors };
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Walks parent links from a node and returns the members of the cycle it hits.
|
|
1283
|
+
*
|
|
1284
|
+
* @remarks
|
|
1285
|
+
* Returns the cycle itself, not the starting node. Walking up from a node that
|
|
1286
|
+
* merely points *into* a cycle passes through that cycle without belonging to
|
|
1287
|
+
* it — the caller needs the members to blame the right nodes and to recognise
|
|
1288
|
+
* the same cycle reached from different starting points.
|
|
1289
|
+
*
|
|
1290
|
+
* @param startId - Node to start from.
|
|
1291
|
+
* @param parentOf - Parent map built during the walk.
|
|
1292
|
+
* @returns Member ids of the cycle, in traversal order; null when the chain
|
|
1293
|
+
* ends without looping.
|
|
1294
|
+
*/
|
|
1295
|
+
function findParentCycle(startId, parentOf) {
|
|
1296
|
+
const path = [];
|
|
1297
|
+
const indexOf = new Map();
|
|
1298
|
+
let cursor = startId;
|
|
1299
|
+
while (cursor !== null && cursor !== undefined) {
|
|
1300
|
+
const seenAt = indexOf.get(cursor);
|
|
1301
|
+
if (seenAt !== undefined) {
|
|
1302
|
+
// Everything from the first sighting onwards is the cycle; what came
|
|
1303
|
+
// before it is the tail that led in and is not part of it.
|
|
1304
|
+
return path.slice(seenAt);
|
|
1305
|
+
}
|
|
1306
|
+
indexOf.set(cursor, path.length);
|
|
1307
|
+
path.push(cursor);
|
|
1308
|
+
cursor = parentOf.get(cursor);
|
|
1309
|
+
}
|
|
1310
|
+
return null;
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* Validates the per-node style block.
|
|
1314
|
+
*
|
|
1315
|
+
* @param style - Candidate style value.
|
|
1316
|
+
* @param at - Path prefix for messages.
|
|
1317
|
+
* @param errors - Collector.
|
|
1318
|
+
*/
|
|
1319
|
+
function validateNodeStyle(style, at, errors) {
|
|
1320
|
+
if (style === undefined) {
|
|
1321
|
+
return;
|
|
1322
|
+
}
|
|
1323
|
+
if (!isRecord(style)) {
|
|
1324
|
+
errors.push({
|
|
1325
|
+
code: JmValidationCode.StyleRange,
|
|
1326
|
+
path: at,
|
|
1327
|
+
message: '"style" must be an object.',
|
|
1328
|
+
});
|
|
1329
|
+
return;
|
|
1330
|
+
}
|
|
1331
|
+
const tone = style.tone;
|
|
1332
|
+
if (tone !== undefined && (typeof tone !== 'string' || !TONES.has(tone))) {
|
|
1333
|
+
errors.push({
|
|
1334
|
+
code: JmValidationCode.Tone,
|
|
1335
|
+
path: `${at}/tone`,
|
|
1336
|
+
message: `Unknown tone ${JSON.stringify(tone)}. Expected one of ${[...TONES].join(', ')}.`,
|
|
1337
|
+
});
|
|
1338
|
+
}
|
|
1339
|
+
const borderPattern = style.borderStyle;
|
|
1340
|
+
if (borderPattern !== undefined) {
|
|
1341
|
+
if (typeof borderPattern !== 'string' || !LINE_PATTERNS.has(borderPattern)) {
|
|
1342
|
+
errors.push({
|
|
1343
|
+
code: JmValidationCode.LineStyle,
|
|
1344
|
+
path: `${at}/borderStyle`,
|
|
1345
|
+
message: `Unknown line pattern ${JSON.stringify(borderPattern)}. Expected one of ${[...LINE_PATTERNS].join(', ')}.`,
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
for (const field of ['borderWidth', 'fontSize']) {
|
|
1350
|
+
const value = style[field];
|
|
1351
|
+
if (value !== undefined && (typeof value !== 'number' || !(value > 0))) {
|
|
1352
|
+
errors.push({
|
|
1353
|
+
code: JmValidationCode.StyleRange,
|
|
1354
|
+
path: `${at}/${field}`,
|
|
1355
|
+
message: `"${field}" must be a positive number, got ${JSON.stringify(value)}.`,
|
|
1356
|
+
});
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
if (style.incoming !== undefined) {
|
|
1360
|
+
validateLineStyle(style.incoming, `${at}/incoming`, errors);
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
/**
|
|
1364
|
+
* Validates a line style block, shared by node `incoming` and edge `style`.
|
|
1365
|
+
*
|
|
1366
|
+
* @param style - Candidate line style.
|
|
1367
|
+
* @param at - Path prefix for messages.
|
|
1368
|
+
* @param errors - Collector.
|
|
1369
|
+
*/
|
|
1370
|
+
function validateLineStyle(style, at, errors) {
|
|
1371
|
+
if (style === undefined) {
|
|
1372
|
+
return;
|
|
1373
|
+
}
|
|
1374
|
+
if (!isRecord(style)) {
|
|
1375
|
+
errors.push({
|
|
1376
|
+
code: JmValidationCode.LineStyle,
|
|
1377
|
+
path: at,
|
|
1378
|
+
message: 'Line style must be an object.',
|
|
1379
|
+
});
|
|
1380
|
+
return;
|
|
1381
|
+
}
|
|
1382
|
+
if (style.pattern !== undefined) {
|
|
1383
|
+
const pattern = style.pattern;
|
|
1384
|
+
if (typeof pattern !== 'string' || !LINE_PATTERNS.has(pattern)) {
|
|
1385
|
+
errors.push({
|
|
1386
|
+
code: JmValidationCode.LineStyle,
|
|
1387
|
+
path: `${at}/pattern`,
|
|
1388
|
+
message: `Unknown line pattern ${JSON.stringify(pattern)}. Expected one of ${[...LINE_PATTERNS].join(', ')}.`,
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
const width = style.width;
|
|
1393
|
+
if (width !== undefined && (typeof width !== 'number' || !(width > 0))) {
|
|
1394
|
+
errors.push({
|
|
1395
|
+
code: JmValidationCode.StyleRange,
|
|
1396
|
+
path: `${at}/width`,
|
|
1397
|
+
message: `"width" must be a positive number, got ${JSON.stringify(width)}.`,
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
/**
|
|
1402
|
+
* Validates the mind map level style declaration.
|
|
1403
|
+
*
|
|
1404
|
+
* @param style - Candidate style declaration.
|
|
1405
|
+
* @param errors - Collector.
|
|
1406
|
+
*/
|
|
1407
|
+
function validateMindStyle(style, errors) {
|
|
1408
|
+
if (style === undefined) {
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
if (!isRecord(style)) {
|
|
1412
|
+
errors.push({
|
|
1413
|
+
code: JmValidationCode.StyleRange,
|
|
1414
|
+
path: 'style',
|
|
1415
|
+
message: '"style" must be an object.',
|
|
1416
|
+
});
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
const themeName = style.theme;
|
|
1420
|
+
if (themeName !== undefined) {
|
|
1421
|
+
if (typeof themeName !== 'string') {
|
|
1422
|
+
errors.push({
|
|
1423
|
+
code: JmValidationCode.ThemeUnknown,
|
|
1424
|
+
path: 'style/theme',
|
|
1425
|
+
message: '"style.theme" must be a string.',
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
else if (!(themeName in JSMIND_THEME_PRESETS)) {
|
|
1429
|
+
errors.push({
|
|
1430
|
+
code: JmValidationCode.ThemeUnknown,
|
|
1431
|
+
path: 'style/theme',
|
|
1432
|
+
message: `Unknown theme ${JSON.stringify(themeName)}. Known themes: ${Object.keys(JSMIND_THEME_PRESETS).join(', ')}.`,
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
if (style.tones !== undefined) {
|
|
1437
|
+
if (!isRecord(style.tones)) {
|
|
1438
|
+
errors.push({
|
|
1439
|
+
code: JmValidationCode.StyleRange,
|
|
1440
|
+
path: 'style/tones',
|
|
1441
|
+
message: '"style.tones" must be an object.',
|
|
1442
|
+
});
|
|
1443
|
+
}
|
|
1444
|
+
else {
|
|
1445
|
+
for (const toneName of Object.keys(style.tones)) {
|
|
1446
|
+
if (!TONES.has(toneName)) {
|
|
1447
|
+
errors.push({
|
|
1448
|
+
code: JmValidationCode.Tone,
|
|
1449
|
+
path: `style/tones/${toneName}`,
|
|
1450
|
+
message: `Unknown tone ${JSON.stringify(toneName)}.`,
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
for (const section of ['node', 'line', 'expander']) {
|
|
1457
|
+
if (style[section] === undefined) {
|
|
1458
|
+
continue;
|
|
1459
|
+
}
|
|
1460
|
+
if (!isRecord(style[section])) {
|
|
1461
|
+
errors.push({
|
|
1462
|
+
code: JmValidationCode.StyleRange,
|
|
1463
|
+
path: `style/${section}`,
|
|
1464
|
+
message: `"style.${section}" must be an object.`,
|
|
1465
|
+
});
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
/**
|
|
1471
|
+
* @fileoverview A headless browser, driven over the DevTools protocol.
|
|
1472
|
+
*
|
|
1473
|
+
* Exporting an image needs a rendering engine: the picture is produced by
|
|
1474
|
+
* handing markup back to the browser, so there has to be one. That is the only
|
|
1475
|
+
* external requirement the CLI has, and it is confined to this file.
|
|
1476
|
+
*
|
|
1477
|
+
* Talking CDP directly keeps the package dependency-free - no puppeteer, no
|
|
1478
|
+
* playwright. Node's built-in WebSocket and fetch are enough.
|
|
1479
|
+
*
|
|
1480
|
+
* @packageDocumentation
|
|
1481
|
+
*
|
|
1482
|
+
* Excluded from the unit coverage figure (see `test:coverage` in package.json).
|
|
1483
|
+
* This file is a driver: spawn a process, speak a protocol over a socket, wait
|
|
1484
|
+
* for replies. Testing it without a browser would mean mocking `spawn`, the
|
|
1485
|
+
* DevTools socket and the file system - which asserts that the mocks were
|
|
1486
|
+
* called, not that a browser produces an image. The UI suite runs the real
|
|
1487
|
+
* thing against the built bundle; that bundle is why the coverage tool cannot
|
|
1488
|
+
* attribute the lines back here.
|
|
1489
|
+
*/
|
|
1490
|
+
/** Where a Chromium binary is normally installed. */
|
|
1491
|
+
const BROWSER_CANDIDATES = [
|
|
1492
|
+
process.env.CHROME_PATH,
|
|
1493
|
+
process.env.CHROMIUM_PATH,
|
|
1494
|
+
'/usr/bin/chromium',
|
|
1495
|
+
'/usr/bin/chromium-browser',
|
|
1496
|
+
'/usr/bin/google-chrome',
|
|
1497
|
+
'/usr/bin/google-chrome-stable',
|
|
1498
|
+
'/snap/bin/chromium',
|
|
1499
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
1500
|
+
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
1501
|
+
];
|
|
1502
|
+
/** Locates a Chromium binary, or explains what to install. */
|
|
1503
|
+
function findBrowser() {
|
|
1504
|
+
for (const candidate of BROWSER_CANDIDATES) {
|
|
1505
|
+
if (candidate && existsSync(candidate)) {
|
|
1506
|
+
return candidate;
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
// `which` last: PATH may point somewhere the fixed list does not cover.
|
|
1510
|
+
for (const name of ['chromium', 'chromium-browser', 'google-chrome', 'google-chrome-stable']) {
|
|
1511
|
+
const found = whichSync(name);
|
|
1512
|
+
if (found) {
|
|
1513
|
+
return found;
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
throw new CliError('No Chromium found. Image export needs a browser: install chromium, ' +
|
|
1517
|
+
'or point CHROME_PATH at a Chrome or Chromium binary.', CliExit.IoError);
|
|
1518
|
+
}
|
|
1519
|
+
/** Blocking `which`, without pulling in a dependency for it. */
|
|
1520
|
+
function whichSync(name) {
|
|
1521
|
+
const result = spawnSync('which', [name], { encoding: 'utf8' });
|
|
1522
|
+
if (result.status !== 0) {
|
|
1523
|
+
return null;
|
|
1524
|
+
}
|
|
1525
|
+
const path = (result.stdout ?? '').trim();
|
|
1526
|
+
return path.length > 0 ? path : null;
|
|
1527
|
+
}
|
|
1528
|
+
/** Resolves the bundled jsMind build the page should load. */
|
|
1529
|
+
function resolveBundlePath() {
|
|
1530
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
1531
|
+
// Running from dist/ puts the bundle beside this file; running from src/cli/
|
|
1532
|
+
// puts it two levels up. Both are normal during development.
|
|
1533
|
+
const candidates = [
|
|
1534
|
+
resolve(here, 'jsmind.js'),
|
|
1535
|
+
resolve(here, '../../dist/jsmind.js'),
|
|
1536
|
+
];
|
|
1537
|
+
for (const candidate of candidates) {
|
|
1538
|
+
if (existsSync(candidate)) {
|
|
1539
|
+
return candidate;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
throw new CliError(`Cannot find the jsMind bundle (looked in ${candidates.join(', ')}). Run a build first.`, CliExit.IoError);
|
|
1543
|
+
}
|
|
1544
|
+
/** Thrown internally when the page itself raises. */
|
|
1545
|
+
class PageError extends Error {
|
|
1546
|
+
}
|
|
1547
|
+
/**
|
|
1548
|
+
* Expression that imports the ESM bundle.
|
|
1549
|
+
*
|
|
1550
|
+
* The bundle is an ES module (`export`, plus a `globalThis.jsMind` assignment).
|
|
1551
|
+
* Evaluating that source as a classic script is a syntax error, which is how
|
|
1552
|
+
* the CLI used to load the old UMD build. A blob URL is a module.
|
|
1553
|
+
*
|
|
1554
|
+
* @param source - Contents of `dist/jsmind.js`.
|
|
1555
|
+
* @returns An async expression for `Runtime.evaluate`.
|
|
1556
|
+
*/
|
|
1557
|
+
function bundleImportExpression(source) {
|
|
1558
|
+
return `(async () => {
|
|
1559
|
+
const url = URL.createObjectURL(new Blob([${JSON.stringify(source)}], { type: 'text/javascript' }));
|
|
1560
|
+
try {
|
|
1561
|
+
await import(url);
|
|
1562
|
+
} finally {
|
|
1563
|
+
URL.revokeObjectURL(url);
|
|
1564
|
+
}
|
|
1565
|
+
})()`;
|
|
1566
|
+
}
|
|
1567
|
+
/**
|
|
1568
|
+
* Starts a headless browser with jsMind loaded on a blank page.
|
|
1569
|
+
*
|
|
1570
|
+
* @param width - CSS width of the viewport.
|
|
1571
|
+
* @param height - CSS height of the viewport.
|
|
1572
|
+
* @returns A session that can evaluate expressions and must be closed.
|
|
1573
|
+
* @throws {@link CliError} If no browser is found or it fails to start.
|
|
1574
|
+
*/
|
|
1575
|
+
async function openBrowser(width, height) {
|
|
1576
|
+
const binary = findBrowser();
|
|
1577
|
+
const bundle = readFileSync(resolveBundlePath(), 'utf8');
|
|
1578
|
+
const port = 9222 + Math.floor(Math.random() * 2000);
|
|
1579
|
+
const profile = mkdtempSync(join(tmpdir(), 'jsmind-cli-'));
|
|
1580
|
+
const chrome = spawn(binary, [
|
|
1581
|
+
'--headless=new',
|
|
1582
|
+
`--remote-debugging-port=${port}`,
|
|
1583
|
+
`--user-data-dir=${profile}`,
|
|
1584
|
+
'--no-sandbox',
|
|
1585
|
+
'--disable-gpu',
|
|
1586
|
+
'--disable-dev-shm-usage',
|
|
1587
|
+
// Without this the scrollbars land in the picture.
|
|
1588
|
+
'--hide-scrollbars',
|
|
1589
|
+
'about:blank',
|
|
1590
|
+
], { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
1591
|
+
let exited = null;
|
|
1592
|
+
chrome.on('exit', code => {
|
|
1593
|
+
exited = code ?? -1;
|
|
1594
|
+
});
|
|
1595
|
+
let socket = null;
|
|
1596
|
+
const cleanup = async () => {
|
|
1597
|
+
socket?.close();
|
|
1598
|
+
if (exited === null) {
|
|
1599
|
+
chrome.kill('SIGKILL');
|
|
1600
|
+
await new Promise(done => setTimeout(done, 200));
|
|
1601
|
+
}
|
|
1602
|
+
try {
|
|
1603
|
+
rmSync(profile, { recursive: true, force: true });
|
|
1604
|
+
}
|
|
1605
|
+
catch {
|
|
1606
|
+
// The profile is temporary; failing to remove it is not worth a word.
|
|
1607
|
+
}
|
|
1608
|
+
};
|
|
1609
|
+
try {
|
|
1610
|
+
const version = await waitForDevTools(port, () => exited);
|
|
1611
|
+
socket = new WebSocket(version.webSocketDebuggerUrl);
|
|
1612
|
+
await new Promise((ok, fail) => {
|
|
1613
|
+
socket.onopen = () => ok();
|
|
1614
|
+
socket.onerror = () => fail(new CliError('Cannot connect to the browser.', CliExit.IoError));
|
|
1615
|
+
});
|
|
1616
|
+
let nextId = 0;
|
|
1617
|
+
let sessionId = '';
|
|
1618
|
+
const pending = new Map();
|
|
1619
|
+
socket.onmessage = event => {
|
|
1620
|
+
const message = JSON.parse(String(event.data));
|
|
1621
|
+
if (message.id !== undefined) {
|
|
1622
|
+
const settle = pending.get(message.id);
|
|
1623
|
+
if (settle) {
|
|
1624
|
+
pending.delete(message.id);
|
|
1625
|
+
settle(message);
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
};
|
|
1629
|
+
const send = (method, params = {}) => new Promise(done => {
|
|
1630
|
+
const id = ++nextId;
|
|
1631
|
+
pending.set(id, done);
|
|
1632
|
+
socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
|
|
1633
|
+
});
|
|
1634
|
+
const target = await send('Target.createTarget', { url: 'about:blank' });
|
|
1635
|
+
const attached = await send('Target.attachToTarget', {
|
|
1636
|
+
targetId: target.result.targetId,
|
|
1637
|
+
flatten: true,
|
|
1638
|
+
});
|
|
1639
|
+
sessionId = attached.result.sessionId;
|
|
1640
|
+
await send('Page.enable');
|
|
1641
|
+
await send('Runtime.enable');
|
|
1642
|
+
await send('Emulation.setDeviceMetricsOverride', {
|
|
1643
|
+
width,
|
|
1644
|
+
height,
|
|
1645
|
+
deviceScaleFactor: 1,
|
|
1646
|
+
mobile: false,
|
|
1647
|
+
});
|
|
1648
|
+
const frameTree = await send('Page.getFrameTree');
|
|
1649
|
+
const frameId = frameTree.result.frameTree.frame.id;
|
|
1650
|
+
await send('Page.setDocumentContent', {
|
|
1651
|
+
frameId,
|
|
1652
|
+
html: '<!DOCTYPE html><html><head><meta charset="utf-8"><style>' +
|
|
1653
|
+
'html,body{margin:0;padding:0;background:#ffffff}' +
|
|
1654
|
+
`#stage{width:${width}px;height:${height}px}` +
|
|
1655
|
+
'</style></head><body><div id="stage"></div></body></html>',
|
|
1656
|
+
});
|
|
1657
|
+
const loaded = await send('Runtime.evaluate', {
|
|
1658
|
+
expression: bundleImportExpression(bundle),
|
|
1659
|
+
awaitPromise: true,
|
|
1660
|
+
});
|
|
1661
|
+
const loadError = loaded.result?.exceptionDetails;
|
|
1662
|
+
if (loadError) {
|
|
1663
|
+
throw new CliError(loadError.exception?.description ?? loadError.text ?? 'Could not load the jsMind bundle.', CliExit.IoError);
|
|
1664
|
+
}
|
|
1665
|
+
const evaluate = async (expression) => {
|
|
1666
|
+
const message = await send('Runtime.evaluate', {
|
|
1667
|
+
expression,
|
|
1668
|
+
returnByValue: true,
|
|
1669
|
+
awaitPromise: true,
|
|
1670
|
+
});
|
|
1671
|
+
const details = message.result?.exceptionDetails;
|
|
1672
|
+
if (details) {
|
|
1673
|
+
throw new PageError(details.exception?.description ?? details.text ?? 'the page raised an error');
|
|
1674
|
+
}
|
|
1675
|
+
const result = message.result?.result;
|
|
1676
|
+
return result?.value;
|
|
1677
|
+
};
|
|
1678
|
+
return { evaluate, close: cleanup };
|
|
1679
|
+
}
|
|
1680
|
+
catch (error) {
|
|
1681
|
+
await cleanup();
|
|
1682
|
+
throw error;
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
/** Polls the DevTools endpoint until the browser answers. */
|
|
1686
|
+
async function waitForDevTools(port, hasExited) {
|
|
1687
|
+
for (let attempt = 0; attempt < 150; attempt++) {
|
|
1688
|
+
const code = hasExited();
|
|
1689
|
+
if (code !== null) {
|
|
1690
|
+
throw new CliError(`The browser exited while starting (code ${code}).`, CliExit.IoError);
|
|
1691
|
+
}
|
|
1692
|
+
try {
|
|
1693
|
+
const response = await fetch(`http://127.0.0.1:${port}/json/version`);
|
|
1694
|
+
if (response.ok) {
|
|
1695
|
+
return (await response.json());
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
catch {
|
|
1699
|
+
// Not listening yet.
|
|
1700
|
+
}
|
|
1701
|
+
await new Promise(done => setTimeout(done, 200));
|
|
1702
|
+
}
|
|
1703
|
+
throw new CliError('The browser did not start in time.', CliExit.IoError);
|
|
1704
|
+
}
|
|
1705
|
+
/** True when an error came from the page rather than the harness. */
|
|
1706
|
+
function isPageError(error) {
|
|
1707
|
+
return error instanceof PageError;
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
/**
|
|
1711
|
+
* @fileoverview Turns the rendered content of the view's shadow root into an image.
|
|
1712
|
+
*
|
|
1713
|
+
* The browser has no API that converts a DOM subtree into pixels. Element
|
|
1714
|
+
* Capture and Region Capture come closest, but both sit on top of the Screen
|
|
1715
|
+
* Capture API and need the user to grant a capture prompt, which rules them out
|
|
1716
|
+
* for an export a script can call.
|
|
1717
|
+
*
|
|
1718
|
+
* What every DOM-to-image library does instead, and what this does, is hand the
|
|
1719
|
+
* markup back to the browser as an SVG `<foreignObject>` and let the rendering
|
|
1720
|
+
* engine paint it. Canvas only appears at the very end, to turn those pixels
|
|
1721
|
+
* into a file: `drawImage` then `toBlob`. Nothing is redrawn by hand, so the
|
|
1722
|
+
* output matches the view exactly, including text wrapping, shadows and the
|
|
1723
|
+
* theme.
|
|
1724
|
+
*
|
|
1725
|
+
* Excluded from the unit coverage figure (see `test:coverage` in package.json).
|
|
1726
|
+
* Everything left here talks to the browser - cloneNode, Image, canvas - so the
|
|
1727
|
+
* unit suite cannot reach a line of it. The UI suite exercises it for real,
|
|
1728
|
+
* against the built bundle, but a bundle carries no source line numbers to
|
|
1729
|
+
* report coverage against. The parts worth asserting in isolation live in
|
|
1730
|
+
* `export-svg.ts`; what remains is calls into browser APIs with no logic to check.
|
|
1731
|
+
*/
|
|
1732
|
+
/** Image formats a caller may ask for. */
|
|
1733
|
+
const JmImageType = {
|
|
1734
|
+
Png: 'image/png',
|
|
1735
|
+
Jpeg: 'image/jpeg',
|
|
1736
|
+
Webp: 'image/webp',
|
|
1737
|
+
};
|
|
1738
|
+
|
|
1739
|
+
/**
|
|
1740
|
+
* `jsmind export` — render a mind map file to a PNG.
|
|
1741
|
+
*
|
|
1742
|
+
* The rendering itself happens in a browser, because the picture is produced by
|
|
1743
|
+
* handing the markup back to a rendering engine. This command only drives it:
|
|
1744
|
+
* load, open, ask the page for a blob, write the bytes.
|
|
1745
|
+
*
|
|
1746
|
+
* @packageDocumentation
|
|
1747
|
+
*/
|
|
1748
|
+
/** Viewport the map is laid out in when the caller does not say. */
|
|
1749
|
+
const DEFAULT_WIDTH = 1200;
|
|
1750
|
+
/** Viewport height, same default reasoning. */
|
|
1751
|
+
const DEFAULT_HEIGHT = 800;
|
|
1752
|
+
/** Rendered at 2x by default: crisp on a dense screen, still cheap. */
|
|
1753
|
+
const DEFAULT_SCALE = 2;
|
|
1754
|
+
/**
|
|
1755
|
+
* Renders a mind map file to an image.
|
|
1756
|
+
*
|
|
1757
|
+
* @param options - Paths, viewport, scale and format.
|
|
1758
|
+
* @returns The exit code: 0 on success.
|
|
1759
|
+
* @throws {@link CliError} For usage, data, IO and browser failures.
|
|
1760
|
+
*/
|
|
1761
|
+
async function runExport(options) {
|
|
1762
|
+
const data = readJsonFile(options.file);
|
|
1763
|
+
// Validate before starting a browser: a bad file should fail in
|
|
1764
|
+
// milliseconds, not after a Chrome launch.
|
|
1765
|
+
const validation = validateMindData(data);
|
|
1766
|
+
if (!validation.valid) {
|
|
1767
|
+
process.stderr.write(`${options.file}: ${validation.errors.length} problem(s)\n`);
|
|
1768
|
+
for (const issue of validation.errors.slice(0, 10)) {
|
|
1769
|
+
process.stderr.write(` ${issue.code} ${issue.path || '<root>'}\n ${issue.message}\n`);
|
|
1770
|
+
}
|
|
1771
|
+
return CliExit.InvalidData;
|
|
1772
|
+
}
|
|
1773
|
+
const session = await openBrowser(options.width, options.height);
|
|
1774
|
+
try {
|
|
1775
|
+
const script = `
|
|
1776
|
+
(async () => {
|
|
1777
|
+
const stage = document.getElementById('stage');
|
|
1778
|
+
const jm = await jsMind.create(stage);
|
|
1779
|
+
const mind = jsMind.Serializer.create('json')
|
|
1780
|
+
.deserialize(JSON.parse(${JSON.stringify(JSON.stringify(data))}));
|
|
1781
|
+
await jm.open(mind);
|
|
1782
|
+
|
|
1783
|
+
// Fonts before frames: layout measured against a fallback face
|
|
1784
|
+
// stays measured against it, so a map that ends up in a web font
|
|
1785
|
+
// would be exported with the wrong metrics - and the picture
|
|
1786
|
+
// would look plausible, just not like the screen. document.fonts.ready
|
|
1787
|
+
// resolves once they are loaded and applied; the two frames
|
|
1788
|
+
// after it let the relayout that the swap triggered finish.
|
|
1789
|
+
if (document.fonts) {
|
|
1790
|
+
await document.fonts.ready;
|
|
1791
|
+
}
|
|
1792
|
+
await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
|
|
1793
|
+
|
|
1794
|
+
const result = await jm.exportImage({
|
|
1795
|
+
scale: ${JSON.stringify(options.scale)},
|
|
1796
|
+
type: ${JSON.stringify(options.type)},
|
|
1797
|
+
});
|
|
1798
|
+
|
|
1799
|
+
const base64 = await new Promise((resolve, reject) => {
|
|
1800
|
+
const reader = new FileReader();
|
|
1801
|
+
reader.onload = () => {
|
|
1802
|
+
const text = String(reader.result);
|
|
1803
|
+
resolve(text.slice(text.indexOf(',') + 1));
|
|
1804
|
+
};
|
|
1805
|
+
reader.onerror = () => reject(new Error('could not read the blob'));
|
|
1806
|
+
reader.readAsDataURL(result.blob);
|
|
1807
|
+
});
|
|
1808
|
+
|
|
1809
|
+
return {
|
|
1810
|
+
base64,
|
|
1811
|
+
width: result.width,
|
|
1812
|
+
height: result.height,
|
|
1813
|
+
cssWidth: result.cssWidth,
|
|
1814
|
+
cssHeight: result.cssHeight,
|
|
1815
|
+
bytes: result.blob.size,
|
|
1816
|
+
};
|
|
1817
|
+
})()
|
|
1818
|
+
`;
|
|
1819
|
+
const result = (await session.evaluate(script));
|
|
1820
|
+
const bytes = Buffer.from(result.base64, 'base64');
|
|
1821
|
+
// The caller may well name a path under a directory that does not exist
|
|
1822
|
+
// yet (`tmp/preview.png` in CI is exactly that); creating it is cheaper
|
|
1823
|
+
// than making every caller write the mkdir themselves.
|
|
1824
|
+
mkdirSync(dirname(options.output), { recursive: true });
|
|
1825
|
+
writeFileSync(options.output, bytes, { flag: 'w' });
|
|
1826
|
+
if (options.asJson) {
|
|
1827
|
+
process.stdout.write(`${JSON.stringify({
|
|
1828
|
+
output: options.output,
|
|
1829
|
+
width: result.width,
|
|
1830
|
+
height: result.height,
|
|
1831
|
+
cssWidth: Math.round(result.cssWidth),
|
|
1832
|
+
cssHeight: Math.round(result.cssHeight),
|
|
1833
|
+
bytes: bytes.length,
|
|
1834
|
+
type: options.type,
|
|
1835
|
+
}, null, 2)}\n`);
|
|
1836
|
+
}
|
|
1837
|
+
else {
|
|
1838
|
+
process.stdout.write(`${options.output}: ${result.width}x${result.height} ` +
|
|
1839
|
+
`(${(bytes.length / 1024).toFixed(1)} KB)\n`);
|
|
1840
|
+
}
|
|
1841
|
+
return CliExit.Ok;
|
|
1842
|
+
}
|
|
1843
|
+
catch (error) {
|
|
1844
|
+
if (isPageError(error)) {
|
|
1845
|
+
// The page could not render: bad data for the renderer, or a browser
|
|
1846
|
+
// that cannot encode the canvas. Neither is a crash of this tool.
|
|
1847
|
+
throw new CliError(`Rendering failed: ${error.message}`, CliExit.IoError);
|
|
1848
|
+
}
|
|
1849
|
+
throw error;
|
|
1850
|
+
}
|
|
1851
|
+
finally {
|
|
1852
|
+
await session.close();
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
/** The formats this command will accept on the command line. */
|
|
1856
|
+
const EXPORT_TYPES = Object.values(JmImageType);
|
|
1857
|
+
|
|
1858
|
+
/**
|
|
1859
|
+
* `jsmind validate` — check a mind map file without touching it.
|
|
1860
|
+
*
|
|
1861
|
+
* @packageDocumentation
|
|
1862
|
+
*/
|
|
1863
|
+
/**
|
|
1864
|
+
* Runs the validate command.
|
|
1865
|
+
*
|
|
1866
|
+
* @param file - Path to the mind map JSON.
|
|
1867
|
+
* @param asJson - Emit machine-readable output instead of prose.
|
|
1868
|
+
* @returns The exit code: 0 when valid, 1 when the data is invalid.
|
|
1869
|
+
* @throws {@link CliError} With `IoError` when the file cannot be read.
|
|
1870
|
+
*/
|
|
1871
|
+
function runValidate(file, asJson) {
|
|
1872
|
+
const data = readJsonFile(file);
|
|
1873
|
+
const result = validateMindData(data);
|
|
1874
|
+
if (asJson) {
|
|
1875
|
+
process.stdout.write(`${JSON.stringify({ valid: result.valid, errors: result.errors }, null, 2)}\n`);
|
|
1876
|
+
return result.valid ? CliExit.Ok : CliExit.InvalidData;
|
|
1877
|
+
}
|
|
1878
|
+
if (result.valid) {
|
|
1879
|
+
process.stdout.write(`${file}: valid\n`);
|
|
1880
|
+
return CliExit.Ok;
|
|
1881
|
+
}
|
|
1882
|
+
// One line per issue, code first so it lines up for scanning.
|
|
1883
|
+
process.stderr.write(`${file}: ${result.errors.length} problem(s)\n\n`);
|
|
1884
|
+
for (const issue of result.errors) {
|
|
1885
|
+
process.stderr.write(` ${issue.code} ${issue.path || '<root>'}\n ${issue.message}\n`);
|
|
1886
|
+
}
|
|
1887
|
+
return CliExit.InvalidData;
|
|
1888
|
+
}
|
|
1889
|
+
/**
|
|
1890
|
+
* Describes the validate command for `--help`.
|
|
1891
|
+
*/
|
|
1892
|
+
const validateHelp = `jsmind validate <file> [--json]
|
|
1893
|
+
|
|
1894
|
+
Checks a v2 mind map file against the format specification and reports every
|
|
1895
|
+
problem found. Does not modify the file.
|
|
1896
|
+
|
|
1897
|
+
Exit codes:
|
|
1898
|
+
0 valid
|
|
1899
|
+
1 invalid data
|
|
1900
|
+
3 file cannot be read`;
|
|
1901
|
+
/**
|
|
1902
|
+
* Throws when the argument list does not fit the command.
|
|
1903
|
+
*
|
|
1904
|
+
* @param positional - Positional arguments after the command name.
|
|
1905
|
+
*/
|
|
1906
|
+
function assertValidateArgs(positional) {
|
|
1907
|
+
if (positional.length === 0) {
|
|
1908
|
+
throw usageError('validate requires a file path');
|
|
1909
|
+
}
|
|
1910
|
+
if (positional.length > 1) {
|
|
1911
|
+
throw usageError(`validate takes one file, got ${positional.length}`);
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
/**
|
|
1916
|
+
* Manager for observers of an observed object.
|
|
1917
|
+
*
|
|
1918
|
+
* @public
|
|
1919
|
+
*/
|
|
1920
|
+
class JmObserverManager {
|
|
1921
|
+
/** The object being observed. */
|
|
1922
|
+
observedObject;
|
|
1923
|
+
/** @internal */
|
|
1924
|
+
_observers;
|
|
1925
|
+
/**
|
|
1926
|
+
* Creates an observer manager for an observed object.
|
|
1927
|
+
*
|
|
1928
|
+
* @param observedObject - The object to observe.
|
|
1929
|
+
*/
|
|
1930
|
+
constructor(observedObject) {
|
|
1931
|
+
this.observedObject = observedObject;
|
|
1932
|
+
this._observers = [];
|
|
1933
|
+
}
|
|
1934
|
+
/**
|
|
1935
|
+
* Adds an observer to the observed object.
|
|
1936
|
+
*
|
|
1937
|
+
* @param observer - An object that contains an `update(observedObject, event)` method.
|
|
1938
|
+
* @throws {@link JsMindError} If the observer is not a valid JmObserver instance.
|
|
1939
|
+
*/
|
|
1940
|
+
addObserver(observer) {
|
|
1941
|
+
if (!observer || !('update' in observer) || typeof observer.update !== 'function') {
|
|
1942
|
+
throw new JsMindError('observer is not a valid JmObserver instance');
|
|
1943
|
+
}
|
|
1944
|
+
this._observers.push(observer);
|
|
1945
|
+
}
|
|
1946
|
+
/**
|
|
1947
|
+
* Removes an observer that was previously added by the `addObserver` method.
|
|
1948
|
+
*
|
|
1949
|
+
* @param observer - The observer to remove.
|
|
1950
|
+
*/
|
|
1951
|
+
removeObserver(observer) {
|
|
1952
|
+
this._observers = this._observers.filter(o => o !== observer);
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* Removes all observers from the object.
|
|
1956
|
+
*/
|
|
1957
|
+
clearObservers() {
|
|
1958
|
+
this._observers = [];
|
|
1959
|
+
}
|
|
1960
|
+
/**
|
|
1961
|
+
* Notifies the event to all observers.
|
|
1962
|
+
*
|
|
1963
|
+
* @remarks
|
|
1964
|
+
* This is an asynchronous method. Each observer is notified in a separate
|
|
1965
|
+
* asynchronous operation.
|
|
1966
|
+
*
|
|
1967
|
+
* @param event - Events are defined by different observed objects, which
|
|
1968
|
+
* represent specific information about the changes.
|
|
1969
|
+
*/
|
|
1970
|
+
async notifyObservers(event) {
|
|
1971
|
+
this._observers.forEach(async (observer) => {
|
|
1972
|
+
await new Promise((resolve) => {
|
|
1973
|
+
setTimeout(() => {
|
|
1974
|
+
observer.update(this.observedObject, event);
|
|
1975
|
+
resolve();
|
|
1976
|
+
});
|
|
1977
|
+
});
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
|
|
1982
|
+
/**
|
|
1983
|
+
* Metadata for the mind map.
|
|
1984
|
+
*
|
|
1985
|
+
* @public
|
|
1986
|
+
*/
|
|
1987
|
+
const DEFAULT_METADATA = {
|
|
1988
|
+
author: 'hizzgdev@163.com',
|
|
1989
|
+
name: 'jsMind Mindmap',
|
|
1990
|
+
version: '1.0'
|
|
1991
|
+
};
|
|
1992
|
+
const DEFAULT_OPTIONS = {
|
|
1993
|
+
mind: {
|
|
1994
|
+
rootNodeId: 'root'
|
|
1995
|
+
}};
|
|
1996
|
+
|
|
1997
|
+
/**
|
|
1998
|
+
* Interface for generating unique IDs.
|
|
1999
|
+
*
|
|
2000
|
+
* @remarks
|
|
2001
|
+
* IdGenerator is an interface for generating unique IDs.
|
|
2002
|
+
*
|
|
2003
|
+
* @example
|
|
2004
|
+
* ```typescript
|
|
2005
|
+
* class MyIdGenerator extends IdGenerator {
|
|
2006
|
+
* constructor() {
|
|
2007
|
+
* super();
|
|
2008
|
+
* this._seq = 0;
|
|
2009
|
+
* }
|
|
2010
|
+
* newId() {
|
|
2011
|
+
* return 'my' + (this._seq++);
|
|
2012
|
+
* }
|
|
2013
|
+
* }
|
|
2014
|
+
* ```
|
|
2015
|
+
*
|
|
2016
|
+
* @public
|
|
2017
|
+
*/
|
|
2018
|
+
class IdGenerator {
|
|
2019
|
+
/**
|
|
2020
|
+
* Generates a new unique ID.
|
|
2021
|
+
*
|
|
2022
|
+
* @returns A new unique ID.
|
|
2023
|
+
* @throws {@link Error} If not implemented.
|
|
2024
|
+
*/
|
|
2025
|
+
newId() {
|
|
2026
|
+
throw new Error('not implemented');
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
/**
|
|
2030
|
+
* Simple implementation of IdGenerator.
|
|
2031
|
+
*
|
|
2032
|
+
* @public
|
|
2033
|
+
*/
|
|
2034
|
+
class SimpleIdGenerator extends IdGenerator {
|
|
2035
|
+
/** The seed value for ID generation. */
|
|
2036
|
+
seed;
|
|
2037
|
+
/** The sequence counter. */
|
|
2038
|
+
seq;
|
|
2039
|
+
/** The prefix for generated IDs. */
|
|
2040
|
+
prefix;
|
|
2041
|
+
/**
|
|
2042
|
+
* Creates a new SimpleIdGenerator instance.
|
|
2043
|
+
*
|
|
2044
|
+
* @param prefix - Optional prefix for generated IDs. Defaults to empty string.
|
|
2045
|
+
*/
|
|
2046
|
+
constructor(prefix) {
|
|
2047
|
+
super();
|
|
2048
|
+
this.seed = new Date().getTime();
|
|
2049
|
+
this.seq = 0;
|
|
2050
|
+
this.prefix = prefix || '';
|
|
2051
|
+
}
|
|
2052
|
+
/**
|
|
2053
|
+
* Generates a new unique ID.
|
|
2054
|
+
*
|
|
2055
|
+
* @returns A new unique ID with the format: prefix + (seed + seq).toString(36)
|
|
2056
|
+
*/
|
|
2057
|
+
newId() {
|
|
2058
|
+
this.seq++;
|
|
2059
|
+
return this.prefix + (this.seed + this.seq).toString(36);
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
/**
|
|
2063
|
+
* Global ID generator instance.
|
|
2064
|
+
*
|
|
2065
|
+
* @public
|
|
2066
|
+
*/
|
|
2067
|
+
new SimpleIdGenerator('jm-');
|
|
2068
|
+
|
|
2069
|
+
/**
|
|
2070
|
+
* Enumeration of mind map event types.
|
|
2071
|
+
*
|
|
2072
|
+
* @public
|
|
2073
|
+
*/
|
|
2074
|
+
const JmMindEventType = {
|
|
2075
|
+
/** Event fired when a node is added. */
|
|
2076
|
+
NodeAdded: 1,
|
|
2077
|
+
/** Event fired when a node is removed. */
|
|
2078
|
+
NodeRemoved: 2,
|
|
2079
|
+
/** Event fired when a node is updated. */
|
|
2080
|
+
NodeUpdated: 3,
|
|
2081
|
+
/** Event fired when a node is moved. */
|
|
2082
|
+
NodeMoved: 4,
|
|
2083
|
+
/** Event fired when an edge is added. */
|
|
2084
|
+
EdgeAdded: 5,
|
|
2085
|
+
/** Event fired when an edge is removed. */
|
|
2086
|
+
EdgeRemoved: 6,
|
|
2087
|
+
};
|
|
2088
|
+
|
|
2089
|
+
/**
|
|
2090
|
+
* Event data containing the state change in JmMind.
|
|
2091
|
+
*
|
|
2092
|
+
* @public
|
|
2093
|
+
*/
|
|
2094
|
+
class JmMindEvent {
|
|
2095
|
+
/** The type of the event. */
|
|
2096
|
+
type;
|
|
2097
|
+
/** The event data. */
|
|
2098
|
+
data;
|
|
2099
|
+
/**
|
|
2100
|
+
* Creates a new JmMindEvent instance.
|
|
2101
|
+
*
|
|
2102
|
+
* @param type - The type of the event.
|
|
2103
|
+
* @param data - The event data.
|
|
2104
|
+
*/
|
|
2105
|
+
constructor(type, data) {
|
|
2106
|
+
this.type = type;
|
|
2107
|
+
this.data = data;
|
|
2108
|
+
}
|
|
2109
|
+
static onNodeAdded(node) {
|
|
2110
|
+
return new JmMindEvent(JmMindEventType.NodeAdded, new JmMindEventDataOnNodeAdded(node));
|
|
2111
|
+
}
|
|
2112
|
+
static onNodeRemoved(node, removedNodeIds, removedEdgeIds) {
|
|
2113
|
+
return new JmMindEvent(JmMindEventType.NodeRemoved, new JmMindEventDataOnNodeRemoved(node, removedNodeIds, removedEdgeIds));
|
|
2114
|
+
}
|
|
2115
|
+
static onNodeUpdated(node, property, originValue, newValue) {
|
|
2116
|
+
return new JmMindEvent(JmMindEventType.NodeUpdated, new JmMindEventDataOnNodeUpdated(node, property, originValue, newValue));
|
|
2117
|
+
}
|
|
2118
|
+
static onNodeMoved(node, oldParentId, oldPosition, oldSide) {
|
|
2119
|
+
return new JmMindEvent(JmMindEventType.NodeMoved, new JmMindEventDataOnNodeMoved(node, oldParentId, oldPosition, oldSide));
|
|
2120
|
+
}
|
|
2121
|
+
static onEdgeAdded(edge) {
|
|
2122
|
+
return new JmMindEvent(JmMindEventType.EdgeAdded, new JmMindEventDataOnEdgeAdded(edge));
|
|
2123
|
+
}
|
|
2124
|
+
static onEdgeRemoved(edge) {
|
|
2125
|
+
return new JmMindEvent(JmMindEventType.EdgeRemoved, new JmMindEventDataOnEdgeRemoved(edge));
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
class JmMindEventDataOnNodeAdded {
|
|
2129
|
+
node;
|
|
2130
|
+
constructor(node) {
|
|
2131
|
+
this.node = node;
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
class JmMindEventDataOnNodeRemoved {
|
|
2135
|
+
node;
|
|
2136
|
+
removedNodeIds;
|
|
2137
|
+
removedEdgeIds;
|
|
2138
|
+
constructor(node, removedNodeIds, removedEdgeIds) {
|
|
2139
|
+
this.node = node;
|
|
2140
|
+
this.removedNodeIds = removedNodeIds.slice();
|
|
2141
|
+
this.removedEdgeIds = removedEdgeIds.slice();
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
class JmMindEventDataOnNodeUpdated {
|
|
2145
|
+
node;
|
|
2146
|
+
property;
|
|
2147
|
+
originValue;
|
|
2148
|
+
newValue;
|
|
2149
|
+
constructor(node, property, originValue, newValue) {
|
|
2150
|
+
this.node = node;
|
|
2151
|
+
this.property = property;
|
|
2152
|
+
this.originValue = originValue;
|
|
2153
|
+
this.newValue = newValue;
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
class JmMindEventDataOnNodeMoved {
|
|
2157
|
+
node;
|
|
2158
|
+
oldParentId;
|
|
2159
|
+
oldPosition;
|
|
2160
|
+
oldSide;
|
|
2161
|
+
constructor(node, oldParentId, oldPosition, oldSide) {
|
|
2162
|
+
this.node = node;
|
|
2163
|
+
this.oldParentId = oldParentId;
|
|
2164
|
+
this.oldPosition = oldPosition;
|
|
2165
|
+
this.oldSide = oldSide;
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
class JmMindEventDataOnEdgeAdded {
|
|
2169
|
+
edge;
|
|
2170
|
+
constructor(edge) {
|
|
2171
|
+
this.edge = edge;
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
class JmMindEventDataOnEdgeRemoved {
|
|
2175
|
+
edge;
|
|
2176
|
+
constructor(edge) {
|
|
2177
|
+
this.edge = edge;
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
/**
|
|
2182
|
+
* Represents a mind map with nodes and edges.
|
|
2183
|
+
*
|
|
2184
|
+
* @public
|
|
2185
|
+
*/
|
|
2186
|
+
class JmMind {
|
|
2187
|
+
/** Metadata for the mind map. */
|
|
2188
|
+
meta;
|
|
2189
|
+
/** Configuration options for the mind map. */
|
|
2190
|
+
options;
|
|
2191
|
+
/**
|
|
2192
|
+
* Style declaration for the mind map.
|
|
2193
|
+
*
|
|
2194
|
+
* @remarks
|
|
2195
|
+
* This mind map inherits from `style.theme` (default `"default"`) and
|
|
2196
|
+
* overrides whatever else the declaration lists. Resolution and deep
|
|
2197
|
+
* merging happen at render time via `resolveJmStyle`, not here — this
|
|
2198
|
+
* field only stores what the file said.
|
|
2199
|
+
*/
|
|
2200
|
+
style;
|
|
2201
|
+
/** Manager for observers of this mind map. */
|
|
2202
|
+
observerManager;
|
|
2203
|
+
/** Manager for node operations. */
|
|
2204
|
+
nodeManager;
|
|
2205
|
+
/** @internal Internal ID generator for nodes and edges. */
|
|
2206
|
+
_idGenerator;
|
|
2207
|
+
/** @internal Dictionary of all nodes by ID. */
|
|
2208
|
+
_nodes;
|
|
2209
|
+
/** @internal Dictionary of all edges by ID. */
|
|
2210
|
+
_edges;
|
|
2211
|
+
/** @internal The root node of the mind map. */
|
|
2212
|
+
_root;
|
|
2213
|
+
/**
|
|
2214
|
+
* Creates a new mind map.
|
|
2215
|
+
*
|
|
2216
|
+
* @param metadata - Metadata for the mind map.
|
|
2217
|
+
* @param options - Configuration options for the mind map.
|
|
2218
|
+
*/
|
|
2219
|
+
constructor(metadata = {}, options = {}) {
|
|
2220
|
+
this.meta = mergeObjects(DEFAULT_METADATA, metadata);
|
|
2221
|
+
this.options = mergeObjects(DEFAULT_OPTIONS.mind, options);
|
|
2222
|
+
this.observerManager = new JmObserverManager(this);
|
|
2223
|
+
this.nodeManager = new JmNodeManager(this);
|
|
2224
|
+
this._idGenerator = new SimpleIdGenerator('jm-');
|
|
2225
|
+
this._nodes = {};
|
|
2226
|
+
this._edges = {};
|
|
2227
|
+
this._root = this._createRootNode();
|
|
2228
|
+
}
|
|
2229
|
+
/**
|
|
2230
|
+
* Gets the root node.
|
|
2231
|
+
*
|
|
2232
|
+
* @returns The root node.
|
|
2233
|
+
*/
|
|
2234
|
+
get root() {
|
|
2235
|
+
return this.lite(this._root);
|
|
2236
|
+
}
|
|
2237
|
+
/**
|
|
2238
|
+
* Adds an edge between two nodes.
|
|
2239
|
+
*
|
|
2240
|
+
* @param sourceNodeId - The source node ID.
|
|
2241
|
+
* @param targetNodeId - The target node ID.
|
|
2242
|
+
* @param type - The edge type.
|
|
2243
|
+
* @param options - Optional edge creation options.
|
|
2244
|
+
* @returns The created edge.
|
|
2245
|
+
* @throws {@link JsMindError} If the source or target node does not exist.
|
|
2246
|
+
*/
|
|
2247
|
+
addEdge(sourceNodeId, targetNodeId, type, options) {
|
|
2248
|
+
// Validate nodes exist
|
|
2249
|
+
this._getNodeById(sourceNodeId);
|
|
2250
|
+
this._getNodeById(targetNodeId);
|
|
2251
|
+
const edgeId = (options && options.edgeId) || this._idGenerator.newId();
|
|
2252
|
+
const label = (options && options.label) || null;
|
|
2253
|
+
const edge = new JmEdge(edgeId, sourceNodeId, targetNodeId, type, label);
|
|
2254
|
+
if (options && options.style !== undefined) {
|
|
2255
|
+
edge.style = options.style;
|
|
2256
|
+
}
|
|
2257
|
+
this._edges[edgeId] = edge;
|
|
2258
|
+
// Emit event
|
|
2259
|
+
this.observerManager.notifyObservers(JmMindEvent.onEdgeAdded(edge));
|
|
2260
|
+
return edge;
|
|
2261
|
+
}
|
|
2262
|
+
addChildNode(content, parentId) {
|
|
2263
|
+
if (!parentId) {
|
|
2264
|
+
throw new JsMindError('parentId is required for addChildNode');
|
|
2265
|
+
}
|
|
2266
|
+
if (!content) {
|
|
2267
|
+
throw new JsMindError('content is required for addChildNode');
|
|
2268
|
+
}
|
|
2269
|
+
let nodeContent;
|
|
2270
|
+
if (content instanceof JmNodeContent) {
|
|
2271
|
+
nodeContent = content;
|
|
2272
|
+
}
|
|
2273
|
+
else if (typeof content === 'string') {
|
|
2274
|
+
nodeContent = JmNodeContent.createText(content);
|
|
2275
|
+
}
|
|
2276
|
+
else {
|
|
2277
|
+
throw new JsMindError('content must be a string or a JmNodeContent object');
|
|
2278
|
+
}
|
|
2279
|
+
return this.addNode(nodeContent, { parentId: parentId });
|
|
2280
|
+
}
|
|
2281
|
+
/**
|
|
2282
|
+
* Adds a new node to the mind map at a specific destination.
|
|
2283
|
+
*
|
|
2284
|
+
* @param content - Content for the new node.
|
|
2285
|
+
* @param destOptions - Destination options (required).
|
|
2286
|
+
* @param nodeOptions - Optional node creation options.
|
|
2287
|
+
* @returns The created node.
|
|
2288
|
+
* @throws {@link JsMindError} If destOptions.parentId is missing.
|
|
2289
|
+
*/
|
|
2290
|
+
addNode(content, destOptions, nodeOptions) {
|
|
2291
|
+
// Validate destination options
|
|
2292
|
+
if (!destOptions || !destOptions.parentId) {
|
|
2293
|
+
throw new JsMindError('destOptions.parentId is required for addNode');
|
|
2294
|
+
}
|
|
2295
|
+
// Get target parent
|
|
2296
|
+
const targetParent = this._getNodeById(destOptions.parentId);
|
|
2297
|
+
// Create node content
|
|
2298
|
+
const nodeContent = content instanceof JmNodeContent ? content : JmNodeContent.fromObject(content);
|
|
2299
|
+
// Create and initialize the node
|
|
2300
|
+
const node = this._newNode(nodeContent, nodeOptions);
|
|
2301
|
+
// Use existing helper method for placement
|
|
2302
|
+
this._addNodeToParent(node, targetParent, destOptions.position);
|
|
2303
|
+
// Apply destination side if specified
|
|
2304
|
+
if (destOptions.side !== undefined && destOptions.side !== null) {
|
|
2305
|
+
node.side = destOptions.side;
|
|
2306
|
+
}
|
|
2307
|
+
// Emit event
|
|
2308
|
+
this.observerManager.notifyObservers(JmMindEvent.onNodeAdded(node));
|
|
2309
|
+
return this.lite(node);
|
|
2310
|
+
}
|
|
2311
|
+
/**
|
|
2312
|
+
* Finds a node from the mind map by the given ID.
|
|
2313
|
+
*
|
|
2314
|
+
* @param nodeId - The given node ID.
|
|
2315
|
+
* @returns The corresponding node in this mind map if it exists, otherwise null.
|
|
2316
|
+
*/
|
|
2317
|
+
findNodeById(nodeId) {
|
|
2318
|
+
const node = this._nodes[nodeId];
|
|
2319
|
+
return !!node ? this.lite(node) : null;
|
|
2320
|
+
}
|
|
2321
|
+
/**
|
|
2322
|
+
* Gets all edges for a specific node.
|
|
2323
|
+
*
|
|
2324
|
+
* @param nodeId - The node ID.
|
|
2325
|
+
* @param type - Optional edge type filter.
|
|
2326
|
+
* @returns Array of edges involving the node.
|
|
2327
|
+
*/
|
|
2328
|
+
getEdges(nodeId, type = null) {
|
|
2329
|
+
return Object.values(this._edges).filter(edge => {
|
|
2330
|
+
return (edge.sourceNodeId === nodeId || edge.targetNodeId === nodeId) &&
|
|
2331
|
+
(!type || edge.type === type);
|
|
2332
|
+
});
|
|
2333
|
+
}
|
|
2334
|
+
/**
|
|
2335
|
+
* Moves a node to a new parent and position.
|
|
2336
|
+
*
|
|
2337
|
+
* @param nodeId - The ID of the node to move.
|
|
2338
|
+
* @param destOptions - Destination options.
|
|
2339
|
+
* @returns The moved node.
|
|
2340
|
+
* @throws {@link JsMindError} If destOptions are missing, node not found, or invalid move operation.
|
|
2341
|
+
*/
|
|
2342
|
+
moveNode(nodeId, destOptions) {
|
|
2343
|
+
if (!destOptions || Object.keys(destOptions).length === 0) {
|
|
2344
|
+
throw new JsMindError('destOptions are required for moveNode operation');
|
|
2345
|
+
}
|
|
2346
|
+
const node = this._getNodeById(nodeId);
|
|
2347
|
+
if (!node) {
|
|
2348
|
+
throw new JsMindError(`Node with ID '${nodeId}' not found`);
|
|
2349
|
+
}
|
|
2350
|
+
// Skip all logic for root node - it cannot be moved
|
|
2351
|
+
if (node === this.root) {
|
|
2352
|
+
return this.lite(node);
|
|
2353
|
+
}
|
|
2354
|
+
// Extract options
|
|
2355
|
+
const targetParentId = destOptions.parentId;
|
|
2356
|
+
const targetPosition = destOptions.position;
|
|
2357
|
+
const targetSide = destOptions.side;
|
|
2358
|
+
// Capture original values before any changes
|
|
2359
|
+
const oldParent = node.parent;
|
|
2360
|
+
const oldPosition = node.parent ? node.parent.children.indexOf(node) : -1;
|
|
2361
|
+
const oldSide = node.side;
|
|
2362
|
+
// 1. Update parent and position if the node parent is provided and changed
|
|
2363
|
+
if (targetParentId && (!node.parent || node.parent.id !== targetParentId)) {
|
|
2364
|
+
const targetParent = this._getNodeById(targetParentId);
|
|
2365
|
+
if (!targetParent) {
|
|
2366
|
+
throw new JsMindError(`Target parent with ID '${targetParentId}' not found`);
|
|
2367
|
+
}
|
|
2368
|
+
// Validate that we're not moving a node to be its own descendant
|
|
2369
|
+
if (targetParent.isDescendant(node)) {
|
|
2370
|
+
throw new JsMindError('Cannot move a node to be its own descendant');
|
|
2371
|
+
}
|
|
2372
|
+
// Remove from current parent
|
|
2373
|
+
this._removeNodeFromParent(node);
|
|
2374
|
+
// Add to new parent at specified position and create edge
|
|
2375
|
+
this._addNodeToParent(node, targetParent, targetPosition);
|
|
2376
|
+
}
|
|
2377
|
+
// 2. Reposition if the node parent is not provided or is not changed, and the targetPosition is provided and changed
|
|
2378
|
+
if ((!targetParentId || (node.parent && node.parent.id === targetParentId)) &&
|
|
2379
|
+
targetPosition !== undefined && targetPosition !== null) {
|
|
2380
|
+
this._repositionNode(node, targetPosition);
|
|
2381
|
+
}
|
|
2382
|
+
// 3. Update side if the target side is provided and changed
|
|
2383
|
+
if (targetSide !== undefined && targetSide !== null) {
|
|
2384
|
+
node.side = targetSide;
|
|
2385
|
+
}
|
|
2386
|
+
// 4. Emit event only if something actually changed
|
|
2387
|
+
this._emitNodeMovedEventIfChanged(node, oldParent, oldPosition, oldSide);
|
|
2388
|
+
return this.lite(node);
|
|
2389
|
+
}
|
|
2390
|
+
/**
|
|
2391
|
+
* Removes an edge by ID.
|
|
2392
|
+
*
|
|
2393
|
+
* @param edgeId - The edge ID to remove.
|
|
2394
|
+
* @returns True if the edge was removed, false if not found.
|
|
2395
|
+
*/
|
|
2396
|
+
removeEdge(edgeId) {
|
|
2397
|
+
const edge = this._edges[edgeId];
|
|
2398
|
+
if (edge) {
|
|
2399
|
+
delete this._edges[edgeId];
|
|
2400
|
+
// Emit event
|
|
2401
|
+
this.observerManager.notifyObservers(JmMindEvent.onEdgeRemoved(edge));
|
|
2402
|
+
return true;
|
|
2403
|
+
}
|
|
2404
|
+
return false;
|
|
2405
|
+
}
|
|
2406
|
+
/**
|
|
2407
|
+
* Removes a node and all its descendants.
|
|
2408
|
+
*
|
|
2409
|
+
* @param nodeId - The ID of the node to remove.
|
|
2410
|
+
* @throws {@link JsMindError} If trying to remove the root node.
|
|
2411
|
+
*/
|
|
2412
|
+
removeNode(nodeId) {
|
|
2413
|
+
const node = this._getNodeById(nodeId);
|
|
2414
|
+
if (nodeId == this._root.id) {
|
|
2415
|
+
throw new JsMindError('root node can not be removed');
|
|
2416
|
+
}
|
|
2417
|
+
// remove node from parent's children
|
|
2418
|
+
const nodeIndex = node.parent.children.indexOf(node);
|
|
2419
|
+
node.parent.children.splice(nodeIndex, 1);
|
|
2420
|
+
// identify all nodes that need to be cleared
|
|
2421
|
+
const nodeIds = node.getAllSubnodeIds();
|
|
2422
|
+
nodeIds.push(node.id);
|
|
2423
|
+
// remove those nodes
|
|
2424
|
+
nodeIds.forEach((id) => delete this._nodes[id]);
|
|
2425
|
+
// remove all relevant edges
|
|
2426
|
+
const edgeIds = Object.values(this._edges)
|
|
2427
|
+
.filter((e) => nodeIds.includes(e.sourceNodeId) || nodeIds.includes(e.targetNodeId))
|
|
2428
|
+
.map((e) => e.id);
|
|
2429
|
+
edgeIds.forEach((id) => delete this._edges[id]);
|
|
2430
|
+
// emit event
|
|
2431
|
+
this.observerManager.notifyObservers(JmMindEvent.onNodeRemoved(node, nodeIds, edgeIds));
|
|
2432
|
+
}
|
|
2433
|
+
/**
|
|
2434
|
+
* Adds a node to a new parent at a specific position.
|
|
2435
|
+
*
|
|
2436
|
+
* @private
|
|
2437
|
+
* @param node - The node to add.
|
|
2438
|
+
* @param targetParent - The new parent node.
|
|
2439
|
+
* @param targetPosition - The position index among siblings.
|
|
2440
|
+
*/
|
|
2441
|
+
_addNodeToParent(node, targetParent, targetPosition) {
|
|
2442
|
+
node.parent = targetParent;
|
|
2443
|
+
if (targetPosition === undefined || targetPosition === null) {
|
|
2444
|
+
// Add to the end if no position specified
|
|
2445
|
+
targetParent.children.push(node);
|
|
2446
|
+
}
|
|
2447
|
+
else {
|
|
2448
|
+
// Insert at specific position
|
|
2449
|
+
const position = Math.max(0, Math.min(targetPosition, targetParent.children.length));
|
|
2450
|
+
targetParent.children.splice(position, 0, node);
|
|
2451
|
+
}
|
|
2452
|
+
}
|
|
2453
|
+
/**
|
|
2454
|
+
* Creates the root node.
|
|
2455
|
+
*
|
|
2456
|
+
* @private
|
|
2457
|
+
* @returns The created root node.
|
|
2458
|
+
*/
|
|
2459
|
+
_createRootNode() {
|
|
2460
|
+
const nodeOptions = {
|
|
2461
|
+
nodeId: this.options.rootNodeId,
|
|
2462
|
+
side: JmNodeSide.Center
|
|
2463
|
+
};
|
|
2464
|
+
return this._newNode(JmNodeContent.createText(this.meta.name), nodeOptions);
|
|
2465
|
+
}
|
|
2466
|
+
/**
|
|
2467
|
+
* Emits NodeMoved event only if something actually changed.
|
|
2468
|
+
*
|
|
2469
|
+
* @private
|
|
2470
|
+
* @param node - The node that was moved.
|
|
2471
|
+
* @param oldParent - The old parent node.
|
|
2472
|
+
* @param oldPosition - The old position index.
|
|
2473
|
+
* @param oldSide - The old side.
|
|
2474
|
+
*/
|
|
2475
|
+
_emitNodeMovedEventIfChanged(node, oldParent, oldPosition, oldSide) {
|
|
2476
|
+
// Compare actual updated node properties with old values
|
|
2477
|
+
const parentChanged = oldParent.id !== node.parent.id;
|
|
2478
|
+
const positionChanged = oldPosition !== node.parent.children.indexOf(node);
|
|
2479
|
+
const sideChanged = oldSide !== node.side;
|
|
2480
|
+
if (parentChanged || positionChanged || sideChanged) {
|
|
2481
|
+
const oldParentId = parentChanged ? oldParent.id : null;
|
|
2482
|
+
const oldPositionData = positionChanged ? oldPosition : null;
|
|
2483
|
+
const oldSideData = sideChanged ? oldSide : null;
|
|
2484
|
+
this.observerManager.notifyObservers(JmMindEvent.onNodeMoved(node, oldParentId, oldPositionData, oldSideData));
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
/**
|
|
2488
|
+
* Creates a new node and adds it to the mind map.
|
|
2489
|
+
*
|
|
2490
|
+
* @private
|
|
2491
|
+
* @param content - Content for the node.
|
|
2492
|
+
* @param nodeOptions - Optional node creation options.
|
|
2493
|
+
* @returns The created node.
|
|
2494
|
+
*/
|
|
2495
|
+
_newNode(content, nodeOptions) {
|
|
2496
|
+
const nodeId = (nodeOptions && nodeOptions.nodeId) || this._idGenerator.newId();
|
|
2497
|
+
const node = new JmNode(nodeId, content);
|
|
2498
|
+
if (nodeOptions) {
|
|
2499
|
+
if (nodeOptions.folded !== undefined) {
|
|
2500
|
+
node.folded = nodeOptions.folded;
|
|
2501
|
+
}
|
|
2502
|
+
if (nodeOptions.side !== undefined) {
|
|
2503
|
+
node.side = nodeOptions.side;
|
|
2504
|
+
}
|
|
2505
|
+
if (nodeOptions.data !== undefined) {
|
|
2506
|
+
node.data = nodeOptions.data;
|
|
2507
|
+
}
|
|
2508
|
+
if (nodeOptions.style !== undefined) {
|
|
2509
|
+
node.style = nodeOptions.style;
|
|
2510
|
+
}
|
|
2511
|
+
}
|
|
2512
|
+
this._nodes[nodeId] = node;
|
|
2513
|
+
return node;
|
|
2514
|
+
}
|
|
2515
|
+
/**
|
|
2516
|
+
* Handles node update events.
|
|
2517
|
+
*
|
|
2518
|
+
* @private
|
|
2519
|
+
* @param node - The node that was updated.
|
|
2520
|
+
* @param prop - The property that was updated.
|
|
2521
|
+
* @param originValue - The original value.
|
|
2522
|
+
* @param newValue - The new value.
|
|
2523
|
+
*/
|
|
2524
|
+
_onNodeUpdated(node, prop, originValue, newValue) {
|
|
2525
|
+
this.observerManager.notifyObservers(JmMindEvent.onNodeUpdated(node, prop, originValue, newValue));
|
|
2526
|
+
}
|
|
2527
|
+
/**
|
|
2528
|
+
* Removes a node from its current parent.
|
|
2529
|
+
*
|
|
2530
|
+
* @private
|
|
2531
|
+
* @param node - The node to remove from parent.
|
|
2532
|
+
*/
|
|
2533
|
+
_removeNodeFromParent(node) {
|
|
2534
|
+
if (!node.parent) {
|
|
2535
|
+
return;
|
|
2536
|
+
}
|
|
2537
|
+
const parent = node.parent;
|
|
2538
|
+
const index = parent.children.indexOf(node);
|
|
2539
|
+
if (index > -1) {
|
|
2540
|
+
parent.children.splice(index, 1);
|
|
2541
|
+
}
|
|
2542
|
+
node.parent = null;
|
|
2543
|
+
}
|
|
2544
|
+
/**
|
|
2545
|
+
* Repositions a node within the same parent (optimized operation).
|
|
2546
|
+
*
|
|
2547
|
+
* @private
|
|
2548
|
+
* @param node - The node to reposition.
|
|
2549
|
+
* @param targetPosition - The new position index among siblings.
|
|
2550
|
+
*/
|
|
2551
|
+
_repositionNode(node, targetPosition) {
|
|
2552
|
+
if (targetPosition === undefined || targetPosition === null) {
|
|
2553
|
+
return;
|
|
2554
|
+
}
|
|
2555
|
+
const parent = node.parent;
|
|
2556
|
+
const currentIndex = parent.children.indexOf(node);
|
|
2557
|
+
const newPosition = Math.max(0, Math.min(targetPosition, parent.children.length));
|
|
2558
|
+
if (currentIndex !== newPosition) {
|
|
2559
|
+
parent.children.splice(currentIndex, 1);
|
|
2560
|
+
parent.children.splice(newPosition, 0, node);
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
/**
|
|
2564
|
+
* Retrieves a node by node ID.
|
|
2565
|
+
*
|
|
2566
|
+
* @private
|
|
2567
|
+
* @param nodeId - The node ID.
|
|
2568
|
+
* @returns The corresponding node.
|
|
2569
|
+
* @throws {@link JsMindError} If the node doesn't exist.
|
|
2570
|
+
*/
|
|
2571
|
+
_getNodeById(nodeId) {
|
|
2572
|
+
const node = this._nodes[nodeId];
|
|
2573
|
+
if (!!node) {
|
|
2574
|
+
return node;
|
|
2575
|
+
}
|
|
2576
|
+
throw new JsMindError(`node[id=${nodeId}] does not exist`);
|
|
2577
|
+
}
|
|
2578
|
+
lite(node) {
|
|
2579
|
+
return this.nodeManager.manage(node);
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
/**
|
|
2583
|
+
* Manager for node operations with proxy-based access control.
|
|
2584
|
+
*
|
|
2585
|
+
* @internal
|
|
2586
|
+
*/
|
|
2587
|
+
class JmNodeManager {
|
|
2588
|
+
/** The mind map instance. */
|
|
2589
|
+
mind;
|
|
2590
|
+
/** Set of readonly field names. */
|
|
2591
|
+
readonlyFields;
|
|
2592
|
+
/** Set of unsafe array method names. */
|
|
2593
|
+
unsafeArrayMethods;
|
|
2594
|
+
/**
|
|
2595
|
+
* Creates a new JmNodeManager instance.
|
|
2596
|
+
*
|
|
2597
|
+
* @param mind - The mind map instance.
|
|
2598
|
+
*/
|
|
2599
|
+
constructor(mind) {
|
|
2600
|
+
this.mind = mind;
|
|
2601
|
+
this.readonlyFields = new Set(['id', 'parent', 'children', 'data']);
|
|
2602
|
+
this.unsafeArrayMethods = new Set(['fill', 'pop', 'push', 'shift', 'unshift', 'reverse', 'sort', 'splice']);
|
|
2603
|
+
}
|
|
2604
|
+
/**
|
|
2605
|
+
* Manages a node with proxy-based access control.
|
|
2606
|
+
*
|
|
2607
|
+
* @param node - The node to manage.
|
|
2608
|
+
* @returns The managed node with proxy.
|
|
2609
|
+
*/
|
|
2610
|
+
manage(node) {
|
|
2611
|
+
return new Proxy(node, {
|
|
2612
|
+
get: this.getterTrap.bind(this),
|
|
2613
|
+
set: this.setterTrap.bind(this)
|
|
2614
|
+
});
|
|
2615
|
+
}
|
|
2616
|
+
/**
|
|
2617
|
+
* Getter trap for the proxy.
|
|
2618
|
+
*
|
|
2619
|
+
* @param node - The node.
|
|
2620
|
+
* @param prop - The property name.
|
|
2621
|
+
* @returns The property value.
|
|
2622
|
+
*/
|
|
2623
|
+
getterTrap(node, prop) {
|
|
2624
|
+
const ori = node[prop];
|
|
2625
|
+
if (prop === 'children') {
|
|
2626
|
+
const itemManagedArray = ori.map((n) => this.manage(n));
|
|
2627
|
+
return new Proxy(itemManagedArray, {
|
|
2628
|
+
get: (arr, prop) => {
|
|
2629
|
+
if (this.unsafeArrayMethods.has(prop)) {
|
|
2630
|
+
return function () {
|
|
2631
|
+
throw new JsMindError(`unsupported method ${String(prop)} on node.children, please follow the document to operate the mindmap.`);
|
|
2632
|
+
};
|
|
2633
|
+
}
|
|
2634
|
+
return arr[prop];
|
|
2635
|
+
}
|
|
2636
|
+
});
|
|
2637
|
+
}
|
|
2638
|
+
if (prop === 'parent') {
|
|
2639
|
+
return !!ori ? this.manage(ori) : null;
|
|
2640
|
+
}
|
|
2641
|
+
return ori;
|
|
2642
|
+
}
|
|
2643
|
+
/**
|
|
2644
|
+
* Setter trap for the proxy.
|
|
2645
|
+
*
|
|
2646
|
+
* @param node - The node.
|
|
2647
|
+
* @param prop - The property name.
|
|
2648
|
+
* @param value - The new value.
|
|
2649
|
+
* @returns True if the operation succeeded.
|
|
2650
|
+
* @throws {@link JsMindError} If trying to set a readonly property.
|
|
2651
|
+
*/
|
|
2652
|
+
setterTrap(node, prop, value) {
|
|
2653
|
+
if (this.readonlyFields.has(prop)) {
|
|
2654
|
+
throw new JsMindError(`the property[${String(prop)}] is readonly`);
|
|
2655
|
+
}
|
|
2656
|
+
const ori = node[prop];
|
|
2657
|
+
if (ori !== value) {
|
|
2658
|
+
node[prop] = value;
|
|
2659
|
+
this.mind._onNodeUpdated(node, prop, ori, value);
|
|
2660
|
+
}
|
|
2661
|
+
return true;
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
|
|
2665
|
+
/**
|
|
2666
|
+
* Format identifier written to every v2 data file.
|
|
2667
|
+
*
|
|
2668
|
+
* @public
|
|
2669
|
+
*/
|
|
2670
|
+
const JSMIND_FORMAT_V2 = 'jsmind_v2';
|
|
2671
|
+
/**
|
|
2672
|
+
* JSON serializer for mind maps.
|
|
2673
|
+
*
|
|
2674
|
+
* @public
|
|
2675
|
+
*/
|
|
2676
|
+
class JmMindJsonSerializer {
|
|
2677
|
+
/**
|
|
2678
|
+
* Gets the format name this serializer supports.
|
|
2679
|
+
*
|
|
2680
|
+
* @returns The format name.
|
|
2681
|
+
*/
|
|
2682
|
+
getFormatName() {
|
|
2683
|
+
return 'json';
|
|
2684
|
+
}
|
|
2685
|
+
/**
|
|
2686
|
+
* Serializes a mind map to JSON format.
|
|
2687
|
+
*
|
|
2688
|
+
* @param mind - The mind map to serialize.
|
|
2689
|
+
* @returns The serialized JSON data.
|
|
2690
|
+
* @throws {@link JsMindError} If the mind map is not provided.
|
|
2691
|
+
*/
|
|
2692
|
+
serialize(mind) {
|
|
2693
|
+
if (!mind) {
|
|
2694
|
+
throw new JsMindError('Mind map is required for serialization');
|
|
2695
|
+
}
|
|
2696
|
+
const serializedData = {
|
|
2697
|
+
format: JSMIND_FORMAT_V2,
|
|
2698
|
+
meta: mind.meta,
|
|
2699
|
+
root: mind._root.id,
|
|
2700
|
+
nodes: {},
|
|
2701
|
+
edges: {}
|
|
2702
|
+
};
|
|
2703
|
+
if (mind.style !== undefined) {
|
|
2704
|
+
serializedData.style = mind.style;
|
|
2705
|
+
}
|
|
2706
|
+
// Serialize all nodes
|
|
2707
|
+
Object.values(mind._nodes).forEach(node => {
|
|
2708
|
+
serializedData.nodes[node.id] = this._serializeNode(node);
|
|
2709
|
+
});
|
|
2710
|
+
// Serialize all additional edges
|
|
2711
|
+
Object.values(mind._edges).forEach(edge => {
|
|
2712
|
+
serializedData.edges[edge.id] = this._serializeEdge(edge);
|
|
2713
|
+
});
|
|
2714
|
+
return serializedData;
|
|
2715
|
+
}
|
|
2716
|
+
/**
|
|
2717
|
+
* Deserializes JSON data to a mind map.
|
|
2718
|
+
*
|
|
2719
|
+
* @param data - The JSON data to deserialize.
|
|
2720
|
+
* @returns The deserialized mind map.
|
|
2721
|
+
* @throws {@link JsMindError} If the JSON data format is invalid.
|
|
2722
|
+
*/
|
|
2723
|
+
deserialize(data) {
|
|
2724
|
+
const result = this.check(data);
|
|
2725
|
+
if (!result.valid) {
|
|
2726
|
+
throw new JsMindError(`Invalid JSON data format: ${summarise(result.errors)}`, { errors: result.errors }, result.errors[0].code);
|
|
2727
|
+
}
|
|
2728
|
+
// Create mind map with metadata and options
|
|
2729
|
+
const mind = new JmMind(data.meta, { rootNodeId: data.root });
|
|
2730
|
+
if (data.style !== undefined) {
|
|
2731
|
+
mind.style = data.style;
|
|
2732
|
+
}
|
|
2733
|
+
// Restore nodes
|
|
2734
|
+
Object.values(data.nodes).forEach((nodeData) => {
|
|
2735
|
+
const node = this._deserializeNode(nodeData);
|
|
2736
|
+
mind._nodes[node.id] = node;
|
|
2737
|
+
});
|
|
2738
|
+
// Restore additional edges
|
|
2739
|
+
if (data.edges) {
|
|
2740
|
+
Object.values(data.edges).forEach((edgeData) => {
|
|
2741
|
+
const edge = this._deserializeEdge(edgeData);
|
|
2742
|
+
mind._edges[edge.id] = edge;
|
|
2743
|
+
});
|
|
2744
|
+
}
|
|
2745
|
+
// Restore root
|
|
2746
|
+
mind._root = mind._nodes[data.root];
|
|
2747
|
+
// Restore parent-child relationships
|
|
2748
|
+
this._restoreNodeRelationships(mind, data);
|
|
2749
|
+
return mind;
|
|
2750
|
+
}
|
|
2751
|
+
/**
|
|
2752
|
+
* Validates if the data can be deserialized by this serializer.
|
|
2753
|
+
*
|
|
2754
|
+
* @param data - The data to validate.
|
|
2755
|
+
* @returns True if the data is valid for this format.
|
|
2756
|
+
*/
|
|
2757
|
+
validate(data) {
|
|
2758
|
+
return this.check(data).valid;
|
|
2759
|
+
}
|
|
2760
|
+
/**
|
|
2761
|
+
* Validates data and returns every problem found.
|
|
2762
|
+
*
|
|
2763
|
+
* @remarks
|
|
2764
|
+
* Use this instead of `validate` when the caller needs to know *why* data
|
|
2765
|
+
* was rejected. Each issue carries a stable `code`, a `path` into the
|
|
2766
|
+
* document, and a message written for humans.
|
|
2767
|
+
*
|
|
2768
|
+
* @param data - The data to validate.
|
|
2769
|
+
* @returns Every issue found; `valid` is true only when there are none.
|
|
2770
|
+
*/
|
|
2771
|
+
check(data) {
|
|
2772
|
+
return validateMindData(data);
|
|
2773
|
+
}
|
|
2774
|
+
/**
|
|
2775
|
+
* Serializes a single node.
|
|
2776
|
+
*
|
|
2777
|
+
* @private
|
|
2778
|
+
* @param node - The node to serialize.
|
|
2779
|
+
* @returns The serialized node data.
|
|
2780
|
+
*/
|
|
2781
|
+
_serializeNode(node) {
|
|
2782
|
+
return {
|
|
2783
|
+
id: node.id,
|
|
2784
|
+
content: {
|
|
2785
|
+
type: node.content.type,
|
|
2786
|
+
value: node.content.value
|
|
2787
|
+
},
|
|
2788
|
+
parent: node.parent ? node.parent.id : null,
|
|
2789
|
+
children: node.children.map(child => child.id),
|
|
2790
|
+
folded: node.folded,
|
|
2791
|
+
side: node.side,
|
|
2792
|
+
data: { ...node.data },
|
|
2793
|
+
...(node.style ? { style: copyNodeStyle(node.style) } : {})
|
|
2794
|
+
};
|
|
2795
|
+
}
|
|
2796
|
+
/**
|
|
2797
|
+
* Deserializes a single node.
|
|
2798
|
+
*
|
|
2799
|
+
* @private
|
|
2800
|
+
* @param nodeData - The node data to deserialize.
|
|
2801
|
+
* @returns The deserialized node.
|
|
2802
|
+
*/
|
|
2803
|
+
_deserializeNode(nodeData) {
|
|
2804
|
+
const content = new JmNodeContent(nodeData.content.type, nodeData.content.value);
|
|
2805
|
+
const node = new JmNode(nodeData.id, content);
|
|
2806
|
+
node.folded = nodeData.folded;
|
|
2807
|
+
node.side = nodeData.side;
|
|
2808
|
+
node.data = { ...nodeData.data };
|
|
2809
|
+
if (nodeData.style) {
|
|
2810
|
+
node.style = copyNodeStyle(nodeData.style);
|
|
2811
|
+
}
|
|
2812
|
+
return node;
|
|
2813
|
+
}
|
|
2814
|
+
/**
|
|
2815
|
+
* Serializes a single edge.
|
|
2816
|
+
*
|
|
2817
|
+
* @private
|
|
2818
|
+
* @param edge - The edge to serialize.
|
|
2819
|
+
* @returns The serialized edge data.
|
|
2820
|
+
*/
|
|
2821
|
+
_serializeEdge(edge) {
|
|
2822
|
+
return {
|
|
2823
|
+
id: edge.id,
|
|
2824
|
+
sourceNodeId: edge.sourceNodeId,
|
|
2825
|
+
targetNodeId: edge.targetNodeId,
|
|
2826
|
+
type: edge.type,
|
|
2827
|
+
label: edge.label,
|
|
2828
|
+
...(edge.style ? { style: copyLineStyle(edge.style) } : {})
|
|
2829
|
+
};
|
|
2830
|
+
}
|
|
2831
|
+
/**
|
|
2832
|
+
* Deserializes a single edge.
|
|
2833
|
+
*
|
|
2834
|
+
* @private
|
|
2835
|
+
* @param edgeData - The edge data to deserialize.
|
|
2836
|
+
* @returns The deserialized edge.
|
|
2837
|
+
*/
|
|
2838
|
+
_deserializeEdge(edgeData) {
|
|
2839
|
+
const edge = new JmEdge(edgeData.id, edgeData.sourceNodeId, edgeData.targetNodeId, edgeData.type, edgeData.label);
|
|
2840
|
+
if (edgeData.style) {
|
|
2841
|
+
edge.style = copyLineStyle(edgeData.style);
|
|
2842
|
+
}
|
|
2843
|
+
return edge;
|
|
2844
|
+
}
|
|
2845
|
+
/**
|
|
2846
|
+
* Restores parent-child relationships between nodes.
|
|
2847
|
+
*
|
|
2848
|
+
* @private
|
|
2849
|
+
* @param mind - The mind map to restore relationships for.
|
|
2850
|
+
* @param data - The serialized data containing parent and children information.
|
|
2851
|
+
*/
|
|
2852
|
+
_restoreNodeRelationships(mind, data) {
|
|
2853
|
+
// Restore parent relationships
|
|
2854
|
+
Object.values(data.nodes).forEach((nodeData) => {
|
|
2855
|
+
const node = mind._nodes[nodeData.id];
|
|
2856
|
+
if (nodeData.parent !== null) {
|
|
2857
|
+
const parentNode = mind._nodes[nodeData.parent];
|
|
2858
|
+
if (parentNode) {
|
|
2859
|
+
node.parent = parentNode;
|
|
2860
|
+
}
|
|
2861
|
+
}
|
|
2862
|
+
else {
|
|
2863
|
+
node.parent = null;
|
|
2864
|
+
}
|
|
2865
|
+
});
|
|
2866
|
+
// Restore children relationships
|
|
2867
|
+
Object.values(data.nodes).forEach((nodeData) => {
|
|
2868
|
+
const node = mind._nodes[nodeData.id];
|
|
2869
|
+
node.children = nodeData.children
|
|
2870
|
+
.map((childId) => mind._nodes[childId])
|
|
2871
|
+
.filter((child) => child !== undefined);
|
|
2872
|
+
});
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
/**
|
|
2876
|
+
* Summarises validation issues into one readable sentence.
|
|
2877
|
+
*
|
|
2878
|
+
* @remarks
|
|
2879
|
+
* The first issue carries the most useful detail; the remaining count tells
|
|
2880
|
+
* the reader whether to expect more. Full detail is in `error.data.errors`.
|
|
2881
|
+
*
|
|
2882
|
+
* @param errors - Issues to summarise.
|
|
2883
|
+
* @returns A single human-readable line.
|
|
2884
|
+
*/
|
|
2885
|
+
function summarise(errors) {
|
|
2886
|
+
const first = errors[0];
|
|
2887
|
+
const rest = errors.length - 1;
|
|
2888
|
+
const suffix = rest > 0 ? ` (and ${rest} more)` : '';
|
|
2889
|
+
return `${first.code} at ${first.path || '<root>'}: ${first.message}${suffix}`;
|
|
2890
|
+
}
|
|
2891
|
+
/**
|
|
2892
|
+
* Copies a node style so the serialized snapshot does not share nested objects
|
|
2893
|
+
* with the live model.
|
|
2894
|
+
*
|
|
2895
|
+
* @remarks
|
|
2896
|
+
* `incoming` is the only nested field, so a two-level copy covers the whole
|
|
2897
|
+
* structure. Sharing it would let a later edit to `node.style.incoming` reach
|
|
2898
|
+
* back into data that was already serialized.
|
|
2899
|
+
*
|
|
2900
|
+
* @param style - The style to copy.
|
|
2901
|
+
* @returns A detached copy.
|
|
2902
|
+
*/
|
|
2903
|
+
function copyNodeStyle(style) {
|
|
2904
|
+
return style.incoming
|
|
2905
|
+
? { ...style, incoming: copyLineStyle(style.incoming) }
|
|
2906
|
+
: { ...style };
|
|
2907
|
+
}
|
|
2908
|
+
/**
|
|
2909
|
+
* Copies a line style.
|
|
2910
|
+
*
|
|
2911
|
+
* @remarks
|
|
2912
|
+
* `JmLineStyle` holds scalars only, so a spread is a full copy. Kept as a
|
|
2913
|
+
* named function so node styles and edge styles go through one path — if the
|
|
2914
|
+
* shape ever grows a nested field, only this function needs to change.
|
|
2915
|
+
*
|
|
2916
|
+
* @param style - The line style to copy.
|
|
2917
|
+
* @returns A detached copy.
|
|
2918
|
+
*/
|
|
2919
|
+
function copyLineStyle(style) {
|
|
2920
|
+
return { ...style };
|
|
2921
|
+
}
|
|
2922
|
+
|
|
2923
|
+
/**
|
|
2924
|
+
* Rendering of validation issues for humans.
|
|
2925
|
+
*
|
|
2926
|
+
* @packageDocumentation
|
|
2927
|
+
*/
|
|
2928
|
+
/**
|
|
2929
|
+
* Renders validation issues as an indented block.
|
|
2930
|
+
*
|
|
2931
|
+
* @remarks
|
|
2932
|
+
* Code first so a reader can scan a column of caps-lock tokens and find the one
|
|
2933
|
+
* that matters, path second because that is what they need to act on.
|
|
2934
|
+
*
|
|
2935
|
+
* @param errors - Issues to render.
|
|
2936
|
+
* @returns One block of text, no trailing newline.
|
|
2937
|
+
*/
|
|
2938
|
+
function formatIssues(errors) {
|
|
2939
|
+
return errors
|
|
2940
|
+
.map(issue => ` ${issue.code} ${issue.path || '<root>'}\n ${issue.message}`)
|
|
2941
|
+
.join('\n');
|
|
2942
|
+
}
|
|
2943
|
+
|
|
2944
|
+
/**
|
|
2945
|
+
* Load → mutate → write → verify → roll back, shared by every mutating
|
|
2946
|
+
* command.
|
|
2947
|
+
*
|
|
2948
|
+
* @remarks
|
|
2949
|
+
* The post-write validation is not optional. A CLI that can silently corrupt a
|
|
2950
|
+
* file is worse than no CLI: an agent would keep using the damaged document.
|
|
2951
|
+
* Every mutation therefore runs the full integrity check against what actually
|
|
2952
|
+
* landed on disk and restores the original bytes when it fails.
|
|
2953
|
+
*
|
|
2954
|
+
* @packageDocumentation
|
|
2955
|
+
*/
|
|
2956
|
+
/**
|
|
2957
|
+
* Runs one mutating command against a file.
|
|
2958
|
+
*
|
|
2959
|
+
* @remarks
|
|
2960
|
+
* Three protections apply: `dryRun` never touches the file, `backup` keeps a
|
|
2961
|
+
* `.bak`, and `output` redirects the write. When none are set the input file is
|
|
2962
|
+
* rewritten in place, which is the agent's normal workflow.
|
|
2963
|
+
*
|
|
2964
|
+
* @param file - Input mind map.
|
|
2965
|
+
* @param options - Dry-run / backup / output settings.
|
|
2966
|
+
* @param mutate - Receives the loaded mind map, returns the value to report.
|
|
2967
|
+
* @returns The reported value, with the exit code assumed to be 0.
|
|
2968
|
+
* @throws {@link CliError} With `InvalidData` when the file or result does not
|
|
2969
|
+
* validate, or `IoError` when the file cannot be read or written.
|
|
2970
|
+
*/
|
|
2971
|
+
function runMutation(file, options, mutate) {
|
|
2972
|
+
const serializer = new JmMindJsonSerializer();
|
|
2973
|
+
// Refuse to operate on a document that is already broken: any change we make
|
|
2974
|
+
// would be layered on top of existing damage and the post-write check would
|
|
2975
|
+
// blame our edit.
|
|
2976
|
+
const original = readJsonFile(file);
|
|
2977
|
+
const before = validateMindData(original);
|
|
2978
|
+
if (!before.valid) {
|
|
2979
|
+
throw dataError(`Refusing to modify ${file}: it does not validate.\n${formatIssues(before.errors)}`);
|
|
2980
|
+
}
|
|
2981
|
+
const mind = serializer.deserialize(original);
|
|
2982
|
+
const value = mutate(mind);
|
|
2983
|
+
const next = serializer.serialize(mind);
|
|
2984
|
+
const target = options.output ?? file;
|
|
2985
|
+
if (options.dryRun) {
|
|
2986
|
+
process.stdout.write(`${renderJson(next)}`);
|
|
2987
|
+
return value;
|
|
2988
|
+
}
|
|
2989
|
+
// Capture the exact bytes before writing so a failed check can put them back.
|
|
2990
|
+
let previous = null;
|
|
2991
|
+
try {
|
|
2992
|
+
previous = readFileSync(target, 'utf8');
|
|
2993
|
+
}
|
|
2994
|
+
catch {
|
|
2995
|
+
// Target did not exist (--output to a new path). Nothing to restore.
|
|
2996
|
+
}
|
|
2997
|
+
writeJsonFile(next, target, options);
|
|
2998
|
+
const after = validateMindData(next);
|
|
2999
|
+
if (!after.valid) {
|
|
3000
|
+
if (previous !== null) {
|
|
3001
|
+
restoreFile(target, previous);
|
|
3002
|
+
}
|
|
3003
|
+
throw dataError(`Validation failed after write, ${previous === null ? 'new file left in place' : 'rolled back'}:\n` +
|
|
3004
|
+
`${formatIssues(after.errors)}\nFile unchanged.`);
|
|
3005
|
+
}
|
|
3006
|
+
return value;
|
|
3007
|
+
}
|
|
3008
|
+
|
|
3009
|
+
/**
|
|
3010
|
+
* Helpers shared by more than one command group.
|
|
3011
|
+
*
|
|
3012
|
+
* @remarks
|
|
3013
|
+
* Only things that are genuinely identical between groups live here. When two
|
|
3014
|
+
* call sites look alike but answer different questions, they stay separate —
|
|
3015
|
+
* merging those is how a shared helper turns into a function with a mode flag.
|
|
3016
|
+
*
|
|
3017
|
+
* @packageDocumentation
|
|
3018
|
+
*/
|
|
3019
|
+
/**
|
|
3020
|
+
* Synonyms accepted for each side, and the value they normalise to.
|
|
3021
|
+
*
|
|
3022
|
+
* @remarks
|
|
3023
|
+
* The model deliberately names its sides A and B rather than left and right, so
|
|
3024
|
+
* the values stay usable if a vertical layout ever arrives. The command line
|
|
3025
|
+
* cannot be that abstract — nobody types `--side b` — so the words live here, in
|
|
3026
|
+
* one table, and every accepted spelling normalises to the same numeric value.
|
|
3027
|
+
*
|
|
3028
|
+
* When a vertical layout lands, `up` and `down` are added to this table pointing
|
|
3029
|
+
* at the existing values. The words change; the data does not.
|
|
3030
|
+
*
|
|
3031
|
+
* Current mapping, per the JmNodeSide comments in the model:
|
|
3032
|
+
*
|
|
3033
|
+
* | word | value | model name |
|
|
3034
|
+
* |--------|-------|------------|
|
|
3035
|
+
* | left | -1 | SideB |
|
|
3036
|
+
* | center | 0 | Center |
|
|
3037
|
+
* | right | 1 | SideA |
|
|
3038
|
+
*/
|
|
3039
|
+
const SIDE_SYNONYMS = {
|
|
3040
|
+
left: JmNodeSide.SideB,
|
|
3041
|
+
center: JmNodeSide.Center,
|
|
3042
|
+
right: JmNodeSide.SideA,
|
|
3043
|
+
};
|
|
3044
|
+
/**
|
|
3045
|
+
* Every spelling the `--side` option accepts.
|
|
3046
|
+
*
|
|
3047
|
+
* @remarks
|
|
3048
|
+
* Derived from the table rather than restated, so an error message cannot drift
|
|
3049
|
+
* away from what the parser actually accepts.
|
|
3050
|
+
*/
|
|
3051
|
+
const SIDE_WORDS = Object.keys(SIDE_SYNONYMS).join(', ');
|
|
3052
|
+
/**
|
|
3053
|
+
* Converts a `--side` value to the numeric enum.
|
|
3054
|
+
*
|
|
3055
|
+
* @param raw - Value from the command line.
|
|
3056
|
+
* @returns The normalised side.
|
|
3057
|
+
* @throws {@link CliError} With `Usage` for an unknown name.
|
|
3058
|
+
*/
|
|
3059
|
+
function parseSide(raw) {
|
|
3060
|
+
const value = SIDE_SYNONYMS[raw];
|
|
3061
|
+
if (value === undefined) {
|
|
3062
|
+
throw usageError(`--side must be one of ${SIDE_WORDS}, got "${raw}"`);
|
|
3063
|
+
}
|
|
3064
|
+
return value;
|
|
3065
|
+
}
|
|
3066
|
+
/**
|
|
3067
|
+
* Converts a numeric side to its display word — the inverse of {@link parseSide}.
|
|
3068
|
+
*
|
|
3069
|
+
* @param side - The raw value from a node.
|
|
3070
|
+
* @returns `"left"`, `"center"`, or `"right"`.
|
|
3071
|
+
* @remarks
|
|
3072
|
+
* The model stores sides as −1 / 0 / 1 so a vertical layout can reuse the same
|
|
3073
|
+
* values with different words later. This function is the place that picks the
|
|
3074
|
+
* current word, and it is deliberately the only place: if a vertical layout ever
|
|
3075
|
+
* lands, changing these three strings changes every caller at once.
|
|
3076
|
+
*/
|
|
3077
|
+
function formatSide(side) {
|
|
3078
|
+
if (side === JmNodeSide.SideB)
|
|
3079
|
+
return 'left';
|
|
3080
|
+
if (side === JmNodeSide.SideA)
|
|
3081
|
+
return 'right';
|
|
3082
|
+
return 'center';
|
|
3083
|
+
}
|
|
3084
|
+
/**
|
|
3085
|
+
* Writes a command result in the shape the caller asked for.
|
|
3086
|
+
*
|
|
3087
|
+
* @param asJson - Emit JSON instead of prose.
|
|
3088
|
+
* @param prose - Human-readable summary.
|
|
3089
|
+
* @param payload - Machine-readable result.
|
|
3090
|
+
*/
|
|
3091
|
+
function report(asJson, prose, payload) {
|
|
3092
|
+
process.stdout.write(asJson ? `${JSON.stringify(payload, null, 2)}\n` : `${prose}\n`);
|
|
3093
|
+
}
|
|
3094
|
+
/**
|
|
3095
|
+
* Describes a node's style block for output.
|
|
3096
|
+
*
|
|
3097
|
+
* @param style - The node's overrides, if any.
|
|
3098
|
+
* @returns A plain object, or `null` when the node overrides nothing.
|
|
3099
|
+
* @remarks
|
|
3100
|
+
* A style block records only what differs from the theme, and that shape is
|
|
3101
|
+
* carried through unchanged: a field the caller never set is absent here too.
|
|
3102
|
+
* Reporting defaults would make every described node longer for information the
|
|
3103
|
+
* theme already implies, and this output is read on every discovery step.
|
|
3104
|
+
*/
|
|
3105
|
+
function describeStyle(style) {
|
|
3106
|
+
return style === undefined ? null : structuredClone(style);
|
|
3107
|
+
}
|
|
3108
|
+
/**
|
|
3109
|
+
* Describes a node for output.
|
|
3110
|
+
*
|
|
3111
|
+
* @remarks
|
|
3112
|
+
* `parent` and `children` hold live JmNode references, not ids. Serialising a
|
|
3113
|
+
* node as-is walks straight back into the tree and blows the stack, so every id
|
|
3114
|
+
* crossing this boundary is extracted explicitly.
|
|
3115
|
+
*
|
|
3116
|
+
* `side` is emitted as the word that `parseSide()` accepts (`"left"` / `"center"`
|
|
3117
|
+
* / `"right"`), not the internal number, so an agent can copy the value straight
|
|
3118
|
+
* into `jsmind node set-side`.
|
|
3119
|
+
*
|
|
3120
|
+
* `folded` appears only when `true` — every node defaults to unfolded, and
|
|
3121
|
+
* reporting a key the caller never set would add noise to every response.
|
|
3122
|
+
*
|
|
3123
|
+
* `style` is included only when the node overrides something. A command can set
|
|
3124
|
+
* it, so a discovery command has to be able to show it - otherwise the only way
|
|
3125
|
+
* to confirm a style change is to render an image and look, which costs a vision
|
|
3126
|
+
* call per check and is unreliable at that.
|
|
3127
|
+
*
|
|
3128
|
+
* @param node - Node to describe.
|
|
3129
|
+
* @returns Plain object for output.
|
|
3130
|
+
*/
|
|
3131
|
+
function describeNode(node) {
|
|
3132
|
+
const described = {
|
|
3133
|
+
id: node.id,
|
|
3134
|
+
text: node.content.value,
|
|
3135
|
+
parent: node.parent === null ? null : node.parent.id,
|
|
3136
|
+
children: node.children.map(child => child.id),
|
|
3137
|
+
side: formatSide(node.side),
|
|
3138
|
+
};
|
|
3139
|
+
// folded only when the node is collapsed — the default is false for every
|
|
3140
|
+
// node and reporting it would add a key the caller never asked for.
|
|
3141
|
+
if (node.folded) {
|
|
3142
|
+
described.folded = true;
|
|
3143
|
+
}
|
|
3144
|
+
const style = describeStyle(node.style);
|
|
3145
|
+
if (style !== null) {
|
|
3146
|
+
described.style = style;
|
|
3147
|
+
}
|
|
3148
|
+
return described;
|
|
3149
|
+
}
|
|
3150
|
+
/**
|
|
3151
|
+
* Describes an edge for output.
|
|
3152
|
+
*
|
|
3153
|
+
* @param edge - Edge to describe.
|
|
3154
|
+
* @returns Plain object for output.
|
|
3155
|
+
*/
|
|
3156
|
+
function describeEdge(edge) {
|
|
3157
|
+
return {
|
|
3158
|
+
id: edge.id,
|
|
3159
|
+
source: edge.sourceNodeId,
|
|
3160
|
+
target: edge.targetNodeId,
|
|
3161
|
+
type: edge.type,
|
|
3162
|
+
label: edge.label,
|
|
3163
|
+
};
|
|
3164
|
+
}
|
|
3165
|
+
/**
|
|
3166
|
+
* Loads a mind map, reporting structural faults as data errors.
|
|
3167
|
+
*
|
|
3168
|
+
* @remarks
|
|
3169
|
+
* `deserialize()` already validates — it calls the same `validateMindData()`
|
|
3170
|
+
* internally — so validating here first would run the check twice. Measured at
|
|
3171
|
+
* 5000 nodes the duplicate pass costs about as much as the real one, roughly
|
|
3172
|
+
* 40% of the load time. The catch below is not defensive padding: it is the
|
|
3173
|
+
* only way to keep a single validation while still converting the error.
|
|
3174
|
+
*
|
|
3175
|
+
* Every read path goes through here so a structural fault surfaces as
|
|
3176
|
+
* `InvalidData` (exit 1) rather than escaping as a raw `JsMindError` and landing
|
|
3177
|
+
* in the generic runtime branch (exit 3).
|
|
3178
|
+
*
|
|
3179
|
+
* @param serializer - Serializer to use.
|
|
3180
|
+
* @param doc - Parsed document.
|
|
3181
|
+
* @param file - Path, for the error message.
|
|
3182
|
+
* @returns The loaded mind map.
|
|
3183
|
+
* @throws {@link CliError} With `InvalidData` when the document is invalid.
|
|
3184
|
+
*/
|
|
3185
|
+
function loadMindOrThrow(serializer, doc, file) {
|
|
3186
|
+
try {
|
|
3187
|
+
return serializer.deserialize(doc);
|
|
3188
|
+
}
|
|
3189
|
+
catch (err) {
|
|
3190
|
+
if (err instanceof JsMindError) {
|
|
3191
|
+
const issues = err.data.errors;
|
|
3192
|
+
throw dataError(`${file} does not validate:\n${formatIssues(issues ?? [])}`);
|
|
3193
|
+
}
|
|
3194
|
+
throw err;
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
|
|
3198
|
+
/**
|
|
3199
|
+
* `jsmind mind *` — structure and edge commands.
|
|
3200
|
+
*
|
|
3201
|
+
* @remarks
|
|
3202
|
+
* Each command is a thin wrapper over a `JmMind` method. Locators are ids only:
|
|
3203
|
+
* pointing at a node by path or by text is deliberately not offered, because
|
|
3204
|
+
* both are ambiguous in a document the agent has not read.
|
|
3205
|
+
*
|
|
3206
|
+
* @packageDocumentation
|
|
3207
|
+
*/
|
|
3208
|
+
/** Subcommands this group understands. */
|
|
3209
|
+
const SUBCOMMANDS$1 = [
|
|
3210
|
+
'find',
|
|
3211
|
+
'add-child',
|
|
3212
|
+
'add-node',
|
|
3213
|
+
'move',
|
|
3214
|
+
'remove-node',
|
|
3215
|
+
'add-edge',
|
|
3216
|
+
'remove-edge',
|
|
3217
|
+
'list-edges',
|
|
3218
|
+
];
|
|
3219
|
+
/**
|
|
3220
|
+
* Runs a `mind` subcommand.
|
|
3221
|
+
*
|
|
3222
|
+
* @param file - Mind map file.
|
|
3223
|
+
* @param subcommand - Which subcommand.
|
|
3224
|
+
* @param values - Parsed options.
|
|
3225
|
+
* @param options - Dry-run / backup / output settings.
|
|
3226
|
+
* @returns Exit code.
|
|
3227
|
+
*/
|
|
3228
|
+
function runMind(file, subcommand, values, options) {
|
|
3229
|
+
if (!SUBCOMMANDS$1.includes(subcommand)) {
|
|
3230
|
+
throw usageError(`Unknown mind subcommand: ${subcommand}\nKnown: ${SUBCOMMANDS$1.join(', ')}`);
|
|
3231
|
+
}
|
|
3232
|
+
const asJson = values.json === true;
|
|
3233
|
+
// Read-only subcommands do not need the mutation pipeline.
|
|
3234
|
+
if (subcommand === 'find') {
|
|
3235
|
+
const nodeId = requireOption(values, 'node-id');
|
|
3236
|
+
const doc = readJsonFile(file);
|
|
3237
|
+
const mind = loadMindOrThrow(new JmMindJsonSerializer(), doc, file);
|
|
3238
|
+
const node = mind.findNodeById(nodeId);
|
|
3239
|
+
if (node === null) {
|
|
3240
|
+
throw dataError(`No node with id "${nodeId}" in ${file}`);
|
|
3241
|
+
}
|
|
3242
|
+
process.stdout.write(`${JSON.stringify(describeNode(node), null, 2)}\n`);
|
|
3243
|
+
return CliExit.Ok;
|
|
3244
|
+
}
|
|
3245
|
+
if (subcommand === 'list-edges') {
|
|
3246
|
+
const nodeId = requireOption(values, 'node-id');
|
|
3247
|
+
const doc = readJsonFile(file);
|
|
3248
|
+
const mind = loadMindOrThrow(new JmMindJsonSerializer(), doc, file);
|
|
3249
|
+
if (mind.findNodeById(nodeId) === null) {
|
|
3250
|
+
throw dataError(`No node with id "${nodeId}" in ${file}`);
|
|
3251
|
+
}
|
|
3252
|
+
const edges = mind.getEdges(nodeId);
|
|
3253
|
+
process.stdout.write(`${JSON.stringify(edges.map(describeEdge), null, 2)}\n`);
|
|
3254
|
+
return CliExit.Ok;
|
|
3255
|
+
}
|
|
3256
|
+
switch (subcommand) {
|
|
3257
|
+
case 'add-child': {
|
|
3258
|
+
const parentId = requireOption(values, 'parent-id');
|
|
3259
|
+
const text = requireOption(values, 'text');
|
|
3260
|
+
const created = runMutation(file, options, (mind) => {
|
|
3261
|
+
const node = mind.addChildNode(text, parentId);
|
|
3262
|
+
return node.id;
|
|
3263
|
+
});
|
|
3264
|
+
report(asJson, `added ${created} under ${parentId}`, { id: created });
|
|
3265
|
+
return CliExit.Ok;
|
|
3266
|
+
}
|
|
3267
|
+
case 'add-node': {
|
|
3268
|
+
const parentId = requireOption(values, 'parent-id');
|
|
3269
|
+
const text = requireOption(values, 'text');
|
|
3270
|
+
const position = optionalIntOption(values, 'position');
|
|
3271
|
+
const sideRaw = optionalOption(values, 'side');
|
|
3272
|
+
const created = runMutation(file, options, (mind) => {
|
|
3273
|
+
const dest = {
|
|
3274
|
+
parentId,
|
|
3275
|
+
};
|
|
3276
|
+
if (position !== undefined) {
|
|
3277
|
+
dest.position = position;
|
|
3278
|
+
}
|
|
3279
|
+
if (sideRaw !== undefined) {
|
|
3280
|
+
dest.side = parseSide(sideRaw);
|
|
3281
|
+
}
|
|
3282
|
+
const node = mind.addNode(JmNodeContent.createText(text), dest);
|
|
3283
|
+
return node.id;
|
|
3284
|
+
});
|
|
3285
|
+
report(asJson, `added ${created} under ${parentId}`, { id: created });
|
|
3286
|
+
return CliExit.Ok;
|
|
3287
|
+
}
|
|
3288
|
+
case 'move': {
|
|
3289
|
+
const nodeId = requireOption(values, 'node-id');
|
|
3290
|
+
const parentId = requireOption(values, 'parent-id');
|
|
3291
|
+
const position = optionalIntOption(values, 'position');
|
|
3292
|
+
runMutation(file, options, (mind) => {
|
|
3293
|
+
const dest = { parentId };
|
|
3294
|
+
if (position !== undefined) {
|
|
3295
|
+
dest.position = position;
|
|
3296
|
+
}
|
|
3297
|
+
mind.moveNode(nodeId, dest);
|
|
3298
|
+
return nodeId;
|
|
3299
|
+
});
|
|
3300
|
+
report(asJson, `moved ${nodeId} under ${parentId}`, { id: nodeId, parent: parentId });
|
|
3301
|
+
return CliExit.Ok;
|
|
3302
|
+
}
|
|
3303
|
+
case 'remove-node': {
|
|
3304
|
+
const nodeId = requireOption(values, 'node-id');
|
|
3305
|
+
runMutation(file, options, (mind) => {
|
|
3306
|
+
mind.removeNode(nodeId);
|
|
3307
|
+
return nodeId;
|
|
3308
|
+
});
|
|
3309
|
+
report(asJson, `removed ${nodeId}`, { id: nodeId });
|
|
3310
|
+
return CliExit.Ok;
|
|
3311
|
+
}
|
|
3312
|
+
case 'add-edge': {
|
|
3313
|
+
const sourceId = requireOption(values, 'source-id');
|
|
3314
|
+
const targetId = requireOption(values, 'target-id');
|
|
3315
|
+
const typeRaw = optionalOption(values, 'type') ?? JmEdgeType.Link;
|
|
3316
|
+
const label = optionalOption(values, 'label') ?? null;
|
|
3317
|
+
const created = runMutation(file, options, (mind) => {
|
|
3318
|
+
const edge = mind.addEdge(sourceId, targetId, typeRaw, label === null ? undefined : { label });
|
|
3319
|
+
return edge.id;
|
|
3320
|
+
});
|
|
3321
|
+
report(asJson, `added edge ${created}`, { id: created });
|
|
3322
|
+
return CliExit.Ok;
|
|
3323
|
+
}
|
|
3324
|
+
case 'remove-edge': {
|
|
3325
|
+
const edgeId = requireOption(values, 'edge-id');
|
|
3326
|
+
runMutation(file, options, (mind) => {
|
|
3327
|
+
if (!mind.removeEdge(edgeId)) {
|
|
3328
|
+
throw dataError(`No edge with id "${edgeId}" in ${file}`);
|
|
3329
|
+
}
|
|
3330
|
+
return edgeId;
|
|
3331
|
+
});
|
|
3332
|
+
report(asJson, `removed edge ${edgeId}`, { id: edgeId });
|
|
3333
|
+
return CliExit.Ok;
|
|
3334
|
+
}
|
|
3335
|
+
default:
|
|
3336
|
+
throw usageError(`Unhandled mind subcommand: ${subcommand}`);
|
|
3337
|
+
}
|
|
3338
|
+
}
|
|
3339
|
+
/**
|
|
3340
|
+
* Describes the `mind` command group for `--help`.
|
|
3341
|
+
*/
|
|
3342
|
+
const mindHelp = `jsmind mind <subcommand> <file> [options]
|
|
3343
|
+
|
|
3344
|
+
Structure and edges (mirrors JmMind methods). Locators are ids only.
|
|
3345
|
+
|
|
3346
|
+
find --node-id <id> Show one node
|
|
3347
|
+
list-edges --node-id <id> Edges touching a node
|
|
3348
|
+
add-child --parent-id <id> --text <text> Add a leaf (JmMind.addChildNode)
|
|
3349
|
+
add-node --parent-id <id> --text <text> Add with placement (JmMind.addNode)
|
|
3350
|
+
[--position <n>] [--side left|center|right]
|
|
3351
|
+
move --node-id <id> --parent-id <id> Reparent (JmMind.moveNode)
|
|
3352
|
+
[--position <n>]
|
|
3353
|
+
remove-node --node-id <id> Remove the node, its whole
|
|
3354
|
+
subtree, and every edge touching any of them
|
|
3355
|
+
add-edge --source-id <id> --target-id <id> Add a relation (JmMind.addEdge)
|
|
3356
|
+
[--type link] [--label <text>]
|
|
3357
|
+
remove-edge --edge-id <id> Remove a relation
|
|
3358
|
+
|
|
3359
|
+
Every mutating subcommand validates the result and rolls back on failure.`;
|
|
3360
|
+
|
|
3361
|
+
/**
|
|
3362
|
+
* Reading, writing and deleting a nested field by path.
|
|
3363
|
+
*
|
|
3364
|
+
* @remarks
|
|
3365
|
+
* A command that lets a caller set one field of a nested object needs the same
|
|
3366
|
+
* three operations whatever the object is: set a value somewhere down a path,
|
|
3367
|
+
* remove one, and report what is there. Keeping those here rather than beside
|
|
3368
|
+
* one command means the next command that reaches into a nested field does not
|
|
3369
|
+
* write them again - and does not have to know, as this module does not, which
|
|
3370
|
+
* fields exist.
|
|
3371
|
+
*
|
|
3372
|
+
* Paths are plain string arrays. `['incoming', 'color']` is `style.incoming.color`.
|
|
3373
|
+
* Nothing here assumes a depth or a name.
|
|
3374
|
+
*
|
|
3375
|
+
* @packageDocumentation
|
|
3376
|
+
*/
|
|
3377
|
+
/**
|
|
3378
|
+
* Turns a command-line flag name into a path.
|
|
3379
|
+
*
|
|
3380
|
+
* @param flag - Flag name without leading dashes, e.g. `incoming.color` or
|
|
3381
|
+
* `font-size`.
|
|
3382
|
+
* @returns The path, e.g. `['incoming', 'color']` or `['fontSize']`.
|
|
3383
|
+
* @remarks
|
|
3384
|
+
* Dots mark a level, dashes join the words of one level. That split means the
|
|
3385
|
+
* flag name is the only place a field's location is written down: the path is
|
|
3386
|
+
* derived, so the two cannot drift apart.
|
|
3387
|
+
*/
|
|
3388
|
+
function flagToPath(flag) {
|
|
3389
|
+
return flag.split('.').map(segment => segment.replace(/-([a-z])/g, (_, c) => c.toUpperCase()));
|
|
3390
|
+
}
|
|
3391
|
+
/**
|
|
3392
|
+
* Writes a value at a path, creating intermediate objects.
|
|
3393
|
+
*
|
|
3394
|
+
* @param target - Object to write into, mutated in place.
|
|
3395
|
+
* @param path - Route into it.
|
|
3396
|
+
* @param value - Value to store.
|
|
3397
|
+
* @remarks
|
|
3398
|
+
* Intermediate objects are created as plain objects. A path that runs through a
|
|
3399
|
+
* non-object would have to overwrite it, so it stops instead: that is a
|
|
3400
|
+
* contradiction in the caller's data, not something to paper over.
|
|
3401
|
+
*/
|
|
3402
|
+
function setAtPath(target, path, value) {
|
|
3403
|
+
if (path.length === 0) {
|
|
3404
|
+
throw new Error('setAtPath needs a non-empty path');
|
|
3405
|
+
}
|
|
3406
|
+
let current = target;
|
|
3407
|
+
for (const key of path.slice(0, -1)) {
|
|
3408
|
+
const next = current[key];
|
|
3409
|
+
if (next === undefined) {
|
|
3410
|
+
const created = {};
|
|
3411
|
+
current[key] = created;
|
|
3412
|
+
current = created;
|
|
3413
|
+
continue;
|
|
3414
|
+
}
|
|
3415
|
+
if (next === null || typeof next !== 'object') {
|
|
3416
|
+
throw new Error(`Cannot descend into "${key}": it holds a ${typeof next}, not an object`);
|
|
3417
|
+
}
|
|
3418
|
+
current = next;
|
|
3419
|
+
}
|
|
3420
|
+
current[path[path.length - 1]] = value;
|
|
3421
|
+
}
|
|
3422
|
+
/**
|
|
3423
|
+
* Removes the value at a path.
|
|
3424
|
+
*
|
|
3425
|
+
* @param target - Object to modify, mutated in place.
|
|
3426
|
+
* @param path - Route into it.
|
|
3427
|
+
* @returns Whether anything was removed.
|
|
3428
|
+
* @remarks
|
|
3429
|
+
* Intermediate objects left empty by the removal are dropped as well. Without
|
|
3430
|
+
* that, clearing the last field of a nested block leaves `{ incoming: {} }`
|
|
3431
|
+
* behind, which means the same as absent but does not serialise to nothing.
|
|
3432
|
+
*/
|
|
3433
|
+
function deleteAtPath(target, path) {
|
|
3434
|
+
if (path.length === 0) {
|
|
3435
|
+
return false;
|
|
3436
|
+
}
|
|
3437
|
+
const chain = [target];
|
|
3438
|
+
let current = target;
|
|
3439
|
+
for (const key of path.slice(0, -1)) {
|
|
3440
|
+
if (current === null || typeof current !== 'object') {
|
|
3441
|
+
return false;
|
|
3442
|
+
}
|
|
3443
|
+
current = current[key];
|
|
3444
|
+
if (current === null || typeof current !== 'object') {
|
|
3445
|
+
return false;
|
|
3446
|
+
}
|
|
3447
|
+
chain.push(current);
|
|
3448
|
+
}
|
|
3449
|
+
const leaf = path[path.length - 1];
|
|
3450
|
+
const holder = chain[chain.length - 1];
|
|
3451
|
+
if (!(leaf in holder)) {
|
|
3452
|
+
return false;
|
|
3453
|
+
}
|
|
3454
|
+
delete holder[leaf];
|
|
3455
|
+
if (path.length === 1) {
|
|
3456
|
+
return true;
|
|
3457
|
+
}
|
|
3458
|
+
// Walk back up dropping containers this removal emptied.
|
|
3459
|
+
for (let i = chain.length - 1; i > 0; i -= 1) {
|
|
3460
|
+
if (Object.keys(chain[i]).length > 0) {
|
|
3461
|
+
break;
|
|
3462
|
+
}
|
|
3463
|
+
delete chain[i - 1][path[i - 1]];
|
|
3464
|
+
}
|
|
3465
|
+
return true;
|
|
3466
|
+
}
|
|
3467
|
+
|
|
3468
|
+
/**
|
|
3469
|
+
* `jsmind node *` — node attribute commands.
|
|
3470
|
+
*
|
|
3471
|
+
* @remarks
|
|
3472
|
+
* These map to `JmNode`'s writable fields (`content` / `folded` / `side` /
|
|
3473
|
+
* `style`), not to `JmMind` methods. That split is not cosmetic: `id`,
|
|
3474
|
+
* `parent` and `children` are on the model's readonly list, so moving a node or
|
|
3475
|
+
* changing its parent goes through `mind` instead. Everything here is a plain
|
|
3476
|
+
* field assignment.
|
|
3477
|
+
*
|
|
3478
|
+
* @packageDocumentation
|
|
3479
|
+
*/
|
|
3480
|
+
/** Subcommands this group understands. */
|
|
3481
|
+
const SUBCOMMANDS = ['set-text', 'set-folded', 'set-side', 'set-style'];
|
|
3482
|
+
/**
|
|
3483
|
+
* Parses a boolean flag value written as a word.
|
|
3484
|
+
*
|
|
3485
|
+
* @param raw - `true` / `false` as given on the command line.
|
|
3486
|
+
* @returns The boolean.
|
|
3487
|
+
* @throws {@link CliError} With `Usage` for anything else.
|
|
3488
|
+
*/
|
|
3489
|
+
function parseBoolean(raw) {
|
|
3490
|
+
if (raw === 'true') {
|
|
3491
|
+
return true;
|
|
3492
|
+
}
|
|
3493
|
+
if (raw === 'false') {
|
|
3494
|
+
return false;
|
|
3495
|
+
}
|
|
3496
|
+
throw usageError(`Expected true or false, got "${raw}"`);
|
|
3497
|
+
}
|
|
3498
|
+
/**
|
|
3499
|
+
* Accepted values, read from the model's own enums.
|
|
3500
|
+
*
|
|
3501
|
+
* @remarks
|
|
3502
|
+
* Not restated here. A hand-written copy of these lists drifts: the first
|
|
3503
|
+
* version of this file listed six tones while `JmTone` had seven, so `--tone
|
|
3504
|
+
* accent` was rejected as a bad value when it was perfectly legal. Nothing
|
|
3505
|
+
* failed loudly - the missing entry only showed up when someone used it.
|
|
3506
|
+
*/
|
|
3507
|
+
const TONE_WORDS = Object.values(JmTone);
|
|
3508
|
+
const FONT_WEIGHT_WORDS = Object.values(JmFontWeight);
|
|
3509
|
+
const LINE_PATTERN_WORDS = Object.values(JmLinePattern);
|
|
3510
|
+
const LINE_CURVE_WORDS = Object.values(JmLineCurve);
|
|
3511
|
+
/** Every style field the command accepts. */
|
|
3512
|
+
const STYLE_FIELDS = [
|
|
3513
|
+
{ flag: 'tone', parse: raw => enumOption(raw, JmTone.Default, TONE_WORDS, 'tone') },
|
|
3514
|
+
{ flag: 'background', parse: raw => String(raw) },
|
|
3515
|
+
{ flag: 'color', parse: raw => String(raw) },
|
|
3516
|
+
{ flag: 'border-color', parse: raw => String(raw) },
|
|
3517
|
+
{ flag: 'border-width', parse: raw => numberOption(raw, 1, 'border-width') },
|
|
3518
|
+
{
|
|
3519
|
+
flag: 'border-style',
|
|
3520
|
+
parse: raw => enumOption(raw, JmLinePattern.Solid, LINE_PATTERN_WORDS, 'border-style'),
|
|
3521
|
+
},
|
|
3522
|
+
{ flag: 'font-size', parse: raw => numberOption(raw, 1, 'font-size') },
|
|
3523
|
+
{
|
|
3524
|
+
flag: 'font-weight',
|
|
3525
|
+
parse: raw => enumOption(raw, JmFontWeight.Normal, FONT_WEIGHT_WORDS, 'font-weight'),
|
|
3526
|
+
},
|
|
3527
|
+
{ flag: 'incoming.color', parse: raw => String(raw) },
|
|
3528
|
+
{ flag: 'incoming.width', parse: raw => numberOption(raw, 1, 'incoming-width') },
|
|
3529
|
+
{
|
|
3530
|
+
flag: 'incoming.pattern',
|
|
3531
|
+
parse: raw => enumOption(raw, JmLinePattern.Solid, LINE_PATTERN_WORDS, 'incoming.pattern'),
|
|
3532
|
+
},
|
|
3533
|
+
{
|
|
3534
|
+
flag: 'incoming.curve',
|
|
3535
|
+
parse: raw => enumOption(raw, JmLineCurve.Bezier, LINE_CURVE_WORDS, 'incoming.curve'),
|
|
3536
|
+
},
|
|
3537
|
+
];
|
|
3538
|
+
/**
|
|
3539
|
+
* Normalises a field name given to `--clear`.
|
|
3540
|
+
*
|
|
3541
|
+
* @param name - Name as typed: `incoming.color`, `font-size` or `fontSize`.
|
|
3542
|
+
* @returns The flag spelling this module compares against.
|
|
3543
|
+
* @remarks
|
|
3544
|
+
* Both spellings are natural at different moments - reading the file shows
|
|
3545
|
+
* `fontSize`, typing the command shows `--font-size` - so both are accepted
|
|
3546
|
+
* rather than making the user remember which one `--clear` wants.
|
|
3547
|
+
*/
|
|
3548
|
+
function normalizeClearName(name) {
|
|
3549
|
+
return name
|
|
3550
|
+
.trim()
|
|
3551
|
+
.split('.')
|
|
3552
|
+
.map(segment => segment
|
|
3553
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
3554
|
+
.toLowerCase())
|
|
3555
|
+
.join('.');
|
|
3556
|
+
}
|
|
3557
|
+
/**
|
|
3558
|
+
* Validates the style flags and turns them into a patch.
|
|
3559
|
+
*
|
|
3560
|
+
* @param values - Parsed options.
|
|
3561
|
+
* @returns The patch to apply.
|
|
3562
|
+
* @throws {@link CliError} With `Usage` when the flags do not make sense.
|
|
3563
|
+
* @remarks
|
|
3564
|
+
* Touches no file. Every check here is about the arguments alone.
|
|
3565
|
+
*/
|
|
3566
|
+
function parseStyleArgs(values) {
|
|
3567
|
+
const set = [];
|
|
3568
|
+
for (const field of STYLE_FIELDS) {
|
|
3569
|
+
const raw = values[field.flag];
|
|
3570
|
+
if (raw === undefined) {
|
|
3571
|
+
continue;
|
|
3572
|
+
}
|
|
3573
|
+
set.push({ flag: field.flag, value: field.parse(raw) });
|
|
3574
|
+
}
|
|
3575
|
+
const clear = [];
|
|
3576
|
+
const clearRaw = values.clear;
|
|
3577
|
+
if (clearRaw !== undefined) {
|
|
3578
|
+
if (typeof clearRaw !== 'string') {
|
|
3579
|
+
throw usageError('--clear expects a comma-separated list of fields');
|
|
3580
|
+
}
|
|
3581
|
+
for (const name of clearRaw
|
|
3582
|
+
.split(',')
|
|
3583
|
+
.map(s => s.trim())
|
|
3584
|
+
.filter(s => s !== '')) {
|
|
3585
|
+
const normalized = normalizeClearName(name);
|
|
3586
|
+
if (!STYLE_FIELDS.some(f => f.flag === normalized)) {
|
|
3587
|
+
throw usageError(`--clear does not know "${name}". Known fields: ${STYLE_FIELDS.map(f => f.flag).join(', ')}`);
|
|
3588
|
+
}
|
|
3589
|
+
clear.push(normalized);
|
|
3590
|
+
}
|
|
3591
|
+
}
|
|
3592
|
+
// `--reset` is exhaustive: it says the node should carry no overrides at
|
|
3593
|
+
// all, so anything combined with it is either redundant or a contradiction.
|
|
3594
|
+
if (values.reset === true) {
|
|
3595
|
+
const conflicting = [...set.map(s => s.flag), ...(clear.length > 0 ? ['clear'] : [])];
|
|
3596
|
+
if (conflicting.length > 0) {
|
|
3597
|
+
throw usageError(`--reset clears every style field, so it cannot be combined with ${conflicting
|
|
3598
|
+
.map(f => `--${f}`)
|
|
3599
|
+
.join(', ')}`);
|
|
3600
|
+
}
|
|
3601
|
+
return { reset: true, clear: [], set: [] };
|
|
3602
|
+
}
|
|
3603
|
+
if (set.length === 0 && clear.length === 0) {
|
|
3604
|
+
throw usageError(`set-style needs at least one field, --clear or --reset.\nFields: ${STYLE_FIELDS.map(f => `--${f.flag}`).join(', ')}`);
|
|
3605
|
+
}
|
|
3606
|
+
return { reset: false, clear, set };
|
|
3607
|
+
}
|
|
3608
|
+
/**
|
|
3609
|
+
* Applies a patch to a node's current style.
|
|
3610
|
+
*
|
|
3611
|
+
* @param current - The node's current style, if any.
|
|
3612
|
+
* @param patch - Validated instruction.
|
|
3613
|
+
* @returns The new style, or `undefined` when nothing should be stored.
|
|
3614
|
+
* @remarks
|
|
3615
|
+
* A style block records only what differs from the theme, so this never merges
|
|
3616
|
+
* against theme values - only against the node's own overrides. An empty result
|
|
3617
|
+
* becomes `undefined` rather than `{}`: both resolve identically, but only the
|
|
3618
|
+
* former serialises to nothing.
|
|
3619
|
+
*/
|
|
3620
|
+
function applyStyle(current, patch) {
|
|
3621
|
+
if (patch.reset) {
|
|
3622
|
+
return undefined;
|
|
3623
|
+
}
|
|
3624
|
+
const style = current === undefined ? {} : structuredClone(current);
|
|
3625
|
+
for (const flag of patch.clear) {
|
|
3626
|
+
deleteAtPath(style, flagToPath(flag));
|
|
3627
|
+
}
|
|
3628
|
+
for (const { flag, value } of patch.set) {
|
|
3629
|
+
setAtPath(style, flagToPath(flag), value);
|
|
3630
|
+
}
|
|
3631
|
+
return Object.keys(style).length === 0 ? undefined : style;
|
|
3632
|
+
}
|
|
3633
|
+
/**
|
|
3634
|
+
* Runs a `node` subcommand.
|
|
3635
|
+
*
|
|
3636
|
+
* @param file - Mind map file.
|
|
3637
|
+
* @param subcommand - Which subcommand.
|
|
3638
|
+
* @param values - Parsed options.
|
|
3639
|
+
* @param options - Dry-run / backup / output settings.
|
|
3640
|
+
* @returns Exit code.
|
|
3641
|
+
*/
|
|
3642
|
+
function runNode(file, subcommand, values, options) {
|
|
3643
|
+
if (!SUBCOMMANDS.includes(subcommand)) {
|
|
3644
|
+
throw usageError(`Unknown node subcommand: ${subcommand}\nKnown: ${SUBCOMMANDS.join(', ')}`);
|
|
3645
|
+
}
|
|
3646
|
+
const nodeId = requireOption(values, 'node-id');
|
|
3647
|
+
const asJson = values.json === true;
|
|
3648
|
+
switch (subcommand) {
|
|
3649
|
+
case 'set-text': {
|
|
3650
|
+
const text = requireOption(values, 'text');
|
|
3651
|
+
runMutation(file, options, (mind) => {
|
|
3652
|
+
const node = mind.findNodeById(nodeId);
|
|
3653
|
+
if (node === null) {
|
|
3654
|
+
throw dataError(`No node with id "${nodeId}" in ${file}`);
|
|
3655
|
+
}
|
|
3656
|
+
node.content = new JmNodeContent(node.content.type, text);
|
|
3657
|
+
return nodeId;
|
|
3658
|
+
});
|
|
3659
|
+
report(asJson, `set text of ${nodeId}`, { id: nodeId, text });
|
|
3660
|
+
return CliExit.Ok;
|
|
3661
|
+
}
|
|
3662
|
+
case 'set-folded': {
|
|
3663
|
+
const raw = requireOption(values, 'folded');
|
|
3664
|
+
const folded = parseBoolean(raw);
|
|
3665
|
+
runMutation(file, options, (mind) => {
|
|
3666
|
+
const node = mind.findNodeById(nodeId);
|
|
3667
|
+
if (node === null) {
|
|
3668
|
+
throw dataError(`No node with id "${nodeId}" in ${file}`);
|
|
3669
|
+
}
|
|
3670
|
+
node.folded = folded;
|
|
3671
|
+
return nodeId;
|
|
3672
|
+
});
|
|
3673
|
+
report(asJson, `set folded of ${nodeId} to ${folded}`, { id: nodeId, folded });
|
|
3674
|
+
return CliExit.Ok;
|
|
3675
|
+
}
|
|
3676
|
+
case 'set-side': {
|
|
3677
|
+
const raw = requireOption(values, 'side');
|
|
3678
|
+
const side = parseSide(raw);
|
|
3679
|
+
runMutation(file, options, (mind) => {
|
|
3680
|
+
const node = mind.findNodeById(nodeId);
|
|
3681
|
+
if (node === null) {
|
|
3682
|
+
throw dataError(`No node with id "${nodeId}" in ${file}`);
|
|
3683
|
+
}
|
|
3684
|
+
node.side = side;
|
|
3685
|
+
return nodeId;
|
|
3686
|
+
});
|
|
3687
|
+
report(asJson, `set side of ${nodeId} to ${raw}`, { id: nodeId, side: raw });
|
|
3688
|
+
return CliExit.Ok;
|
|
3689
|
+
}
|
|
3690
|
+
case 'set-style': {
|
|
3691
|
+
// Validate before touching the file: a bad flag should not depend on
|
|
3692
|
+
// whether the document happens to load.
|
|
3693
|
+
const patch = parseStyleArgs(values);
|
|
3694
|
+
// Report what the mutation produced, not the arguments: `--clear` and
|
|
3695
|
+
// `--reset` remove fields, so the result is not derivable from the
|
|
3696
|
+
// flags. Reading the file again to find out would also be wrong under
|
|
3697
|
+
// --dry-run, where nothing was written and the reread returns the old
|
|
3698
|
+
// value.
|
|
3699
|
+
const applied = runMutation(file, options, (mind) => {
|
|
3700
|
+
const node = mind.findNodeById(nodeId);
|
|
3701
|
+
if (node === null) {
|
|
3702
|
+
throw dataError(`No node with id "${nodeId}" in ${file}`);
|
|
3703
|
+
}
|
|
3704
|
+
node.style = applyStyle(node.style, patch);
|
|
3705
|
+
return describeStyle(node.style);
|
|
3706
|
+
});
|
|
3707
|
+
report(asJson, applied === null
|
|
3708
|
+
? `cleared style of ${nodeId}`
|
|
3709
|
+
: `set style of ${nodeId}: ${JSON.stringify(applied)}`, { id: nodeId, style: applied });
|
|
3710
|
+
return CliExit.Ok;
|
|
3711
|
+
}
|
|
3712
|
+
default:
|
|
3713
|
+
throw usageError(`Unhandled node subcommand: ${subcommand}`);
|
|
3714
|
+
}
|
|
3715
|
+
}
|
|
3716
|
+
/**
|
|
3717
|
+
* Describes the `node` command group for `--help`.
|
|
3718
|
+
*/
|
|
3719
|
+
const nodeHelp = `jsmind node <subcommand> <file> --node-id <id> [options]
|
|
3720
|
+
|
|
3721
|
+
Node attributes (JmNode writable fields). Structure goes through \`jsmind mind\`.
|
|
3722
|
+
|
|
3723
|
+
set-text --node-id <id> --text <text> Change the label
|
|
3724
|
+
set-folded --node-id <id> --folded true|false Collapse or expand
|
|
3725
|
+
set-side --node-id <id> --side left|center|right
|
|
3726
|
+
set-style --node-id <id> [style fields] Override the theme for one node
|
|
3727
|
+
|
|
3728
|
+
set-style fields (any combination, applied in one write). A dot marks a level, so
|
|
3729
|
+
--incoming.color addresses \`style.incoming.color\`. Accepted values are read from
|
|
3730
|
+
the model's own enums, so this list cannot fall behind them:
|
|
3731
|
+
|
|
3732
|
+
--tone <value> ${TONE_WORDS.join(' | ')}
|
|
3733
|
+
--background <color>
|
|
3734
|
+
--color <color>
|
|
3735
|
+
--border-color <color>
|
|
3736
|
+
--border-width <number> positive
|
|
3737
|
+
--border-style <value> ${LINE_PATTERN_WORDS.join(' | ')}
|
|
3738
|
+
--font-size <number> positive
|
|
3739
|
+
--font-weight <value> ${FONT_WEIGHT_WORDS.join(' | ')}
|
|
3740
|
+
--incoming.color <color>
|
|
3741
|
+
--incoming.width <number> positive
|
|
3742
|
+
--incoming.pattern <value> ${LINE_PATTERN_WORDS.join(' | ')}
|
|
3743
|
+
--incoming.curve <value> ${LINE_CURVE_WORDS.join(' | ')}
|
|
3744
|
+
|
|
3745
|
+
Clearing, when the theme's value should come back:
|
|
3746
|
+
|
|
3747
|
+
--clear <fields> Comma-separated field names in the same spelling
|
|
3748
|
+
--reset Drop every override on this node
|
|
3749
|
+
|
|
3750
|
+
A style block records only what differs from the theme, so removing a key is what
|
|
3751
|
+
restores the theme's value. There is no \`unset\` sentinel - an absent key means an
|
|
3752
|
+
absent override. \`--reset\` cannot be combined with fields or \`--clear\`.
|
|
3753
|
+
|
|
3754
|
+
Colours are not checked beyond being strings; the theme accepts any CSS colour.
|
|
3755
|
+
Tones, patterns and weights are checked here so a bad value names the flag you
|
|
3756
|
+
typed rather than a JSON path.
|
|
3757
|
+
|
|
3758
|
+
Why the split: id, parent and children are readonly on the model, so they are only
|
|
3759
|
+
reachable through JmMind methods (\`jsmind mind\`). These fields are plain assignments.
|
|
3760
|
+
|
|
3761
|
+
Every subcommand validates the result and rolls back on failure.`;
|
|
3762
|
+
|
|
3763
|
+
/**
|
|
3764
|
+
* `jsmind context` — the agent's discovery step.
|
|
3765
|
+
*
|
|
3766
|
+
* @remarks
|
|
3767
|
+
* This is the only command allowed to fuzzy-match, because it is what an agent
|
|
3768
|
+
* runs before it knows any ids. Everything downstream takes ids only.
|
|
3769
|
+
*
|
|
3770
|
+
* Two constraints shape the output: ids come first so they can be copied
|
|
3771
|
+
* straight into the next command, and node text is flattened to one line so a
|
|
3772
|
+
* multi-line label cannot break the tree's shape.
|
|
3773
|
+
*
|
|
3774
|
+
* @packageDocumentation
|
|
3775
|
+
*/
|
|
3776
|
+
/** Default number of levels shown below the root. */
|
|
3777
|
+
const DEFAULT_DEPTH = 2;
|
|
3778
|
+
/** Default truncation width for node text. */
|
|
3779
|
+
const DEFAULT_MAX_TEXT = 40;
|
|
3780
|
+
/**
|
|
3781
|
+
* Collapses a label to a single line.
|
|
3782
|
+
*
|
|
3783
|
+
* @param text - Raw node text.
|
|
3784
|
+
* @returns Text with every run of whitespace squeezed to one space.
|
|
3785
|
+
*/
|
|
3786
|
+
function flatten(text) {
|
|
3787
|
+
return text.replace(/\s+/g, ' ').trim();
|
|
3788
|
+
}
|
|
3789
|
+
/**
|
|
3790
|
+
* Truncates text to the configured width.
|
|
3791
|
+
*
|
|
3792
|
+
* @param text - Already flattened text.
|
|
3793
|
+
* @param maxText - Maximum characters.
|
|
3794
|
+
* @param fullText - When true, no truncation happens.
|
|
3795
|
+
* @returns The text, ending in an ellipsis when it was cut.
|
|
3796
|
+
*/
|
|
3797
|
+
function clip(text, maxText, fullText) {
|
|
3798
|
+
if (fullText || text.length <= maxText) {
|
|
3799
|
+
return text;
|
|
3800
|
+
}
|
|
3801
|
+
// -1 so the ellipsis is inside the budget rather than on top of it.
|
|
3802
|
+
return `${text.slice(0, Math.max(0, maxText - 1))}…`;
|
|
3803
|
+
}
|
|
3804
|
+
/**
|
|
3805
|
+
* Reads a node's label as a string.
|
|
3806
|
+
*
|
|
3807
|
+
* @param node - Node to read.
|
|
3808
|
+
* @returns The text, or an empty string for non-text content.
|
|
3809
|
+
*/
|
|
3810
|
+
function textOf(node) {
|
|
3811
|
+
const value = node.content.value;
|
|
3812
|
+
return typeof value === 'string' ? value : '';
|
|
3813
|
+
}
|
|
3814
|
+
/**
|
|
3815
|
+
* Walks the tree depth-first, collecting ids by depth.
|
|
3816
|
+
*
|
|
3817
|
+
* @param root - Where to start.
|
|
3818
|
+
* @param depth - Levels to descend (0 = root only).
|
|
3819
|
+
* @returns Entries in display order.
|
|
3820
|
+
*/
|
|
3821
|
+
function outline(root, depth) {
|
|
3822
|
+
const out = [];
|
|
3823
|
+
const walk = (node, level) => {
|
|
3824
|
+
if (level > depth) {
|
|
3825
|
+
return;
|
|
3826
|
+
}
|
|
3827
|
+
out.push({ node, level });
|
|
3828
|
+
for (const child of node.children) {
|
|
3829
|
+
walk(child, level + 1);
|
|
3830
|
+
}
|
|
3831
|
+
};
|
|
3832
|
+
walk(root, 0);
|
|
3833
|
+
return out;
|
|
3834
|
+
}
|
|
3835
|
+
/**
|
|
3836
|
+
* Finds nodes whose text contains the focus string, case-insensitively.
|
|
3837
|
+
*
|
|
3838
|
+
* @param nodes - Every node to consider.
|
|
3839
|
+
* @param focus - Needle.
|
|
3840
|
+
* @returns Matches in document order.
|
|
3841
|
+
*/
|
|
3842
|
+
function matchNodes(nodes, focus) {
|
|
3843
|
+
const needle = focus.toLowerCase();
|
|
3844
|
+
return nodes.filter(node => flatten(textOf(node)).toLowerCase()
|
|
3845
|
+
.includes(needle));
|
|
3846
|
+
}
|
|
3847
|
+
/**
|
|
3848
|
+
* Collects every node reachable from the root.
|
|
3849
|
+
*
|
|
3850
|
+
* @param root - Root node.
|
|
3851
|
+
* @returns All nodes in depth-first order.
|
|
3852
|
+
*/
|
|
3853
|
+
function allNodes(root) {
|
|
3854
|
+
const out = [];
|
|
3855
|
+
const walk = (node) => {
|
|
3856
|
+
out.push(node);
|
|
3857
|
+
for (const child of node.children) {
|
|
3858
|
+
walk(child);
|
|
3859
|
+
}
|
|
3860
|
+
};
|
|
3861
|
+
walk(root);
|
|
3862
|
+
return out;
|
|
3863
|
+
}
|
|
3864
|
+
/**
|
|
3865
|
+
* Ranks suggestions for a focus string that matched nothing.
|
|
3866
|
+
*
|
|
3867
|
+
* @remarks
|
|
3868
|
+
* Scored by how many characters of the needle appear in order in the label —
|
|
3869
|
+
* a cheap resemblance measure that needs no dictionary and still puts the
|
|
3870
|
+
* obviously-closest candidates first.
|
|
3871
|
+
*
|
|
3872
|
+
* @param nodes - Candidates.
|
|
3873
|
+
* @param focus - The needle that missed.
|
|
3874
|
+
* @returns Up to five nodes, closest first.
|
|
3875
|
+
*/
|
|
3876
|
+
function suggest(nodes, focus) {
|
|
3877
|
+
const needle = focus.toLowerCase();
|
|
3878
|
+
const scored = nodes
|
|
3879
|
+
.map(node => {
|
|
3880
|
+
const label = flatten(textOf(node)).toLowerCase();
|
|
3881
|
+
let cursor = 0;
|
|
3882
|
+
let hits = 0;
|
|
3883
|
+
for (const char of needle) {
|
|
3884
|
+
const at = label.indexOf(char, cursor);
|
|
3885
|
+
if (at >= 0) {
|
|
3886
|
+
hits += 1;
|
|
3887
|
+
cursor = at + 1;
|
|
3888
|
+
}
|
|
3889
|
+
}
|
|
3890
|
+
return { node, hits };
|
|
3891
|
+
})
|
|
3892
|
+
.filter(entry => entry.hits > 0)
|
|
3893
|
+
.sort((a, b) => b.hits - a.hits || a.node.id.localeCompare(b.node.id))
|
|
3894
|
+
.map(entry => entry.node);
|
|
3895
|
+
if (scored.length > 0) {
|
|
3896
|
+
return scored.slice(0, 5);
|
|
3897
|
+
}
|
|
3898
|
+
// Nothing resembles the needle at all. Returning an empty list would leave
|
|
3899
|
+
// the agent with no ids and no next move, so fall back to the top of the
|
|
3900
|
+
// tree: shallow nodes are the most likely starting points for a second
|
|
3901
|
+
// attempt, and they are always cheap to show.
|
|
3902
|
+
return nodes.slice(0, 8);
|
|
3903
|
+
}
|
|
3904
|
+
/**
|
|
3905
|
+
* Flattens a nested style block to dotted keys.
|
|
3906
|
+
*
|
|
3907
|
+
* @param style - Style object, possibly nested.
|
|
3908
|
+
* @param prefix - Key prefix accumulated so far.
|
|
3909
|
+
* @returns Stringified values keyed by dotted path.
|
|
3910
|
+
* @remarks
|
|
3911
|
+
* A dotted key is the flag that set it, so a value shown here can be changed or
|
|
3912
|
+
* cleared by writing that same spelling back.
|
|
3913
|
+
*/
|
|
3914
|
+
function flattenStyle(style, prefix = '') {
|
|
3915
|
+
const out = {};
|
|
3916
|
+
for (const [key, value] of Object.entries(style)) {
|
|
3917
|
+
const path = prefix === '' ? key : `${prefix}.${key}`;
|
|
3918
|
+
if (value !== null && typeof value === 'object') {
|
|
3919
|
+
Object.assign(out, flattenStyle(value, path));
|
|
3920
|
+
}
|
|
3921
|
+
else {
|
|
3922
|
+
out[path] = String(value);
|
|
3923
|
+
}
|
|
3924
|
+
}
|
|
3925
|
+
return out;
|
|
3926
|
+
}
|
|
3927
|
+
/**
|
|
3928
|
+
* Summarises a node's state for the text output — side (when it is meaningful),
|
|
3929
|
+
* folded, and any style overrides.
|
|
3930
|
+
*
|
|
3931
|
+
* @param node - Node to summarise.
|
|
3932
|
+
* @param level - Depth in the printed tree: 0 is the root, 1 is a direct child
|
|
3933
|
+
* of the root.
|
|
3934
|
+
* @returns A ` {side=left tone=danger}` suffix, or an empty string when the
|
|
3935
|
+
* node has nothing to report.
|
|
3936
|
+
* @remarks
|
|
3937
|
+
* `side` is only meaningful for the root and the root's direct children, so it
|
|
3938
|
+
* is shown only when `level` is 0 or 1. Deeper nodes inherit layout from their
|
|
3939
|
+
* ancestor on the root; printing `side` there would look like a fact the agent
|
|
3940
|
+
* should act on. `folded` appears only when the node is collapsed, and style
|
|
3941
|
+
* overrides appear when the node differs from the theme. After a parent is
|
|
3942
|
+
* moved to the other side, descendants are left alone: their stored `side` is
|
|
3943
|
+
* not rewritten, and it is not printed either.
|
|
3944
|
+
*/
|
|
3945
|
+
function stateSummary(node, level) {
|
|
3946
|
+
const parts = [];
|
|
3947
|
+
// side is only meaningful for the root and the root's direct children.
|
|
3948
|
+
if (level <= 1) {
|
|
3949
|
+
const sideLabel = formatSide(node.side);
|
|
3950
|
+
parts.push(`side=${sideLabel}`);
|
|
3951
|
+
}
|
|
3952
|
+
if (node.folded) {
|
|
3953
|
+
parts.push('folded');
|
|
3954
|
+
}
|
|
3955
|
+
const style = describeStyle(node.style);
|
|
3956
|
+
if (style !== null) {
|
|
3957
|
+
for (const [key, value] of Object.entries(flattenStyle(style))) {
|
|
3958
|
+
parts.push(`${key}=${value}`);
|
|
3959
|
+
}
|
|
3960
|
+
}
|
|
3961
|
+
if (parts.length === 0) {
|
|
3962
|
+
return '';
|
|
3963
|
+
}
|
|
3964
|
+
return ` {${parts.join(' ')}}`;
|
|
3965
|
+
}
|
|
3966
|
+
/**
|
|
3967
|
+
* Renders entries as aligned text.
|
|
3968
|
+
*
|
|
3969
|
+
* @param entries - Nodes with their depth.
|
|
3970
|
+
* @param options - Truncation settings.
|
|
3971
|
+
* @returns Lines ready to print.
|
|
3972
|
+
*/
|
|
3973
|
+
function renderTree(entries, options) {
|
|
3974
|
+
const width = Math.max(...entries.map(entry => entry.node.id.length), 2);
|
|
3975
|
+
return entries.map(({ node, level }) => {
|
|
3976
|
+
const id = node.id.padEnd(width);
|
|
3977
|
+
if (options.idsOnly) {
|
|
3978
|
+
return id.trimEnd();
|
|
3979
|
+
}
|
|
3980
|
+
const label = clip(flatten(textOf(node)), options.maxText, options.fullText);
|
|
3981
|
+
// Three spaces per level, after the id column.
|
|
3982
|
+
return `${id} ${' '.repeat(level)}${label}${stateSummary(node, level)}`;
|
|
3983
|
+
});
|
|
3984
|
+
}
|
|
3985
|
+
/**
|
|
3986
|
+
* Runs the context command.
|
|
3987
|
+
*
|
|
3988
|
+
* @param options - Parsed options.
|
|
3989
|
+
* @returns Exit code.
|
|
3990
|
+
*/
|
|
3991
|
+
function runContext(options) {
|
|
3992
|
+
const doc = readJsonFile(options.file);
|
|
3993
|
+
// Same loader as every other read path: a structural fault must surface as
|
|
3994
|
+
// InvalidData rather than escaping as a raw JsMindError and landing in the
|
|
3995
|
+
// generic exit-3 branch.
|
|
3996
|
+
const mind = loadMindOrThrow(new JmMindJsonSerializer(), doc, options.file);
|
|
3997
|
+
const root = mind.findNodeById(mind.root?.id ?? '');
|
|
3998
|
+
if (root === null) {
|
|
3999
|
+
throw dataError(`Cannot locate the root node in ${options.file}`);
|
|
4000
|
+
}
|
|
4001
|
+
const every = allNodes(root);
|
|
4002
|
+
// --focus: show matches and their surrounding structure.
|
|
4003
|
+
if (options.focus !== undefined && options.focus.length > 0) {
|
|
4004
|
+
const matches = matchNodes(every, options.focus);
|
|
4005
|
+
if (matches.length === 0) {
|
|
4006
|
+
const candidates = suggest(every, options.focus);
|
|
4007
|
+
if (options.asJson) {
|
|
4008
|
+
process.stdout.write(`${JSON.stringify({
|
|
4009
|
+
matched: false,
|
|
4010
|
+
focus: options.focus,
|
|
4011
|
+
candidates: candidates.map(node => ({
|
|
4012
|
+
id: node.id,
|
|
4013
|
+
text: clip(flatten(textOf(node)), options.maxText, options.fullText),
|
|
4014
|
+
})),
|
|
4015
|
+
}, null, 2)}\n`);
|
|
4016
|
+
}
|
|
4017
|
+
else {
|
|
4018
|
+
process.stderr.write(`No node matches "${options.focus}".`);
|
|
4019
|
+
if (candidates.length > 0) {
|
|
4020
|
+
process.stderr.write(' Candidates from the top of the tree:\n');
|
|
4021
|
+
for (const node of candidates) {
|
|
4022
|
+
const label = clip(flatten(textOf(node)), options.maxText, options.fullText);
|
|
4023
|
+
process.stderr.write(` ${node.id.padEnd(6)} ${label}\n`);
|
|
4024
|
+
}
|
|
4025
|
+
}
|
|
4026
|
+
else {
|
|
4027
|
+
process.stderr.write('\n');
|
|
4028
|
+
}
|
|
4029
|
+
}
|
|
4030
|
+
// A miss is not a data error: the file is fine, the search found
|
|
4031
|
+
// nothing. Usage stays 0 so an agent can read the candidates and
|
|
4032
|
+
// carry on rather than treating it as a failed run.
|
|
4033
|
+
return CliExit.Ok;
|
|
4034
|
+
}
|
|
4035
|
+
// Show each match plus its ancestors, so the agent sees where it sits.
|
|
4036
|
+
const shown = new Set();
|
|
4037
|
+
const entries = [];
|
|
4038
|
+
for (const match of matches) {
|
|
4039
|
+
const chain = [];
|
|
4040
|
+
let cursor = match;
|
|
4041
|
+
while (cursor !== null) {
|
|
4042
|
+
chain.unshift(cursor);
|
|
4043
|
+
cursor = cursor.parent;
|
|
4044
|
+
}
|
|
4045
|
+
chain.forEach((node, level) => {
|
|
4046
|
+
if (shown.has(node.id)) {
|
|
4047
|
+
return;
|
|
4048
|
+
}
|
|
4049
|
+
shown.add(node.id);
|
|
4050
|
+
entries.push({ node, level });
|
|
4051
|
+
});
|
|
4052
|
+
}
|
|
4053
|
+
emit(entries, options);
|
|
4054
|
+
return CliExit.Ok;
|
|
4055
|
+
}
|
|
4056
|
+
emit(outline(root, options.depth), options);
|
|
4057
|
+
return CliExit.Ok;
|
|
4058
|
+
}
|
|
4059
|
+
/**
|
|
4060
|
+
* Writes entries in the requested shape.
|
|
4061
|
+
*
|
|
4062
|
+
* @param entries - Nodes with depth.
|
|
4063
|
+
* @param options - Output settings.
|
|
4064
|
+
*/
|
|
4065
|
+
function emit(entries, options) {
|
|
4066
|
+
if (options.asJson) {
|
|
4067
|
+
const payload = entries.map(({ node, level }) => {
|
|
4068
|
+
const entry = {
|
|
4069
|
+
id: node.id,
|
|
4070
|
+
level,
|
|
4071
|
+
text: options.idsOnly
|
|
4072
|
+
? undefined
|
|
4073
|
+
: clip(flatten(textOf(node)), options.maxText, options.fullText),
|
|
4074
|
+
};
|
|
4075
|
+
// Same rule as the text output: side only for the root and its
|
|
4076
|
+
// direct children. Deeper nodes keep whatever side is stored; it
|
|
4077
|
+
// is just not printed, and it is not rewritten when a parent moves.
|
|
4078
|
+
if (level <= 1) {
|
|
4079
|
+
entry.side = formatSide(node.side);
|
|
4080
|
+
}
|
|
4081
|
+
if (node.folded) {
|
|
4082
|
+
entry.folded = true;
|
|
4083
|
+
}
|
|
4084
|
+
// Only when the node overrides something. A style block records the
|
|
4085
|
+
// difference from the theme, so a node that overrode nothing would
|
|
4086
|
+
// contribute the same absent entry every time - length for
|
|
4087
|
+
// information the theme already implies, on an output an agent reads
|
|
4088
|
+
// at every step.
|
|
4089
|
+
const style = describeStyle(node.style);
|
|
4090
|
+
if (style !== null) {
|
|
4091
|
+
entry.style = style;
|
|
4092
|
+
}
|
|
4093
|
+
return entry;
|
|
4094
|
+
});
|
|
4095
|
+
process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
|
|
4096
|
+
return;
|
|
4097
|
+
}
|
|
4098
|
+
for (const line of renderTree(entries, options)) {
|
|
4099
|
+
process.stdout.write(`${line}\n`);
|
|
4100
|
+
}
|
|
4101
|
+
}
|
|
4102
|
+
/**
|
|
4103
|
+
* Describes the context command for `--help`.
|
|
4104
|
+
*/
|
|
4105
|
+
const contextHelp = `jsmind context <file> [options]
|
|
4106
|
+
|
|
4107
|
+
Discovery step: shows the tree so an agent can find the ids it needs.
|
|
4108
|
+
|
|
4109
|
+
--focus <text> Fuzzy-match node text; shows matches with their ancestors
|
|
4110
|
+
--depth <n> Levels below the root to show (default ${DEFAULT_DEPTH})
|
|
4111
|
+
--max-text <n> Truncate labels at n characters (default ${DEFAULT_MAX_TEXT})
|
|
4112
|
+
--full-text Do not truncate
|
|
4113
|
+
--ids-only Print ids only
|
|
4114
|
+
--json Machine-readable output
|
|
4115
|
+
|
|
4116
|
+
Ids are printed in a left-aligned column so they can be copied into the next
|
|
4117
|
+
command. Multi-line labels are flattened, and truncation ends in an ellipsis.
|
|
4118
|
+
Each line may end with a {…} block. side is shown only for the root and the
|
|
4119
|
+
root's direct children. folded appears when the node is collapsed, and style
|
|
4120
|
+
overrides appear when the node differs from the theme.
|
|
4121
|
+
|
|
4122
|
+
When --focus matches nothing, the closest candidates are listed instead.`;
|
|
4123
|
+
|
|
4124
|
+
/**
|
|
4125
|
+
* `jsmind create` — start a new mind map file.
|
|
4126
|
+
*
|
|
4127
|
+
* @remarks
|
|
4128
|
+
* Every other command needs a mind map to exist already; this is the only one
|
|
4129
|
+
* that produces one from nothing. Without it the CLI can edit maps but not
|
|
4130
|
+
* begin one, which leaves the agent hand-writing the initial JSON — exactly
|
|
4131
|
+
* what the CLI exists to prevent.
|
|
4132
|
+
*
|
|
4133
|
+
* The document is built through `JmMind` and `serialize()` rather than assembled
|
|
4134
|
+
* as a literal, so a new file cannot drift away from what the serialiser emits
|
|
4135
|
+
* for every other map.
|
|
4136
|
+
*
|
|
4137
|
+
* @packageDocumentation
|
|
4138
|
+
*/
|
|
4139
|
+
/**
|
|
4140
|
+
* Runs the create command.
|
|
4141
|
+
*
|
|
4142
|
+
* @param options - Parsed options.
|
|
4143
|
+
* @returns Exit code.
|
|
4144
|
+
*/
|
|
4145
|
+
function runCreate(options) {
|
|
4146
|
+
// Refuse to clobber by default. The same principle as every mutating
|
|
4147
|
+
// command: do not quietly destroy something that is already there.
|
|
4148
|
+
if (existsSync(options.file) && !options.force) {
|
|
4149
|
+
throw usageError(`${options.file} already exists. Use --force to overwrite, or pick another path.`);
|
|
4150
|
+
}
|
|
4151
|
+
// Build the object only from the fields that were actually given.
|
|
4152
|
+
//
|
|
4153
|
+
// Do not "simplify" this to `new JmMind({ name, author })`: mergeObjects
|
|
4154
|
+
// spreads user values over the defaults, and a present-but-undefined key
|
|
4155
|
+
// overwrites the default with undefined rather than being skipped. That
|
|
4156
|
+
// silently produces a document missing meta.name and meta.author, which the
|
|
4157
|
+
// validator then rejects as E_META.
|
|
4158
|
+
const metadata = {};
|
|
4159
|
+
// A mind map is normally named after its root. Defaulting name to title
|
|
4160
|
+
// means the common case needs one flag instead of two, and a document that
|
|
4161
|
+
// says "jsMind Mindmap" while its root says something else needs an
|
|
4162
|
+
// explicit --name to happen.
|
|
4163
|
+
metadata.name = options.name ?? options.title;
|
|
4164
|
+
if (options.author !== undefined) {
|
|
4165
|
+
metadata.author = options.author;
|
|
4166
|
+
}
|
|
4167
|
+
const mind = new JmMind(metadata);
|
|
4168
|
+
mind.root.content = new JmNodeContent('text', options.title);
|
|
4169
|
+
const serializer = new JmMindJsonSerializer();
|
|
4170
|
+
const doc = serializer.serialize(mind);
|
|
4171
|
+
// Check its own output before touching the disk. If the serialiser ever
|
|
4172
|
+
// emits something the validator rejects, that is a bug in this project,
|
|
4173
|
+
// not in the caller's data — the message says so.
|
|
4174
|
+
const check = validateMindData(doc);
|
|
4175
|
+
if (!check.valid) {
|
|
4176
|
+
throw dataError(`Refusing to write ${options.file}: the document built for it does not validate.\n` +
|
|
4177
|
+
`This is a bug in jsmind, not in your input.\n${formatIssues(check.errors)}`);
|
|
4178
|
+
}
|
|
4179
|
+
if (options.dryRun) {
|
|
4180
|
+
process.stdout.write(renderJson(doc));
|
|
4181
|
+
return CliExit.Ok;
|
|
4182
|
+
}
|
|
4183
|
+
writeJsonFile(doc, options.file, { dryRun: false, backup: options.backup });
|
|
4184
|
+
process.stdout.write(`created ${options.file}\n`);
|
|
4185
|
+
return CliExit.Ok;
|
|
4186
|
+
}
|
|
4187
|
+
/**
|
|
4188
|
+
* Describes the create command for `--help`.
|
|
4189
|
+
*/
|
|
4190
|
+
const createHelp = `jsmind create <file> --title <title> [options]
|
|
4191
|
+
|
|
4192
|
+
Start a new mind map containing a single root node.
|
|
4193
|
+
|
|
4194
|
+
--title <title> Root node label; also becomes meta.name (required)
|
|
4195
|
+
--name <name> Override meta.name when it should differ from the title
|
|
4196
|
+
--author <author> Author recorded in meta
|
|
4197
|
+
--force Overwrite the file if it already exists
|
|
4198
|
+
--backup Keep a .bak copy of the file being overwritten
|
|
4199
|
+
--dry-run Print the document instead of writing it
|
|
4200
|
+
|
|
4201
|
+
Refuses to overwrite an existing file without --force. Every other command
|
|
4202
|
+
assumes a file exists; this is where one comes from.`;
|
|
4203
|
+
|
|
4204
|
+
/**
|
|
4205
|
+
* jsMind v2 command line entry point.
|
|
4206
|
+
*
|
|
4207
|
+
* @remarks
|
|
4208
|
+
* The CLI is the agent-facing surface: it exposes the data layer (model +
|
|
4209
|
+
* serialization) without dragging in the renderer, so it runs on plain Node.
|
|
4210
|
+
*
|
|
4211
|
+
* Commands are grouped by what they operate on:
|
|
4212
|
+
*
|
|
4213
|
+
* cross-boundary validate, context — whole-document operations
|
|
4214
|
+
* mind structure and edges — JmMind methods
|
|
4215
|
+
* node node attributes — JmNode writable fields
|
|
4216
|
+
*
|
|
4217
|
+
* @packageDocumentation
|
|
4218
|
+
*/
|
|
4219
|
+
const PROGRAM = 'jsmind';
|
|
4220
|
+
const HELP = `${PROGRAM} v2 — mind map data commands
|
|
4221
|
+
|
|
4222
|
+
Usage: ${PROGRAM} <command> [options]
|
|
4223
|
+
|
|
4224
|
+
Cross-boundary commands:
|
|
4225
|
+
create <file> --title <title> Start a new mind map
|
|
4226
|
+
validate <file> Check a file against the format spec
|
|
4227
|
+
export <file> <out.png> Render to an image (needs a browser)
|
|
4228
|
+
context <file> [options] Discovery: show the tree and its ids
|
|
4229
|
+
|
|
4230
|
+
Structure and edges:
|
|
4231
|
+
mind <sub> <file> [options] JmMind methods (see: jsmind mind --help)
|
|
4232
|
+
|
|
4233
|
+
Node attributes:
|
|
4234
|
+
node <sub> <file> [options] JmNode writable fields (see: jsmind node --help)
|
|
4235
|
+
|
|
4236
|
+
Options:
|
|
4237
|
+
--json Machine-readable output
|
|
4238
|
+
--dry-run Show what would change, write nothing
|
|
4239
|
+
--output <path> Write somewhere other than the input file
|
|
4240
|
+
--backup Keep a .bak copy before overwriting
|
|
4241
|
+
-h, --help Show this help
|
|
4242
|
+
|
|
4243
|
+
Exit codes:
|
|
4244
|
+
0 success
|
|
4245
|
+
1 invalid data
|
|
4246
|
+
2 usage error
|
|
4247
|
+
3 IO or runtime error
|
|
4248
|
+
|
|
4249
|
+
${createHelp}
|
|
4250
|
+
|
|
4251
|
+
${validateHelp}
|
|
4252
|
+
|
|
4253
|
+
${contextHelp}
|
|
4254
|
+
|
|
4255
|
+
${mindHelp}
|
|
4256
|
+
|
|
4257
|
+
${nodeHelp}`;
|
|
4258
|
+
/**
|
|
4259
|
+
* Parses argv into options and positionals.
|
|
4260
|
+
*
|
|
4261
|
+
* @returns Parsed arguments, with the program and command stripped from
|
|
4262
|
+
* positionals.
|
|
4263
|
+
* @throws {@link CliError} With `Usage` when the command line cannot be parsed.
|
|
4264
|
+
*/
|
|
4265
|
+
function parse(argv) {
|
|
4266
|
+
try {
|
|
4267
|
+
const { values, positionals } = parseArgs({
|
|
4268
|
+
args: argv,
|
|
4269
|
+
allowPositionals: true,
|
|
4270
|
+
strict: true,
|
|
4271
|
+
options: {
|
|
4272
|
+
'json': { type: 'boolean', default: false },
|
|
4273
|
+
'dry-run': { type: 'boolean', default: false },
|
|
4274
|
+
'output': { type: 'string' },
|
|
4275
|
+
'backup': { type: 'boolean', default: false },
|
|
4276
|
+
'help': { type: 'boolean', short: 'h', default: false },
|
|
4277
|
+
// locators
|
|
4278
|
+
'node-id': { type: 'string' },
|
|
4279
|
+
'parent-id': { type: 'string' },
|
|
4280
|
+
'edge-id': { type: 'string' },
|
|
4281
|
+
'source-id': { type: 'string' },
|
|
4282
|
+
'target-id': { type: 'string' },
|
|
4283
|
+
// payloads
|
|
4284
|
+
'text': { type: 'string' },
|
|
4285
|
+
'folded': { type: 'string' },
|
|
4286
|
+
'side': { type: 'string' },
|
|
4287
|
+
'position': { type: 'string' },
|
|
4288
|
+
'type': { type: 'string' },
|
|
4289
|
+
'label': { type: 'string' },
|
|
4290
|
+
// node style (set-style). Strings, including the numeric ones: the command
|
|
4291
|
+
// parses and range-checks them itself so a bad value names the flag
|
|
4292
|
+
// rather than a JSON path. Dots mark a level, matching the path each
|
|
4293
|
+
// flag addresses.
|
|
4294
|
+
'tone': { type: 'string' },
|
|
4295
|
+
'background': { type: 'string' },
|
|
4296
|
+
'color': { type: 'string' },
|
|
4297
|
+
'border-color': { type: 'string' },
|
|
4298
|
+
'border-width': { type: 'string' },
|
|
4299
|
+
'border-style': { type: 'string' },
|
|
4300
|
+
'font-size': { type: 'string' },
|
|
4301
|
+
'font-weight': { type: 'string' },
|
|
4302
|
+
'incoming.color': { type: 'string' },
|
|
4303
|
+
'incoming.width': { type: 'string' },
|
|
4304
|
+
'incoming.pattern': { type: 'string' },
|
|
4305
|
+
'incoming.curve': { type: 'string' },
|
|
4306
|
+
'clear': { type: 'string' },
|
|
4307
|
+
'reset': { type: 'boolean', default: false },
|
|
4308
|
+
// context
|
|
4309
|
+
'focus': { type: 'string' },
|
|
4310
|
+
'depth': { type: 'string' },
|
|
4311
|
+
'max-text': { type: 'string' },
|
|
4312
|
+
'full-text': { type: 'boolean', default: false },
|
|
4313
|
+
'ids-only': { type: 'boolean', default: false },
|
|
4314
|
+
// create
|
|
4315
|
+
'title': { type: 'string' },
|
|
4316
|
+
'name': { type: 'string' },
|
|
4317
|
+
'author': { type: 'string' },
|
|
4318
|
+
'force': { type: 'boolean', default: false },
|
|
4319
|
+
// export
|
|
4320
|
+
'width': { type: 'string' },
|
|
4321
|
+
'height': { type: 'string' },
|
|
4322
|
+
'scale': { type: 'string' },
|
|
4323
|
+
},
|
|
4324
|
+
});
|
|
4325
|
+
return { values: values, positionals };
|
|
4326
|
+
}
|
|
4327
|
+
catch (err) {
|
|
4328
|
+
// parseArgs throws a plain Error with a decent message; promote it so
|
|
4329
|
+
// the caller gets exit code 2 instead of a stack trace.
|
|
4330
|
+
throw usageError(err.message);
|
|
4331
|
+
}
|
|
4332
|
+
}
|
|
4333
|
+
/**
|
|
4334
|
+
* Reads the write-behaviour flags.
|
|
4335
|
+
*
|
|
4336
|
+
* @param values - Parsed options.
|
|
4337
|
+
* @returns Write options for the mutation pipeline.
|
|
4338
|
+
*/
|
|
4339
|
+
function writeOptions(values) {
|
|
4340
|
+
const result = {
|
|
4341
|
+
dryRun: values['dry-run'] === true,
|
|
4342
|
+
backup: values.backup === true,
|
|
4343
|
+
};
|
|
4344
|
+
if (typeof values.output === 'string') {
|
|
4345
|
+
result.output = values.output;
|
|
4346
|
+
}
|
|
4347
|
+
return result;
|
|
4348
|
+
}
|
|
4349
|
+
/**
|
|
4350
|
+
* Dispatches one parsed invocation.
|
|
4351
|
+
*
|
|
4352
|
+
* @param parsed - Options and positionals.
|
|
4353
|
+
* @returns Exit code.
|
|
4354
|
+
* @throws {@link CliError} When the command fails.
|
|
4355
|
+
*/
|
|
4356
|
+
function dispatch(parsed) {
|
|
4357
|
+
const [command, ...rest] = parsed.positionals;
|
|
4358
|
+
const asJson = parsed.values.json === true;
|
|
4359
|
+
if (parsed.values.help === true || command === undefined || command === 'help') {
|
|
4360
|
+
process.stdout.write(`${HELP}\n`);
|
|
4361
|
+
return CliExit.Ok;
|
|
4362
|
+
}
|
|
4363
|
+
switch (command) {
|
|
4364
|
+
case 'export': {
|
|
4365
|
+
const [file, output, ...extra] = rest;
|
|
4366
|
+
if (file === undefined || output === undefined) {
|
|
4367
|
+
throw usageError('export requires an input file and an output image path');
|
|
4368
|
+
}
|
|
4369
|
+
if (extra.length > 0) {
|
|
4370
|
+
throw usageError(`Unexpected arguments: ${extra.join(' ')}`);
|
|
4371
|
+
}
|
|
4372
|
+
return runExport({
|
|
4373
|
+
file,
|
|
4374
|
+
output,
|
|
4375
|
+
width: numberOption(parsed.values.width, DEFAULT_WIDTH, 'width'),
|
|
4376
|
+
height: numberOption(parsed.values.height, DEFAULT_HEIGHT, 'height'),
|
|
4377
|
+
scale: numberOption(parsed.values.scale, DEFAULT_SCALE, 'scale'),
|
|
4378
|
+
type: enumOption(parsed.values.type, JmImageType.Png, EXPORT_TYPES, 'type'),
|
|
4379
|
+
asJson,
|
|
4380
|
+
});
|
|
4381
|
+
}
|
|
4382
|
+
case 'validate': {
|
|
4383
|
+
assertValidateArgs(rest);
|
|
4384
|
+
return runValidate(rest[0], asJson);
|
|
4385
|
+
}
|
|
4386
|
+
case 'create': {
|
|
4387
|
+
const [file, ...extra] = rest;
|
|
4388
|
+
if (file === undefined) {
|
|
4389
|
+
throw usageError('create requires a file path');
|
|
4390
|
+
}
|
|
4391
|
+
if (extra.length > 0) {
|
|
4392
|
+
throw usageError(`Unexpected arguments: ${extra.join(' ')}`);
|
|
4393
|
+
}
|
|
4394
|
+
const options = {
|
|
4395
|
+
file,
|
|
4396
|
+
title: requireOption(parsed.values, 'title'),
|
|
4397
|
+
force: parsed.values.force === true,
|
|
4398
|
+
dryRun: parsed.values['dry-run'] === true,
|
|
4399
|
+
// --output is deliberately not forwarded: for create the path
|
|
4400
|
+
// is already a positional argument, and an output redirect
|
|
4401
|
+
// would give two competing answers to "where does this go".
|
|
4402
|
+
backup: parsed.values.backup === true,
|
|
4403
|
+
};
|
|
4404
|
+
if (typeof parsed.values.name === 'string') {
|
|
4405
|
+
options.name = parsed.values.name;
|
|
4406
|
+
}
|
|
4407
|
+
if (typeof parsed.values.author === 'string') {
|
|
4408
|
+
options.author = parsed.values.author;
|
|
4409
|
+
}
|
|
4410
|
+
return runCreate(options);
|
|
4411
|
+
}
|
|
4412
|
+
case 'context': {
|
|
4413
|
+
const [file, ...extra] = rest;
|
|
4414
|
+
if (file === undefined) {
|
|
4415
|
+
throw usageError('context requires a file path');
|
|
4416
|
+
}
|
|
4417
|
+
if (extra.length > 0) {
|
|
4418
|
+
throw usageError(`Unexpected arguments: ${extra.join(' ')}`);
|
|
4419
|
+
}
|
|
4420
|
+
const options = {
|
|
4421
|
+
file,
|
|
4422
|
+
depth: intOption(parsed.values.depth, DEFAULT_DEPTH, 'depth'),
|
|
4423
|
+
maxText: intOption(parsed.values['max-text'], DEFAULT_MAX_TEXT, 'max-text'),
|
|
4424
|
+
fullText: parsed.values['full-text'] === true,
|
|
4425
|
+
idsOnly: parsed.values['ids-only'] === true,
|
|
4426
|
+
asJson,
|
|
4427
|
+
};
|
|
4428
|
+
if (typeof parsed.values.focus === 'string') {
|
|
4429
|
+
options.focus = parsed.values.focus;
|
|
4430
|
+
}
|
|
4431
|
+
return runContext(options);
|
|
4432
|
+
}
|
|
4433
|
+
case 'mind': {
|
|
4434
|
+
const [subcommand, file, ...extra] = rest;
|
|
4435
|
+
if (subcommand === undefined || file === undefined) {
|
|
4436
|
+
throw usageError(`mind requires a subcommand and a file\n\n${mindHelp}`);
|
|
4437
|
+
}
|
|
4438
|
+
if (extra.length > 0) {
|
|
4439
|
+
throw usageError(`Unexpected arguments: ${extra.join(' ')}`);
|
|
4440
|
+
}
|
|
4441
|
+
return runMind(file, subcommand, parsed.values, writeOptions(parsed.values));
|
|
4442
|
+
}
|
|
4443
|
+
case 'node': {
|
|
4444
|
+
const [subcommand, file, ...extra] = rest;
|
|
4445
|
+
if (subcommand === undefined || file === undefined) {
|
|
4446
|
+
throw usageError(`node requires a subcommand and a file\n\n${nodeHelp}`);
|
|
4447
|
+
}
|
|
4448
|
+
if (extra.length > 0) {
|
|
4449
|
+
throw usageError(`Unexpected arguments: ${extra.join(' ')}`);
|
|
4450
|
+
}
|
|
4451
|
+
return runNode(file, subcommand, parsed.values, writeOptions(parsed.values));
|
|
4452
|
+
}
|
|
4453
|
+
default:
|
|
4454
|
+
throw usageError(`Unknown command: ${command}\n\nRun "${PROGRAM} --help" for usage.`);
|
|
4455
|
+
}
|
|
4456
|
+
}
|
|
4457
|
+
/**
|
|
4458
|
+
* Runs the CLI and terminates the process.
|
|
4459
|
+
*
|
|
4460
|
+
* @param argv - Arguments after the executable and script path.
|
|
4461
|
+
*/
|
|
4462
|
+
async function main(argv) {
|
|
4463
|
+
try {
|
|
4464
|
+
process.exitCode = await dispatch(parse(argv));
|
|
4465
|
+
}
|
|
4466
|
+
catch (err) {
|
|
4467
|
+
if (err instanceof CliError) {
|
|
4468
|
+
process.stderr.write(`${err.message}\n`);
|
|
4469
|
+
process.exitCode = err.exit;
|
|
4470
|
+
return;
|
|
4471
|
+
}
|
|
4472
|
+
// Anything unexpected is a runtime failure, not a usage problem — the
|
|
4473
|
+
// caller should stop and look rather than retry with a different
|
|
4474
|
+
// command line.
|
|
4475
|
+
process.stderr.write(`Unexpected failure: ${err.message}\n`);
|
|
4476
|
+
process.exitCode = CliExit.IoError;
|
|
4477
|
+
}
|
|
4478
|
+
}
|
|
4479
|
+
void main(process.argv.slice(2));
|
|
4480
|
+
|
|
4481
|
+
export { HELP };
|
|
4482
|
+
//# sourceMappingURL=cli.js.map
|