-
Notifications
You must be signed in to change notification settings - Fork 19
/
layout.ts
519 lines (478 loc) · 17.2 KB
/
layout.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
export const themes: { [name: string]: Theme } = {
"classic": {
"dark": false,
"edge": "#2B303A",
"edge-text": "#DB2955",
"backwards-edge": "#7692FF",
"reality-fill": "#2B303A",
"reality-text": "#FFFFFF",
"fact-fill": "#C6CCD2",
"attack-fill": "#ED96AC",
"mitigation-fill": "#ABD2FA",
"goal-fill": "#DB2955",
"goal-text": "#FFFFFF",
},
"dark": {
"dark": true,
"edge": "#c4c9d4",
"edge-text": "#c4c9d4",
"backwards-edge": "#FFFD98",
"backwards-edge-penwidth": 3,
"backwards-edge-arrowsize": .5,
"reality-fill": "#d9d9d9",
"reality-text": "black",
"fact-fill": "#707070",
"fact-text": "white",
"attack-fill": "#FBCAEF",
"attack-text": "black",
"mitigation-fill": "#5BCEFA",
"mitigation-text": "black",
"goal-fill": "#ED33B9",
"goal-text": "white",
"title": "white",
},
"default": {
"dark": false,
"edge": "#2B303A",
"edge-text": "#010065",
"backwards-edge": "#7692FF",
"backwards-edge-penwidth": 3,
"backwards-edge-arrowsize": .5,
"reality-fill": "#272727",
"reality-text": "#FFFFFF",
"fact-fill": "#D2D5DD",
"attack-fill": "#ff92cc",
"mitigation-fill": "#B9D6F2",
"goal-fill": "#5f00c2",
"goal-text": "#FFFFFF",
},
"accessible": {
"dark": false,
"edge": "#2B303A",
"edge-text": "#010065",
"backwards-edge": "#7692FF",
"backwards-edge-penwidth": 3,
"backwards-edge-arrowsize": .5,
"reality-fill": "#272727",
"reality-text": "#FFFFFF",
"fact-fill": "#D2D5DD",
"attack-fill": "#FF7EC3",
"mitigation-fill": "#CCCCFF",
"goal-fill": "#5f00c2",
"goal-text": "#FFFFFF",
},
};
function mangleName(name: string) {
if (/^[A-Za-z]\w*$/.test(name)) {
return name;
}
return JSON.stringify(name);
}
export type Input = {
theme?: keyof typeof themes | string;
dark?: boolean;
title?: string;
goals?: NodeDeclaration[];
facts?: NodeDeclaration[];
attacks?: NodeDeclaration[];
mitigations?: NodeDeclaration[];
filter?: string[];
legend?: boolean;
};
export type Node = {
from: FromDeclaration[];
};
export type NodeDeclaration = Node;
export type FromDeclaration = string | ({
backwards?: boolean;
ungrouped?: boolean;
} & { [name: string]: string | null; });
export type ParsedFrom = {
name: string;
backwards: boolean;
ungrouped: boolean;
implemented: boolean;
label?: string;
};
type NodeType = "attack" | "mitigation" | "fact" | "goal";
type Theme = {
"dark"?: boolean;
"title"?: string;
"edge": string;
"edge-text": string;
"backwards-edge": string;
"backwards-edge-penwidth"?: number;
"backwards-edge-arrowsize"?: number;
"reality-fill": string;
"reality-text": string;
"fact-fill": string;
"fact-text"?: string;
"attack-fill": string;
"attack-text"?: string;
"mitigation-fill": string;
"mitigation-text"?: string;
"goal-fill": string;
"goal-text": string;
};
function firstProperty<T>(obj: { [key: string]: T }): [string, T] {
const entries = Object.entries(obj);
if (entries.length === 0) {
throw new Error("expected at least one key in object");
}
return entries[0];
}
function parseFrom(raw: FromDeclaration): ParsedFrom {
if (typeof raw == "object") {
const [fromName, label] = firstProperty(raw);
const result: ParsedFrom = {
name: fromName,
backwards: typeof raw.backwards === "boolean" ? raw.backwards : false,
ungrouped: typeof raw.ungrouped === "boolean" ? raw.ungrouped : false,
implemented: typeof raw.implemented === "boolean" ? raw.implemented : true,
};
if (typeof label === "string") {
result.label = label;
}
return result;
}
return {
name: String(raw),
backwards: false,
ungrouped: false,
implemented: true,
};
}
function wordwrap(text: string, limit: number): string {
text = String(text);
if (text.indexOf("\n") != -1) {
return text;
}
const split = text.split(" ");
let all = [];
let current: string[] = [];
let currentLength = 0;
for (let i = 0; i < split.length; i++) {
const line = split[i];
if (currentLength == 0 || (currentLength + line.length < limit && line[0] != "(")) {
current.push(line);
currentLength += line.length;
} else {
all.push(current.join(" "));
current = [line];
currentLength = line.length;
}
}
all.push(current.join(" "));
return all.join("\n");
}
type GraphvizNodeProperties = { [key: string]: string };
function line(name: string, properties: GraphvizNodeProperties) {
const entries = Object.entries(properties);
if (entries.length == 0) {
return name;
}
return name + " [ " + entries.map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(" ") + " ]";
}
export type RenderedOutput = {
dot: string;
title: string;
types: { [key: string]: string };
themeName: string;
};
export function convertToDot(parsed: Input): RenderedOutput {
const font = 'Arial'
const themeName = typeof parsed.theme === "string" && Object.hasOwnProperty.call(themes, parsed.theme) ? parsed.theme : "default";
const theme = themes[themeName] as Theme;
const dark = theme.dark ? true : false;
const propertiesOfReality = { fillcolor: theme["reality-fill"], fontcolor: theme["reality-text"] } as const;
const header = `// Generated from https://www.deciduous.app/
digraph {
// base graph styling
rankdir="TB";
splines=true;
overlap=false;
nodesep="0.2";
ranksep="0.4";
label=${JSON.stringify(typeof parsed.title === "string" ? parsed.title : "")};
labelloc="t";
bgcolor=${JSON.stringify(dark ? "black" : "white")}
fontcolor=${JSON.stringify(theme["title"] || "black")}
fontname=${JSON.stringify(font)};
node [ shape="plaintext" style="filled, rounded" fontname=${JSON.stringify(font)} margin=0.2 ]
edge [ fontname=${JSON.stringify(font)} fontsize=12 color="${theme["edge"]}" ]
// is reality a hologram?
${line("reality", { label: "Reality", ...propertiesOfReality })}
`;
const goals = parsed.goals || [];
const facts = parsed.facts || [];
const attacks = parsed.attacks || [];
const mitigations = parsed.mitigations || [];
const filter = parsed.filter || [];
const subgraphs = [];
const forwards: { [name: string]: string[] } = {};
const forwardsAll: { [name: string]: string[] } = {};
const backwards: { [name: string]: string[] } = {};
const allNodes = [...facts, ...attacks, ...mitigations, ...goals];
const types: { [name: string]: NodeType } = {};
for (const node of allNodes) {
if (typeof node != "object" || node === null) {
throw new Error(`nodes must each be an object containing at least one property`);
}
const [toName] = firstProperty(node);
const fromNames = backwards[toName] || (backwards[toName] = []);
if (node.from) {
for (const from of node.from) {
const { name, label, backwards, ungrouped } = parseFrom(from);
if (!backwards && !ungrouped) {
const toNames = forwards[name] || (forwards[name] = []);
toNames.push(toName);
fromNames.push(name);
}
const toNames = forwardsAll[name] || (forwardsAll[name] = []);
toNames.push(toName);
}
}
}
function anyDominates(forwards: { [name: string]: string[] }, d: string[], n: string) {
// search to see if any nodes in d dominate n
// nodes dominate themselves
const search = [];
const added: { [key: string]: true } = {};
for (const other of d) {
added[other] = true;
search.push(other);
}
let cur: string | undefined;
while ((cur = search.shift()) !== undefined) {
if (cur === n) {
return true;
}
const others: string[] | undefined = forwards[cur];
if (others !== undefined) {
for (const other of others) {
if (!Object.hasOwnProperty.call(added, other)) {
added[other] = true;
search.push(other);
}
}
}
}
return false;
}
function shouldShow(n: string) {
if (filter.length == 0 || anyDominates(forwardsAll, filter, n)) {
return true;
}
const arrayN = [n];
return filter.find(other => anyDominates(forwardsAll, arrayN, other));
}
function defaultLabelForName(name: string): string {
return name.replace(/_/g, " ").replace(/^[a-z]/, c => c.toUpperCase());
}
function nodes(type: NodeType, values: NodeDeclaration[], properties: GraphvizNodeProperties) {
const result = [];
for (const value of values) {
const [name, label] = firstProperty(value);
if (Object.hasOwnProperty.call(types, name)) {
throw new Error(`${name} cannot be declared twice. It was previously declared as ${types[name]}`);
}
types[name] = type;
if (shouldShow(name)) {
result.push(line(mangleName(name), {
label: wordwrap(label === null ? defaultLabelForName(name) : String(label), 18),
...name === "reality" ? propertiesOfReality : properties,
}));
}
}
return result;
}
const allNodeLines = [
`// facts`,
...nodes("fact", facts, {
fillcolor: theme["fact-fill"],
fontcolor: theme["fact-text"] || "black",
}),
``,
`// attacks`,
...nodes("attack", attacks, {
fillcolor: theme["attack-fill"],
fontcolor: theme["attack-text"] || "black",
}),
``,
`// mitigations`,
...nodes("mitigation", mitigations, {
fillcolor: theme["mitigation-fill"],
fontcolor: theme["mitigation-text"] || "black",
}),
``,
`// goals`,
...nodes("goal", goals, {
fillcolor: theme["goal-fill"],
fontcolor: theme["goal-text"],
})
];
function edges(entries: NodeDeclaration[], properties: GraphvizNodeProperties) {
return entries.reduce((edges, value) => {
const [name] = firstProperty(value);
if (!shouldShow(name)) {
return edges;
}
(value.from || []).forEach((from) => {
const { name: fromName, label, backwards, implemented } = parseFrom(from);
if (!shouldShow(fromName)) {
return;
}
const props = {
...properties,
};
if (typeof label === "string") {
props.xlabel = wordwrap(label, 20);
props.fontcolor = theme["edge-text"];
}
if (!implemented) {
props.style = "dotted";
}
if (backwards) {
props.style = "dotted";
props.color = theme["backwards-edge"];
if (typeof theme["backwards-edge-penwidth"] === "string") {
props.penwidth = theme["backwards-edge-penwidth"];
}
if (typeof theme["backwards-edge-arrowsize"] === "string") {
props.arrowsize = theme["backwards-edge-arrowsize"];
}
props.weight = "0";
}
edges.push(line(`${mangleName(fromName)} -> ${mangleName(name)}`, props));
});
return edges;
}, [] as string[]);
}
const allEdgeLines = [...edges(goals, {}), ...edges(attacks, {}), ...edges(mitigations, {}), ...edges(facts, {})];
const goalNames = goals.map((goal) => {
const [goalName] = firstProperty(goal);
return goalName;
});
for (const [fromName, toNames] of Object.entries(forwards)) {
if (!shouldShow(fromName)) {
continue;
}
const copy = toNames.concat();
const filteredToNames = [];
for (let i = 0; i < toNames.length; i++) {
copy.splice(i, 1);
if (!anyDominates(forwards, copy, toNames[i]) && goalNames.indexOf(toNames[i]) == -1 && shouldShow(toNames[i])) {
filteredToNames.push(toNames[i]);
}
copy.splice(i, 0, toNames[i]);
}
if (filteredToNames.length > 1) {
subgraphs.push(` subgraph ${mangleName(fromName)}_order {
rank=same;
${filteredToNames.map(toName => mangleName(toName) + ";").join("\n ")}
}
${line(filteredToNames.map(mangleName).join(" -> "), { style: "invis" })}`);
}
}
const shownGoals = goalNames.filter(shouldShow);
if (shownGoals.length > 1) {
subgraphs.push(` subgraph goal_order {
rank=same;
${shownGoals.concat(parsed.legend ? ["legend_invis"] : []).map(goalName => mangleName(goalName) + ";").join("\n ")}
}`);
subgraphs.push(" " + line(shownGoals.join(" -> "), { style: "invis" }));
}
subgraphs.push(` // top-to-bottom layout directives`);
subgraphs.push(` { rank=min; reality; }`);
for (const node of allNodes) {
const [toName] = firstProperty(node);
if (shouldShow(toName) && !forwards[toName] && shownGoals.indexOf(toName) === -1) {
for (const goalName of shownGoals) {
subgraphs.push(" " + line(mangleName(toName) + " -> " + mangleName(goalName), { style: "invis", weight: "0" }));
}
}
}
subgraphs.push(`
// legend pseudo-nodes
{ rank=max; ${shownGoals.concat(parsed.legend ? ["legend_invis"] : []).map(goalName => mangleName(goalName) + "; ").join("")}}`);
let footer = "\n\n}\n";
if (typeof parsed.legend !== "undefined" && typeof parsed.legend !== "boolean") {
throw new Error(`legend attribute must be a boolean, instead was ${typeof parsed.legend}`);
}
if (parsed.legend) {
footer = ` ${line("legend_reality", {
label: "Reality",
...propertiesOfReality,
})}
${line("legend_fact", {
label: "Fact",
fillcolor: theme["fact-fill"],
fontcolor: theme["fact-text"] || "black",
})}
${line("legend_attack", {
label: "Attack",
fillcolor: theme["attack-fill"],
fontcolor: theme["attack-text"] || "black",
})}
${line("legend_mitigation", {
label: "Mitigation",
fillcolor: theme["mitigation-fill"],
fontcolor: theme["mitigation-text"] || "black",
})}
${line("legend_goal", {
label: "Goal",
fillcolor: theme["goal-fill"],
fontcolor: theme["goal-text"],
})}
legend_invis [ label=""; style=invis; ]
subgraph legend {
cluster=true;
margin=10;
color=${JSON.stringify(theme["edge"])};
label="Legend";
legend_reality;
legend_fact;
legend_attack;
legend_mitigation;
legend_goal;
}
legend_reality -> legend_fact -> legend_attack -> legend_mitigation -> legend_goal -> legend_invis [ style=invis; weight=50; ];
${shownGoals.map((goalName) => `${line("legend_invis -> " + mangleName(goalName), { style: "invis", weight: "0" })};`).join("\n\t")}
${footer}`;
}
return {
dot: header + " " + allNodeLines.join("\n ") + "\n\n // edges\n " + allEdgeLines.join("\n ") + "\n\n // left-to-right layout directives\n" + subgraphs.join("\n\n") + footer,
title: typeof parsed.title === "string" ? parsed.title : "",
types,
themeName,
};
}
declare function btoa(text: string): string;
function base64Encode(text: string): string {
return btoa(encodeURIComponent(text).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode(parseInt(p1, 16))
}));
}
declare function atob(text: string): string;
function base64Decode(text: string): string {
return decodeURIComponent(Array.prototype.map.call(atob(text), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
}).join(''))
}
export function embedDotComment(dot: string, input: string): string {
return dot + "// deciduous:" + base64Encode(input);
}
export function embedSvgComment(svg: string, input: string): string {
return svg + "<!-- deciduous:" + base64Encode(input) + " -->";
}
export function trailingPngComment(input: string): string {
return "\n// deciduous:" + base64Encode(input);
}
export function parseEmbeddedComment(text: string): string | undefined {
// extract hidden embedded comment
const match = text.match(/\n(\/\/|<!--) deciduous:([a-zA-Z0-9]+=*)( -->)?$/);
if (match) {
return base64Decode(match[2]);
}
return undefined;
}