codechart 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +218 -2
- package/THIRD_PARTY_NOTICES.md +11 -0
- package/config.schema.json +142 -0
- package/dist/cli.js +2651 -0
- package/package.json +61 -4
- package/skills/codechart/SKILL.md +96 -0
- package/skills/codechart/example.md +73 -0
- package/skills/codechart/flow-guide.md +116 -0
- package/skills/codechart/spec-guide.md +72 -0
- package/templates/codechart.yaml +32 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,2651 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/program.ts
|
|
4
|
+
import { Command as Command7, CommanderError } from "commander";
|
|
5
|
+
|
|
6
|
+
// src/commands/check.ts
|
|
7
|
+
import path2 from "path";
|
|
8
|
+
import { Command } from "commander";
|
|
9
|
+
|
|
10
|
+
// src/config/load.ts
|
|
11
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "fs";
|
|
12
|
+
import { homedir } from "os";
|
|
13
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "path";
|
|
14
|
+
import { parse } from "yaml";
|
|
15
|
+
|
|
16
|
+
// src/config/builtin-rules.ts
|
|
17
|
+
var MAP_RULES = [
|
|
18
|
+
{
|
|
19
|
+
name: "migrations",
|
|
20
|
+
paths: [
|
|
21
|
+
"**/migrations/**",
|
|
22
|
+
"**/alembic/versions/**",
|
|
23
|
+
"**/db/migrate/**",
|
|
24
|
+
"**/database/migrations/**",
|
|
25
|
+
"**/drizzle/**"
|
|
26
|
+
]
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
name: "orm-schema",
|
|
30
|
+
paths: [
|
|
31
|
+
"**/prisma/schema.prisma",
|
|
32
|
+
"**/models.py",
|
|
33
|
+
"**/models/**",
|
|
34
|
+
"**/entities/**",
|
|
35
|
+
"**/*.entity.ts",
|
|
36
|
+
"**/app/models/**"
|
|
37
|
+
]
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
name: "related-files",
|
|
41
|
+
when: "more than 2 changed files depend on each other"
|
|
42
|
+
}
|
|
43
|
+
];
|
|
44
|
+
var FLOW_WHEN = {
|
|
45
|
+
auto: "the change adds or alters behaviour with at least 2 decisions or edge cases a reader would want to see",
|
|
46
|
+
always: "the change adds or alters any behaviour with at least one decision"
|
|
47
|
+
};
|
|
48
|
+
function builtinRules(flows) {
|
|
49
|
+
if (flows === "request") return MAP_RULES;
|
|
50
|
+
return [...MAP_RULES, { name: "behaviour-flow", diagram: "flow", when: FLOW_WHEN[flows], output: "auto" }];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/config/schema.ts
|
|
54
|
+
import { z as z2 } from "zod";
|
|
55
|
+
|
|
56
|
+
// src/spec/shared.ts
|
|
57
|
+
import { z } from "zod";
|
|
58
|
+
|
|
59
|
+
// src/render/strip.ts
|
|
60
|
+
var INVISIBLE = /[\u200b\u200c\u200e\u200f\u202a-\u202e\u2060-\u2069\ufeff]/g;
|
|
61
|
+
var stripInvisible = (s) => s.replace(INVISIBLE, "");
|
|
62
|
+
var sanitizeText = (s) => stripInvisible(s).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "");
|
|
63
|
+
var escapeJsonControls = (json) => json.replace(/[\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
64
|
+
var hasHiddenChars = (s) => /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/.test(s);
|
|
65
|
+
|
|
66
|
+
// src/spec/shared.ts
|
|
67
|
+
var SHORT = 200;
|
|
68
|
+
var LONG = 2e3;
|
|
69
|
+
var PATH = 1e3;
|
|
70
|
+
var MAX_SPEC_BYTES = 2 * 1024 * 1024;
|
|
71
|
+
var short = () => z.string().min(1).max(SHORT);
|
|
72
|
+
var ident = () => short().refine((v) => !hasHiddenChars(v), "must not contain control or invisible characters");
|
|
73
|
+
var shortOpt = () => z.string().max(SHORT);
|
|
74
|
+
var long = () => z.string().max(LONG);
|
|
75
|
+
var pathStr = () => z.string().max(PATH);
|
|
76
|
+
function hashToken(label) {
|
|
77
|
+
return label.split(/[^A-Za-z0-9]+/).find((t) => /^[0-9a-f]{7,}$/i.test(t) && /\d/.test(t) && /[a-f]/i.test(t));
|
|
78
|
+
}
|
|
79
|
+
function labelIssues(label, noun, fileField, example) {
|
|
80
|
+
const issues = [];
|
|
81
|
+
const hash = hashToken(label);
|
|
82
|
+
if (hash) {
|
|
83
|
+
issues.push(
|
|
84
|
+
`looks like a hash or file name ("${hash}"); label it by what it is (e.g. "${example}") and put the file in ${fileField}`
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
if (label.includes(" / ") || label.includes(" + ")) {
|
|
88
|
+
const hint = noun === "step" ? " (one action per step; no '+' or 'and')" : "";
|
|
89
|
+
issues.push(`one ${noun} per entity; split "${label}" into separate ${noun}s${hint}`);
|
|
90
|
+
}
|
|
91
|
+
return issues;
|
|
92
|
+
}
|
|
93
|
+
function formatPath(path3) {
|
|
94
|
+
if (path3.length === 0) return "$";
|
|
95
|
+
return path3.reduce((acc, seg) => {
|
|
96
|
+
if (typeof seg === "number") return `${acc}[${seg}]`;
|
|
97
|
+
const s = String(seg);
|
|
98
|
+
return acc ? `${acc}.${s}` : s;
|
|
99
|
+
}, "");
|
|
100
|
+
}
|
|
101
|
+
var oneLine = (s) => s.split("\n").map((l) => l.trim()).join(" ");
|
|
102
|
+
function formatIssues(error) {
|
|
103
|
+
return error.issues.map(
|
|
104
|
+
(issue) => `${formatPath(issue.path)}: ${oneLine(issue.message)}`
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// src/config/schema.ts
|
|
109
|
+
var OUTPUTS = ["auto", "cli", "web", "both", "none"];
|
|
110
|
+
var CONTEXT_MODES = ["short", "full"];
|
|
111
|
+
var THEMES = ["auto", "light", "dark"];
|
|
112
|
+
var OPEN_MODES = ["auto", "always", "never"];
|
|
113
|
+
var DIAGRAMS = ["map", "flow"];
|
|
114
|
+
var FLOWS = ["auto", "always", "request"];
|
|
115
|
+
var RULE_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
116
|
+
var ONE_LINE_VISIBLE = /^[^\u0000-\u001f\u007f-\u009f\u200b\u200c\u200e\u200f\u2028-\u202e\u2060-\u2069\ufeff]*$/;
|
|
117
|
+
var CHARS_MESSAGE = "must be one line without control or invisible characters";
|
|
118
|
+
var glob = z2.string().min(1).max(200).regex(ONE_LINE_VISIBLE, CHARS_MESSAGE).refine((g) => !/[{(]/.test(g.replace(/\\./g, "")), { message: "braces and extglobs aren't supported; list each pattern separately" }).refine((g) => g.split("/").every((seg) => (seg.match(/[*?]/g) ?? []).length <= 8), {
|
|
119
|
+
message: "at most 8 of * ? per path segment"
|
|
120
|
+
});
|
|
121
|
+
var ruleSchema = z2.strictObject({
|
|
122
|
+
name: z2.string().regex(RULE_NAME, "use 1-64 lowercase letters, digits or hyphens, not starting with a hyphen"),
|
|
123
|
+
diagram: z2.enum(DIAGRAMS).optional(),
|
|
124
|
+
paths: z2.array(glob).min(1).optional(),
|
|
125
|
+
when: z2.string().min(1).max(300).regex(ONE_LINE_VISIBLE, CHARS_MESSAGE).optional(),
|
|
126
|
+
output: z2.enum(OUTPUTS).optional(),
|
|
127
|
+
context: z2.enum(CONTEXT_MODES).optional()
|
|
128
|
+
}).refine((r) => r.paths === void 0 !== (r.when === void 0), {
|
|
129
|
+
message: "set exactly one of paths or when"
|
|
130
|
+
}).refine((r) => r.diagram !== "flow" || r.context === void 0, {
|
|
131
|
+
message: "context applies only to map rules"
|
|
132
|
+
});
|
|
133
|
+
var configFileSchema = z2.strictObject({
|
|
134
|
+
defaults: z2.strictObject({
|
|
135
|
+
output: z2.enum(OUTPUTS).optional(),
|
|
136
|
+
context: z2.enum(CONTEXT_MODES).optional(),
|
|
137
|
+
flows: z2.enum(FLOWS).optional(),
|
|
138
|
+
terminalMaxNodes: z2.number().int().positive().optional()
|
|
139
|
+
}).optional(),
|
|
140
|
+
web: z2.strictObject({
|
|
141
|
+
outDir: z2.string().min(1).optional(),
|
|
142
|
+
theme: z2.enum(THEMES).optional(),
|
|
143
|
+
minNodes: z2.number().int().positive().optional(),
|
|
144
|
+
keep: z2.number().int().positive().optional(),
|
|
145
|
+
maxAgeDays: z2.number().nonnegative().optional(),
|
|
146
|
+
open: z2.enum(OPEN_MODES).optional()
|
|
147
|
+
}).optional(),
|
|
148
|
+
useBuiltinRules: z2.boolean().optional(),
|
|
149
|
+
rules: z2.array(ruleSchema).optional()
|
|
150
|
+
});
|
|
151
|
+
function configJsonSchema() {
|
|
152
|
+
return z2.toJSONSchema(configFileSchema, { io: "input" });
|
|
153
|
+
}
|
|
154
|
+
function formatPath2(path3) {
|
|
155
|
+
if (path3.length === 0) return "$";
|
|
156
|
+
return path3.reduce((acc, seg) => {
|
|
157
|
+
if (typeof seg === "number") return `${acc}[${seg}]`;
|
|
158
|
+
const s = String(seg);
|
|
159
|
+
return acc ? `${acc}.${s}` : s;
|
|
160
|
+
}, "");
|
|
161
|
+
}
|
|
162
|
+
function parseConfigFile(input) {
|
|
163
|
+
const result = configFileSchema.safeParse(input ?? {});
|
|
164
|
+
if (result.success) return { ok: true, config: result.data };
|
|
165
|
+
return {
|
|
166
|
+
ok: false,
|
|
167
|
+
errors: result.error.issues.map(
|
|
168
|
+
(i) => `${formatPath2(i.path)}: ${oneLine(i.message)}`
|
|
169
|
+
)
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/config/load.ts
|
|
174
|
+
var BUILTIN = "built-in";
|
|
175
|
+
var MAX_BYTES = 1024 * 1024;
|
|
176
|
+
var BUILTIN_DEFAULTS = { output: "auto", context: "short", flows: "auto", terminalMaxNodes: 15 };
|
|
177
|
+
var GLOBAL_ONLY = ["web.outDir", "web.keep", "web.maxAgeDays", "web.open"];
|
|
178
|
+
function findRepoRoot(cwd) {
|
|
179
|
+
let dir = resolve(cwd);
|
|
180
|
+
for (; ; ) {
|
|
181
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
182
|
+
const parent = dirname(dir);
|
|
183
|
+
if (parent === dir) return void 0;
|
|
184
|
+
dir = parent;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function readConfigFile(file, root) {
|
|
188
|
+
if (!existsSync(file)) return void 0;
|
|
189
|
+
const real = realpathSync(file);
|
|
190
|
+
if (root !== void 0) {
|
|
191
|
+
const rel = relative(realpathSync(root), real);
|
|
192
|
+
if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error(`${file}: resolves outside the repo`);
|
|
193
|
+
}
|
|
194
|
+
const st = statSync(real);
|
|
195
|
+
if (!st.isFile()) throw new Error(`${file}: not a regular file`);
|
|
196
|
+
if (st.size > MAX_BYTES) throw new Error(`${file}: too large (over 1 MB)`);
|
|
197
|
+
let raw;
|
|
198
|
+
try {
|
|
199
|
+
raw = parse(readFileSync(real, "utf8"));
|
|
200
|
+
} catch (e) {
|
|
201
|
+
throw new Error(`${file}: ${e.message.split("\n")[0]}`);
|
|
202
|
+
}
|
|
203
|
+
const defaults = raw?.defaults;
|
|
204
|
+
if (typeof defaults === "object" && defaults !== null && "icons" in defaults) throw new Error(`${file}: defaults.icons was removed (the map always uses + - ~ \xB7 \u25C6); delete it`);
|
|
205
|
+
const result = parseConfigFile(raw);
|
|
206
|
+
if (!result.ok) throw new Error(result.errors.map((m) => `${file}: ${m}`).join("\n"));
|
|
207
|
+
const seen = /* @__PURE__ */ new Set();
|
|
208
|
+
(result.config.rules ?? []).forEach((rule, i) => {
|
|
209
|
+
if (seen.has(rule.name)) throw new Error(`${file}: rules[${i}].name: duplicate "${rule.name}"`);
|
|
210
|
+
seen.add(rule.name);
|
|
211
|
+
});
|
|
212
|
+
return result.config;
|
|
213
|
+
}
|
|
214
|
+
function dropGlobalOnly(file, path3, warn) {
|
|
215
|
+
if (!file?.web) return file;
|
|
216
|
+
const { outDir, keep, maxAgeDays, open, ...web } = file.web;
|
|
217
|
+
const ignored = Object.entries({ outDir, keep, maxAgeDays, open }).filter(([, v]) => v !== void 0);
|
|
218
|
+
if (ignored.length) warn?.(`${path3}: ${ignored.map(([k]) => `web.${k}`).join(", ")} are global-only; ignored`);
|
|
219
|
+
return { ...file, web };
|
|
220
|
+
}
|
|
221
|
+
function firstByName(items) {
|
|
222
|
+
const seen = /* @__PURE__ */ new Set();
|
|
223
|
+
return items.filter(({ rule }) => !seen.has(rule.name) && seen.add(rule.name));
|
|
224
|
+
}
|
|
225
|
+
function resolveOutDir(dir, home) {
|
|
226
|
+
const expanded = dir === "~" ? home : dir.startsWith("~/") ? join(home, dir.slice(2)) : dir;
|
|
227
|
+
return resolve(home, expanded);
|
|
228
|
+
}
|
|
229
|
+
function loadConfigWithSources(opts) {
|
|
230
|
+
const env = opts.env ?? process.env;
|
|
231
|
+
const home = opts.home ?? homedir();
|
|
232
|
+
const xdg = env.XDG_CONFIG_HOME;
|
|
233
|
+
const configHome = xdg && isAbsolute(xdg) ? xdg : home ? join(home, ".config") : void 0;
|
|
234
|
+
const root = findRepoRoot(opts.cwd) ?? resolve(opts.cwd);
|
|
235
|
+
const globalPath = configHome ? join(configHome, "codechart", "config.yaml") : void 0;
|
|
236
|
+
const repoPath = join(root, ".codechart.yaml");
|
|
237
|
+
const global = globalPath ? readConfigFile(globalPath) : void 0;
|
|
238
|
+
const repo = dropGlobalOnly(readConfigFile(repoPath, root), repoPath, opts.warn);
|
|
239
|
+
const globalSource = `global: ${globalPath}`;
|
|
240
|
+
const repoSource = `repo: ${repoPath}`;
|
|
241
|
+
const files = [
|
|
242
|
+
{ file: global, source: globalSource },
|
|
243
|
+
{ file: repo, source: repoSource }
|
|
244
|
+
];
|
|
245
|
+
const defaults = { ...BUILTIN_DEFAULTS };
|
|
246
|
+
const web = {
|
|
247
|
+
outDir: "~/.cache/codechart",
|
|
248
|
+
theme: "auto",
|
|
249
|
+
minNodes: 8,
|
|
250
|
+
keep: 20,
|
|
251
|
+
maxAgeDays: 7,
|
|
252
|
+
open: "auto"
|
|
253
|
+
};
|
|
254
|
+
const sources = {};
|
|
255
|
+
for (const key of Object.keys(defaults)) sources[`defaults.${key}`] = BUILTIN;
|
|
256
|
+
for (const key of Object.keys(web)) sources[`web.${key}`] = BUILTIN;
|
|
257
|
+
sources.useBuiltinRules = BUILTIN;
|
|
258
|
+
for (const { file, source } of files) {
|
|
259
|
+
Object.assign(defaults, file?.defaults);
|
|
260
|
+
Object.assign(web, file?.web);
|
|
261
|
+
for (const key of Object.keys(file?.defaults ?? {})) sources[`defaults.${key}`] = source;
|
|
262
|
+
for (const key of Object.keys(file?.web ?? {})) sources[`web.${key}`] = source;
|
|
263
|
+
}
|
|
264
|
+
web.outDir = resolveOutDir(web.outDir, home);
|
|
265
|
+
const useBuiltinRules = global?.useBuiltinRules !== false && repo?.useBuiltinRules !== false;
|
|
266
|
+
for (const { file, source } of files) {
|
|
267
|
+
if (file?.useBuiltinRules === useBuiltinRules) sources.useBuiltinRules = source;
|
|
268
|
+
}
|
|
269
|
+
const tagged = firstByName([
|
|
270
|
+
...(repo?.rules ?? []).map((rule) => ({ rule, source: repoSource })),
|
|
271
|
+
...(global?.rules ?? []).map((rule) => ({ rule, source: globalSource })),
|
|
272
|
+
...(useBuiltinRules ? builtinRules(defaults.flows) : []).map((rule) => ({ rule, source: BUILTIN }))
|
|
273
|
+
]);
|
|
274
|
+
return {
|
|
275
|
+
config: { defaults, web, useBuiltinRules, rules: tagged.map((t) => t.rule) },
|
|
276
|
+
sources,
|
|
277
|
+
ruleSources: tagged.map((t) => t.source)
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
function loadConfig(opts) {
|
|
281
|
+
return loadConfigWithSources(opts).config;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// src/rules/git-files.ts
|
|
285
|
+
import { execFileSync } from "child_process";
|
|
286
|
+
import { existsSync as existsSync2 } from "fs";
|
|
287
|
+
import { win32 } from "path";
|
|
288
|
+
var MAX_REF = 200;
|
|
289
|
+
function gitBinary(platform = process.platform, env = process.env, exists = existsSync2) {
|
|
290
|
+
if (platform !== "win32") return "git";
|
|
291
|
+
for (const raw of (env.PATH ?? env.Path ?? "").split(";")) {
|
|
292
|
+
const dir = raw.replace(/^"(.*)"$/, "$1");
|
|
293
|
+
if (!win32.isAbsolute(dir)) continue;
|
|
294
|
+
const file = win32.join(dir, "git.exe");
|
|
295
|
+
if (exists(file)) return file;
|
|
296
|
+
}
|
|
297
|
+
throw new Error("git not found on PATH");
|
|
298
|
+
}
|
|
299
|
+
var gitPath;
|
|
300
|
+
var SAFE_ARGS = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "protocol.allow=never"];
|
|
301
|
+
function git(cwd, args, config = []) {
|
|
302
|
+
try {
|
|
303
|
+
gitPath ??= gitBinary();
|
|
304
|
+
const n = Number(process.env.GIT_CONFIG_COUNT) || 0;
|
|
305
|
+
const env = { ...process.env, GIT_NO_LAZY_FETCH: "1", GIT_CONFIG_COUNT: String(n + config.length) };
|
|
306
|
+
config.forEach(([k, v], i) => {
|
|
307
|
+
env[`GIT_CONFIG_KEY_${n + i}`] = k;
|
|
308
|
+
env[`GIT_CONFIG_VALUE_${n + i}`] = v;
|
|
309
|
+
});
|
|
310
|
+
return execFileSync(gitPath, [...SAFE_ARGS, ...args], {
|
|
311
|
+
cwd,
|
|
312
|
+
env,
|
|
313
|
+
timeout: 3e4,
|
|
314
|
+
encoding: "utf8",
|
|
315
|
+
// -uall on big trees can exceed the 1 MiB default
|
|
316
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
317
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
318
|
+
});
|
|
319
|
+
} catch (e) {
|
|
320
|
+
const stderr = String(e.stderr ?? "").trim().split("\n")[0];
|
|
321
|
+
throw new Error(`git ${args.find((a) => !a.startsWith("-"))} failed: ${stderr || e.message}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
function repoFilterOverrides(cwd) {
|
|
325
|
+
let out;
|
|
326
|
+
try {
|
|
327
|
+
out = git(cwd, ["config", "--show-scope", "--includes", "-z", "--name-only", "--get-regexp", "^filter\\."]);
|
|
328
|
+
} catch {
|
|
329
|
+
return [];
|
|
330
|
+
}
|
|
331
|
+
const keys = /* @__PURE__ */ new Set();
|
|
332
|
+
const drivers = /* @__PURE__ */ new Set();
|
|
333
|
+
const recs = out.split("\0");
|
|
334
|
+
for (let i = 0; i + 1 < recs.length; i += 2) {
|
|
335
|
+
const [scope, key] = [recs[i], recs[i + 1]];
|
|
336
|
+
const m = /^(filter\..+)\.(clean|process)$/i.exec(key);
|
|
337
|
+
if ((scope === "local" || scope === "worktree") && m) {
|
|
338
|
+
keys.add(key);
|
|
339
|
+
drivers.add(m[1]);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return [...[...keys].map((k) => [k, ""]), ...[...drivers].map((d) => [`${d}.required`, "false"])];
|
|
343
|
+
}
|
|
344
|
+
var nulList = (out) => out.split("\0").filter(Boolean);
|
|
345
|
+
function refProblem(ref) {
|
|
346
|
+
if (ref === "") return "is empty";
|
|
347
|
+
if (ref.length > MAX_REF) return `is longer than ${MAX_REF} characters`;
|
|
348
|
+
if (ref.startsWith("-")) return 'must not start with "-"';
|
|
349
|
+
if (/\s/.test(ref) || hasHiddenChars(ref)) return "must not contain spaces, control or invisible characters";
|
|
350
|
+
return void 0;
|
|
351
|
+
}
|
|
352
|
+
function checkRef(flag, ref) {
|
|
353
|
+
const problem = refProblem(ref);
|
|
354
|
+
if (problem) throw new Error(`${flag} ${problem}`);
|
|
355
|
+
}
|
|
356
|
+
function gitChangedFiles(cwd) {
|
|
357
|
+
const records = git(cwd, ["status", "--porcelain=v1", "-z", "-uall"], repoFilterOverrides(cwd)).split("\0");
|
|
358
|
+
const files = [];
|
|
359
|
+
for (let i = 0; i < records.length; i++) {
|
|
360
|
+
const rec = records[i];
|
|
361
|
+
if (!rec || rec.length < 4) continue;
|
|
362
|
+
files.push(rec.slice(3));
|
|
363
|
+
if (rec[0] === "R" || rec[0] === "C" || rec[1] === "R" || rec[1] === "C") i++;
|
|
364
|
+
}
|
|
365
|
+
return files;
|
|
366
|
+
}
|
|
367
|
+
function resolveCommit(cwd, flag, ref) {
|
|
368
|
+
checkRef(flag, ref);
|
|
369
|
+
try {
|
|
370
|
+
return git(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]).trim();
|
|
371
|
+
} catch {
|
|
372
|
+
throw new Error(`${flag} ${ref} is not a commit`);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
function gitCommitFiles(cwd, ref) {
|
|
376
|
+
const sha = resolveCommit(cwd, "--commit", ref);
|
|
377
|
+
const parent = git(cwd, ["rev-list", "--parents", "-n", "1", sha, "--"]).trim().split(" ")[1];
|
|
378
|
+
if (!parent) return nulList(git(cwd, ["diff-tree", "-r", "--root", "--no-commit-id", "--name-only", "-z", sha]));
|
|
379
|
+
return nulList(git(cwd, ["diff", "--no-renames", "--name-only", "-z", parent, sha, "--"]));
|
|
380
|
+
}
|
|
381
|
+
function gitSinceFiles(cwd, base, head = "HEAD") {
|
|
382
|
+
checkRef("--since", base);
|
|
383
|
+
checkRef("--head", head);
|
|
384
|
+
return nulList(git(cwd, ["diff", "--no-renames", "--name-only", "-z", `${base}...${head}`, "--"]));
|
|
385
|
+
}
|
|
386
|
+
function gitListFiles(cwd, sha) {
|
|
387
|
+
return nulList(
|
|
388
|
+
sha ? git(cwd, ["ls-tree", "-r", "-z", "--name-only", "--full-tree", sha]) : git(cwd, ["ls-files", "-z", "--cached", "--full-name"])
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
function gitFileAt(cwd, sha, rel, maxBytes) {
|
|
392
|
+
const entry = git(cwd, ["--literal-pathspecs", "ls-tree", "-z", "--full-tree", sha, "--", rel]).split("\0")[0];
|
|
393
|
+
if (!entry) return null;
|
|
394
|
+
const [meta, path3] = entry.split(" ");
|
|
395
|
+
const [mode, type, oid] = meta.split(" ");
|
|
396
|
+
if (path3 !== rel) return null;
|
|
397
|
+
if (type !== "blob" || mode === "120000") return { error: `${rel} is not a regular file at ${sha.slice(0, 12)}` };
|
|
398
|
+
if (Number(git(cwd, ["cat-file", "-s", oid]).trim()) > maxBytes) return { error: `${rel} is too large (over 5 MB)` };
|
|
399
|
+
return git(cwd, ["cat-file", "blob", oid]);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// src/rules/resolve.ts
|
|
403
|
+
import path from "path";
|
|
404
|
+
import picomatch from "picomatch";
|
|
405
|
+
var DRIVE_PATH = /^[A-Za-z]:\//;
|
|
406
|
+
function normalizePath(p, root) {
|
|
407
|
+
const slashed = p.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
408
|
+
const rootSlashed = root.replace(/\\/g, "/");
|
|
409
|
+
if (DRIVE_PATH.test(slashed)) {
|
|
410
|
+
if (!DRIVE_PATH.test(rootSlashed)) return slashed;
|
|
411
|
+
const relative4 = path.posix.relative(lowerDrive(rootSlashed), lowerDrive(slashed));
|
|
412
|
+
return isInside(relative4) ? relative4 : slashed;
|
|
413
|
+
}
|
|
414
|
+
if (!path.posix.isAbsolute(slashed)) return slashed;
|
|
415
|
+
const relative3 = path.posix.relative(rootSlashed, slashed);
|
|
416
|
+
return isInside(relative3) ? relative3 : slashed;
|
|
417
|
+
}
|
|
418
|
+
function lowerDrive(p) {
|
|
419
|
+
return p.charAt(0).toLowerCase() + p.slice(1);
|
|
420
|
+
}
|
|
421
|
+
function isInside(relative3) {
|
|
422
|
+
return relative3 !== "" && relative3 !== ".." && !relative3.startsWith("../");
|
|
423
|
+
}
|
|
424
|
+
function isPathRule(rule) {
|
|
425
|
+
return rule.paths !== void 0;
|
|
426
|
+
}
|
|
427
|
+
var diagramOf = (rule) => rule.diagram ?? "map";
|
|
428
|
+
function toContribution(rule, config) {
|
|
429
|
+
const diagram = diagramOf(rule);
|
|
430
|
+
const output = rule.output ?? config.defaults.output;
|
|
431
|
+
if (diagram === "flow") return { rule: rule.name, diagram, output };
|
|
432
|
+
return { rule: rule.name, diagram, output, context: rule.context ?? config.defaults.context };
|
|
433
|
+
}
|
|
434
|
+
function matchPathRules(config, rules, files) {
|
|
435
|
+
const pathRules = rules.filter(isPathRule).map((rule) => ({
|
|
436
|
+
rule,
|
|
437
|
+
isMatch: picomatch(rule.paths, { dot: true, nobrace: true, noextglob: true })
|
|
438
|
+
}));
|
|
439
|
+
const filesByRule = /* @__PURE__ */ new Map();
|
|
440
|
+
for (const file of files) {
|
|
441
|
+
const hit = pathRules.find(({ isMatch }) => isMatch(file));
|
|
442
|
+
if (!hit) continue;
|
|
443
|
+
const list2 = filesByRule.get(hit.rule.name);
|
|
444
|
+
if (list2) list2.push(file);
|
|
445
|
+
else filesByRule.set(hit.rule.name, [file]);
|
|
446
|
+
}
|
|
447
|
+
return pathRules.flatMap(({ rule }) => {
|
|
448
|
+
const matchedFiles = filesByRule.get(rule.name);
|
|
449
|
+
return matchedFiles ? [{ ...toContribution(rule, config), files: matchedFiles }] : [];
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
function unionOutputs(outputs) {
|
|
453
|
+
const hasAuto = outputs.includes("auto");
|
|
454
|
+
const hasCli = hasAuto || outputs.some((o) => o === "cli" || o === "both");
|
|
455
|
+
const hasWeb = outputs.some((o) => o === "web" || o === "both");
|
|
456
|
+
if (hasCli && hasWeb) return "both";
|
|
457
|
+
if (hasAuto) return "auto";
|
|
458
|
+
if (hasCli) return "cli";
|
|
459
|
+
if (hasWeb) return "web";
|
|
460
|
+
return "none";
|
|
461
|
+
}
|
|
462
|
+
function buildFlowFinal(contributions) {
|
|
463
|
+
const drawing = contributions.filter((c) => c.output !== "none");
|
|
464
|
+
const output = unionOutputs(drawing.map((c) => c.output));
|
|
465
|
+
return { draw: output !== "none", output, rules: drawing.map((c) => c.rule) };
|
|
466
|
+
}
|
|
467
|
+
function buildMapFinal(config, contributions) {
|
|
468
|
+
const anyFull = contributions.some((c) => c.output !== "none" && c.context === "full");
|
|
469
|
+
return { ...buildFlowFinal(contributions), context: anyFull ? "full" : config.defaults.context };
|
|
470
|
+
}
|
|
471
|
+
function findPlainRules(config, matched) {
|
|
472
|
+
const wanted = new Set(matched);
|
|
473
|
+
const unknown = [];
|
|
474
|
+
for (const name of wanted) {
|
|
475
|
+
const rule = config.rules.find((r) => r.name === name);
|
|
476
|
+
if (!rule) unknown.push(name);
|
|
477
|
+
else if (isPathRule(rule)) throw new Error(`not a plain-language rule: ${name}`);
|
|
478
|
+
}
|
|
479
|
+
return { rules: config.rules.filter((r) => wanted.has(r.name)), unknown };
|
|
480
|
+
}
|
|
481
|
+
function resolveDiagram(config, diagram, files, plainMatches) {
|
|
482
|
+
const ofType = (r) => diagramOf(r) === diagram;
|
|
483
|
+
const pathMatches = matchPathRules(config, config.rules.filter(ofType), files);
|
|
484
|
+
const excluded = new Set(pathMatches.filter((m) => m.output === "none").flatMap((m) => m.files));
|
|
485
|
+
return {
|
|
486
|
+
pathMatches,
|
|
487
|
+
excluded: [...excluded],
|
|
488
|
+
remaining: files.filter((f) => !excluded.has(f)),
|
|
489
|
+
// Path rules come first so final.rules lists them before plain-language ones.
|
|
490
|
+
contributions: [...pathMatches, ...plainMatches.filter(ofType).map((r) => toContribution(r, config))]
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
function toJudgeEntry(r, config) {
|
|
494
|
+
const { rule, diagram, output, context } = toContribution(r, config);
|
|
495
|
+
return { rule, diagram, when: r.when, output, ...context && { context } };
|
|
496
|
+
}
|
|
497
|
+
var entryKey = (t) => JSON.stringify([t.rule, t.diagram, t.when, t.output, t.context]);
|
|
498
|
+
var BUILTIN_TO_JUDGE = new Set(
|
|
499
|
+
builtinRules(BUILTIN_DEFAULTS.flows).filter((r) => r.when !== void 0).map((r) => entryKey(toJudgeEntry(r, { defaults: BUILTIN_DEFAULTS })))
|
|
500
|
+
);
|
|
501
|
+
function onlyBuiltinsToJudge(toJudge) {
|
|
502
|
+
return toJudge.length === BUILTIN_TO_JUDGE.size && toJudge.every((t) => BUILTIN_TO_JUDGE.has(entryKey(t)));
|
|
503
|
+
}
|
|
504
|
+
function resolveRules(config, files, matched, root = process.cwd()) {
|
|
505
|
+
const normalized = [...new Set(files.map((f) => normalizePath(f, root)))];
|
|
506
|
+
const { rules: plainMatches, unknown } = findPlainRules(config, matched ?? []);
|
|
507
|
+
const map = resolveDiagram(config, "map", normalized, plainMatches);
|
|
508
|
+
const flow = resolveDiagram(config, "flow", normalized, plainMatches);
|
|
509
|
+
const toJudge = config.rules.filter((r) => r.when !== void 0).map((r) => toJudgeEntry(r, config));
|
|
510
|
+
const result = {
|
|
511
|
+
pathMatches: [...map.pathMatches, ...flow.pathMatches],
|
|
512
|
+
excludedFiles: { map: map.excluded, flow: flow.excluded },
|
|
513
|
+
remainingFiles: { map: map.remaining, flow: flow.remaining },
|
|
514
|
+
toJudge
|
|
515
|
+
};
|
|
516
|
+
if (unknown.length > 0) result.unknownMatched = unknown;
|
|
517
|
+
else if (matched !== void 0 || toJudge.length === 0) {
|
|
518
|
+
result.final = { map: buildMapFinal(config, map.contributions), flow: buildFlowFinal(flow.contributions) };
|
|
519
|
+
}
|
|
520
|
+
return result;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// src/commands/check.ts
|
|
524
|
+
var csv = (v) => v.split(",").map((s) => s.trim()).filter(Boolean);
|
|
525
|
+
function terseResult(r) {
|
|
526
|
+
const out = {};
|
|
527
|
+
if (r.pathMatches.length > 0) out.pathMatches = r.pathMatches;
|
|
528
|
+
if (r.excludedFiles.map.length + r.excludedFiles.flow.length > 0) {
|
|
529
|
+
out.excludedFiles = r.excludedFiles;
|
|
530
|
+
out.remainingFiles = r.remainingFiles;
|
|
531
|
+
}
|
|
532
|
+
if (r.toJudge.length > 0 && (r.unknownMatched || !onlyBuiltinsToJudge(r.toJudge))) out.toJudge = r.toJudge;
|
|
533
|
+
else if (r.toJudge.length > 0 && !r.final) out.judgeBuiltins = r.toJudge.map((t) => t.rule);
|
|
534
|
+
if (r.unknownMatched) out.unknownMatched = r.unknownMatched;
|
|
535
|
+
if (r.final) out.final = r.final;
|
|
536
|
+
return out;
|
|
537
|
+
}
|
|
538
|
+
function selectionError(o) {
|
|
539
|
+
if (o.files !== void 0 && csv(o.files).length === 0) return "--files is empty";
|
|
540
|
+
const sources = [o.files !== void 0, o.git, o.commit !== void 0, o.since !== void 0].filter(Boolean).length;
|
|
541
|
+
const gitPlusSince = sources === 2 && o.git && o.since !== void 0;
|
|
542
|
+
if (sources === 0 || sources > 1 && !gitPlusSince) {
|
|
543
|
+
return "specify one of --files, --git, --commit or --since (only --git and --since combine)";
|
|
544
|
+
}
|
|
545
|
+
if (o.head !== void 0 && o.since === void 0) return "--head needs --since";
|
|
546
|
+
if (o.head !== void 0 && o.git) return "--head compares another branch, so it does not combine with --git";
|
|
547
|
+
return void 0;
|
|
548
|
+
}
|
|
549
|
+
function gitFiles(root, o) {
|
|
550
|
+
if (!root) throw new Error("not a git repository (use --files)");
|
|
551
|
+
const files = [];
|
|
552
|
+
if (o.since !== void 0) files.push(...gitSinceFiles(root, o.since, o.head));
|
|
553
|
+
if (o.commit !== void 0) files.push(...gitCommitFiles(root, o.commit));
|
|
554
|
+
if (o.git) files.push(...gitChangedFiles(root));
|
|
555
|
+
return files;
|
|
556
|
+
}
|
|
557
|
+
function checkCommand(opts) {
|
|
558
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
559
|
+
return new Command("check").description("resolve which rules apply to a set of changed files").option("--files <csv>", "comma-separated changed files").option("--git", "use staged, unstaged and untracked files from git").option("--commit <sha>", "use the files one commit changed (a merge: against its first parent)").option("--since <base>", "use the files committed since <base> (git diff <base>...HEAD); add --git for uncommitted ones too").option("--head <ref>", "with --since: compare <base>...<ref> instead of HEAD (another branch)").option("--matched <csv>", "plain-language rules that matched").action((o, cmd) => {
|
|
560
|
+
const usage = selectionError(o);
|
|
561
|
+
if (usage) cmd.error(usage, { exitCode: 2 });
|
|
562
|
+
try {
|
|
563
|
+
const root = findRepoRoot(cwd);
|
|
564
|
+
const files = o.files !== void 0 ? csv(o.files).map((f) => path2.resolve(cwd, f)) : gitFiles(root, o);
|
|
565
|
+
const config = loadConfig({ cwd, home: opts.home, env: opts.env, warn: (l) => opts.stderr(`codechart: ${l}
|
|
566
|
+
`) });
|
|
567
|
+
const result = resolveRules(config, files, o.matched !== void 0 ? csv(o.matched) : void 0, root ?? path2.resolve(cwd));
|
|
568
|
+
opts.stdout(escapeJsonControls(JSON.stringify(terseResult(result), null, 2)) + "\n");
|
|
569
|
+
} catch (e) {
|
|
570
|
+
opts.stderr(`codechart: ${e.message}
|
|
571
|
+
`);
|
|
572
|
+
process.exitCode = 2;
|
|
573
|
+
}
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// src/commands/config.ts
|
|
578
|
+
import { Command as Command2 } from "commander";
|
|
579
|
+
|
|
580
|
+
// src/render/terminal/wrap.ts
|
|
581
|
+
var flat = (s) => stripInvisible(s).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ");
|
|
582
|
+
var ANSI = /\u001b\[[0-9;]*m/g;
|
|
583
|
+
var ZERO = /* @__PURE__ */ new Set([65039, 8205]);
|
|
584
|
+
var WIDE = [
|
|
585
|
+
[4352, 4447],
|
|
586
|
+
[9881, 9881],
|
|
587
|
+
[9898, 9899],
|
|
588
|
+
[9989, 9989],
|
|
589
|
+
[9999, 9999],
|
|
590
|
+
[10060, 10060],
|
|
591
|
+
[11904, 42191],
|
|
592
|
+
[44032, 55203],
|
|
593
|
+
[63744, 64255],
|
|
594
|
+
[65280, 65376],
|
|
595
|
+
[65504, 65510],
|
|
596
|
+
[127744, 129791],
|
|
597
|
+
[131072, 262141]
|
|
598
|
+
];
|
|
599
|
+
var charWidth = (ch) => {
|
|
600
|
+
const cp = ch.codePointAt(0);
|
|
601
|
+
if (ZERO.has(cp)) return 0;
|
|
602
|
+
return WIDE.some(([lo, hi]) => cp >= lo && cp <= hi) ? 2 : 1;
|
|
603
|
+
};
|
|
604
|
+
var columns = (s) => [...s.replace(ANSI, "")].reduce((n, ch) => n + charWidth(ch), 0);
|
|
605
|
+
function split(text, width) {
|
|
606
|
+
const chars = [...text];
|
|
607
|
+
let used = 0;
|
|
608
|
+
let i = 0;
|
|
609
|
+
for (; i < chars.length; i++) {
|
|
610
|
+
used += charWidth(chars[i]);
|
|
611
|
+
if (used > width) break;
|
|
612
|
+
}
|
|
613
|
+
return [chars.slice(0, i).join(""), chars.slice(i).join("")];
|
|
614
|
+
}
|
|
615
|
+
function truncate(text, width, cuts) {
|
|
616
|
+
if (columns(text) <= width) return text;
|
|
617
|
+
if (cuts) cuts.truncated = true;
|
|
618
|
+
return `${split(text, Math.max(width - 1, 0))[0]}\u2026`;
|
|
619
|
+
}
|
|
620
|
+
function renderPieces(pieces) {
|
|
621
|
+
const merged = [];
|
|
622
|
+
for (const p of pieces) {
|
|
623
|
+
const last = merged.at(-1);
|
|
624
|
+
if (last && p.item && last.item === p.item) last.text += p.text;
|
|
625
|
+
else merged.push({ ...p });
|
|
626
|
+
}
|
|
627
|
+
return merged.map((p) => p.item?.paint ? p.item.paint(p.text) : p.text).join("");
|
|
628
|
+
}
|
|
629
|
+
function wrapItems(head, items, width) {
|
|
630
|
+
const indent = " ".repeat(columns(head));
|
|
631
|
+
const lines = [];
|
|
632
|
+
let line = [{ text: head }];
|
|
633
|
+
let fresh = true;
|
|
634
|
+
const room = () => width - line.reduce((n, p) => n + columns(p.text), 0);
|
|
635
|
+
const append = (text, item2) => {
|
|
636
|
+
line.push({ text, item: item2 });
|
|
637
|
+
fresh = false;
|
|
638
|
+
};
|
|
639
|
+
const newLine = () => {
|
|
640
|
+
lines.push(renderPieces(line));
|
|
641
|
+
line = [{ text: indent }];
|
|
642
|
+
fresh = true;
|
|
643
|
+
};
|
|
644
|
+
items.forEach((raw, i) => {
|
|
645
|
+
const item2 = typeof raw === "string" ? { text: raw } : raw;
|
|
646
|
+
const sep3 = i === 0 ? "" : " \xB7 ";
|
|
647
|
+
if (columns(sep3 + item2.text) <= room()) {
|
|
648
|
+
append(sep3);
|
|
649
|
+
return append(item2.text, item2);
|
|
650
|
+
}
|
|
651
|
+
if (!fresh) newLine();
|
|
652
|
+
if (columns(item2.text) <= room()) return append(item2.text, item2);
|
|
653
|
+
for (const word of item2.text.split(" ")) {
|
|
654
|
+
if (!fresh && columns(` ${word}`) > room()) newLine();
|
|
655
|
+
if (!fresh) append(" ", item2);
|
|
656
|
+
const chars = [...word];
|
|
657
|
+
let at = 0;
|
|
658
|
+
let remaining = columns(word);
|
|
659
|
+
while (remaining > room() && fresh) {
|
|
660
|
+
const w = room();
|
|
661
|
+
let used = 0;
|
|
662
|
+
let end = at;
|
|
663
|
+
while (end < chars.length && used + charWidth(chars[end]) <= w) used += charWidth(chars[end++]);
|
|
664
|
+
if (end === at) used = charWidth(chars[end++]);
|
|
665
|
+
append(chars.slice(at, end).join(""), item2);
|
|
666
|
+
remaining -= used;
|
|
667
|
+
at = end;
|
|
668
|
+
if (at < chars.length) newLine();
|
|
669
|
+
}
|
|
670
|
+
if (at < chars.length) append(chars.slice(at).join(""), item2);
|
|
671
|
+
}
|
|
672
|
+
});
|
|
673
|
+
lines.push(renderPieces(line));
|
|
674
|
+
return lines.join("\n");
|
|
675
|
+
}
|
|
676
|
+
function fit(segments, width, cuts) {
|
|
677
|
+
let left = width;
|
|
678
|
+
let out = "";
|
|
679
|
+
for (const { text, paint: paint2 } of segments) {
|
|
680
|
+
const cut2 = columns(text) <= left ? text : truncate(text, Math.max(left, 1), cuts);
|
|
681
|
+
out += paint2 ? paint2(cut2) : cut2;
|
|
682
|
+
if (cut2 !== text) break;
|
|
683
|
+
left -= columns(text);
|
|
684
|
+
}
|
|
685
|
+
return out;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// src/commands/config.ts
|
|
689
|
+
function formatText({ config, sources, ruleSources }) {
|
|
690
|
+
const values = {
|
|
691
|
+
...Object.fromEntries(Object.entries(config.defaults).map(([k, v]) => [`defaults.${k}`, v])),
|
|
692
|
+
...Object.fromEntries(Object.entries(config.web).map(([k, v]) => [`web.${k}`, v])),
|
|
693
|
+
useBuiltinRules: config.useBuiltinRules
|
|
694
|
+
};
|
|
695
|
+
if (!config.useBuiltinRules) values["defaults.flows"] = "inactive (built-in rules off)";
|
|
696
|
+
const globalOnly = (key) => GLOBAL_ONLY.includes(key) ? "; global-only" : "";
|
|
697
|
+
const lines = Object.entries(values).map(([key, value]) => `${key}: ${value} (${sources[key]}${globalOnly(key)})`);
|
|
698
|
+
lines.push("rules (evaluation order):");
|
|
699
|
+
config.rules.forEach((rule, i) => {
|
|
700
|
+
const match = rule.paths ? `paths: ${rule.paths.join(", ")}` : `when: ${JSON.stringify(rule.when)}`;
|
|
701
|
+
const diagram = rule.diagram ?? "map";
|
|
702
|
+
const context = diagram === "map" ? ` context: ${rule.context ?? config.defaults.context}` : "";
|
|
703
|
+
lines.push(` ${rule.name} ${diagram} ${match} ${rule.output ?? config.defaults.output}${context} (${ruleSources[i]})`);
|
|
704
|
+
});
|
|
705
|
+
return lines.map(flat).join("\n") + "\n";
|
|
706
|
+
}
|
|
707
|
+
function configCommand(opts) {
|
|
708
|
+
return new Command2("config").description("print the config in effect and where each value comes from").option("--json", "print as JSON").action((o) => {
|
|
709
|
+
try {
|
|
710
|
+
const result = loadConfigWithSources({
|
|
711
|
+
cwd: opts.cwd ?? process.cwd(),
|
|
712
|
+
home: opts.home,
|
|
713
|
+
env: opts.env,
|
|
714
|
+
warn: (l) => opts.stderr(`codechart: ${l}
|
|
715
|
+
`)
|
|
716
|
+
});
|
|
717
|
+
opts.stdout(o.json ? escapeJsonControls(JSON.stringify(result, null, 2)) + "\n" : formatText(result));
|
|
718
|
+
} catch (e) {
|
|
719
|
+
opts.stderr(e.message.split("\n").map((l) => `codechart: ${l}
|
|
720
|
+
`).join(""));
|
|
721
|
+
process.exitCode = 1;
|
|
722
|
+
}
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// src/commands/init.ts
|
|
727
|
+
import { join as join3 } from "path";
|
|
728
|
+
import { Command as Command3 } from "commander";
|
|
729
|
+
|
|
730
|
+
// src/assets.ts
|
|
731
|
+
import { existsSync as existsSync3 } from "fs";
|
|
732
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
733
|
+
import { fileURLToPath } from "url";
|
|
734
|
+
function packageFile(relative3) {
|
|
735
|
+
let dir = dirname2(fileURLToPath(import.meta.url));
|
|
736
|
+
while (!existsSync3(join2(dir, "package.json"))) {
|
|
737
|
+
const parent = dirname2(dir);
|
|
738
|
+
if (parent === dir) throw new Error("package root not found");
|
|
739
|
+
dir = parent;
|
|
740
|
+
}
|
|
741
|
+
return join2(dir, relative3);
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// src/commands/copy-file.ts
|
|
745
|
+
import { constants, copyFileSync, existsSync as existsSync4, lstatSync, mkdirSync, unlinkSync } from "fs";
|
|
746
|
+
import { dirname as dirname3 } from "path";
|
|
747
|
+
var isSymlink = (path3) => lstatSync(path3, { throwIfNoEntry: false })?.isSymbolicLink() === true;
|
|
748
|
+
function copyFiles(pairs, force, opts) {
|
|
749
|
+
try {
|
|
750
|
+
const link = force ? void 0 : pairs.find(({ target }) => isSymlink(target));
|
|
751
|
+
if (link) {
|
|
752
|
+
opts.stderr(`codechart: ${link.target}: is a symlink (use --force to replace it)
|
|
753
|
+
`);
|
|
754
|
+
process.exitCode = 1;
|
|
755
|
+
return false;
|
|
756
|
+
}
|
|
757
|
+
const conflict = force ? void 0 : pairs.find(({ target }) => existsSync4(target));
|
|
758
|
+
if (conflict) {
|
|
759
|
+
opts.stderr(`exists: ${conflict.target} (use --force)
|
|
760
|
+
`);
|
|
761
|
+
process.exitCode = 1;
|
|
762
|
+
return false;
|
|
763
|
+
}
|
|
764
|
+
for (const { source, target } of pairs) {
|
|
765
|
+
mkdirSync(dirname3(target), { recursive: true });
|
|
766
|
+
if (force && isSymlink(target)) unlinkSync(target);
|
|
767
|
+
copyFileSync(source, target, force ? 0 : constants.COPYFILE_EXCL);
|
|
768
|
+
opts.stdout(`wrote ${target}
|
|
769
|
+
`);
|
|
770
|
+
}
|
|
771
|
+
return true;
|
|
772
|
+
} catch (e) {
|
|
773
|
+
opts.stderr(`codechart: ${e.message}
|
|
774
|
+
`);
|
|
775
|
+
process.exitCode = 1;
|
|
776
|
+
return false;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// src/commands/init.ts
|
|
781
|
+
function initCommand(opts) {
|
|
782
|
+
return new Command3("init").description("write a commented starter .codechart.yaml at the git root").option("--force", "overwrite an existing .codechart.yaml").action((o) => {
|
|
783
|
+
const root = findRepoRoot(opts.cwd ?? process.cwd());
|
|
784
|
+
if (!root) {
|
|
785
|
+
opts.stderr("codechart: not a git repository\n");
|
|
786
|
+
process.exitCode = 1;
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
copyFiles([{ source: packageFile("templates/codechart.yaml"), target: join3(root, ".codechart.yaml") }], o.force === true, opts);
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// src/commands/install-skill.ts
|
|
794
|
+
import { existsSync as existsSync5, lstatSync as lstatSync2, readdirSync } from "fs";
|
|
795
|
+
import { homedir as homedir2 } from "os";
|
|
796
|
+
import { join as join4, resolve as resolve2 } from "path";
|
|
797
|
+
import { Command as Command4 } from "commander";
|
|
798
|
+
|
|
799
|
+
// src/commands/agents.ts
|
|
800
|
+
var SHARED = ".agents/skills";
|
|
801
|
+
var AGENTS = [
|
|
802
|
+
{ name: "claude", label: "Claude Code", home: ".claude", skills: ".claude/skills", reads: [] },
|
|
803
|
+
{ name: "codex", label: "Codex", home: ".codex", skills: SHARED, reads: [] },
|
|
804
|
+
{ name: "gemini", label: "Gemini CLI", home: ".gemini", skills: ".gemini/skills", reads: [SHARED] },
|
|
805
|
+
{ name: "copilot", label: "GitHub Copilot", home: ".copilot", skills: ".copilot/skills", reads: [SHARED] },
|
|
806
|
+
{ name: "cursor", label: "Cursor", home: ".cursor", skills: ".cursor/skills", reads: [SHARED, ".claude/skills", ".codex/skills"] },
|
|
807
|
+
{ name: "opencode", label: "OpenCode", home: ".config/opencode", skills: ".config/opencode/skills", reads: [SHARED, ".claude/skills"] },
|
|
808
|
+
{ name: "goose", label: "Goose", home: ".config/goose", skills: SHARED, reads: [".claude/skills"] },
|
|
809
|
+
{ name: "amp", label: "Amp", home: ".config/amp", skills: ".config/agents/skills", reads: [".claude/skills"] },
|
|
810
|
+
{ name: "windsurf", label: "Windsurf", home: ".codeium/windsurf", skills: ".codeium/windsurf/skills", reads: [SHARED] },
|
|
811
|
+
{ name: "cline", label: "Cline", home: ".cline", skills: ".cline/skills", reads: [] },
|
|
812
|
+
{ name: "roo", label: "Roo Code", home: ".roo", skills: ".roo/skills", reads: [SHARED] },
|
|
813
|
+
{ name: "kiro", label: "Kiro", home: ".kiro", skills: ".kiro/skills", reads: [] },
|
|
814
|
+
{ name: "junie", label: "Junie", home: ".junie", skills: ".junie/skills", reads: [] },
|
|
815
|
+
{ name: "droid", label: "Factory Droid", home: ".factory", skills: ".factory/skills", reads: [] }
|
|
816
|
+
];
|
|
817
|
+
function skillFolders(agents) {
|
|
818
|
+
const groups = [];
|
|
819
|
+
for (const a of agents) {
|
|
820
|
+
const shared = groups.find((g) => [a.skills, ...a.reads].includes(g.folder));
|
|
821
|
+
if (shared) shared.agents.push(a);
|
|
822
|
+
else groups.push({ folder: a.skills, agents: [a] });
|
|
823
|
+
}
|
|
824
|
+
return groups;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
// src/commands/picker.ts
|
|
828
|
+
import { emitKeypressEvents } from "readline";
|
|
829
|
+
function pickerStep(s, key) {
|
|
830
|
+
const n = s.checked.length;
|
|
831
|
+
switch (key.ctrl ? `ctrl-${key.name}` : key.name ?? key.sequence) {
|
|
832
|
+
case "up":
|
|
833
|
+
case "k":
|
|
834
|
+
return { ...s, cursor: (s.cursor + n - 1) % n };
|
|
835
|
+
case "down":
|
|
836
|
+
case "j":
|
|
837
|
+
return { ...s, cursor: (s.cursor + 1) % n };
|
|
838
|
+
case "space":
|
|
839
|
+
return { ...s, checked: s.checked.map((c, i) => i === s.cursor ? !c : c) };
|
|
840
|
+
case "a": {
|
|
841
|
+
const all = s.checked.every(Boolean);
|
|
842
|
+
return { ...s, checked: s.checked.map(() => !all) };
|
|
843
|
+
}
|
|
844
|
+
case "return":
|
|
845
|
+
return { ...s, done: "ok" };
|
|
846
|
+
case "escape":
|
|
847
|
+
case "ctrl-c":
|
|
848
|
+
return { ...s, done: "cancel" };
|
|
849
|
+
default:
|
|
850
|
+
return s;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
var cut = (text, max) => text.length <= max ? text : `${text.slice(0, Math.max(0, max - 1))}\u2026`;
|
|
854
|
+
var dim = (text) => text ? `\x1B[2m${text}\x1B[0m` : "";
|
|
855
|
+
function pickerLines(title, items, s, width = Infinity) {
|
|
856
|
+
const pad2 = Math.max(...items.map((i) => i.label.length));
|
|
857
|
+
return [
|
|
858
|
+
cut(title, width),
|
|
859
|
+
...items.map((it, i) => {
|
|
860
|
+
const head = cut(`${i === s.cursor ? "\u276F" : " "} ${s.checked[i] ? "\u25C9" : "\u25EF"} ${it.label.padEnd(pad2)} `, width);
|
|
861
|
+
return head + dim(cut(it.hint, width - head.length));
|
|
862
|
+
}),
|
|
863
|
+
dim(cut("\u2191/\u2193 move \xB7 Space toggle \xB7 a all \xB7 Enter install \xB7 Esc cancel", width))
|
|
864
|
+
];
|
|
865
|
+
}
|
|
866
|
+
function terminalPicker(title, items) {
|
|
867
|
+
const { stdin, stdout } = process;
|
|
868
|
+
let s = { cursor: 0, checked: items.map(() => true) };
|
|
869
|
+
let drawn = 0;
|
|
870
|
+
const draw = () => {
|
|
871
|
+
const lines = pickerLines(title, items, s, (stdout.columns || 80) - 1);
|
|
872
|
+
stdout.write((drawn ? `\x1B[${drawn}A\r\x1B[0J` : "") + lines.join("\n") + "\n");
|
|
873
|
+
drawn = lines.length;
|
|
874
|
+
};
|
|
875
|
+
return new Promise((resolve7) => {
|
|
876
|
+
emitKeypressEvents(stdin);
|
|
877
|
+
stdin.setRawMode(true);
|
|
878
|
+
stdin.resume();
|
|
879
|
+
stdout.write("\x1B[?25l");
|
|
880
|
+
draw();
|
|
881
|
+
const onKey = (_, key) => {
|
|
882
|
+
s = pickerStep(s, key ?? {});
|
|
883
|
+
if (!s.done) return draw();
|
|
884
|
+
stdin.off("keypress", onKey);
|
|
885
|
+
stdin.setRawMode(false);
|
|
886
|
+
stdin.pause();
|
|
887
|
+
stdout.write("\x1B[?25h");
|
|
888
|
+
resolve7(s.done === "ok" ? s.checked.flatMap((c, i) => c ? [i] : []) : void 0);
|
|
889
|
+
};
|
|
890
|
+
stdin.on("keypress", onKey);
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// src/commands/install-skill.ts
|
|
895
|
+
var NAMES = AGENTS.map((a) => a.name).join(", ");
|
|
896
|
+
var terminalChoose = () => process.stdin.isTTY && process.stdout.isTTY ? terminalPicker : void 0;
|
|
897
|
+
var hasAny = (paths) => paths.some((p) => {
|
|
898
|
+
try {
|
|
899
|
+
return lstatSync2(p, { throwIfNoEntry: false }) !== void 0;
|
|
900
|
+
} catch {
|
|
901
|
+
return false;
|
|
902
|
+
}
|
|
903
|
+
});
|
|
904
|
+
function installSkillCommand(opts) {
|
|
905
|
+
return new Command4("install-skill").description("install the skill for the agents found in your home folder (or --agent / --dir)").option("--agent <names...>", `install for these agents: ${NAMES}`).option("--dir <path>", "install into this skills folder").option("--force", "overwrite an existing install").action(async (o) => {
|
|
906
|
+
const home = opts.home ?? homedir2();
|
|
907
|
+
const names = o.agent?.flatMap((n) => n.split(",")).map((n) => n.trim().toLowerCase()).filter(Boolean);
|
|
908
|
+
const unknown = names?.find((n) => !AGENTS.some((a) => a.name === n));
|
|
909
|
+
if (unknown !== void 0) {
|
|
910
|
+
opts.stderr(`codechart: unknown agent '${unknown}' (known: ${NAMES})
|
|
911
|
+
`);
|
|
912
|
+
process.exitCode = 1;
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
let agents = names ? AGENTS.filter((a) => names.includes(a.name)) : o.dir === void 0 ? AGENTS.filter((a) => existsSync5(join4(home, a.home))) : [];
|
|
916
|
+
if (agents.length === 0 && o.dir === void 0) {
|
|
917
|
+
opts.stderr(`codechart: no agent found in ${home}; use --agent <name> (${NAMES}) or --dir <path>
|
|
918
|
+
`);
|
|
919
|
+
process.exitCode = 1;
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
if (!names && agents.length > 0) {
|
|
923
|
+
const choose = opts.choose ?? terminalChoose();
|
|
924
|
+
if (choose && agents.length > 1) {
|
|
925
|
+
const found = agents;
|
|
926
|
+
const picked = await choose(
|
|
927
|
+
"Install the codechart skill for:",
|
|
928
|
+
found.map((a) => ({ label: a.label, hint: `~/${a.skills}` }))
|
|
929
|
+
);
|
|
930
|
+
if (picked === void 0) {
|
|
931
|
+
opts.stderr("codechart: cancelled, nothing installed\n");
|
|
932
|
+
process.exitCode = 1;
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
if (picked.length === 0) {
|
|
936
|
+
opts.stdout("nothing selected, nothing installed\n");
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
agents = picked.map((i) => found[i]);
|
|
940
|
+
} else {
|
|
941
|
+
opts.stdout(`agents: ${agents.map((a) => a.label).join(", ")}
|
|
942
|
+
`);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
const files = readdirSync(packageFile("skills/codechart")).sort((a, b) => Number(b === "SKILL.md") - Number(a === "SKILL.md"));
|
|
946
|
+
const groups = skillFolders(agents);
|
|
947
|
+
for (const folder of new Set(agents.flatMap((a) => [a.skills, ...a.reads]))) {
|
|
948
|
+
if (groups.some((g) => g.folder === folder) || !hasAny(files.map((f) => join4(home, folder, "codechart", f)))) continue;
|
|
949
|
+
groups.push({ folder, agents: agents.filter((a) => [a.skills, ...a.reads].includes(folder)) });
|
|
950
|
+
}
|
|
951
|
+
const targets = groups.map((g) => ({ dir: join4(home, g.folder, "codechart"), who: g.agents.map((a) => a.label).join(", ") }));
|
|
952
|
+
if (o.dir !== void 0) targets.push({ dir: join4(resolve2(opts.cwd ?? process.cwd(), o.dir), "codechart"), who: "your folder" });
|
|
953
|
+
for (const { dir, who } of targets) {
|
|
954
|
+
const pairs = files.map((f) => ({ source: packageFile(`skills/codechart/${f}`), target: join4(dir, f) }));
|
|
955
|
+
if (o.force !== true && hasAny(pairs.map((p) => p.target))) {
|
|
956
|
+
opts.stdout(`already installed for ${who}: ${dir} (--force to update)
|
|
957
|
+
`);
|
|
958
|
+
continue;
|
|
959
|
+
}
|
|
960
|
+
if (copyFiles(pairs, o.force === true, { ...opts, stdout: () => {
|
|
961
|
+
} })) opts.stdout(`installed for ${who}: ${dir}
|
|
962
|
+
`);
|
|
963
|
+
}
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// src/commands/render.ts
|
|
968
|
+
import { chmodSync, constants as constants2, closeSync, fstatSync, lstatSync as lstatSync4, mkdirSync as mkdirSync2, openSync, readSync, writeFileSync } from "fs";
|
|
969
|
+
import { basename as basename2, dirname as dirname4, resolve as resolve6 } from "path";
|
|
970
|
+
import { Command as Command5, Option } from "commander";
|
|
971
|
+
|
|
972
|
+
// src/render/flow/anchors.ts
|
|
973
|
+
import { readFileSync as readFileSync2, realpathSync as realpathSync2, statSync as statSync2 } from "fs";
|
|
974
|
+
import { isAbsolute as isAbsolute2, relative as relative2, resolve as resolve3, sep as sep2 } from "path";
|
|
975
|
+
var SNIPPET_MAX_LINES = 15;
|
|
976
|
+
var MAX_BYTES2 = 5 * 1024 * 1024;
|
|
977
|
+
var MAX_TOTAL_BYTES = 25 * 1024 * 1024;
|
|
978
|
+
var escapes = (rel) => rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute2(rel);
|
|
979
|
+
var inGit = (rel) => rel.split(sep2).some((s) => s.toLowerCase() === ".git");
|
|
980
|
+
var toLines = (text) => {
|
|
981
|
+
const lines = text.split(/\r?\n/);
|
|
982
|
+
if (lines[lines.length - 1] === "") lines.pop();
|
|
983
|
+
return lines;
|
|
984
|
+
};
|
|
985
|
+
var overBudget = (path3) => ({
|
|
986
|
+
error: `${path3} not read: the anchored files pass ${MAX_TOTAL_BYTES / 1024 / 1024} MB together; anchor fewer or smaller files`
|
|
987
|
+
});
|
|
988
|
+
function readLinesAt(path3, rel, root, sha, budget) {
|
|
989
|
+
try {
|
|
990
|
+
if (budget.left <= 0) return overBudget(path3);
|
|
991
|
+
const r = gitFileAt(root, sha, rel.split(sep2).join("/"), MAX_BYTES2);
|
|
992
|
+
if (typeof r !== "string") return r;
|
|
993
|
+
budget.left -= Buffer.byteLength(r);
|
|
994
|
+
return budget.left < 0 ? overBudget(path3) : toLines(r);
|
|
995
|
+
} catch (e) {
|
|
996
|
+
return { error: `${path3} cannot be read at ${sha.slice(0, 12)} (${e.message})` };
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
function readLines(path3, root, realRoot, budget) {
|
|
1000
|
+
let real;
|
|
1001
|
+
try {
|
|
1002
|
+
real = realpathSync2(resolve3(root, path3));
|
|
1003
|
+
} catch (e) {
|
|
1004
|
+
const code = e.code;
|
|
1005
|
+
return code === "ENOENT" || code === "ENOTDIR" ? null : { error: `${path3} cannot be read (${code})` };
|
|
1006
|
+
}
|
|
1007
|
+
const rel = relative2(realRoot, real);
|
|
1008
|
+
if (escapes(rel)) return { error: `${path3} is outside the repo` };
|
|
1009
|
+
if (inGit(rel)) return { error: `${path3} is inside .git` };
|
|
1010
|
+
try {
|
|
1011
|
+
const st = statSync2(real);
|
|
1012
|
+
if (!st.isFile()) return { error: `${path3} is not a regular file` };
|
|
1013
|
+
if (st.size > MAX_BYTES2) return { error: `${path3} is too large (over 5 MB)` };
|
|
1014
|
+
if (st.size > budget.left) return overBudget(path3);
|
|
1015
|
+
budget.left -= st.size;
|
|
1016
|
+
return toLines(readFileSync2(real, "utf8"));
|
|
1017
|
+
} catch (e) {
|
|
1018
|
+
return { error: `${path3} cannot be read (${e.code})` };
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
var MAX_LISTED = 10;
|
|
1022
|
+
var SNIPPET_MAX_CHARS = 300;
|
|
1023
|
+
var clip = (l) => l.length > SNIPPET_MAX_CHARS ? `${l.slice(0, SNIPPET_MAX_CHARS)}\u2026` : l;
|
|
1024
|
+
function lineList(hits) {
|
|
1025
|
+
const shown2 = hits.slice(0, MAX_LISTED).join(", ");
|
|
1026
|
+
return hits.length > MAX_LISTED ? `${shown2} and ${hits.length - MAX_LISTED} more` : shown2;
|
|
1027
|
+
}
|
|
1028
|
+
function findMatch(path3, match, lines) {
|
|
1029
|
+
const needle = match.trim();
|
|
1030
|
+
const hits = [];
|
|
1031
|
+
lines.forEach((l, i) => {
|
|
1032
|
+
if (l.includes(needle)) hits.push(i + 1);
|
|
1033
|
+
});
|
|
1034
|
+
if (hits.length === 0) return { field: "match", error: `"${needle}" not found in ${path3}` };
|
|
1035
|
+
if (hits.length > 1) {
|
|
1036
|
+
return {
|
|
1037
|
+
field: "match",
|
|
1038
|
+
error: `"${needle}" is on ${hits.length} lines of ${path3} (${lineList(hits)}); quote a more distinctive piece of the line or drop match and use source '${path3}:${hits[0]}'`
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
const line = hits[0];
|
|
1042
|
+
return { snippet: { source: `${path3}:${line}`, startLine: line, lines: [clip(lines[line - 1])] } };
|
|
1043
|
+
}
|
|
1044
|
+
function read(c, path3) {
|
|
1045
|
+
const rel = relative2(c.root, resolve3(c.root, path3));
|
|
1046
|
+
if (isAbsolute2(path3) || escapes(rel)) return { error: `${path3} is outside the repo` };
|
|
1047
|
+
if (inGit(rel)) return { error: `${path3} is inside .git` };
|
|
1048
|
+
return c.at ? readLinesAt(path3, rel, c.root, c.at, c.budget) : readLines(path3, c.root, c.realRoot, c.budget);
|
|
1049
|
+
}
|
|
1050
|
+
function load(c, path3) {
|
|
1051
|
+
const hit = c.cache.get(path3);
|
|
1052
|
+
if (hit) return hit;
|
|
1053
|
+
const direct = read(c, path3);
|
|
1054
|
+
let loaded = { path: path3, lines: direct };
|
|
1055
|
+
const outside = !isAbsolute2(path3) && escapes(relative2(c.root, resolve3(c.root, path3)));
|
|
1056
|
+
if (c.cwd && (direct === null || outside)) {
|
|
1057
|
+
const rel = relative2(c.root, resolve3(c.cwd, path3));
|
|
1058
|
+
if (rel !== "" && !escapes(rel)) {
|
|
1059
|
+
const alt = rel.split(sep2).join("/");
|
|
1060
|
+
const lines = read(c, alt);
|
|
1061
|
+
if (lines !== null) loaded = { path: alt, lines };
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
c.cache.set(path3, loaded);
|
|
1065
|
+
return loaded;
|
|
1066
|
+
}
|
|
1067
|
+
var MAX_LISTED_FILES = 2e5;
|
|
1068
|
+
function likelyPath(c, path3) {
|
|
1069
|
+
const slashed = path3.replaceAll("\\", "/");
|
|
1070
|
+
if (isAbsolute2(path3) || slashed.split("/").includes("..")) return "";
|
|
1071
|
+
const tail = `/${slashed.replace(/^(\.\/)+/, "")}`;
|
|
1072
|
+
if (!c.listing) {
|
|
1073
|
+
try {
|
|
1074
|
+
c.listing = gitListFiles(c.root, c.at);
|
|
1075
|
+
} catch {
|
|
1076
|
+
c.listing = [];
|
|
1077
|
+
}
|
|
1078
|
+
if (c.listing.length > MAX_LISTED_FILES) c.listing = [];
|
|
1079
|
+
}
|
|
1080
|
+
const hits = c.listing.filter((f) => f.endsWith(tail) && !hasHiddenChars(f));
|
|
1081
|
+
return hits.length === 1 ? `; did you mean ${hits[0]}` : "";
|
|
1082
|
+
}
|
|
1083
|
+
function resolveAnchor(source, match, c) {
|
|
1084
|
+
let path3 = source;
|
|
1085
|
+
let a = "";
|
|
1086
|
+
let b;
|
|
1087
|
+
if (match === void 0) {
|
|
1088
|
+
const m = /^(.+):(\d+)(?:-(\d+))?$/.exec(source);
|
|
1089
|
+
if (!m) return { error: `${source} not found (not path:line or path:start-end)` };
|
|
1090
|
+
[, path3, a, b] = m;
|
|
1091
|
+
}
|
|
1092
|
+
const loaded = load(c, path3);
|
|
1093
|
+
const lines = loaded.lines;
|
|
1094
|
+
const notFound = (why) => ({ error: `${source} not found (${why})` });
|
|
1095
|
+
if (lines === null) {
|
|
1096
|
+
const where = c.at ? `file does not exist at ${c.at.slice(0, 12)}` : "file does not exist";
|
|
1097
|
+
return notFound(`${where}; repo root is ${c.root}${likelyPath(c, path3)}`);
|
|
1098
|
+
}
|
|
1099
|
+
if (!Array.isArray(lines)) return lines;
|
|
1100
|
+
if (match !== void 0) return findMatch(loaded.path, match, lines);
|
|
1101
|
+
const start = Number(a);
|
|
1102
|
+
const end = b === void 0 ? start : Number(b);
|
|
1103
|
+
if (start < 1) return notFound("lines start at 1");
|
|
1104
|
+
if (start > end) return notFound("start is after end");
|
|
1105
|
+
if (end > lines.length) return notFound(`file has ${lines.length} lines`);
|
|
1106
|
+
return {
|
|
1107
|
+
snippet: {
|
|
1108
|
+
source: loaded.path === path3 ? source : `${loaded.path}:${a}${b === void 0 ? "" : `-${b}`}`,
|
|
1109
|
+
startLine: start,
|
|
1110
|
+
lines: lines.slice(start - 1, Math.min(end, start - 1 + SNIPPET_MAX_LINES)).map(clip)
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
function checkFlowAnchors(spec, root, at, cwd) {
|
|
1115
|
+
const ctx = {
|
|
1116
|
+
root,
|
|
1117
|
+
realRoot: realpathSync2(root),
|
|
1118
|
+
at,
|
|
1119
|
+
budget: { left: MAX_TOTAL_BYTES },
|
|
1120
|
+
cwd: cwd !== void 0 && resolve3(cwd) !== resolve3(root) ? resolve3(cwd) : void 0,
|
|
1121
|
+
cache: /* @__PURE__ */ new Map()
|
|
1122
|
+
};
|
|
1123
|
+
const errors = [];
|
|
1124
|
+
const snippets = { steps: /* @__PURE__ */ new Map(), links: {} };
|
|
1125
|
+
const check = (label, { source, match }, store) => {
|
|
1126
|
+
if (!source) return;
|
|
1127
|
+
const r = resolveAnchor(source, match, ctx);
|
|
1128
|
+
if ("error" in r) errors.push(`${label}.${r.field ?? "source"}: ${r.error}`);
|
|
1129
|
+
else store(r.snippet);
|
|
1130
|
+
};
|
|
1131
|
+
spec.steps.forEach((step, i) => check(`steps[${i}]`, step, (s) => snippets.steps.set(step.id, s)));
|
|
1132
|
+
spec.links.forEach((link, i) => check(`links[${i}]`, link, (s) => snippets.links[i] = s));
|
|
1133
|
+
return errors.length ? { ok: false, errors } : { ok: true, snippets };
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
// src/render/markdown.ts
|
|
1137
|
+
import { resolve as resolve4 } from "path";
|
|
1138
|
+
import { pathToFileURL } from "url";
|
|
1139
|
+
var longestTicks = (s) => Math.max(0, ...(s.match(/`+/g) ?? []).map((run) => run.length));
|
|
1140
|
+
function markdownBlock(header, body, htmlPath) {
|
|
1141
|
+
const lines = [header];
|
|
1142
|
+
if (body !== void 0) {
|
|
1143
|
+
const fence = "`".repeat(Math.max(3, longestTicks(body) + 1));
|
|
1144
|
+
lines.push(`${fence}text
|
|
1145
|
+
${body.trimEnd()}
|
|
1146
|
+
${fence}`);
|
|
1147
|
+
}
|
|
1148
|
+
if (htmlPath) {
|
|
1149
|
+
const href = pathToFileURL(resolve4(htmlPath)).href;
|
|
1150
|
+
lines.push("", `[Open full map](${href.replace(/\(/g, "%28").replace(/\)/g, "%29")})`);
|
|
1151
|
+
}
|
|
1152
|
+
return `${lines.join("\n")}
|
|
1153
|
+
`;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
// src/render/output-path.ts
|
|
1157
|
+
import { createHash } from "crypto";
|
|
1158
|
+
import { basename, join as join5 } from "path";
|
|
1159
|
+
var HTML_NAME = /^(\d{8}-\d{6})-([a-z0-9-]+(?:\.flow)?)\.html$/;
|
|
1160
|
+
var pad = (n) => String(n).padStart(2, "0");
|
|
1161
|
+
function stamp(d) {
|
|
1162
|
+
return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
|
1163
|
+
}
|
|
1164
|
+
function parseStamp(s) {
|
|
1165
|
+
const n = (from, to) => Number(s.slice(from, to));
|
|
1166
|
+
return new Date(n(0, 4), n(4, 6) - 1, n(6, 8), n(9, 11), n(11, 13), n(13, 15));
|
|
1167
|
+
}
|
|
1168
|
+
function slugify(title) {
|
|
1169
|
+
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40).replace(/^-+|-+$/g, "");
|
|
1170
|
+
return slug || "map";
|
|
1171
|
+
}
|
|
1172
|
+
function needsWeb(spec, hidden, minNodes) {
|
|
1173
|
+
return hidden > 0 || spec.nodes.length >= minNodes;
|
|
1174
|
+
}
|
|
1175
|
+
var fileSlug = (title, diagram) => diagram === "flow" ? `${slugify(title)}.flow` : slugify(title);
|
|
1176
|
+
function htmlOutputPath(config, repo, slug, now) {
|
|
1177
|
+
return join5(config.web.outDir, repo, `${stamp(now)}-${slug}.html`);
|
|
1178
|
+
}
|
|
1179
|
+
function repoFolder(root) {
|
|
1180
|
+
return `${basename(root)}-${createHash("sha256").update(root).digest("hex").slice(0, 8)}`;
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
// src/render/prune.ts
|
|
1184
|
+
import { lstatSync as lstatSync3, readdirSync as readdirSync2, rmSync } from "fs";
|
|
1185
|
+
import { join as join6 } from "path";
|
|
1186
|
+
var DAY_MS = 864e5;
|
|
1187
|
+
function pruneHtml(dir, opts) {
|
|
1188
|
+
let names;
|
|
1189
|
+
try {
|
|
1190
|
+
if (lstatSync3(dir).isSymbolicLink()) return [];
|
|
1191
|
+
names = readdirSync2(dir);
|
|
1192
|
+
} catch {
|
|
1193
|
+
return [];
|
|
1194
|
+
}
|
|
1195
|
+
const current = stamp(opts.now);
|
|
1196
|
+
const files = names.map((name) => ({ name, m: HTML_NAME.exec(name) })).filter((f) => f.m !== null).map(({ name, m }) => ({ name, stamp: m[1], slug: m[2] })).sort((a, b) => b.stamp.localeCompare(a.stamp));
|
|
1197
|
+
const doomed = /* @__PURE__ */ new Set();
|
|
1198
|
+
for (const f of files) if (f.slug === opts.replaceSlug && f.stamp < current) doomed.add(f.name);
|
|
1199
|
+
const cutoff = opts.now.getTime() - opts.maxAgeDays * DAY_MS;
|
|
1200
|
+
files.filter((f) => !doomed.has(f.name)).forEach((f, i) => {
|
|
1201
|
+
if (f.stamp !== current && i >= opts.keep && parseStamp(f.stamp).getTime() < cutoff) doomed.add(f.name);
|
|
1202
|
+
});
|
|
1203
|
+
const deleted = [];
|
|
1204
|
+
for (const name of doomed) {
|
|
1205
|
+
const file = join6(dir, name);
|
|
1206
|
+
try {
|
|
1207
|
+
rmSync(file);
|
|
1208
|
+
deleted.push(file);
|
|
1209
|
+
} catch {
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
return deleted;
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
// src/render/terminal/render.ts
|
|
1216
|
+
import { resolve as resolve5 } from "path";
|
|
1217
|
+
import { pathToFileURL as pathToFileURL2 } from "url";
|
|
1218
|
+
|
|
1219
|
+
// src/render/terminal/labels.ts
|
|
1220
|
+
var MARKER = { new: "+", changed: "~", removed: "-", context: "\xB7", config: "\u25C6" };
|
|
1221
|
+
var SGR = { new: "32", changed: "33", removed: "31", context: "2", config: "36" };
|
|
1222
|
+
var marker = (status) => MARKER[status];
|
|
1223
|
+
var plainLabel = (node) => marker(node.status) + flat(node.label);
|
|
1224
|
+
var paint = (node, text) => text ? `\x1B[${SGR[node.status]}m${text}\x1B[0m` : text;
|
|
1225
|
+
var KINDLESS = /* @__PURE__ */ new Set(["table", "file", "other", "config"]);
|
|
1226
|
+
var targetLabel = (node) => KINDLESS.has(node.kind) ? plainLabel(node) : `${marker(node.status)}${node.kind} ${flat(node.label)}`;
|
|
1227
|
+
|
|
1228
|
+
// src/render/terminal/fields.ts
|
|
1229
|
+
var MARKER2 = { added: "+", removed: "-", modified: "~" };
|
|
1230
|
+
var shown = (node) => {
|
|
1231
|
+
if (node.status === "new") return node.fields ?? [];
|
|
1232
|
+
if (node.status === "changed") return (node.fields ?? []).filter((f) => f.change !== void 0);
|
|
1233
|
+
return [];
|
|
1234
|
+
};
|
|
1235
|
+
var item = (f) => flat(`${f.change ? MARKER2[f.change] : ""}${f.name}${f.type ? ` ${f.type}` : ""}`);
|
|
1236
|
+
function renderFieldLines(spec, ids, width, color, cuts) {
|
|
1237
|
+
const rows = spec.nodes.filter((n) => ids.has(n.id) && shown(n).length > 0).map((n) => ({ node: n, label: plainLabel(n) }));
|
|
1238
|
+
const pad2 = Math.min(Math.max(0, ...rows.map((r) => columns(r.label))), Math.floor(width / 3));
|
|
1239
|
+
const lines = rows.map(({ node, label: full }) => {
|
|
1240
|
+
const label = truncate(full, pad2, cuts);
|
|
1241
|
+
const gap = " ".repeat(Math.max(pad2 - columns(label), 0) + 2);
|
|
1242
|
+
const head = `${color ? paint(node, label) : label}${gap}`;
|
|
1243
|
+
return wrapItems(head, shown(node).map(item), width);
|
|
1244
|
+
});
|
|
1245
|
+
return lines.length > 0 ? `${truncate("fields:", width)}
|
|
1246
|
+
${lines.join("\n")}` : "";
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
// src/render/terminal/select.ts
|
|
1250
|
+
var PRIMARY = /* @__PURE__ */ new Set(["new", "changed", "removed", "config"]);
|
|
1251
|
+
var TIER = {
|
|
1252
|
+
new: 0,
|
|
1253
|
+
changed: 0,
|
|
1254
|
+
removed: 0,
|
|
1255
|
+
config: 1,
|
|
1256
|
+
context: 2
|
|
1257
|
+
};
|
|
1258
|
+
function candidates(spec) {
|
|
1259
|
+
if (!spec.nodes.some((n) => TIER[n.status] === 0))
|
|
1260
|
+
return spec.nodes;
|
|
1261
|
+
const primary = new Set(
|
|
1262
|
+
spec.nodes.filter((n) => PRIMARY.has(n.status)).map((n) => n.id)
|
|
1263
|
+
);
|
|
1264
|
+
const endpoints = new Set(
|
|
1265
|
+
spec.edges.filter((e) => primary.has(e.from) || primary.has(e.to)).flatMap((e) => [e.from, e.to])
|
|
1266
|
+
);
|
|
1267
|
+
return spec.nodes.filter((n) => primary.has(n.id) || endpoints.has(n.id));
|
|
1268
|
+
}
|
|
1269
|
+
function rankByImportance(spec, nodes) {
|
|
1270
|
+
const ids = new Set(nodes.map((n) => n.id));
|
|
1271
|
+
const degree = new Map(nodes.map((n) => [n.id, 0]));
|
|
1272
|
+
for (const e of spec.edges) {
|
|
1273
|
+
if (!ids.has(e.from) || !ids.has(e.to)) continue;
|
|
1274
|
+
degree.set(e.from, degree.get(e.from) + 1);
|
|
1275
|
+
degree.set(e.to, degree.get(e.to) + 1);
|
|
1276
|
+
}
|
|
1277
|
+
return [...nodes].sort(
|
|
1278
|
+
(a, b) => TIER[a.status] - TIER[b.status] || degree.get(b.id) - degree.get(a.id)
|
|
1279
|
+
);
|
|
1280
|
+
}
|
|
1281
|
+
function selectTerminalNodes(spec, max) {
|
|
1282
|
+
const pool = candidates(spec);
|
|
1283
|
+
if (pool.length <= max)
|
|
1284
|
+
return { ids: new Set(pool.map((n) => n.id)), hidden: 0 };
|
|
1285
|
+
const kept = rankByImportance(spec, pool).slice(0, max);
|
|
1286
|
+
return {
|
|
1287
|
+
ids: new Set(kept.map((n) => n.id)),
|
|
1288
|
+
hidden: pool.length - kept.length
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
// src/render/terminal/links.ts
|
|
1293
|
+
var linksAmong = (spec, ids) => spec.edges.filter((e) => ids.has(e.from) && ids.has(e.to));
|
|
1294
|
+
function sourceLines(source, links, byId, width, color, cuts) {
|
|
1295
|
+
const cap = Math.floor(width / 3);
|
|
1296
|
+
const name = truncate(plainLabel(source), cap, cuts);
|
|
1297
|
+
const indent = 2 + columns(name) + 1;
|
|
1298
|
+
const labels = links.map((e) => flat(e.label ?? ""));
|
|
1299
|
+
const targets = links.map((e) => byId.get(e.to));
|
|
1300
|
+
const longest = Math.max(...labels.map(columns));
|
|
1301
|
+
const room = Math.min(...targets.map((t) => width - indent - 4 - columns(targetLabel(t))));
|
|
1302
|
+
const col = Math.min(longest, Math.max(room, Math.min(longest, cap)));
|
|
1303
|
+
const painter2 = (node) => color ? (text) => paint(node, text) : void 0;
|
|
1304
|
+
return links.map((_, i) => {
|
|
1305
|
+
const label = labels[i];
|
|
1306
|
+
const shown2 = columns(label) <= col ? label : truncate(label, col, cuts);
|
|
1307
|
+
const arrow = `\u2500${shown2}${"\u2500".repeat(col - columns(shown2) + 1)}\u25B6`;
|
|
1308
|
+
const target = targets[i];
|
|
1309
|
+
return fit(
|
|
1310
|
+
[
|
|
1311
|
+
{ text: " " },
|
|
1312
|
+
i === 0 ? { text: name, paint: painter2(source) } : { text: " ".repeat(columns(name)) },
|
|
1313
|
+
{ text: ` ${arrow} ` },
|
|
1314
|
+
{ text: truncate(targetLabel(target), width - indent - 4 - col, cuts), paint: painter2(target) }
|
|
1315
|
+
],
|
|
1316
|
+
width,
|
|
1317
|
+
cuts
|
|
1318
|
+
);
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
function renderLinks(spec, ids, width, color, cuts = { truncated: false }) {
|
|
1322
|
+
const byId = new Map(spec.nodes.map((n) => [n.id, n]));
|
|
1323
|
+
const links = linksAmong(spec, ids);
|
|
1324
|
+
const layers = [...new Set(spec.nodes.map((n) => n.layer))];
|
|
1325
|
+
const sections = layers.flatMap((layer) => {
|
|
1326
|
+
const blocks = spec.nodes.filter((n) => n.layer === layer).flatMap((n) => {
|
|
1327
|
+
const own = links.filter((e) => e.from === n.id);
|
|
1328
|
+
return own.length > 0 ? sourceLines(n, own, byId, width, color, cuts) : [];
|
|
1329
|
+
});
|
|
1330
|
+
return blocks.length > 0 ? [[truncate(flat(layer), width, cuts), ...blocks].join("\n")] : [];
|
|
1331
|
+
});
|
|
1332
|
+
return sections.join("\n\n");
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
// src/render/terminal/render.ts
|
|
1336
|
+
var MIN_WIDTH = 20;
|
|
1337
|
+
var MAX_WIDTH = 100;
|
|
1338
|
+
var NOT_TTY_WIDTH = 80;
|
|
1339
|
+
var MAX_ENV_WIDTH = 300;
|
|
1340
|
+
var KEY_ORDER = ["new", "removed", "changed", "context", "config"];
|
|
1341
|
+
var KEY = `key: ${KEY_ORDER.map((s) => `${marker(s)} ${s}`).join(" ")}`;
|
|
1342
|
+
var fullMapLine = (htmlPath) => `full map \u2192 ${pathToFileURL2(resolve5(htmlPath)).href}`;
|
|
1343
|
+
function defaultWidth(stdout = process.stdout, env = process.env) {
|
|
1344
|
+
if (stdout.isTTY) return Math.min(stdout.columns || MAX_WIDTH, MAX_WIDTH);
|
|
1345
|
+
const fromEnv = Math.floor(Number(env.COLUMNS));
|
|
1346
|
+
return Number.isFinite(fromEnv) && fromEnv > 0 && fromEnv <= MAX_ENV_WIDTH ? fromEnv : NOT_TTY_WIDTH;
|
|
1347
|
+
}
|
|
1348
|
+
function footer(spec, hidden, width, keyLine, htmlPath) {
|
|
1349
|
+
const count = (status) => spec.nodes.filter((n) => n.status === status).length;
|
|
1350
|
+
const removed = count("removed") > 0 ? ` \xB7 ${count("removed")} removed` : "";
|
|
1351
|
+
const lines = [
|
|
1352
|
+
truncate(`${spec.nodes.length} nodes \xB7 ${count("new")} new \xB7 ${count("changed")} changed${removed} \xB7 ${count("config")} config`, width)
|
|
1353
|
+
];
|
|
1354
|
+
if (keyLine) lines.push(truncate(KEY, width));
|
|
1355
|
+
if (spec.gaps?.length) lines.push(wrapItems("gaps: ", spec.gaps.map(flat), width));
|
|
1356
|
+
if (spec.omitted?.length) lines.push(wrapItems("not on map: ", spec.omitted.map(flat), width));
|
|
1357
|
+
if (hidden > 0) lines.push(truncate(`+${hidden} more ${htmlPath ? "in web view" : "not shown"}`, width));
|
|
1358
|
+
if (htmlPath) lines.push(fullMapLine(htmlPath));
|
|
1359
|
+
return lines.join("\n");
|
|
1360
|
+
}
|
|
1361
|
+
function renderTerminalDetailed(spec, opts) {
|
|
1362
|
+
const cuts = { truncated: false };
|
|
1363
|
+
const width = Math.max(opts.width ?? defaultWidth(), MIN_WIDTH);
|
|
1364
|
+
const { ids, hidden } = selectTerminalNodes(spec, opts.maxNodes);
|
|
1365
|
+
const sections = [];
|
|
1366
|
+
const links = renderLinks(spec, ids, width, opts.color, cuts);
|
|
1367
|
+
if (links) sections.push(links);
|
|
1368
|
+
const shown2 = new Set(linksAmong(spec, ids).flatMap((e) => [e.from, e.to]));
|
|
1369
|
+
const lone = spec.nodes.filter((n) => ids.has(n.id) && !shown2.has(n.id));
|
|
1370
|
+
const items = lone.map((n) => ({
|
|
1371
|
+
text: plainLabel(n),
|
|
1372
|
+
paint: opts.color ? (piece) => paint(n, piece) : void 0
|
|
1373
|
+
}));
|
|
1374
|
+
if (items.length > 0) sections.push(wrapItems("also: ", items, width));
|
|
1375
|
+
if (!opts.htmlPath) {
|
|
1376
|
+
const fields = renderFieldLines(spec, ids, width, opts.color, cuts);
|
|
1377
|
+
if (fields) sections.push(fields);
|
|
1378
|
+
}
|
|
1379
|
+
sections.push(footer(spec, hidden, width, opts.keyLine ?? true, opts.htmlPath));
|
|
1380
|
+
return { text: `${sections.join("\n\n")}
|
|
1381
|
+
`, truncated: cuts.truncated };
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
// src/render/web/layout.ts
|
|
1385
|
+
var NODE_WIDTH = 220;
|
|
1386
|
+
var HEADER_HEIGHT = 28;
|
|
1387
|
+
var LINE_HEIGHT = 16;
|
|
1388
|
+
var LAYER_PREFIX = "layer:";
|
|
1389
|
+
var SUMMARY_CHARS_PER_LINE = 34;
|
|
1390
|
+
var SUMMARY_MAX_LINES = 3;
|
|
1391
|
+
function wrapSummary(text) {
|
|
1392
|
+
return wrapText(text, SUMMARY_CHARS_PER_LINE, SUMMARY_MAX_LINES);
|
|
1393
|
+
}
|
|
1394
|
+
function wrapText(text, chars, maxLines) {
|
|
1395
|
+
const words = text.split(/\s+/).filter(Boolean).flatMap((w) => {
|
|
1396
|
+
const parts = [];
|
|
1397
|
+
for (let i = 0; i < w.length; i += chars) {
|
|
1398
|
+
parts.push(w.slice(i, i + chars));
|
|
1399
|
+
}
|
|
1400
|
+
return parts;
|
|
1401
|
+
});
|
|
1402
|
+
const lines = [];
|
|
1403
|
+
let cur = "";
|
|
1404
|
+
let overflow = false;
|
|
1405
|
+
for (const w of words) {
|
|
1406
|
+
if (cur && cur.length + 1 + w.length <= chars) {
|
|
1407
|
+
cur += " " + w;
|
|
1408
|
+
continue;
|
|
1409
|
+
}
|
|
1410
|
+
if (cur) lines.push(cur);
|
|
1411
|
+
if (lines.length === maxLines) {
|
|
1412
|
+
overflow = true;
|
|
1413
|
+
cur = "";
|
|
1414
|
+
break;
|
|
1415
|
+
}
|
|
1416
|
+
cur = w;
|
|
1417
|
+
}
|
|
1418
|
+
if (cur) lines.push(cur);
|
|
1419
|
+
if (overflow) {
|
|
1420
|
+
const last = lines[maxLines - 1];
|
|
1421
|
+
const room = chars - 1;
|
|
1422
|
+
lines[maxLines - 1] = last.slice(0, room).trimEnd() + "\u2026";
|
|
1423
|
+
}
|
|
1424
|
+
return lines;
|
|
1425
|
+
}
|
|
1426
|
+
function nodeHeight(fields, summary) {
|
|
1427
|
+
const summaryLines = summary ? wrapSummary(summary).length : 0;
|
|
1428
|
+
return HEADER_HEIGHT + LINE_HEIGHT * (fields + summaryLines);
|
|
1429
|
+
}
|
|
1430
|
+
async function layoutSpec(spec) {
|
|
1431
|
+
const layers = [...new Set(spec.nodes.map((n) => n.layer))];
|
|
1432
|
+
const children = layers.map((layer) => ({
|
|
1433
|
+
id: LAYER_PREFIX + layer,
|
|
1434
|
+
labels: [{ text: layer }],
|
|
1435
|
+
layoutOptions: { "elk.padding": "[top=32,left=16,bottom=16,right=16]" },
|
|
1436
|
+
children: spec.nodes.filter((n) => n.layer === layer).map((n) => ({
|
|
1437
|
+
id: n.id,
|
|
1438
|
+
width: NODE_WIDTH,
|
|
1439
|
+
height: nodeHeight(n.fields?.length ?? 0, n.summary)
|
|
1440
|
+
}))
|
|
1441
|
+
}));
|
|
1442
|
+
const edges = spec.edges.map((e, i) => ({
|
|
1443
|
+
id: `e${i}`,
|
|
1444
|
+
sources: [e.from],
|
|
1445
|
+
targets: [e.to],
|
|
1446
|
+
...e.label ? { labels: [{ text: e.label, width: e.label.length * 6, height: 14 }] } : {}
|
|
1447
|
+
}));
|
|
1448
|
+
const graph = {
|
|
1449
|
+
id: "root",
|
|
1450
|
+
layoutOptions: {
|
|
1451
|
+
"elk.algorithm": "layered",
|
|
1452
|
+
"elk.direction": "RIGHT",
|
|
1453
|
+
"elk.hierarchyHandling": "INCLUDE_CHILDREN",
|
|
1454
|
+
"elk.spacing.nodeNode": "24",
|
|
1455
|
+
"elk.layered.spacing.nodeNodeBetweenLayers": "60"
|
|
1456
|
+
},
|
|
1457
|
+
children,
|
|
1458
|
+
edges
|
|
1459
|
+
};
|
|
1460
|
+
const { default: ELK } = await import("elkjs/lib/elk.bundled.js");
|
|
1461
|
+
const root = await new ELK().layout(graph);
|
|
1462
|
+
const containerOrigin = /* @__PURE__ */ new Map();
|
|
1463
|
+
const groups = [];
|
|
1464
|
+
const nodes = [];
|
|
1465
|
+
for (const g of root.children ?? []) {
|
|
1466
|
+
const gx = g.x ?? 0;
|
|
1467
|
+
const gy = g.y ?? 0;
|
|
1468
|
+
containerOrigin.set(g.id, { x: gx, y: gy });
|
|
1469
|
+
groups.push({ layer: g.id.slice(LAYER_PREFIX.length), x: gx, y: gy, w: g.width ?? 0, h: g.height ?? 0 });
|
|
1470
|
+
for (const n of g.children ?? []) {
|
|
1471
|
+
nodes.push({ id: n.id, x: gx + (n.x ?? 0), y: gy + (n.y ?? 0), w: n.width ?? 0, h: n.height ?? 0 });
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
const outEdges = (root.edges ?? []).map((e) => {
|
|
1475
|
+
const idx = Number(e.id.slice(1));
|
|
1476
|
+
const specEdge = spec.edges[idx];
|
|
1477
|
+
const sec = e.sections?.[0];
|
|
1478
|
+
const points = sec ? [sec.startPoint, ...sec.bendPoints ?? [], sec.endPoint] : [];
|
|
1479
|
+
const origin = e.container && containerOrigin.get(e.container) || { x: 0, y: 0 };
|
|
1480
|
+
return {
|
|
1481
|
+
from: specEdge.from,
|
|
1482
|
+
to: specEdge.to,
|
|
1483
|
+
...specEdge.label ? { label: specEdge.label } : {},
|
|
1484
|
+
points: points.map((p) => ({ x: p.x + origin.x, y: p.y + origin.y }))
|
|
1485
|
+
};
|
|
1486
|
+
});
|
|
1487
|
+
return { width: root.width ?? 0, height: root.height ?? 0, groups, nodes, edges: outEdges };
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
// src/render/web/page.ts
|
|
1491
|
+
import { createHash as createHash2 } from "crypto";
|
|
1492
|
+
|
|
1493
|
+
// src/render/web/styles.ts
|
|
1494
|
+
var DARK_VARS = "--bg:#0f1115;--panel:#161b22;--card:#161b22;--line:#30363d;--text:#c9d1d9;--muted:#8b949e;--edge:#79c0ff;--new:#3fb950;--new-t:#7ee787;--chg:#d29922;--chg-t:#f2cc60;--cfg:#a371f7;--cfg-t:#d2a8ff;--add:#7ee787;--rem:#ff7b72";
|
|
1495
|
+
var DARK_AUTO = `@media (prefers-color-scheme: dark){:root[data-theme="auto"]{${DARK_VARS}}}`;
|
|
1496
|
+
var DARK_FORCED = `:root[data-theme="dark"]{${DARK_VARS}}`;
|
|
1497
|
+
var CSS = `
|
|
1498
|
+
:root{color-scheme:light dark;--bg:#f6f8fa;--panel:#fff;--card:#fff;--line:#d0d7de;--text:#1f2328;--muted:#656d76;--edge:#0969da;--new:#2ea043;--new-t:#1a7f37;--chg:#d29922;--chg-t:#9a6700;--cfg:#8957e5;--cfg-t:#8250df;--add:#1a7f37;--rem:#cf222e}
|
|
1499
|
+
:root[data-theme="light"]{color-scheme:light}
|
|
1500
|
+
:root[data-theme="dark"]{color-scheme:dark}
|
|
1501
|
+
${DARK_AUTO}
|
|
1502
|
+
${DARK_FORCED}
|
|
1503
|
+
*{box-sizing:border-box}
|
|
1504
|
+
body{margin:0;height:100vh;display:flex;flex-direction:column;background:var(--bg);color:var(--text);font:13px system-ui,sans-serif}
|
|
1505
|
+
header{padding:8px 14px;border-bottom:1px solid var(--line);background:var(--panel);display:flex;gap:12px;align-items:baseline}
|
|
1506
|
+
header h1{margin:0;font-size:15px}
|
|
1507
|
+
header .meta{color:var(--muted);font-size:11px;margin-right:auto}
|
|
1508
|
+
main{flex:1;display:flex;min-height:0}
|
|
1509
|
+
#canvas{flex:1;min-width:0;cursor:grab;overflow:hidden;touch-action:none}
|
|
1510
|
+
#canvas.drag{cursor:grabbing}
|
|
1511
|
+
#canvas svg{width:100%;height:100%;display:block}
|
|
1512
|
+
aside{width:300px;border-left:1px solid var(--line);background:var(--panel);overflow:auto;padding:10px 14px}
|
|
1513
|
+
aside h2{margin:0 0 6px;font-size:13px}
|
|
1514
|
+
aside h3{margin:12px 0 4px;font-size:11px;text-transform:uppercase;color:var(--muted)}
|
|
1515
|
+
aside ul{margin:0;padding-left:18px}
|
|
1516
|
+
aside .fields-note{color:var(--muted);font-size:11.5px;font-style:italic;margin:6px 0 0}
|
|
1517
|
+
aside code{font-family:ui-monospace,monospace;font-size:11px;font-style:normal}
|
|
1518
|
+
aside .path{font-family:ui-monospace,monospace;font-size:11px;word-break:break-all;color:var(--muted)}
|
|
1519
|
+
.group rect{fill:none;stroke:var(--line);stroke-dasharray:4 3}
|
|
1520
|
+
.group text{fill:var(--muted);font-size:10px;text-transform:uppercase}
|
|
1521
|
+
.edge path{fill:none;stroke:var(--edge);stroke-width:1.2}
|
|
1522
|
+
.edge text{fill:var(--edge);font-size:9.5px;text-anchor:middle}
|
|
1523
|
+
.edge rect{fill:var(--bg);opacity:.9}
|
|
1524
|
+
#arrow path{fill:var(--edge)}
|
|
1525
|
+
.node{cursor:pointer}
|
|
1526
|
+
.node .card{fill:var(--card);stroke:var(--line);stroke-width:1}
|
|
1527
|
+
.node .head{stroke:var(--line);stroke-width:1}
|
|
1528
|
+
.node .label{fill:var(--text);font-size:11px;font-weight:600}
|
|
1529
|
+
.node .badge{font-size:8.5px;text-transform:uppercase;text-anchor:end}
|
|
1530
|
+
.node .summary{fill:var(--muted);font-size:10.5px;font-style:italic}
|
|
1531
|
+
.node .field{fill:var(--text);font-size:10.5px}
|
|
1532
|
+
.node .field-added{fill:var(--add)}
|
|
1533
|
+
.node .field-removed{fill:var(--rem);text-decoration:line-through}
|
|
1534
|
+
.node .field-modified{fill:var(--chg-t)}
|
|
1535
|
+
.node.selected .card{stroke-width:2.5}
|
|
1536
|
+
.node:focus{outline:none}
|
|
1537
|
+
.node:focus-visible .card{stroke:var(--edge);stroke-width:3.5}
|
|
1538
|
+
.status-new .card{stroke:var(--new)}.status-new .badge{fill:var(--new-t)}
|
|
1539
|
+
.status-changed .card{stroke:var(--chg)}.status-changed .badge{fill:var(--chg-t)}
|
|
1540
|
+
.status-removed .card{stroke:var(--rem)}.status-removed .badge{fill:var(--rem)}.status-removed .label{text-decoration:line-through}
|
|
1541
|
+
.status-config .card{stroke:var(--cfg)}.status-config .badge{fill:var(--cfg-t)}
|
|
1542
|
+
.status-context .card{stroke-dasharray:4 3}.status-context{opacity:.75}.status-context .badge{fill:var(--muted)}
|
|
1543
|
+
.field-added-t{color:var(--add)}.field-removed-t{color:var(--muted);text-decoration:line-through}.field-modified-t{color:var(--chg-t)}
|
|
1544
|
+
|
|
1545
|
+
#info-toggle[aria-expanded="true"]{border-color:var(--edge)}
|
|
1546
|
+
#info-toggle,#theme-toggle{align-self:center;padding:4px 10px;font:11px system-ui,sans-serif;color:var(--text);background:var(--panel);border:1px solid var(--line);border-radius:12px;cursor:pointer}
|
|
1547
|
+
#info-toggle:hover,#theme-toggle:hover{border-color:var(--edge)}
|
|
1548
|
+
`;
|
|
1549
|
+
|
|
1550
|
+
// src/render/web/client.ts
|
|
1551
|
+
var CLIENT_JS = `
|
|
1552
|
+
(function () {
|
|
1553
|
+
var data = JSON.parse(document.getElementById('spec-data').textContent);
|
|
1554
|
+
var svg = document.querySelector('#canvas svg');
|
|
1555
|
+
var vp = document.getElementById('viewport');
|
|
1556
|
+
var canvas = document.getElementById('canvas');
|
|
1557
|
+
var panel = document.getElementById('panel');
|
|
1558
|
+
var info = document.getElementById('page-info');
|
|
1559
|
+
var infoBtn = document.getElementById('info-toggle');
|
|
1560
|
+
var t = { x: 0, y: 0, k: 1 };
|
|
1561
|
+
function apply() { vp.setAttribute('transform', 'translate(' + t.x + ',' + t.y + ') scale(' + t.k + ')'); }
|
|
1562
|
+
function fit() {
|
|
1563
|
+
var r = svg.getBoundingClientRect();
|
|
1564
|
+
var k = Math.min(r.width / data.width, r.height / data.height, 1) || 1;
|
|
1565
|
+
t = { k: k, x: (r.width - data.width * k) / 2, y: (r.height - data.height * k) / 2 };
|
|
1566
|
+
apply();
|
|
1567
|
+
}
|
|
1568
|
+
canvas.addEventListener('wheel', function (e) {
|
|
1569
|
+
e.preventDefault();
|
|
1570
|
+
var r = svg.getBoundingClientRect();
|
|
1571
|
+
var px = e.clientX - r.left, py = e.clientY - r.top;
|
|
1572
|
+
var k = Math.min(4, Math.max(0.1, t.k * Math.exp(-e.deltaY * 0.0015)));
|
|
1573
|
+
t.x = px - ((px - t.x) / t.k) * k;
|
|
1574
|
+
t.y = py - ((py - t.y) / t.k) * k;
|
|
1575
|
+
t.k = k;
|
|
1576
|
+
apply();
|
|
1577
|
+
}, { passive: false });
|
|
1578
|
+
var drag = null, moved = false;
|
|
1579
|
+
canvas.addEventListener('pointerdown', function (e) {
|
|
1580
|
+
drag = { x: e.clientX - t.x, y: e.clientY - t.y, sx: e.clientX, sy: e.clientY };
|
|
1581
|
+
moved = false;
|
|
1582
|
+
});
|
|
1583
|
+
window.addEventListener('pointermove', function (e) {
|
|
1584
|
+
if (!drag) return;
|
|
1585
|
+
if (Math.abs(e.clientX - drag.sx) + Math.abs(e.clientY - drag.sy) > 3) { moved = true; canvas.classList.add('drag'); }
|
|
1586
|
+
if (!moved) return;
|
|
1587
|
+
t.x = e.clientX - drag.x; t.y = e.clientY - drag.y; apply();
|
|
1588
|
+
});
|
|
1589
|
+
function endDrag() { drag = null; canvas.classList.remove('drag'); }
|
|
1590
|
+
window.addEventListener('pointerup', endDrag);
|
|
1591
|
+
window.addEventListener('pointercancel', endDrag);
|
|
1592
|
+
function select(id) {
|
|
1593
|
+
document.querySelectorAll('.node.selected').forEach(function (g) { g.classList.remove('selected'); });
|
|
1594
|
+
if (id == null) return;
|
|
1595
|
+
var g = document.querySelector('.node[data-id="' + CSS.escape(id) + '"]');
|
|
1596
|
+
if (g) g.classList.add('selected');
|
|
1597
|
+
}
|
|
1598
|
+
function setInfo(on) {
|
|
1599
|
+
info.hidden = !on;
|
|
1600
|
+
panel.hidden = on;
|
|
1601
|
+
if (infoBtn) infoBtn.setAttribute('aria-expanded', String(on));
|
|
1602
|
+
}
|
|
1603
|
+
function show(id) {
|
|
1604
|
+
var tpl = document.querySelector('template.card-panel[data-for="' + CSS.escape(id) + '"]');
|
|
1605
|
+
if (!tpl) return;
|
|
1606
|
+
select(id);
|
|
1607
|
+
panel.textContent = '';
|
|
1608
|
+
panel.appendChild(tpl.content.cloneNode(true));
|
|
1609
|
+
setInfo(false);
|
|
1610
|
+
}
|
|
1611
|
+
if (infoBtn) infoBtn.addEventListener('click', function () { select(null); setInfo(true); });
|
|
1612
|
+
setInfo(true);
|
|
1613
|
+
document.querySelectorAll('.node').forEach(function (g) {
|
|
1614
|
+
g.addEventListener('click', function () { if (!moved) show(g.getAttribute('data-id')); });
|
|
1615
|
+
g.addEventListener('keydown', function (e) {
|
|
1616
|
+
if (e.target !== g) return;
|
|
1617
|
+
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); show(g.getAttribute('data-id')); }
|
|
1618
|
+
});
|
|
1619
|
+
});
|
|
1620
|
+
var themes = ['auto', 'light', 'dark'];
|
|
1621
|
+
var root = document.documentElement;
|
|
1622
|
+
var btn = document.getElementById('theme-toggle');
|
|
1623
|
+
function setTheme(v, save) {
|
|
1624
|
+
root.setAttribute('data-theme', v);
|
|
1625
|
+
btn.textContent = 'Theme: ' + v;
|
|
1626
|
+
if (save) { try { localStorage.setItem('codechart.theme', v); } catch (e) {} }
|
|
1627
|
+
}
|
|
1628
|
+
var saved = null;
|
|
1629
|
+
try { saved = localStorage.getItem('codechart.theme'); } catch (e) {}
|
|
1630
|
+
setTheme(themes.indexOf(saved) >= 0 ? saved : root.getAttribute('data-theme'), false);
|
|
1631
|
+
btn.addEventListener('click', function () {
|
|
1632
|
+
var i = themes.indexOf(root.getAttribute('data-theme'));
|
|
1633
|
+
setTheme(themes[(i + 1) % themes.length], true);
|
|
1634
|
+
});
|
|
1635
|
+
window.addEventListener('resize', fit);
|
|
1636
|
+
fit();
|
|
1637
|
+
})();
|
|
1638
|
+
`;
|
|
1639
|
+
|
|
1640
|
+
// src/render/web/page.ts
|
|
1641
|
+
function esc(s) {
|
|
1642
|
+
return stripInvisible(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1643
|
+
}
|
|
1644
|
+
function jsonForScript(v) {
|
|
1645
|
+
return JSON.stringify(v).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
1646
|
+
}
|
|
1647
|
+
var num = (n) => String(Math.round(n * 10) / 10);
|
|
1648
|
+
function list(items) {
|
|
1649
|
+
return `<ul>${items.map((i) => `<li>${esc(i)}</li>`).join("")}</ul>`;
|
|
1650
|
+
}
|
|
1651
|
+
function midpoint(points) {
|
|
1652
|
+
let total = 0;
|
|
1653
|
+
for (let i = 1; i < points.length; i++) {
|
|
1654
|
+
total += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
|
|
1655
|
+
}
|
|
1656
|
+
let rest = total / 2;
|
|
1657
|
+
for (let i = 1; i < points.length; i++) {
|
|
1658
|
+
const a = points[i - 1];
|
|
1659
|
+
const b = points[i];
|
|
1660
|
+
const len = Math.hypot(b.x - a.x, b.y - a.y);
|
|
1661
|
+
if (len >= rest && len > 0) {
|
|
1662
|
+
const f = rest / len;
|
|
1663
|
+
return { x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f };
|
|
1664
|
+
}
|
|
1665
|
+
rest -= len;
|
|
1666
|
+
}
|
|
1667
|
+
return points[0] ?? { x: 0, y: 0 };
|
|
1668
|
+
}
|
|
1669
|
+
var CSP = `default-src 'none'; style-src 'unsafe-inline'; script-src 'sha256-${createHash2("sha256").update(CLIENT_JS).digest("base64")}'; img-src data:; base-uri 'none'; form-action 'none'`;
|
|
1670
|
+
function renderPage(p) {
|
|
1671
|
+
const theme = p.meta.theme && THEMES.includes(p.meta.theme) ? p.meta.theme : "auto";
|
|
1672
|
+
const data = { width: p.width, height: p.height };
|
|
1673
|
+
return `<!doctype html>
|
|
1674
|
+
<html lang="en" data-theme="${theme}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1675
|
+
<meta http-equiv="Content-Security-Policy" content="${CSP}">
|
|
1676
|
+
<title>${esc(p.title)}</title>
|
|
1677
|
+
<style>${CSS}${p.extraCss ?? ""}</style></head>
|
|
1678
|
+
<body>
|
|
1679
|
+
<header><h1>${esc(p.title)}</h1><span class="meta">${esc(p.meta.repo)} \xB7 ${esc(p.meta.generatedAt.toISOString())}</span>${p.infoButton}<button id="theme-toggle" type="button" title="Cycle theme: auto, light, dark"></button></header>
|
|
1680
|
+
<main>
|
|
1681
|
+
<div id="canvas"><svg><defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0 L10,5 L0,10 z"/></marker>${p.extraDefs ?? ""}</defs>
|
|
1682
|
+
<g id="viewport">${p.viewport}</g></svg></div>
|
|
1683
|
+
<aside>${p.aside}</aside>
|
|
1684
|
+
</main>
|
|
1685
|
+
<script type="application/json" id="spec-data">${jsonForScript(data)}</script>
|
|
1686
|
+
<script>${CLIENT_JS}</script>
|
|
1687
|
+
</body></html>
|
|
1688
|
+
`;
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
// src/render/web/html.ts
|
|
1692
|
+
var FIELD_CHARS = 34;
|
|
1693
|
+
function clip2(s, max) {
|
|
1694
|
+
return s.length > max ? s.slice(0, max - 1) + "\u2026" : s;
|
|
1695
|
+
}
|
|
1696
|
+
var FIELD_MARK = { added: "+ ", removed: "- ", modified: "~ " };
|
|
1697
|
+
function fieldText(f) {
|
|
1698
|
+
return `${f.change ? FIELD_MARK[f.change] : ""}${f.name}${f.type ? ": " + f.type : ""}${f.note ? " (" + f.note + ")" : ""}`;
|
|
1699
|
+
}
|
|
1700
|
+
function renderEdge(e) {
|
|
1701
|
+
if (e.points.length < 2) return "";
|
|
1702
|
+
const d = e.points.map((p, i) => `${i ? "L" : "M"}${num(p.x)},${num(p.y)}`).join(" ");
|
|
1703
|
+
let out = `<path d="${d}" marker-end="url(#arrow)"/>`;
|
|
1704
|
+
if (e.label) {
|
|
1705
|
+
const m = midpoint(e.points);
|
|
1706
|
+
const w = e.label.length * 5.6 + 6;
|
|
1707
|
+
out += `<rect x="${num(m.x - w / 2)}" y="${num(m.y - 8)}" width="${num(w)}" height="12" rx="2"/><text x="${num(m.x)}" y="${num(m.y + 1)}">${esc(e.label)}</text>`;
|
|
1708
|
+
}
|
|
1709
|
+
return `<g class="edge">${out}</g>`;
|
|
1710
|
+
}
|
|
1711
|
+
function renderNode(n, box) {
|
|
1712
|
+
const x = Math.round(box.x * 10) / 10;
|
|
1713
|
+
const y = Math.round(box.y * 10) / 10;
|
|
1714
|
+
const w = box.w;
|
|
1715
|
+
const lines = [];
|
|
1716
|
+
let row = 28;
|
|
1717
|
+
const text = (cls, s) => {
|
|
1718
|
+
lines.push(`<text class="${cls}" x="${x + 8}" y="${y + row + 12}">${esc(s)}</text>`);
|
|
1719
|
+
row += 16;
|
|
1720
|
+
};
|
|
1721
|
+
if (n.summary) for (const l of wrapSummary(n.summary)) text("summary", l);
|
|
1722
|
+
for (const f of n.fields ?? []) {
|
|
1723
|
+
text(f.change ? `field field-${f.change}` : "field", clip2(fieldText(f), FIELD_CHARS));
|
|
1724
|
+
}
|
|
1725
|
+
return `<g class="node status-${n.status}" data-id="${esc(n.id)}" tabindex="0" role="button" aria-label="${esc(`${n.label} (${n.status})`)}"><rect class="card" x="${x}" y="${y}" width="${w}" height="${row}" rx="6"/><line class="head" x1="${x}" y1="${y + 28}" x2="${x + w}" y2="${y + 28}"/><text class="label" x="${x + 8}" y="${y + 18}">${esc(clip2(n.label, 22))}</text><text class="badge" x="${x + w - 8}" y="${y + 18}">${esc(n.status)}</text>` + lines.join("") + `</g>`;
|
|
1726
|
+
}
|
|
1727
|
+
var FIELDS_NOTE = "Only the fields the agent saw are listed. Set <code>defaults.context: full</code> in <code>.codechart.yaml</code> to let it read the full definition.";
|
|
1728
|
+
function cardPanel(n) {
|
|
1729
|
+
let out = `<h2>${esc(`${n.label} (${n.status} ${n.kind})`)}</h2>`;
|
|
1730
|
+
if (n.path) out += `<div class="path">${esc(n.path)}</div>`;
|
|
1731
|
+
if (n.summary) out += `<p>${esc(n.summary)}</p>`;
|
|
1732
|
+
if (n.fields?.length) {
|
|
1733
|
+
out += `<h3>Fields</h3><ul>${n.fields.map((f) => `<li${f.change ? ` class="field-${f.change}-t"` : ""}>${esc(fieldText(f))}</li>`).join("")}</ul>`;
|
|
1734
|
+
if (n.fieldsComplete === false) out += `<p class="fields-note">${FIELDS_NOTE}</p>`;
|
|
1735
|
+
}
|
|
1736
|
+
if (n.notes?.length) out += `<h3>Notes</h3>${list(n.notes)}`;
|
|
1737
|
+
return `<template class="card-panel" data-for="${esc(n.id)}">${out}</template>`;
|
|
1738
|
+
}
|
|
1739
|
+
function pageInfo(spec) {
|
|
1740
|
+
let out = "<p>Click a node for details. Scroll to zoom, drag to pan.</p>";
|
|
1741
|
+
if (spec.gaps?.length) out += `<h3>Gaps</h3>${list(spec.gaps)}`;
|
|
1742
|
+
if (spec.omitted?.length) out += `<h3>Not on map</h3>${list(spec.omitted)}`;
|
|
1743
|
+
return `<section id="page-info">${out}</section>`;
|
|
1744
|
+
}
|
|
1745
|
+
function renderHtml(spec, layout, meta) {
|
|
1746
|
+
const boxes = new Map(layout.nodes.map((n) => [n.id, n]));
|
|
1747
|
+
const groups = layout.groups.map(
|
|
1748
|
+
(g) => `<g class="group"><rect x="${num(g.x)}" y="${num(g.y)}" width="${num(g.w)}" height="${num(g.h)}" rx="8"/><text x="${num(g.x + 10)}" y="${num(g.y + 16)}">${esc(g.layer)}</text></g>`
|
|
1749
|
+
).join("");
|
|
1750
|
+
const nodes = spec.nodes.map((n) => {
|
|
1751
|
+
const b = boxes.get(n.id);
|
|
1752
|
+
return b ? renderNode(n, b) : "";
|
|
1753
|
+
}).join("");
|
|
1754
|
+
const edges = layout.edges.map(renderEdge).join("");
|
|
1755
|
+
const infoButton = spec.gaps?.length || spec.omitted?.length ? '<button id="info-toggle" type="button" aria-controls="page-info" title="Show what is not on the map and what the agent did not read">Not on map / gaps</button>' : "";
|
|
1756
|
+
return renderPage({
|
|
1757
|
+
title: spec.title,
|
|
1758
|
+
meta,
|
|
1759
|
+
infoButton,
|
|
1760
|
+
viewport: `${groups}${edges}${nodes}`,
|
|
1761
|
+
aside: `${pageInfo(spec)}<div id="panel" hidden></div>${spec.nodes.map(cardPanel).join("")}`,
|
|
1762
|
+
width: layout.width,
|
|
1763
|
+
height: layout.height
|
|
1764
|
+
});
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
// src/spec/schema.ts
|
|
1768
|
+
import { z as z4 } from "zod";
|
|
1769
|
+
|
|
1770
|
+
// src/spec/flow.ts
|
|
1771
|
+
import { z as z3 } from "zod";
|
|
1772
|
+
var STEP_TYPES = ["step", "decision", "end"];
|
|
1773
|
+
var STEP_STATUSES = ["existing", "new", "changed", "planned"];
|
|
1774
|
+
var SOURCE_RE = /^[^\s:\u0000-\u001f\u007f-\u009f]+(:\d+(-\d+)?)?$/;
|
|
1775
|
+
var sourceSchema = pathStr().regex(SOURCE_RE, "must be path:line or path:start-end, or a path with match");
|
|
1776
|
+
var hasLine = (source) => source.includes(":");
|
|
1777
|
+
var ANCHOR = "(path:line, path:start-end, or a path with match)";
|
|
1778
|
+
var matchSchema = z3.string().trim().min(1, "must not be blank").max(SHORT).refine((v) => !hasHiddenChars(v.replaceAll(" ", " ")), "must be one line without control or invisible characters (tabs are fine); quote a single line").describe("Text on the anchored line (plain substring, not a regex); source is then the path only");
|
|
1779
|
+
var stepSchema = z3.strictObject({
|
|
1780
|
+
id: ident(),
|
|
1781
|
+
label: short(),
|
|
1782
|
+
type: z3.enum(STEP_TYPES).optional().describe("Inferred when left out: 0 outgoing links end, 1 step, 2 or more decision"),
|
|
1783
|
+
status: z3.enum(STEP_STATUSES),
|
|
1784
|
+
source: sourceSchema.optional(),
|
|
1785
|
+
match: matchSchema.optional()
|
|
1786
|
+
});
|
|
1787
|
+
var linkSchema = z3.strictObject({
|
|
1788
|
+
from: ident(),
|
|
1789
|
+
to: ident(),
|
|
1790
|
+
label: short().optional(),
|
|
1791
|
+
source: sourceSchema.optional(),
|
|
1792
|
+
match: matchSchema.optional(),
|
|
1793
|
+
planned: z3.boolean().optional()
|
|
1794
|
+
});
|
|
1795
|
+
var MAX_ITEMS = 200;
|
|
1796
|
+
function anchorIssues(a) {
|
|
1797
|
+
if (a.match !== void 0 && !a.source) return [["match", "needs source set to the file path"]];
|
|
1798
|
+
if (!a.source || !SOURCE_RE.test(a.source)) return [];
|
|
1799
|
+
if (a.match !== void 0 && hasLine(a.source)) return [["source", "with match, give only the path (no :line)"]];
|
|
1800
|
+
if (a.match === void 0 && !hasLine(a.source)) return [["source", "needs a line (path:line or path:start-end) or a match"]];
|
|
1801
|
+
return [];
|
|
1802
|
+
}
|
|
1803
|
+
function isPlannedLink(spec, link) {
|
|
1804
|
+
const planned = (id) => spec.steps.some((s) => s.id === id && s.status === "planned");
|
|
1805
|
+
return link.planned === true || planned(link.from) || planned(link.to);
|
|
1806
|
+
}
|
|
1807
|
+
var inferType = (outgoing) => outgoing === 0 ? "end" : outgoing >= 2 ? "decision" : "step";
|
|
1808
|
+
function outgoingCounts(links) {
|
|
1809
|
+
const counts = /* @__PURE__ */ new Map();
|
|
1810
|
+
for (const l of links) counts.set(l.from, (counts.get(l.from) ?? 0) + 1);
|
|
1811
|
+
return counts;
|
|
1812
|
+
}
|
|
1813
|
+
var flowSchema = z3.strictObject({
|
|
1814
|
+
diagram: z3.literal("flow").optional().describe("Optional: a spec with steps is a flow"),
|
|
1815
|
+
kind: z3.enum(["plan", "summary"]),
|
|
1816
|
+
title: short(),
|
|
1817
|
+
rules: z3.array(shortOpt()).optional(),
|
|
1818
|
+
start: ident(),
|
|
1819
|
+
steps: z3.array(stepSchema).max(MAX_ITEMS, `at most ${MAX_ITEMS} steps; split the flow`),
|
|
1820
|
+
links: z3.array(linkSchema).max(MAX_ITEMS, `at most ${MAX_ITEMS} links; split the flow`),
|
|
1821
|
+
gaps: z3.array(long()).optional()
|
|
1822
|
+
}).superRefine((spec, ctx) => {
|
|
1823
|
+
const issue = (path3, message) => ctx.addIssue({ code: "custom", path: path3, message });
|
|
1824
|
+
const counts = outgoingCounts(spec.links);
|
|
1825
|
+
const typeOf = (step) => step.type ?? inferType(counts.get(step.id) ?? 0);
|
|
1826
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1827
|
+
spec.steps.forEach((step, i) => {
|
|
1828
|
+
if (byId.has(step.id)) issue(["steps", i, "id"], `duplicate "${step.id}"`);
|
|
1829
|
+
byId.set(step.id, step);
|
|
1830
|
+
for (const m of labelIssues(step.label, "step", "source", "migration: add invoices")) {
|
|
1831
|
+
issue(["steps", i, "label"], m);
|
|
1832
|
+
}
|
|
1833
|
+
if (spec.kind === "summary" && step.status === "planned") {
|
|
1834
|
+
issue(["steps", i, "status"], 'a summary describes code that exists; "planned" is for plans');
|
|
1835
|
+
}
|
|
1836
|
+
if (spec.kind === "plan" && step.status !== "existing" && step.status !== "planned") {
|
|
1837
|
+
issue(["steps", i, "status"], `a plan uses only "existing" or "planned" steps, not "${step.status}"`);
|
|
1838
|
+
}
|
|
1839
|
+
if (step.status !== "planned" && !step.source) {
|
|
1840
|
+
issue(["steps", i, "source"], `required for a non-planned step ${ANCHOR}`);
|
|
1841
|
+
}
|
|
1842
|
+
for (const [field, m] of anchorIssues(step)) issue(["steps", i, field], m);
|
|
1843
|
+
});
|
|
1844
|
+
let refsOk = byId.has(spec.start);
|
|
1845
|
+
if (!refsOk) issue(["start"], `unknown step "${spec.start}"`);
|
|
1846
|
+
const outgoing = /* @__PURE__ */ new Map();
|
|
1847
|
+
spec.links.forEach((link, i) => {
|
|
1848
|
+
for (const end of ["from", "to"]) {
|
|
1849
|
+
if (byId.has(link[end])) continue;
|
|
1850
|
+
refsOk = false;
|
|
1851
|
+
issue(["links", i, end], `unknown step "${link[end]}"`);
|
|
1852
|
+
}
|
|
1853
|
+
const list2 = outgoing.get(link.from) ?? [];
|
|
1854
|
+
list2.push(i);
|
|
1855
|
+
outgoing.set(link.from, list2);
|
|
1856
|
+
if (spec.kind === "summary" && link.planned) {
|
|
1857
|
+
issue(["links", i, "planned"], 'a summary describes code that exists; "planned" is for plans');
|
|
1858
|
+
}
|
|
1859
|
+
const from = byId.get(link.from);
|
|
1860
|
+
const leavesDecision = from !== void 0 && typeOf(from) === "decision";
|
|
1861
|
+
if (leavesDecision && !isPlannedLink(spec, link) && !link.source) {
|
|
1862
|
+
issue(["links", i, "source"], `required for a non-planned branch leaving a decision ${ANCHOR}`);
|
|
1863
|
+
}
|
|
1864
|
+
for (const [field, m] of anchorIssues(link)) issue(["links", i, field], m);
|
|
1865
|
+
});
|
|
1866
|
+
spec.steps.forEach((step, i) => {
|
|
1867
|
+
const links = outgoing.get(step.id) ?? [];
|
|
1868
|
+
if (step.type === void 0 && step.label.trim().endsWith("?") && links.length < 2) {
|
|
1869
|
+
issue(["steps", i, "type"], `label ends in "?", so this is a decision: it needs at least 2 outgoing links, has ${links.length}`);
|
|
1870
|
+
return;
|
|
1871
|
+
}
|
|
1872
|
+
const type = typeOf(step);
|
|
1873
|
+
if (type === "end" && links.length > 0) {
|
|
1874
|
+
issue(["steps", i, "type"], `an end has no outgoing links, has ${links.length}`);
|
|
1875
|
+
}
|
|
1876
|
+
if (type === "step" && links.length > 1) {
|
|
1877
|
+
issue(["steps", i, "type"], `has ${links.length} outgoing links; make it a decision with labelled branches`);
|
|
1878
|
+
}
|
|
1879
|
+
if (type !== "decision") return;
|
|
1880
|
+
if (links.length < 2) {
|
|
1881
|
+
issue(["steps", i, "id"], `decision "${step.id}" needs at least 2 outgoing links, has ${links.length}`);
|
|
1882
|
+
}
|
|
1883
|
+
for (const li of links) {
|
|
1884
|
+
if (!spec.links[li].label) issue(["links", li, "label"], "required on a link leaving a decision");
|
|
1885
|
+
}
|
|
1886
|
+
});
|
|
1887
|
+
if (refsOk) {
|
|
1888
|
+
const reached = /* @__PURE__ */ new Set([spec.start]);
|
|
1889
|
+
for (const id of reached) {
|
|
1890
|
+
for (const li of outgoing.get(id) ?? []) reached.add(spec.links[li].to);
|
|
1891
|
+
}
|
|
1892
|
+
spec.steps.forEach((step, i) => {
|
|
1893
|
+
if (!reached.has(step.id)) issue(["steps", i], "not reachable from start");
|
|
1894
|
+
});
|
|
1895
|
+
}
|
|
1896
|
+
});
|
|
1897
|
+
function validateFlowSpec(input) {
|
|
1898
|
+
const result = flowSchema.safeParse(input);
|
|
1899
|
+
if (!result.success) return { ok: false, errors: formatIssues(result.error) };
|
|
1900
|
+
const counts = outgoingCounts(result.data.links);
|
|
1901
|
+
const steps = result.data.steps.map((s) => ({ ...s, type: s.type ?? inferType(counts.get(s.id) ?? 0) }));
|
|
1902
|
+
return { ok: true, spec: { ...result.data, diagram: "flow", steps } };
|
|
1903
|
+
}
|
|
1904
|
+
function flowJsonSchema() {
|
|
1905
|
+
return z3.toJSONSchema(flowSchema, { io: "input" });
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
// src/spec/schema.ts
|
|
1909
|
+
var STATUSES = ["new", "changed", "removed", "context", "config"];
|
|
1910
|
+
var NODE_KINDS = [
|
|
1911
|
+
"table",
|
|
1912
|
+
"enum",
|
|
1913
|
+
"model",
|
|
1914
|
+
"service",
|
|
1915
|
+
"endpoint",
|
|
1916
|
+
"component",
|
|
1917
|
+
"file",
|
|
1918
|
+
"config",
|
|
1919
|
+
"other"
|
|
1920
|
+
];
|
|
1921
|
+
var EDGE_KINDS = [
|
|
1922
|
+
"fk",
|
|
1923
|
+
"calls",
|
|
1924
|
+
"imports",
|
|
1925
|
+
"reads",
|
|
1926
|
+
"writes",
|
|
1927
|
+
"renders",
|
|
1928
|
+
"configures",
|
|
1929
|
+
"other"
|
|
1930
|
+
];
|
|
1931
|
+
var fieldSchema = z4.strictObject({
|
|
1932
|
+
name: short(),
|
|
1933
|
+
type: shortOpt().optional(),
|
|
1934
|
+
note: long().optional(),
|
|
1935
|
+
change: z4.enum(["added", "removed", "modified"]).optional()
|
|
1936
|
+
});
|
|
1937
|
+
var nodeSchema = z4.strictObject({
|
|
1938
|
+
id: ident(),
|
|
1939
|
+
label: short(),
|
|
1940
|
+
kind: z4.enum(NODE_KINDS).optional().describe("Defaults to file when path is set"),
|
|
1941
|
+
status: z4.enum(STATUSES),
|
|
1942
|
+
layer: short(),
|
|
1943
|
+
summary: long().optional(),
|
|
1944
|
+
path: pathStr().optional(),
|
|
1945
|
+
fields: z4.array(fieldSchema).optional(),
|
|
1946
|
+
fieldsComplete: z4.boolean().optional().describe("Required when fields is non-empty: true if every field is listed, false if only the fields you saw"),
|
|
1947
|
+
notes: z4.array(long()).optional()
|
|
1948
|
+
});
|
|
1949
|
+
var edgeSchema = z4.strictObject({
|
|
1950
|
+
from: ident(),
|
|
1951
|
+
to: ident(),
|
|
1952
|
+
label: shortOpt().optional(),
|
|
1953
|
+
kind: z4.enum(EDGE_KINDS).optional()
|
|
1954
|
+
});
|
|
1955
|
+
var MAX_NODES = 500;
|
|
1956
|
+
var MAX_EDGES = 1e3;
|
|
1957
|
+
var specSchema = z4.strictObject({
|
|
1958
|
+
diagram: z4.literal("map").optional(),
|
|
1959
|
+
title: short(),
|
|
1960
|
+
kind: z4.enum(["plan", "summary"]),
|
|
1961
|
+
rules: z4.array(shortOpt()).optional(),
|
|
1962
|
+
nodes: z4.array(nodeSchema).max(MAX_NODES, `at most ${MAX_NODES} nodes; split the map`),
|
|
1963
|
+
edges: z4.array(edgeSchema).max(MAX_EDGES, `at most ${MAX_EDGES} edges; split the map`),
|
|
1964
|
+
gaps: z4.array(long()).optional(),
|
|
1965
|
+
omitted: z4.array(long()).optional()
|
|
1966
|
+
}).superRefine((spec, ctx) => {
|
|
1967
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1968
|
+
spec.nodes.forEach((node, i) => {
|
|
1969
|
+
if (ids.has(node.id)) {
|
|
1970
|
+
ctx.addIssue({
|
|
1971
|
+
code: "custom",
|
|
1972
|
+
path: ["nodes", i, "id"],
|
|
1973
|
+
message: `duplicate "${node.id}"`
|
|
1974
|
+
});
|
|
1975
|
+
}
|
|
1976
|
+
ids.add(node.id);
|
|
1977
|
+
if (node.kind === void 0 && node.path === void 0) {
|
|
1978
|
+
ctx.addIssue({ code: "custom", path: ["nodes", i, "kind"], message: 'required unless path is set (then it defaults to "file")' });
|
|
1979
|
+
}
|
|
1980
|
+
if (node.fields?.length && node.fieldsComplete === void 0) {
|
|
1981
|
+
ctx.addIssue({
|
|
1982
|
+
code: "custom",
|
|
1983
|
+
path: ["nodes", i, "fieldsComplete"],
|
|
1984
|
+
message: "required when fields are listed (true if you listed every field, false if only what you saw)"
|
|
1985
|
+
});
|
|
1986
|
+
}
|
|
1987
|
+
for (const message of labelIssues(
|
|
1988
|
+
node.label,
|
|
1989
|
+
"node",
|
|
1990
|
+
"path",
|
|
1991
|
+
"migration: add invoices"
|
|
1992
|
+
)) {
|
|
1993
|
+
ctx.addIssue({ code: "custom", path: ["nodes", i, "label"], message });
|
|
1994
|
+
}
|
|
1995
|
+
});
|
|
1996
|
+
spec.edges.forEach((edge, i) => {
|
|
1997
|
+
for (const end of ["from", "to"]) {
|
|
1998
|
+
if (!ids.has(edge[end])) {
|
|
1999
|
+
ctx.addIssue({
|
|
2000
|
+
code: "custom",
|
|
2001
|
+
path: ["edges", i, end],
|
|
2002
|
+
message: `unknown node "${edge[end]}"`
|
|
2003
|
+
});
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
});
|
|
2007
|
+
});
|
|
2008
|
+
function isFlow(input) {
|
|
2009
|
+
if (typeof input !== "object" || input === null) return false;
|
|
2010
|
+
const diagram = input.diagram;
|
|
2011
|
+
return diagram === "flow" || diagram === void 0 && Object.hasOwn(input, "steps");
|
|
2012
|
+
}
|
|
2013
|
+
function validateSpec(input) {
|
|
2014
|
+
if (isFlow(input)) return validateFlowSpec(input);
|
|
2015
|
+
const result = specSchema.safeParse(input);
|
|
2016
|
+
if (!result.success) return { ok: false, errors: formatIssues(result.error) };
|
|
2017
|
+
const nodes = result.data.nodes.map((n) => ({ ...n, kind: n.kind ?? "file" }));
|
|
2018
|
+
return { ok: true, spec: { ...result.data, nodes } };
|
|
2019
|
+
}
|
|
2020
|
+
function specJsonSchema() {
|
|
2021
|
+
return z4.toJSONSchema(specSchema, { io: "input" });
|
|
2022
|
+
}
|
|
2023
|
+
|
|
2024
|
+
// src/commands/open.ts
|
|
2025
|
+
import { spawn } from "child_process";
|
|
2026
|
+
import { win32 as win322 } from "path";
|
|
2027
|
+
function openArgv(platform, file, env = process.env) {
|
|
2028
|
+
if (platform === "darwin") return ["open", [file]];
|
|
2029
|
+
if (platform === "win32") {
|
|
2030
|
+
return [win322.join(env.SystemRoot ?? "C:\\Windows", "System32", "rundll32.exe"), ["url.dll,FileProtocolHandler", file]];
|
|
2031
|
+
}
|
|
2032
|
+
return ["xdg-open", [file]];
|
|
2033
|
+
}
|
|
2034
|
+
function inCodeEditor(env) {
|
|
2035
|
+
return Boolean(env.VSCODE_PID) || env.TERM_PROGRAM === "vscode";
|
|
2036
|
+
}
|
|
2037
|
+
function openInBrowser(file) {
|
|
2038
|
+
const [cmd, args] = openArgv(process.platform, file);
|
|
2039
|
+
try {
|
|
2040
|
+
spawn(cmd, args, { detached: true, stdio: "ignore" }).on("error", () => {
|
|
2041
|
+
}).unref();
|
|
2042
|
+
} catch {
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
|
|
2046
|
+
// src/render/flow/layout.ts
|
|
2047
|
+
var LINE_HEIGHT2 = 14;
|
|
2048
|
+
var BADGE_HEIGHT = 12;
|
|
2049
|
+
var PAD = 8;
|
|
2050
|
+
var MAX_LINES = 3;
|
|
2051
|
+
var CHAR_W = 6;
|
|
2052
|
+
var SHAPE = {
|
|
2053
|
+
step: { w: 180, chars: 26 },
|
|
2054
|
+
end: { w: 180, chars: 26 },
|
|
2055
|
+
decision: { w: 220, chars: 18 }
|
|
2056
|
+
};
|
|
2057
|
+
function sizeOf(step) {
|
|
2058
|
+
const { w, chars } = SHAPE[step.type];
|
|
2059
|
+
const lines = wrapText(step.label, chars, MAX_LINES);
|
|
2060
|
+
const badge = step.status === "existing" ? void 0 : step.status;
|
|
2061
|
+
const content = lines.length * LINE_HEIGHT2 + (badge ? BADGE_HEIGHT : 0);
|
|
2062
|
+
const h = step.type === "decision" ? 2 * content + 2 * PAD : content + 2 * PAD;
|
|
2063
|
+
return { id: step.id, w, h, lines, ...badge ? { badge } : {} };
|
|
2064
|
+
}
|
|
2065
|
+
function clipToDiamond(p, n) {
|
|
2066
|
+
const cx = n.x + n.w / 2;
|
|
2067
|
+
const cy = n.y + n.h / 2;
|
|
2068
|
+
const hw = n.w / 2;
|
|
2069
|
+
const hh = n.h / 2;
|
|
2070
|
+
const eps = 0.5;
|
|
2071
|
+
if (Math.abs(p.y - n.y) < eps || Math.abs(p.y - n.y - n.h) < eps) {
|
|
2072
|
+
const dy = hh * (1 - Math.min(1, Math.abs(p.x - cx) / hw));
|
|
2073
|
+
return { x: p.x, y: p.y < cy ? cy - dy : cy + dy };
|
|
2074
|
+
}
|
|
2075
|
+
if (Math.abs(p.x - n.x) < eps || Math.abs(p.x - n.x - n.w) < eps) {
|
|
2076
|
+
const dx = hw * (1 - Math.min(1, Math.abs(p.y - cy) / hh));
|
|
2077
|
+
return { x: p.x < cx ? cx - dx : cx + dx, y: p.y };
|
|
2078
|
+
}
|
|
2079
|
+
return p;
|
|
2080
|
+
}
|
|
2081
|
+
async function layoutFlow(spec) {
|
|
2082
|
+
const sizes = spec.steps.map(sizeOf);
|
|
2083
|
+
const edges = spec.links.map((l, i) => ({
|
|
2084
|
+
id: `e${i}`,
|
|
2085
|
+
sources: [l.from],
|
|
2086
|
+
targets: [l.to],
|
|
2087
|
+
...l.label ? { labels: [{ text: l.label, width: l.label.length * CHAR_W + 6, height: LINE_HEIGHT2 }] } : {}
|
|
2088
|
+
}));
|
|
2089
|
+
const graph = {
|
|
2090
|
+
id: "root",
|
|
2091
|
+
layoutOptions: {
|
|
2092
|
+
"elk.algorithm": "layered",
|
|
2093
|
+
"elk.direction": "DOWN",
|
|
2094
|
+
"elk.padding": "[top=16,left=16,bottom=16,right=16]",
|
|
2095
|
+
"elk.spacing.nodeNode": "40",
|
|
2096
|
+
"elk.layered.spacing.nodeNodeBetweenLayers": "48",
|
|
2097
|
+
"elk.spacing.edgeLabel": "4",
|
|
2098
|
+
"elk.layered.considerModelOrder.strategy": "NODES_AND_EDGES"
|
|
2099
|
+
},
|
|
2100
|
+
children: sizes.map((s) => ({ id: s.id, width: s.w, height: s.h })),
|
|
2101
|
+
edges
|
|
2102
|
+
};
|
|
2103
|
+
const { default: ELK } = await import("elkjs/lib/elk.bundled.js");
|
|
2104
|
+
const root = await new ELK().layout(graph);
|
|
2105
|
+
const pos = new Map((root.children ?? []).map((c) => [c.id, c]));
|
|
2106
|
+
const nodes = sizes.map((s) => {
|
|
2107
|
+
const p = pos.get(s.id);
|
|
2108
|
+
return { ...s, x: p?.x ?? 0, y: p?.y ?? 0 };
|
|
2109
|
+
});
|
|
2110
|
+
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
2111
|
+
const decisions = new Set(spec.steps.filter((s) => s.type === "decision").map((s) => s.id));
|
|
2112
|
+
const clip3 = (p, id) => decisions.has(id) ? clipToDiamond(p, byId.get(id)) : p;
|
|
2113
|
+
const laidOut = new Map((root.edges ?? []).map((e) => [e.id, e]));
|
|
2114
|
+
const out = spec.links.map((link, i) => {
|
|
2115
|
+
const e = laidOut.get(`e${i}`);
|
|
2116
|
+
const sec = e?.sections?.[0];
|
|
2117
|
+
const points = sec ? [clip3(sec.startPoint, link.from), ...sec.bendPoints ?? [], clip3(sec.endPoint, link.to)] : [];
|
|
2118
|
+
const lab = e?.labels?.[0];
|
|
2119
|
+
return {
|
|
2120
|
+
points,
|
|
2121
|
+
...lab ? { labelAt: { x: (lab.x ?? 0) + (lab.width ?? 0) / 2, y: (lab.y ?? 0) + (lab.height ?? 0) / 2 } } : {}
|
|
2122
|
+
};
|
|
2123
|
+
});
|
|
2124
|
+
return { width: root.width ?? 0, height: root.height ?? 0, nodes, edges: out };
|
|
2125
|
+
}
|
|
2126
|
+
|
|
2127
|
+
// src/render/flow/html.ts
|
|
2128
|
+
var FLOW_CSS = `
|
|
2129
|
+
.node .shape{fill:var(--card);stroke:var(--muted);stroke-width:1.2}
|
|
2130
|
+
.node .label{font-weight:500;text-anchor:middle}
|
|
2131
|
+
.node .badge{text-anchor:middle;font-weight:600}
|
|
2132
|
+
.node.selected .shape{stroke-width:2.5}
|
|
2133
|
+
.node:focus-visible .shape{stroke:var(--edge);stroke-width:3.5}
|
|
2134
|
+
.status-new .shape{stroke:var(--new)}
|
|
2135
|
+
.status-changed .shape{stroke:var(--chg)}
|
|
2136
|
+
.status-planned .shape{stroke:var(--cfg);stroke-dasharray:6 4;fill:var(--bg)}.status-planned .badge{fill:var(--cfg-t)}
|
|
2137
|
+
.edge.planned path{stroke:var(--cfg);stroke-dasharray:6 4}#arrow-planned path{fill:var(--cfg)}.edge.planned text{fill:var(--cfg-t)}
|
|
2138
|
+
aside .status{color:var(--muted);margin-bottom:4px}
|
|
2139
|
+
aside .tag{font-size:10px;text-transform:uppercase;border:1px solid currentColor;border-radius:8px;padding:0 5px}
|
|
2140
|
+
aside .tag-new{color:var(--new-t)}aside .tag-changed{color:var(--chg-t)}aside .tag-planned{color:var(--cfg-t);border-style:dashed}
|
|
2141
|
+
aside .planned-note{color:var(--cfg-t);font-style:italic;margin:6px 0}
|
|
2142
|
+
aside .snippet{font:11px/1.45 ui-monospace,monospace;background:var(--bg);border:1px solid var(--line);border-radius:4px;padding:6px 8px;margin:6px 0;overflow:auto;white-space:pre}
|
|
2143
|
+
aside .snippet .ln{display:inline-block;min-width:3ch;margin-right:10px;color:var(--muted);text-align:right;user-select:none}
|
|
2144
|
+
aside .more{color:var(--muted);font-size:11px;margin:0}
|
|
2145
|
+
aside .branches{padding-left:0;list-style:none}
|
|
2146
|
+
aside .branches li{margin:0 0 10px}
|
|
2147
|
+
`;
|
|
2148
|
+
function shape(step, b) {
|
|
2149
|
+
if (step.type === "decision") {
|
|
2150
|
+
const cx = b.x + b.w / 2;
|
|
2151
|
+
const cy = b.y + b.h / 2;
|
|
2152
|
+
const pts = [
|
|
2153
|
+
[cx, b.y],
|
|
2154
|
+
[b.x + b.w, cy],
|
|
2155
|
+
[cx, b.y + b.h],
|
|
2156
|
+
[b.x, cy]
|
|
2157
|
+
];
|
|
2158
|
+
return `<polygon class="shape" points="${pts.map(([x, y]) => `${num(x)},${num(y)}`).join(" ")}"/>`;
|
|
2159
|
+
}
|
|
2160
|
+
const rx = step.type === "end" ? b.h / 2 : 4;
|
|
2161
|
+
return `<rect class="shape" x="${num(b.x)}" y="${num(b.y)}" width="${num(b.w)}" height="${num(b.h)}" rx="${num(rx)}"/>`;
|
|
2162
|
+
}
|
|
2163
|
+
function renderStep(step, b) {
|
|
2164
|
+
const cx = num(b.x + b.w / 2);
|
|
2165
|
+
const content = b.lines.length * LINE_HEIGHT2 + (b.badge ? BADGE_HEIGHT : 0);
|
|
2166
|
+
let y = b.y + (b.h - content) / 2;
|
|
2167
|
+
let text = "";
|
|
2168
|
+
if (b.badge) {
|
|
2169
|
+
text += `<text class="badge" x="${cx}" y="${num(y + 9)}">${esc(b.badge)}</text>`;
|
|
2170
|
+
y += BADGE_HEIGHT;
|
|
2171
|
+
}
|
|
2172
|
+
for (const l of b.lines) {
|
|
2173
|
+
text += `<text class="label" x="${cx}" y="${num(y + 11)}">${esc(l)}</text>`;
|
|
2174
|
+
y += LINE_HEIGHT2;
|
|
2175
|
+
}
|
|
2176
|
+
return `<g class="node type-${step.type} status-${step.status}" data-id="${esc(step.id)}" tabindex="0" role="button" aria-label="${esc(`${step.label} (${step.status} ${step.type})`)}">` + shape(step, b) + text + `</g>`;
|
|
2177
|
+
}
|
|
2178
|
+
function renderLink(link, e, planned) {
|
|
2179
|
+
if (e.points.length < 2) return "";
|
|
2180
|
+
const d = e.points.map((p, i) => `${i ? "L" : "M"}${num(p.x)},${num(p.y)}`).join(" ");
|
|
2181
|
+
let out = `<path d="${d}" marker-end="url(#${planned ? "arrow-planned" : "arrow"})"/>`;
|
|
2182
|
+
if (link.label) {
|
|
2183
|
+
const m = e.labelAt ?? midpoint(e.points);
|
|
2184
|
+
const w = link.label.length * 5.6 + 6;
|
|
2185
|
+
out += `<rect x="${num(m.x - w / 2)}" y="${num(m.y - 7)}" width="${num(w)}" height="12" rx="2"/><text x="${num(m.x)}" y="${num(m.y + 2)}">${esc(link.label)}</text>`;
|
|
2186
|
+
}
|
|
2187
|
+
return `<g class="edge${planned ? " planned" : ""}">${out}</g>`;
|
|
2188
|
+
}
|
|
2189
|
+
function snippetHtml(s) {
|
|
2190
|
+
const code = s.lines.map((l, i) => `<span class="ln">${s.startLine + i}</span>${esc(l)}`).join("\n");
|
|
2191
|
+
const end = Number(s.source.match(/-(\d+)$/)?.[1] ?? s.startLine);
|
|
2192
|
+
const total = end - s.startLine + 1;
|
|
2193
|
+
const more = total > s.lines.length ? `<p class="more">first ${s.lines.length} of ${total} lines</p>` : "";
|
|
2194
|
+
return `<div class="path">${esc(s.source)}</div><pre class="snippet"><code>${code}</code></pre>${more}`;
|
|
2195
|
+
}
|
|
2196
|
+
var tag = (status) => `<span class="tag tag-${esc(status)}">${esc(status)}</span>`;
|
|
2197
|
+
function stepPanel(spec, step, snippets, byId) {
|
|
2198
|
+
let out = `<h2>${esc(step.label)}</h2>`;
|
|
2199
|
+
out += `<div class="status">${tag(step.status)} ${esc(step.type)}</div>`;
|
|
2200
|
+
const snip = snippets.steps.get(step.id);
|
|
2201
|
+
if (step.status === "planned") {
|
|
2202
|
+
out += `<p class="planned-note">${snip ? "Planned change to the code below." : "Planned: not in the code yet."}</p>`;
|
|
2203
|
+
}
|
|
2204
|
+
if (snip) out += snippetHtml(snip);
|
|
2205
|
+
else if (step.source) out += `<div class="path">${esc(step.source)}</div>`;
|
|
2206
|
+
const next = spec.links.map((l, i) => ({ l, i })).filter(({ l }) => l.from === step.id);
|
|
2207
|
+
if (next.length) {
|
|
2208
|
+
const items = next.map(({ l, i }) => {
|
|
2209
|
+
const target = byId.get(l.to)?.label ?? l.to;
|
|
2210
|
+
let li = `${l.label ? `<b>${esc(l.label)}</b> \u2192 ` : "\u2192 "}${esc(target)}`;
|
|
2211
|
+
if (isPlannedLink(spec, l)) li += ` ${tag("planned")}`;
|
|
2212
|
+
const s = snippets.links[i];
|
|
2213
|
+
if (s) li += snippetHtml(s);
|
|
2214
|
+
else if (l.source) li += `<div class="path">${esc(l.source)}</div>`;
|
|
2215
|
+
return `<li>${li}</li>`;
|
|
2216
|
+
});
|
|
2217
|
+
out += `<h3>Next</h3><ul class="branches">${items.join("")}</ul>`;
|
|
2218
|
+
}
|
|
2219
|
+
return `<template class="card-panel" data-for="${esc(step.id)}">${out}</template>`;
|
|
2220
|
+
}
|
|
2221
|
+
function pageInfo2(spec, anyPlanned) {
|
|
2222
|
+
let out = "<p>Click a step for its status, source and code. Scroll to zoom, drag to pan.</p>";
|
|
2223
|
+
if (anyPlanned) out += '<p class="planned-note">Dashed steps and arrows are planned: not in the code yet.</p>';
|
|
2224
|
+
if (spec.gaps?.length) out += `<h3>Gaps</h3>${list(spec.gaps)}`;
|
|
2225
|
+
return `<section id="page-info">${out}</section>`;
|
|
2226
|
+
}
|
|
2227
|
+
function renderFlowHtml(spec, layout, snippets, meta) {
|
|
2228
|
+
const byId = new Map(spec.steps.map((s) => [s.id, s]));
|
|
2229
|
+
const boxes = new Map(layout.nodes.map((n) => [n.id, n]));
|
|
2230
|
+
const planned = spec.links.map((l) => isPlannedLink(spec, l));
|
|
2231
|
+
const edges = spec.links.map((l, i) => layout.edges[i] ? renderLink(l, layout.edges[i], planned[i]) : "").join("");
|
|
2232
|
+
const nodes = spec.steps.map((s) => {
|
|
2233
|
+
const b = boxes.get(s.id);
|
|
2234
|
+
return b ? renderStep(s, b) : "";
|
|
2235
|
+
}).join("");
|
|
2236
|
+
const anyPlanned = planned.includes(true) || spec.steps.some((s) => s.status === "planned");
|
|
2237
|
+
const infoButton = spec.gaps?.length ? '<button id="info-toggle" type="button" aria-controls="page-info" title="Show what the agent did not check">Gaps</button>' : "";
|
|
2238
|
+
return renderPage({
|
|
2239
|
+
title: spec.title,
|
|
2240
|
+
meta,
|
|
2241
|
+
infoButton,
|
|
2242
|
+
viewport: `${edges}${nodes}`,
|
|
2243
|
+
aside: `${pageInfo2(spec, anyPlanned)}<div id="panel" hidden></div>${spec.steps.map((s) => stepPanel(spec, s, snippets, byId)).join("")}`,
|
|
2244
|
+
width: layout.width,
|
|
2245
|
+
height: layout.height,
|
|
2246
|
+
extraCss: FLOW_CSS,
|
|
2247
|
+
extraDefs: '<marker id="arrow-planned" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0 L10,5 L0,10 z"/></marker>'
|
|
2248
|
+
});
|
|
2249
|
+
}
|
|
2250
|
+
|
|
2251
|
+
// src/render/flow/walk.ts
|
|
2252
|
+
function walkFlow(spec, budget) {
|
|
2253
|
+
const byId = new Map(spec.steps.map((s) => [s.id, s]));
|
|
2254
|
+
const out = /* @__PURE__ */ new Map();
|
|
2255
|
+
const incoming = /* @__PURE__ */ new Map([[spec.start, 1]]);
|
|
2256
|
+
for (const link of spec.links) {
|
|
2257
|
+
out.set(link.from, [...out.get(link.from) ?? [], link]);
|
|
2258
|
+
incoming.set(link.to, (incoming.get(link.to) ?? 0) + 1);
|
|
2259
|
+
}
|
|
2260
|
+
const shared = new Set([...incoming].filter(([, n]) => n > 1).map(([id]) => id));
|
|
2261
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2262
|
+
const queue = [];
|
|
2263
|
+
let placed = 0;
|
|
2264
|
+
let truncated = false;
|
|
2265
|
+
const take = (id) => {
|
|
2266
|
+
if (placed >= budget) return false;
|
|
2267
|
+
placed++;
|
|
2268
|
+
seen.add(id);
|
|
2269
|
+
return true;
|
|
2270
|
+
};
|
|
2271
|
+
const cut2 = (id, via) => {
|
|
2272
|
+
truncated = true;
|
|
2273
|
+
let hidden = 0;
|
|
2274
|
+
const stack = [id];
|
|
2275
|
+
while (stack.length > 0) {
|
|
2276
|
+
const next = stack.pop();
|
|
2277
|
+
if (seen.has(next)) continue;
|
|
2278
|
+
seen.add(next);
|
|
2279
|
+
hidden++;
|
|
2280
|
+
stack.push(...(out.get(next) ?? []).map((l) => l.to));
|
|
2281
|
+
}
|
|
2282
|
+
return { kind: "cut", hidden, via };
|
|
2283
|
+
};
|
|
2284
|
+
const ref = (step, via) => {
|
|
2285
|
+
if (queue.includes(step.id)) return { kind: "ref", step, via };
|
|
2286
|
+
if (!take(step.id)) return cut2(step.id, via);
|
|
2287
|
+
queue.push(step.id);
|
|
2288
|
+
return { kind: "ref", step, via };
|
|
2289
|
+
};
|
|
2290
|
+
const chain = (first, firstPaid) => {
|
|
2291
|
+
const items = [];
|
|
2292
|
+
let step = first;
|
|
2293
|
+
let via;
|
|
2294
|
+
for (let paid = firstPaid; ; paid = false) {
|
|
2295
|
+
if (!paid && !take(step.id)) return { items: [...items, cut2(step.id, via)] };
|
|
2296
|
+
const links = out.get(step.id) ?? [];
|
|
2297
|
+
if (step.type === "decision" || links.length > 1) {
|
|
2298
|
+
return { items, branch: { head: step, arms: links.map((link) => ({ link, chain: arm(link.to) })) } };
|
|
2299
|
+
}
|
|
2300
|
+
items.push({ kind: "step", step, via });
|
|
2301
|
+
if (links.length === 0) return { items };
|
|
2302
|
+
via = links[0];
|
|
2303
|
+
const next = byId.get(via.to);
|
|
2304
|
+
if (shared.has(next.id)) return { items: [...items, ref(next, via)] };
|
|
2305
|
+
step = next;
|
|
2306
|
+
}
|
|
2307
|
+
};
|
|
2308
|
+
const arm = (to) => {
|
|
2309
|
+
const step = byId.get(to);
|
|
2310
|
+
return shared.has(to) ? { items: [ref(step)] } : chain(step, false);
|
|
2311
|
+
};
|
|
2312
|
+
const start = byId.get(spec.start);
|
|
2313
|
+
let head;
|
|
2314
|
+
if (shared.has(start.id)) {
|
|
2315
|
+
if (!take(start.id)) return { blocks: [], unreachable: 0, truncated: true };
|
|
2316
|
+
queue.push(start.id);
|
|
2317
|
+
head = { shared: true, chain: chain(start, true) };
|
|
2318
|
+
} else {
|
|
2319
|
+
head = { shared: false, chain: chain(start, false) };
|
|
2320
|
+
}
|
|
2321
|
+
if (head.chain.items.some((i) => i.kind === "cut")) return { blocks: [], unreachable: 0, truncated: true };
|
|
2322
|
+
const blocks = [head];
|
|
2323
|
+
for (let i = head.shared ? 1 : 0; i < queue.length; i++) {
|
|
2324
|
+
blocks.push({ shared: true, chain: chain(byId.get(queue[i]), true) });
|
|
2325
|
+
}
|
|
2326
|
+
const unreachable = spec.steps.filter((s) => !seen.has(s.id)).length;
|
|
2327
|
+
return { blocks, unreachable, truncated: truncated || unreachable > 0 };
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
// src/render/flow/tree.ts
|
|
2331
|
+
var FLOW_KEY = "key: + new ~ changed ? planned \u25C7 decision \u2937 shared step";
|
|
2332
|
+
var MARKER3 = { existing: "", new: "+", changed: "~", planned: "?" };
|
|
2333
|
+
var SGR2 = { existing: void 0, new: "32", changed: "33", planned: "35" };
|
|
2334
|
+
var painter = (status, ctx) => ctx.color && SGR2[status] ? (text) => text ? `\x1B[${SGR2[status]}m${text}\x1B[0m` : text : void 0;
|
|
2335
|
+
var stepSegment = (step, ctx) => ({
|
|
2336
|
+
text: MARKER3[step.status] + flat(step.label),
|
|
2337
|
+
paint: painter(step.status, ctx)
|
|
2338
|
+
});
|
|
2339
|
+
var cutText = (hidden, ctx) => hidden > 0 ? `\u2026 (+${hidden} steps ${ctx.htmlPath ? "in web view" : "not shown"})` : "\u2026";
|
|
2340
|
+
function itemSegments(item2, ctx) {
|
|
2341
|
+
if (item2.kind === "cut") return [{ text: cutText(item2.hidden, ctx) }];
|
|
2342
|
+
const label = stepSegment(item2.step, ctx);
|
|
2343
|
+
return item2.kind === "ref" ? [{ text: "\u2937 " }, label] : [label];
|
|
2344
|
+
}
|
|
2345
|
+
var segWidth = (segments) => columns(segments.map((s) => s.text).join(""));
|
|
2346
|
+
var markedLink = (link, ctx) => link.planned === true && !endsPlanned(ctx.spec, link);
|
|
2347
|
+
var endsPlanned = (spec, link) => spec.steps.some((s) => s.status === "planned" && (s.id === link.from || s.id === link.to));
|
|
2348
|
+
function runLines(items, first, rest, ctx) {
|
|
2349
|
+
const lines = [];
|
|
2350
|
+
let line = first;
|
|
2351
|
+
items.forEach((item2, i) => {
|
|
2352
|
+
const segs = itemSegments(item2, ctx);
|
|
2353
|
+
const mark = item2.via && markedLink(item2.via, ctx) ? "?" : "";
|
|
2354
|
+
const arrow = { text: `${mark}\u2192 `, paint: mark ? painter("planned", ctx) : void 0 };
|
|
2355
|
+
if (i === 0) {
|
|
2356
|
+
line = [...line, ...segs];
|
|
2357
|
+
} else if (segWidth(line) + segWidth(segs) + 2 + columns(arrow.text) <= ctx.width) {
|
|
2358
|
+
line = [...line, { text: " " }, arrow, ...segs];
|
|
2359
|
+
} else {
|
|
2360
|
+
lines.push(line);
|
|
2361
|
+
line = [{ text: `${rest} ` }, arrow, ...segs];
|
|
2362
|
+
}
|
|
2363
|
+
});
|
|
2364
|
+
lines.push(line);
|
|
2365
|
+
return lines.map((l) => fit(l, ctx.width, ctx.cuts));
|
|
2366
|
+
}
|
|
2367
|
+
function armLines(arms, rest, ctx) {
|
|
2368
|
+
const planned = arms.map(({ link }) => isPlannedLink(ctx.spec, link));
|
|
2369
|
+
const labels = arms.map(({ link }, i) => (planned[i] ? "?" : "") + flat(link.label ?? ""));
|
|
2370
|
+
const pad2 = Math.min(Math.max(...labels.map(columns)), Math.floor(ctx.width / 3));
|
|
2371
|
+
return arms.flatMap((arm, i) => {
|
|
2372
|
+
const last = i === arms.length - 1;
|
|
2373
|
+
const glyph = last ? "\u2514\u2500 " : "\u251C\u2500 ";
|
|
2374
|
+
const label = truncate(labels[i], pad2, ctx.cuts);
|
|
2375
|
+
const head = [{ text: rest + glyph }];
|
|
2376
|
+
if (pad2 > 0) {
|
|
2377
|
+
const paint2 = planned[i] ? painter("planned", ctx) : void 0;
|
|
2378
|
+
head.push({ text: label, paint: paint2 }, { text: `${" ".repeat(pad2 - columns(label))} \u2192 ` });
|
|
2379
|
+
}
|
|
2380
|
+
const under = `${rest}${last ? " " : "\u2502 "}${pad2 > 0 ? " ".repeat(pad2 + 3) : ""}`;
|
|
2381
|
+
return chainLines(arm.chain, head, under, "", ctx);
|
|
2382
|
+
});
|
|
2383
|
+
}
|
|
2384
|
+
function chainLines(chain, first, rest, lead, ctx) {
|
|
2385
|
+
const lines = [];
|
|
2386
|
+
let prefix = [...first, { text: lead }];
|
|
2387
|
+
if (chain.items.length > 0) {
|
|
2388
|
+
lines.push(...runLines(chain.items, prefix, rest, ctx));
|
|
2389
|
+
prefix = [{ text: rest }];
|
|
2390
|
+
}
|
|
2391
|
+
if (chain.branch) {
|
|
2392
|
+
const { head, arms } = chain.branch;
|
|
2393
|
+
const glyph = head.type === "decision" ? "\u25C7 " : "";
|
|
2394
|
+
lines.push(fit([...prefix, { text: glyph }, stepSegment(head, ctx)], ctx.width, ctx.cuts));
|
|
2395
|
+
lines.push(...armLines(arms, rest, ctx));
|
|
2396
|
+
}
|
|
2397
|
+
return lines;
|
|
2398
|
+
}
|
|
2399
|
+
function footer2(spec, ctx, md) {
|
|
2400
|
+
const count = (status) => spec.steps.filter((s) => s.status === status).length;
|
|
2401
|
+
const lines = [
|
|
2402
|
+
truncate(
|
|
2403
|
+
`${spec.steps.length} steps \xB7 ${count("new")} new \xB7 ${count("changed")} changed \xB7 ${count("planned")} planned`,
|
|
2404
|
+
ctx.width
|
|
2405
|
+
)
|
|
2406
|
+
];
|
|
2407
|
+
if (!md) lines.push(truncate(FLOW_KEY, ctx.width));
|
|
2408
|
+
if (spec.gaps?.length) lines.push(wrapItems("gaps: ", spec.gaps.map(flat), ctx.width));
|
|
2409
|
+
if (ctx.htmlPath && !md) lines.push(fullMapLine(ctx.htmlPath));
|
|
2410
|
+
return lines.join("\n");
|
|
2411
|
+
}
|
|
2412
|
+
function flowMarkdown(title, tree, htmlPath, width, cuts) {
|
|
2413
|
+
const heading = truncate(flat(title), Math.max(width, MIN_WIDTH), cuts);
|
|
2414
|
+
const titled = `${heading}
|
|
2415
|
+
${"\u2500".repeat(columns(heading))}`;
|
|
2416
|
+
return markdownBlock(`**Flow** _(${FLOW_KEY})_`, tree === void 0 ? titled : `${titled}
|
|
2417
|
+
${tree}`, htmlPath);
|
|
2418
|
+
}
|
|
2419
|
+
var TOO_LARGE = "flow too large for the terminal; use --output both or web";
|
|
2420
|
+
function renderFlowTree(spec, opts) {
|
|
2421
|
+
const ctx = {
|
|
2422
|
+
width: Math.max(opts.width ?? defaultWidth(), MIN_WIDTH),
|
|
2423
|
+
color: opts.color && !opts.md,
|
|
2424
|
+
cuts: { truncated: false },
|
|
2425
|
+
htmlPath: opts.htmlPath,
|
|
2426
|
+
spec
|
|
2427
|
+
};
|
|
2428
|
+
const walk = walkFlow(spec, opts.maxNodes);
|
|
2429
|
+
const md = opts.md ?? false;
|
|
2430
|
+
if (walk.blocks.length === 0) {
|
|
2431
|
+
if (!opts.htmlPath) return { text: md ? flowMarkdown(spec.title, TOO_LARGE, void 0, ctx.width) : `${TOO_LARGE}
|
|
2432
|
+
`, truncated: true };
|
|
2433
|
+
return { text: md ? flowMarkdown(spec.title, void 0, opts.htmlPath, ctx.width) : `${fullMapLine(opts.htmlPath)}
|
|
2434
|
+
`, truncated: true };
|
|
2435
|
+
}
|
|
2436
|
+
const blocks = walk.blocks.map((b) => chainLines(b.chain, [], "", b.shared ? "\u2937 " : "", ctx).join("\n"));
|
|
2437
|
+
if (spec.kind === "plan" && (spec.steps.some((s) => s.status === "planned") || spec.links.some((l) => isPlannedLink(spec, l)))) {
|
|
2438
|
+
blocks[0] = `${truncate("planned flow", ctx.width)}
|
|
2439
|
+
${blocks[0]}`;
|
|
2440
|
+
}
|
|
2441
|
+
if (walk.unreachable > 0) blocks[blocks.length - 1] += `
|
|
2442
|
+
${truncate(cutText(walk.unreachable, ctx), ctx.width, ctx.cuts)}`;
|
|
2443
|
+
const tree = [...blocks, footer2(spec, ctx, md)].join("\n\n");
|
|
2444
|
+
const text = md ? flowMarkdown(spec.title, tree, opts.htmlPath, ctx.width, ctx.cuts) : `${tree}
|
|
2445
|
+
`;
|
|
2446
|
+
return { text, truncated: walk.truncated || ctx.cuts.truncated };
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
// src/commands/render-flow.ts
|
|
2450
|
+
async function renderFlow(spec, snippets, ctx) {
|
|
2451
|
+
const { output } = ctx;
|
|
2452
|
+
const writeHtml = () => ctx.writeHtml(async (meta) => renderFlowHtml(spec, await layoutFlow(spec), snippets, meta));
|
|
2453
|
+
let htmlPath;
|
|
2454
|
+
let tree;
|
|
2455
|
+
if (output === "web" || output === "both" || output === "auto" && spec.steps.length >= ctx.minNodes) {
|
|
2456
|
+
htmlPath = await writeHtml();
|
|
2457
|
+
} else if (output === "auto") {
|
|
2458
|
+
tree = renderFlowTree(spec, ctx.tree);
|
|
2459
|
+
if (tree.truncated) {
|
|
2460
|
+
htmlPath = await writeHtml();
|
|
2461
|
+
tree = void 0;
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
if (output === "web") return ctx.tree.md ? flowMarkdown(spec.title, void 0, htmlPath, ctx.tree.width ?? defaultWidth()) : `${fullMapLine(htmlPath)}
|
|
2465
|
+
`;
|
|
2466
|
+
return (tree ?? renderFlowTree(spec, { ...ctx.tree, htmlPath })).text;
|
|
2467
|
+
}
|
|
2468
|
+
|
|
2469
|
+
// src/commands/render.ts
|
|
2470
|
+
var InvalidSpec = class extends Error {
|
|
2471
|
+
constructor(errors) {
|
|
2472
|
+
super("invalid spec");
|
|
2473
|
+
this.errors = errors;
|
|
2474
|
+
}
|
|
2475
|
+
errors;
|
|
2476
|
+
};
|
|
2477
|
+
var TOO_BIG = "spec is larger than 2 MB";
|
|
2478
|
+
async function readStdin() {
|
|
2479
|
+
const chunks = [];
|
|
2480
|
+
let size = 0;
|
|
2481
|
+
for await (const chunk of process.stdin) {
|
|
2482
|
+
size += chunk.length;
|
|
2483
|
+
if (size > MAX_SPEC_BYTES) throw new Error(TOO_BIG);
|
|
2484
|
+
chunks.push(chunk);
|
|
2485
|
+
}
|
|
2486
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
2487
|
+
}
|
|
2488
|
+
function readSpecFile(file) {
|
|
2489
|
+
const fd = openSync(file, constants2.O_RDONLY | (constants2.O_NONBLOCK ?? 0));
|
|
2490
|
+
try {
|
|
2491
|
+
if (!fstatSync(fd).isFile()) throw new Error("not a regular file");
|
|
2492
|
+
const buf = Buffer.alloc(MAX_SPEC_BYTES + 1);
|
|
2493
|
+
let n = 0;
|
|
2494
|
+
for (let r = 1; r > 0 && n < buf.length; n += r) r = readSync(fd, buf, n, buf.length - n, null);
|
|
2495
|
+
if (n > MAX_SPEC_BYTES) throw new Error(TOO_BIG);
|
|
2496
|
+
return buf.toString("utf8", 0, n);
|
|
2497
|
+
} finally {
|
|
2498
|
+
closeSync(fd);
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
function specOutput(config, ruleNames, diagram) {
|
|
2502
|
+
const outputs = ruleNames.map((name) => {
|
|
2503
|
+
const rule = config.rules.find((r) => r.name === name);
|
|
2504
|
+
if (!rule) throw new Error(`unknown rule in spec: ${name}`);
|
|
2505
|
+
if ((rule.diagram ?? "map") !== diagram) throw new Error(`rule in spec is not a ${diagram} rule: ${name}`);
|
|
2506
|
+
return rule.output ?? config.defaults.output;
|
|
2507
|
+
});
|
|
2508
|
+
return unionOutputs(outputs);
|
|
2509
|
+
}
|
|
2510
|
+
async function readSpec(arg, cwd, stdin) {
|
|
2511
|
+
const source = arg === "-" ? "stdin" : resolve6(cwd, arg);
|
|
2512
|
+
let raw;
|
|
2513
|
+
try {
|
|
2514
|
+
const text = arg === "-" ? await stdin() : readSpecFile(source);
|
|
2515
|
+
if (Buffer.byteLength(text) > MAX_SPEC_BYTES) throw new Error(TOO_BIG);
|
|
2516
|
+
raw = JSON.parse(text);
|
|
2517
|
+
} catch (e) {
|
|
2518
|
+
throw new Error(`${source}: ${e.message}`);
|
|
2519
|
+
}
|
|
2520
|
+
const result = validateSpec(raw);
|
|
2521
|
+
if (!result.ok) throw new InvalidSpec(result.errors);
|
|
2522
|
+
return result.spec;
|
|
2523
|
+
}
|
|
2524
|
+
function flowSnippets(spec, root, at, cwd) {
|
|
2525
|
+
const anchors = checkFlowAnchors(spec, root, at, cwd);
|
|
2526
|
+
if (!anchors.ok) throw new InvalidSpec(anchors.errors);
|
|
2527
|
+
return anchors.snippets;
|
|
2528
|
+
}
|
|
2529
|
+
function markdown(map, htmlPath) {
|
|
2530
|
+
const body = map !== void 0 && htmlPath ? map.split("\n").filter((l) => l !== fullMapLine(htmlPath)).join("\n") : map;
|
|
2531
|
+
return markdownBlock(`**Map** _(${KEY})_`, body, htmlPath);
|
|
2532
|
+
}
|
|
2533
|
+
function renderCommand(opts) {
|
|
2534
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
2535
|
+
return new Command5("render").description("render a spec as a terminal map and/or a self-contained HTML map").argument("<spec>", "spec JSON file, or '-' for stdin").addOption(new Option("--output <mode>", "override the output mode").choices(["auto", "cli", "web", "both"])).addOption(new Option("--theme <theme>", "HTML theme").choices(THEMES)).option("--open", "open the HTML file in the browser").option("--md", "print a paste-ready markdown block (no color)").option("--at <rev>", "check flow anchors against the files at this commit instead of the working tree").action(async (arg, o) => {
|
|
2536
|
+
try {
|
|
2537
|
+
const spec = await readSpec(arg, cwd, opts.stdin ?? readStdin);
|
|
2538
|
+
const repoRoot = findRepoRoot(cwd);
|
|
2539
|
+
const root = repoRoot ?? resolve6(cwd);
|
|
2540
|
+
let at;
|
|
2541
|
+
if (o.at !== void 0) {
|
|
2542
|
+
if (!repoRoot) throw new Error("--at needs a git repository");
|
|
2543
|
+
at = resolveCommit(root, "--at", o.at);
|
|
2544
|
+
}
|
|
2545
|
+
const snippets = spec.diagram === "flow" ? flowSnippets(spec, root, at, resolve6(cwd)) : void 0;
|
|
2546
|
+
const config = loadConfig({ cwd, home: opts.home, env: opts.env, warn: (l) => opts.stderr(`codechart: ${l}
|
|
2547
|
+
`) });
|
|
2548
|
+
const diagram = spec.diagram ?? "map";
|
|
2549
|
+
const resolved = spec.rules?.length ? specOutput(config, spec.rules, diagram) : config.defaults.output;
|
|
2550
|
+
const output = o.output ?? resolved;
|
|
2551
|
+
if (output === "none") {
|
|
2552
|
+
const why = spec.rules?.length ? `its rules (${spec.rules.join(", ")}) resolve to output none` : "defaults.output is none";
|
|
2553
|
+
opts.stderr(`codechart: no ${diagram} drawn: ${why}
|
|
2554
|
+
`);
|
|
2555
|
+
return;
|
|
2556
|
+
}
|
|
2557
|
+
const maxNodes = config.defaults.terminalMaxNodes;
|
|
2558
|
+
const color = !o.md && (opts.isTTY ?? process.stdout.isTTY === true);
|
|
2559
|
+
const width = defaultWidth(
|
|
2560
|
+
{ isTTY: opts.isTTY ?? process.stdout.isTTY, columns: process.stdout.columns },
|
|
2561
|
+
opts.env ?? process.env
|
|
2562
|
+
);
|
|
2563
|
+
const print = (text) => opts.stdout(o.md ? `${text}
|
|
2564
|
+
` : text);
|
|
2565
|
+
const slug = fileSlug(spec.title, diagram);
|
|
2566
|
+
const writeHtml = async (build) => {
|
|
2567
|
+
const now = opts.now?.() ?? /* @__PURE__ */ new Date();
|
|
2568
|
+
const file = htmlOutputPath(config, repoFolder(root), slug, now);
|
|
2569
|
+
const html = await build({ generatedAt: now, repo: basename2(root), theme: o.theme ?? config.web.theme });
|
|
2570
|
+
if (lstatSync4(dirname4(file), { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
2571
|
+
throw new Error(`${dirname4(file)}: is a symlink; refusing to write`);
|
|
2572
|
+
}
|
|
2573
|
+
mkdirSync2(dirname4(file), { recursive: true, mode: 448 });
|
|
2574
|
+
chmodSync(dirname4(file), 448);
|
|
2575
|
+
writeFileSync(file, html, { mode: 384 });
|
|
2576
|
+
pruneHtml(dirname4(file), { ...config.web, now, replaceSlug: slug });
|
|
2577
|
+
const mode = config.web.open;
|
|
2578
|
+
if (o.open || mode === "always" || mode === "auto" && inCodeEditor(opts.env ?? process.env)) (opts.open ?? openInBrowser)(file);
|
|
2579
|
+
return file;
|
|
2580
|
+
};
|
|
2581
|
+
if (spec.diagram === "flow") {
|
|
2582
|
+
const tree = { maxNodes, width, color, md: o.md };
|
|
2583
|
+
print(await renderFlow(spec, snippets, { output, minNodes: config.web.minNodes, tree, writeHtml }));
|
|
2584
|
+
return;
|
|
2585
|
+
}
|
|
2586
|
+
const { hidden } = selectTerminalNodes(spec, maxNodes);
|
|
2587
|
+
const termOpts = { maxNodes, keyLine: !o.md, color, width };
|
|
2588
|
+
const writeMapHtml = () => writeHtml(async (meta) => renderHtml(spec, await layoutSpec(spec), meta));
|
|
2589
|
+
let htmlPath;
|
|
2590
|
+
let terminal;
|
|
2591
|
+
if (output === "web" || output === "both" || output === "auto" && needsWeb(spec, hidden, config.web.minNodes)) {
|
|
2592
|
+
htmlPath = await writeMapHtml();
|
|
2593
|
+
} else if (output === "auto") {
|
|
2594
|
+
terminal = renderTerminalDetailed(spec, termOpts);
|
|
2595
|
+
if (terminal.truncated) {
|
|
2596
|
+
htmlPath = await writeMapHtml();
|
|
2597
|
+
terminal = void 0;
|
|
2598
|
+
}
|
|
2599
|
+
}
|
|
2600
|
+
const map = output === "web" ? void 0 : (terminal ?? renderTerminalDetailed(spec, { ...termOpts, htmlPath })).text;
|
|
2601
|
+
if (o.md) print(markdown(map, htmlPath));
|
|
2602
|
+
else print(map ?? `${fullMapLine(htmlPath)}
|
|
2603
|
+
`);
|
|
2604
|
+
} catch (e) {
|
|
2605
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
2606
|
+
const lines = e instanceof InvalidSpec ? e.errors : message.split("\n").map((l) => `codechart: ${l}`);
|
|
2607
|
+
opts.stderr(lines.map((l) => `${l}
|
|
2608
|
+
`).join(""));
|
|
2609
|
+
process.exitCode = 1;
|
|
2610
|
+
}
|
|
2611
|
+
});
|
|
2612
|
+
}
|
|
2613
|
+
|
|
2614
|
+
// src/commands/schema.ts
|
|
2615
|
+
import { Command as Command6 } from "commander";
|
|
2616
|
+
function schemaCommand(opts) {
|
|
2617
|
+
return new Command6("schema").description("print the spec JSON schema, the flow spec schema with --flow, or the config file schema with --config").option("--config", "print the config file schema instead").option("--flow", "print the flow spec schema instead").action((o) => {
|
|
2618
|
+
const schema = o.config ? configJsonSchema() : o.flow ? flowJsonSchema() : specJsonSchema();
|
|
2619
|
+
opts.stdout(JSON.stringify(schema, null, 2) + "\n");
|
|
2620
|
+
});
|
|
2621
|
+
}
|
|
2622
|
+
|
|
2623
|
+
// src/program.ts
|
|
2624
|
+
function buildProgram(opts = {}) {
|
|
2625
|
+
const stdout = opts.stdout ?? ((s) => process.stdout.write(s));
|
|
2626
|
+
const rawStderr = opts.stderr ?? ((s) => process.stderr.write(s));
|
|
2627
|
+
const stderr = (s) => rawStderr(sanitizeText(s));
|
|
2628
|
+
const program = new Command7().name("codechart").version("0.1.0");
|
|
2629
|
+
const cmdOpts = { ...opts, stdout, stderr };
|
|
2630
|
+
program.addCommand(checkCommand(cmdOpts));
|
|
2631
|
+
program.addCommand(renderCommand(cmdOpts));
|
|
2632
|
+
program.addCommand(schemaCommand(cmdOpts));
|
|
2633
|
+
program.addCommand(configCommand(cmdOpts));
|
|
2634
|
+
program.addCommand(initCommand(cmdOpts));
|
|
2635
|
+
program.addCommand(installSkillCommand(cmdOpts));
|
|
2636
|
+
for (const c of [program, ...program.commands]) {
|
|
2637
|
+
c.exitOverride().configureOutput({ writeOut: stdout, writeErr: stderr });
|
|
2638
|
+
}
|
|
2639
|
+
return program;
|
|
2640
|
+
}
|
|
2641
|
+
async function runProgram(program, argv, from) {
|
|
2642
|
+
try {
|
|
2643
|
+
await program.parseAsync(argv, from && { from });
|
|
2644
|
+
} catch (e) {
|
|
2645
|
+
if (!(e instanceof CommanderError)) throw e;
|
|
2646
|
+
process.exitCode = e.exitCode === 0 ? 0 : 2;
|
|
2647
|
+
}
|
|
2648
|
+
}
|
|
2649
|
+
|
|
2650
|
+
// src/cli.ts
|
|
2651
|
+
await runProgram(buildProgram(), process.argv);
|