@yutaura/live-spec 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.
Files changed (47) hide show
  1. package/.claude-plugin/plugin.json +12 -0
  2. package/LICENSE +21 -0
  3. package/README.md +195 -2
  4. package/dist/cli.d.ts +20 -0
  5. package/dist/cli.js +180 -0
  6. package/dist/diff.d.ts +33 -0
  7. package/dist/diff.js +141 -0
  8. package/dist/ensure.d.ts +5 -0
  9. package/dist/ensure.js +10 -0
  10. package/dist/explore.d.ts +6 -0
  11. package/dist/explore.js +270 -0
  12. package/dist/generate.d.ts +15 -0
  13. package/dist/generate.js +147 -0
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +2 -0
  16. package/dist/load.d.ts +52 -0
  17. package/dist/load.js +74 -0
  18. package/dist/model.d.ts +402 -0
  19. package/dist/model.js +175 -0
  20. package/dist/render/collapse.d.ts +4 -0
  21. package/dist/render/collapse.js +22 -0
  22. package/dist/render/escape.d.ts +1 -0
  23. package/dist/render/escape.js +2 -0
  24. package/dist/render/html.d.ts +12 -0
  25. package/dist/render/html.js +685 -0
  26. package/dist/render/layout.d.ts +37 -0
  27. package/dist/render/layout.js +74 -0
  28. package/dist/render/markdown.d.ts +20 -0
  29. package/dist/render/markdown.js +227 -0
  30. package/dist/render/summary.d.ts +62 -0
  31. package/dist/render/summary.js +119 -0
  32. package/dist/render/wireframe.d.ts +3 -0
  33. package/dist/render/wireframe.js +62 -0
  34. package/dist/serve.d.ts +8 -0
  35. package/dist/serve.js +71 -0
  36. package/dist/skills.d.ts +8 -0
  37. package/dist/skills.js +20 -0
  38. package/dist/static.d.ts +10 -0
  39. package/dist/static.js +117 -0
  40. package/dist/surface.d.ts +59 -0
  41. package/dist/surface.js +44 -0
  42. package/dist/watch.d.ts +10 -0
  43. package/dist/watch.js +47 -0
  44. package/package.json +54 -4
  45. package/skills/live-spec-authoring/SKILL.md +160 -0
  46. package/skills/live-spec-from-code/SKILL.md +93 -0
  47. package/skills/live-spec-review/SKILL.md +65 -0
@@ -0,0 +1,37 @@
1
+ import type { Graph } from "../model.js";
2
+ export interface Point {
3
+ readonly x: number;
4
+ readonly y: number;
5
+ }
6
+ export interface LaidOutNode {
7
+ readonly id: string;
8
+ readonly label: string;
9
+ readonly x: number;
10
+ readonly y: number;
11
+ readonly width: number;
12
+ readonly height: number;
13
+ }
14
+ export interface LaidOutEdge {
15
+ readonly from: string;
16
+ readonly to: string;
17
+ readonly action: string;
18
+ readonly points: ReadonlyArray<Point>;
19
+ readonly label: Point & {
20
+ readonly width: number;
21
+ readonly height: number;
22
+ };
23
+ }
24
+ export interface Layout {
25
+ readonly width: number;
26
+ readonly height: number;
27
+ readonly nodes: ReadonlyArray<LaidOutNode>;
28
+ readonly edges: ReadonlyArray<LaidOutEdge>;
29
+ }
30
+ export declare const textWidth: (text: string, halfWidth?: number) => number;
31
+ export interface LayoutOptions {
32
+ readonly nodeSize?: {
33
+ readonly width: number;
34
+ readonly height: number;
35
+ };
36
+ }
37
+ export declare const layout: (graph: Graph, options?: LayoutOptions) => Promise<Layout>;
@@ -0,0 +1,74 @@
1
+ import ElkModule from "elkjs/lib/elk.bundled.js";
2
+ import { ANY, ANY_LABEL, collapseTransitions } from "./collapse.js";
3
+ const NODE_HEIGHT = 40;
4
+ const NODE_PADDING_X = 28;
5
+ const LABEL_HEIGHT = 16;
6
+ // ブラウザで文字幅を測らずに概算する理由: 生成は Node で行い、出力を決定的にしたいため。
7
+ // 全角は半角の約 2 倍の幅として扱う。
8
+ export const textWidth = (text, halfWidth = 7.2) => [...text].reduce((w, ch) => w + ((ch.codePointAt(0) ?? 0) > 0x2e7f ? halfWidth * 1.9 : halfWidth), 0);
9
+ const LAYOUT_OPTIONS = {
10
+ "elk.algorithm": "layered",
11
+ "elk.direction": "RIGHT",
12
+ "elk.edgeRouting": "ORTHOGONAL",
13
+ "elk.spacing.nodeNode": "36",
14
+ "elk.layered.spacing.nodeNodeBetweenLayers": "72",
15
+ "elk.spacing.edgeLabel": "4",
16
+ "elk.layered.spacing.edgeNodeBetweenLayers": "24",
17
+ "elk.padding": "[top=24,left=24,bottom=24,right=24]",
18
+ // 入力の並び(幅優先探索の順)をなるべく保つ理由: spec を少し変えただけで図の配置が大きく入れ替わると、
19
+ // 差分レビューで「どこが変わったか」が分からなくなるため。
20
+ "elk.layered.considerModelOrder.strategy": "NODES_AND_EDGES",
21
+ // 循環を断ち切るときに入力順(幅優先探索の順)を基準にする理由: reject や unpublish のような
22
+ // 「戻る」遷移を逆向きの辺として扱わせ、初期状態から右へ流れる読み順を保つため。
23
+ "elk.layered.cycleBreaking.strategy": "MODEL_ORDER",
24
+ };
25
+ // .default を経由する理由: elkjs は CommonJS で、型定義は `export default` だが実体は module.exports。
26
+ // nodenext ではデフォルト import が module.exports そのものの型になり、コンストラクタとして型付けされない。
27
+ // 実体は ELKNode.default = ELKNode も設定しているので、.default なら型と実行時の両方で正しく動く。
28
+ const ELK = ElkModule.default;
29
+ export const layout = async (graph, options = {}) => {
30
+ const elk = new ELK();
31
+ // 自分自身に戻る遷移は描かない。ほぼすべての状態にあると、図が線で埋まって読めなくなるため。
32
+ const transitions = collapseTransitions(graph).filter((t) => t.from !== t.to);
33
+ const hasAny = transitions.some((t) => t.from === ANY);
34
+ const nodeList = [
35
+ ...(hasAny ? [{ id: ANY, label: ANY_LABEL, initial: false }] : []),
36
+ ...graph.states.map((s) => ({ id: s.id, label: s.label, initial: s.initial })),
37
+ ];
38
+ const input = {
39
+ id: "root",
40
+ layoutOptions: LAYOUT_OPTIONS,
41
+ children: nodeList.map((s) => ({
42
+ id: s.id,
43
+ width: options.nodeSize?.width ?? textWidth(s.label) + NODE_PADDING_X * 2,
44
+ height: options.nodeSize?.height ?? NODE_HEIGHT,
45
+ // 「どの状態からでも」には層の指定をしない。初期状態へ戻る遷移(リセットなど)があると、
46
+ // 初期状態と同じ最初の層に置くことになり、ELK が層の中の辺を扱えずに落ちるため。
47
+ ...(s.initial ? { layoutOptions: { "elk.layered.layering.layerConstraint": "FIRST" } } : {}),
48
+ })),
49
+ edges: transitions.map((t, i) => ({
50
+ id: `e${i}`,
51
+ sources: [t.from],
52
+ targets: [t.to],
53
+ labels: [{ text: t.action, width: textWidth(t.action, 6.6) + 8, height: LABEL_HEIGHT }],
54
+ })),
55
+ };
56
+ const result = await elk.layout(input);
57
+ const nodes = nodeList.map((s) => {
58
+ const n = result.children.find((c) => c.id === s.id);
59
+ return { id: s.id, label: s.label, x: n.x, y: n.y, width: n.width, height: n.height };
60
+ });
61
+ const edges = transitions.map((t, i) => {
62
+ const e = result.edges.find((x) => x.id === `e${i}`);
63
+ const section = e.sections[0];
64
+ const label = e.labels[0];
65
+ return {
66
+ from: t.from,
67
+ to: t.to,
68
+ action: t.action,
69
+ points: [section.startPoint, ...(section.bendPoints ?? []), section.endPoint].map(({ x, y }) => ({ x, y })),
70
+ label: { x: label.x, y: label.y, width: label.width, height: label.height },
71
+ };
72
+ });
73
+ return { width: result.width, height: result.height, nodes, edges };
74
+ };
@@ -0,0 +1,20 @@
1
+ import type { Spec } from "../load.js";
2
+ import type { Finding, Graph } from "../model.js";
3
+ import { type ActionSummary } from "./summary.js";
4
+ type Objects = ReadonlyArray<{
5
+ readonly spec: Spec;
6
+ readonly graph: Graph;
7
+ }>;
8
+ export declare const renderIndexMarkdown: (objects: Objects, title: string) => string;
9
+ export declare const renderMarkdown: (spec: Spec, graph: Graph, objects?: Objects) => string;
10
+ export declare const splitEvidence: (text: string) => {
11
+ readonly path: string;
12
+ readonly rest: string;
13
+ };
14
+ export declare const inputCell: (input: unknown, column: string) => string;
15
+ export declare const resultCell: (r: Graph["decisions"][number]["rows"][number]) => string;
16
+ export declare const questionTarget: (spec: Spec, q: Graph["questions"][number], labelOf: (id: string) => string) => string;
17
+ export declare const describeStep: (spec: Spec, step: Graph["scenarios"][number]["steps"][number]) => string;
18
+ export declare const formatEffect: (a: ActionSummary) => string;
19
+ export declare const describeFinding: (f: Finding, labelOf: (id: string) => string) => string;
20
+ export {};
@@ -0,0 +1,227 @@
1
+ import { ANY, ANY_LABEL, collapseTransitions } from "./collapse.js";
2
+ import { formatTransition, presentBlocked, summarizeActions, summarizeStates } from "./summary.js";
3
+ import { surfaceToText } from "./wireframe.js";
4
+ const actionName = (objects, object, action) => {
5
+ const spec = objects.find((o) => o.spec.name === object)?.spec;
6
+ const doc = spec?.docs[action];
7
+ return doc === undefined ? action : `${doc.replace(/。$/, "")}(${action})`;
8
+ };
9
+ const endpoint = (objects, object, action) => `[${object}](${object}.md)${action === null ? "" : ` の ${actionName(objects, object, action)}`}`;
10
+ const allLinks = (objects) => objects.flatMap(({ spec, graph }) => graph.links.map((l) => ({ ...l, source: spec.name })));
11
+ export const renderIndexMarkdown = (objects, title) => [
12
+ `# ${title}`,
13
+ "",
14
+ `ドメインオブジェクト ${objects.length} 個の仕様書です。`,
15
+ "",
16
+ "| ドメインオブジェクト | 説明 | 状態 | 操作 | 未決 | 検査 |",
17
+ "|---|---|---|---|---|---|",
18
+ ...objects.map(({ spec, graph }) => `| [${spec.name}](${spec.name}.md) | ${spec.stateDoc ?? ""} | ${graph.states.length} | ${spec.actions.length} | ${graph.questions.length} | ${graph.findings.length === 0 ? "OK" : `⚠ ${graph.findings.length}`} |`),
19
+ "",
20
+ ...(allLinks(objects).length === 0
21
+ ? []
22
+ : [
23
+ "## つながり",
24
+ "",
25
+ ...allLinks(objects).map((l) => `- ${endpoint(objects, l.source, l.from)} → ${endpoint(objects, l.to, l.action)}: ${l.label}`),
26
+ "",
27
+ ]),
28
+ ].join("\n");
29
+ export const renderMarkdown = (spec, graph, objects = [{ spec, graph }]) => {
30
+ const incoming = allLinks(objects).filter((l) => l.to === spec.name && l.source !== spec.name);
31
+ const ownAction = (action) => (action === null ? "" : actionName(objects, spec.name, action));
32
+ const labelOf = (id) => graph.states.find((s) => s.id === id)?.label ?? id;
33
+ return [
34
+ `# ${spec.name}`,
35
+ "",
36
+ ...(spec.stateDoc === null ? [] : [spec.stateDoc, ""]),
37
+ // 未決事項を状態遷移図より前に置く理由: AI が書いた仕様のうち、人が判断すべきなのはここだけ、という
38
+ // 入口にしたいため。全体を読む前に、判断が必要な点が目に入るようにする。
39
+ ...(graph.questions.length === 0
40
+ ? []
41
+ : [
42
+ "## 未決事項",
43
+ "",
44
+ ...graph.questions.flatMap((q, i) => [
45
+ `${i + 1}. ${q.ask}${questionTarget(spec, q, labelOf)}`,
46
+ ...(q.note === null ? [] : [` - ${q.note}`]),
47
+ ]),
48
+ "",
49
+ ]),
50
+ "## 状態遷移図",
51
+ "",
52
+ "```mermaid",
53
+ "stateDiagram-v2",
54
+ ...graph.states.map((s) => ` state "${s.label}" as ${s.id}`),
55
+ ...graph.states.filter((s) => s.initial).map((s) => ` [*] --> ${s.id}`),
56
+ // 自分自身に戻る遷移は図に描かない(線が図を埋めるため)。操作の節の「できるとき」には残る。
57
+ ...(collapseTransitions(graph).some((t) => t.from === ANY) ? [` state "${ANY_LABEL}" as any`] : []),
58
+ ...collapseTransitions(graph)
59
+ .filter((t) => t.from !== t.to)
60
+ .map((t) => ` ${t.from === ANY ? "any" : t.from} --> ${t.to}: ${t.action} (${t.actors.join(", ")})`),
61
+ ...graph.states.filter((s) => s.terminal).map((s) => ` ${s.id} --> [*]`),
62
+ "```",
63
+ "",
64
+ ...glossarySection(spec),
65
+ "## 操作",
66
+ "",
67
+ ...summarizeActions(spec, graph).flatMap((a) => [
68
+ ...actionSection(a),
69
+ ...((spec.evidence[a.name] ?? []).length === 0 ? [] : [`- **根拠**: ${spec.evidence[a.name].map(formatEvidence).join("、")}`]),
70
+ ...graph.questions.filter((q) => q.action === a.name).map((q) => `- **未決**: ${q.ask}`),
71
+ "",
72
+ ]),
73
+ ...(graph.links.length + incoming.length === 0
74
+ ? []
75
+ : [
76
+ "## つながり",
77
+ "",
78
+ ...graph.links.map((l) => `- ${l.from === null ? "" : `${ownAction(l.from)} `}→ ${endpoint(objects, l.to, l.action)}: ${l.label}`),
79
+ ...incoming.map((l) => `- ${l.action === null ? "" : `${ownAction(l.action)} `}← ${endpoint(objects, l.source, l.from)}から: ${l.label}`),
80
+ "",
81
+ ]),
82
+ ...(graph.decisions.length === 0 ? [] : ["## ルール", "", ...graph.decisions.flatMap((d) => [...decisionTable(d), ""])]),
83
+ ...(graph.scenarios.length === 0 ? [] : ["## シナリオ", "", ...graph.scenarios.flatMap((s) => [...scenarioSection(spec, s, labelOf), ""])]),
84
+ ...screensSection(spec, graph),
85
+ "## 検査結果",
86
+ "",
87
+ ...(graph.findings.length === 0 ? ["問題は見つかりませんでした。"] : graph.findings.map((f) => `- ⚠ ${describeFinding(f, labelOf)}`)),
88
+ "",
89
+ ].join("\n");
90
+ };
91
+ const actionSection = (a) => {
92
+ const heading = a.summary === null ? `### \`${a.name}\`` : `### ${a.summary}(\`${a.name}\`)`;
93
+ if (a.capable.length === 0)
94
+ return [heading, "", "- **できる人**: なし(どの状態でも誰も実行できない)"];
95
+ const who = a.othersReasons.length === 0 ? a.capable.join(", ") : `${a.capable.join(", ")}(ほかの人は「${a.othersReasons.join("」「")}」)`;
96
+ const groups = presentBlocked(a.blocked).map((b) => `${b.states === null ? "それ以外のすべての状態" : b.states.join(", ")}(${b.reason})`);
97
+ const whenNot = groups.length === 0
98
+ ? "- **できないとき**: なし"
99
+ : groups.length === 1
100
+ ? `- **できないとき**: ${groups[0]}`
101
+ : ["- **できないとき**:", ...groups.map((g) => ` - ${g}`)].join("\n");
102
+ const effect = formatEffect(a);
103
+ return [
104
+ heading,
105
+ "",
106
+ `- **できる人**: ${who}`,
107
+ `- **できるとき**: ${a.when.map(formatTransition).join(" / ")}`,
108
+ whenNot,
109
+ ...(a.inputOutcomes.length === 0
110
+ ? []
111
+ : [
112
+ [
113
+ "- **入力ごとの結果**:",
114
+ ...a.inputOutcomes.map((o) => o.transitions.length > 0
115
+ ? ` - ${o.input}: ${o.transitions.map(formatTransition).join(" / ")}`
116
+ : ` - ${o.input}: ❌ ${o.reasons.join("、")}`),
117
+ ].join("\n"),
118
+ ]),
119
+ ...(effect === "" ? [] : [`- **結果**: ${effect}`]),
120
+ ];
121
+ };
122
+ // 根拠の先頭(空白か「(」まで)をコードの場所としてコード書式にし、残りは補足として続ける。
123
+ export const splitEvidence = (text) => {
124
+ const m = /^(\S+?)((?:(|\s).*)?$/.exec(text);
125
+ return { path: m?.[1] ?? text, rest: m?.[2] ?? "" };
126
+ };
127
+ const formatEvidence = (text) => {
128
+ const { path, rest } = splitEvidence(text);
129
+ return `\`${path}\`${rest}`;
130
+ };
131
+ const glossarySection = (spec) => {
132
+ const fields = Object.entries(spec.fieldDocs).map(([field, doc]) => {
133
+ const values = spec.fields[field];
134
+ return `- **${field}**(項目): ${doc}${values === undefined ? "" : `。値: ${values.map(String).join(" / ")}`}`;
135
+ });
136
+ const terms = Object.entries(spec.glossary).map(([term, doc]) => `- **${term}**: ${doc}`);
137
+ return fields.length + terms.length === 0 ? [] : ["## 用語", "", ...fields, ...terms, ""];
138
+ };
139
+ const screensSection = (spec, graph) => {
140
+ const states = summarizeStates(spec, graph).filter((s) => s.surfaces.length > 0);
141
+ if (states.length === 0)
142
+ return [];
143
+ const invalidFor = (state, actors) => graph.findings.flatMap((f) => (f.kind === "surface-action-not-allowed" && f.state === state && actors.includes(f.actor) ? [f.action] : []));
144
+ return [
145
+ "## 画面",
146
+ "",
147
+ ...states.flatMap((s) => [
148
+ `### ${s.label}`,
149
+ "",
150
+ ...s.surfaces.flatMap((g) => [
151
+ `${g.actors.join(", ")} が見る画面:`,
152
+ "",
153
+ "```text",
154
+ surfaceToText(g.surface, invalidFor(s.id, g.actors)),
155
+ "```",
156
+ "",
157
+ ]),
158
+ ]),
159
+ ];
160
+ };
161
+ const cell = (v) => (v === undefined || v === null ? "" : typeof v === "string" ? v : JSON.stringify(v));
162
+ export const inputCell = (input, column) => typeof input === "object" && input !== null ? cell(input[column]) : cell(input);
163
+ export const resultCell = (r) => r.ok ? cell(r.result) : `❌ ${cell(r.result)}(期待: ${cell(r.expect)})`;
164
+ const decisionTable = (d) => [
165
+ `### ${d.name}`,
166
+ "",
167
+ `| ${[...d.columns, "結果"].join(" | ")} |`,
168
+ `|${[...d.columns, "結果"].map(() => "---").join("|")}|`,
169
+ ...d.rows.map((r) => `| ${[...d.columns.map((c) => inputCell(r.input, c)), resultCell(r)].join(" | ")} |`),
170
+ ];
171
+ export const questionTarget = (spec, q, labelOf) => q.action !== null
172
+ ? `(操作: ${(spec.docs[q.action] ?? q.action).replace(/。$/, "")})`
173
+ : q.states.length > 0
174
+ ? `(状態: ${q.states.map(labelOf).join(", ")})`
175
+ : "";
176
+ export const describeStep = (spec, step) => {
177
+ // 文の途中に入れるので、見出しの末尾の「。」は外す(「起動する。(start)」のようにならないように)。
178
+ const what = (spec.docs[step.action] ?? step.action).replace(/。$/, "");
179
+ const detail = step.input === null ? step.action : `${step.action}、${step.input}`;
180
+ return `${step.actor} が ${what}(${detail})`;
181
+ };
182
+ const scenarioSection = (spec, s, labelOf) => [
183
+ `### ${s.passed ? "✅" : "❌"} ${s.name}`,
184
+ "",
185
+ ...s.steps.map((step, i) => step.ok
186
+ ? `${i + 1}. ${describeStep(spec, step)}: ${labelOf(step.from ?? "")} → ${labelOf(step.to ?? "")}`
187
+ : `${i + 1}. ❌ ${describeStep(spec, step)}: ${step.reason}`),
188
+ ];
189
+ export const formatEffect = (a) => a.effect.map((e) => `${e.field} → ${e.values.join(" / ")}`).join(", ");
190
+ export const describeFinding = (f, labelOf) => {
191
+ switch (f.kind) {
192
+ case "unreachable-value":
193
+ return `${f.field} = ${String(f.value)} は型に書かれているが、到達できるどの状態でもとらない`;
194
+ case "never-enabled-action":
195
+ return `操作 ${f.action} は、到達できるどの状態でも誰も実行できない`;
196
+ case "action-error":
197
+ return `操作 ${f.action} が ${labelOf(f.state)} で ${f.actor} が実行したときに例外を投げた: ${f.message}`;
198
+ case "invalid-return":
199
+ return `操作 ${f.action} が ${labelOf(f.state)} で ${f.actor} が実行したときにオブジェクトを返さなかった`;
200
+ case "invariant-violation": {
201
+ const path = f.path.length === 0 ? "初期状態" : f.path.map((p) => `${p.action} (${p.actor})`).join(" → ");
202
+ return `不変条件「${f.invariant}」を ${labelOf(f.state)} で破る(${path})`;
203
+ }
204
+ case "missing-inputs":
205
+ return `操作 ${f.action} は 3 つ目以降の引数をとるが、inputs に例がないので実行していない`;
206
+ case "unknown-inputs":
207
+ return `inputs に書かれた ${f.action} という操作は存在しない`;
208
+ case "surface-action-not-allowed":
209
+ return `${labelOf(f.state)} で ${f.actor} に ${f.action} のボタンが見えているが、実行できない`;
210
+ case "surface-action-missing":
211
+ return `${labelOf(f.state)} で ${f.actor} は ${f.action} を実行できるが、画面にボタンがない`;
212
+ case "surface-error":
213
+ return `${labelOf(f.state)} で ${f.actor} の画面を作るときに例外を投げた: ${f.message}`;
214
+ case "link-unresolved":
215
+ return `つながりの相手 ${f.to}${f.action === null ? "" : ` の ${f.action}`} が見つからない`;
216
+ case "decision-mismatch":
217
+ return `ルール「${f.decision}」の ${f.row} 行目の結果が期待と違う(期待: ${f.expected}、実際: ${f.actual})`;
218
+ case "decision-error":
219
+ return `ルール「${f.decision}」の ${f.row} 行目で例外を投げた: ${f.message}`;
220
+ case "question-unmatched":
221
+ return `未決事項「${f.ask}」の対象の状態が、到達できるどの状態にも当てはまらない`;
222
+ case "scenario-failed":
223
+ return `シナリオ「${f.scenario}」の ${f.step} 段目で止まった: ${f.reason}`;
224
+ case "state-limit":
225
+ return `状態が ${f.maxStates} 個を超えたので探索を打ち切った(値が増え続ける項目がないか確認する)`;
226
+ }
227
+ };
@@ -0,0 +1,62 @@
1
+ import type { Spec } from "../load.js";
2
+ import type { Graph } from "../model.js";
3
+ export interface ActionSummary {
4
+ readonly name: string;
5
+ readonly summary: string | null;
6
+ readonly capable: ReadonlyArray<string>;
7
+ readonly othersReasons: ReadonlyArray<string>;
8
+ readonly when: ReadonlyArray<{
9
+ readonly from: string;
10
+ readonly to: string;
11
+ }>;
12
+ readonly blocked: ReadonlyArray<{
13
+ readonly reason: string;
14
+ readonly states: ReadonlyArray<string>;
15
+ }>;
16
+ readonly effect: ReadonlyArray<{
17
+ readonly field: string;
18
+ readonly values: ReadonlyArray<string>;
19
+ }>;
20
+ readonly inputReasons: ReadonlyArray<{
21
+ readonly input: string;
22
+ readonly reason: string;
23
+ }>;
24
+ readonly inputOutcomes: ReadonlyArray<{
25
+ readonly input: string;
26
+ readonly transitions: ReadonlyArray<{
27
+ readonly from: string;
28
+ readonly to: string;
29
+ }>;
30
+ readonly reasons: ReadonlyArray<string>;
31
+ }>;
32
+ }
33
+ export interface StateSummary {
34
+ readonly id: string;
35
+ readonly label: string;
36
+ readonly initial: boolean;
37
+ readonly terminal: boolean;
38
+ readonly can: ReadonlyArray<{
39
+ readonly action: string;
40
+ readonly actors: ReadonlyArray<string>;
41
+ readonly to: string;
42
+ }>;
43
+ readonly cannot: ReadonlyArray<{
44
+ readonly action: string;
45
+ readonly reason: string;
46
+ }>;
47
+ readonly violations: ReadonlyArray<string>;
48
+ readonly surfaces: ReadonlyArray<{
49
+ readonly actors: ReadonlyArray<string>;
50
+ readonly surface: unknown;
51
+ }>;
52
+ }
53
+ export declare const summarizeActions: (spec: Spec, graph: Graph) => ReadonlyArray<ActionSummary>;
54
+ export declare const summarizeStates: (spec: Spec, graph: Graph) => ReadonlyArray<StateSummary>;
55
+ export declare const presentBlocked: (blocked: ActionSummary["blocked"]) => ReadonlyArray<{
56
+ readonly reason: string;
57
+ readonly states: ReadonlyArray<string> | null;
58
+ }>;
59
+ export declare const formatTransition: (t: {
60
+ readonly from: string;
61
+ readonly to: string;
62
+ }) => string;
@@ -0,0 +1,119 @@
1
+ import { ANY, ANY_LABEL, collapseTransitions } from "./collapse.js";
2
+ const ERROR_REASON = "エラー";
3
+ // 「担当者」= どこかの状態で一度でもその操作を実行できた登場人物。
4
+ // 担当者が止められた理由を「いつ」の条件、担当者以外が止められた理由を「誰が」の条件とみなす。
5
+ // spec の書き手に ensure を「権限」「状態」と分類させずに、実行結果だけから両者を分けるため。
6
+ // 担当者がいない操作では、全員の理由を「いつ」の条件として扱う。
7
+ const capableOf = (graph, action) => unique(graph.availability.filter((a) => a.action === action && a.enabled).map((a) => a.actor));
8
+ const whenReason = (graph, state, action, capable) => {
9
+ const entries = graph.availability.filter((a) => a.state === state && a.action === action && (capable.length === 0 || capable.includes(a.actor)));
10
+ return unique(entries.map((a) => a.reason ?? ERROR_REASON)).join("、");
11
+ };
12
+ export const summarizeActions = (spec, graph) => {
13
+ const labelOf = labeler(graph);
14
+ return spec.actions.map(([name]) => {
15
+ const entries = graph.availability.filter((a) => a.action === name);
16
+ const capable = capableOf(graph, name);
17
+ const blocked = new Map();
18
+ for (const state of unique(entries.map((a) => a.state))) {
19
+ if (entries.some((a) => a.state === state && a.enabled))
20
+ continue;
21
+ const reason = whenReason(graph, state, name, capable);
22
+ blocked.set(reason, [...(blocked.get(reason) ?? []), labelOf(state)]);
23
+ }
24
+ return {
25
+ name,
26
+ summary: spec.docs[name] ?? null,
27
+ capable,
28
+ othersReasons: capable.length === 0 ? [] : unique(entries.filter((a) => !capable.includes(a.actor)).map((a) => a.reason ?? ERROR_REASON)),
29
+ when: uniqueBy(collapseTransitions(graph)
30
+ .filter((t) => t.action === name)
31
+ .map((t) => ({ from: t.from === ANY ? ANY : labelOf(t.from), to: labelOf(t.to) })), (w) => `${w.from}→${w.to}`),
32
+ blocked: [...blocked.entries()].map(([reason, states]) => ({ reason, states })),
33
+ effect: effectOf(graph, name),
34
+ inputReasons: inputReasonsOf(entries),
35
+ inputOutcomes: inputOutcomesOf(spec, name, entries, labelOf),
36
+ };
37
+ });
38
+ };
39
+ export const summarizeStates = (spec, graph) => {
40
+ const labelOf = labeler(graph);
41
+ return graph.states.map((s) => {
42
+ const can = [];
43
+ const cannot = [];
44
+ for (const [action] of spec.actions) {
45
+ const enabled = graph.availability.filter((a) => a.state === s.id && a.action === action && a.enabled);
46
+ if (enabled.length > 0) {
47
+ for (const to of unique(enabled.map((a) => a.to))) {
48
+ can.push({ action, actors: unique(enabled.filter((a) => a.to === to).map((a) => a.actor)), to: labelOf(to) });
49
+ }
50
+ }
51
+ else if (graph.availability.some((a) => a.state === s.id && a.action === action)) {
52
+ cannot.push({ action, reason: whenReason(graph, s.id, action, capableOf(graph, action)) });
53
+ }
54
+ }
55
+ const violations = graph.findings.flatMap((f) => (f.kind === "invariant-violation" && f.state === s.id ? [f.invariant] : []));
56
+ const groups = new Map();
57
+ for (const sf of graph.surfaces.filter((x) => x.state === s.id)) {
58
+ const key = JSON.stringify(sf.surface);
59
+ const g = groups.get(key) ?? { actors: [], surface: sf.surface };
60
+ g.actors.push(sf.actor);
61
+ groups.set(key, g);
62
+ }
63
+ return { id: s.id, label: s.label, initial: s.initial, terminal: s.terminal, can, cannot, violations, surfaces: [...groups.values()] };
64
+ });
65
+ };
66
+ // 同じ状態・同じ登場人物で、ある入力では成功し別の入力では失敗したときだけ、その失敗を
67
+ // 「入力の条件」とみなす。状態や権限による失敗と混ぜないため。
68
+ const inputReasonsOf = (entries) => {
69
+ const found = entries.filter((a) => !a.enabled &&
70
+ a.input !== null &&
71
+ entries.some((b) => b.enabled && b.state === a.state && b.actor === a.actor));
72
+ return uniqueBy(found.map((a) => ({ input: a.input, reason: a.reason ?? ERROR_REASON })), (r) => `${r.input}|${r.reason}`);
73
+ };
74
+ // 入力ごとに「どこからどこへ移るか」を出す理由: CLI の引数のように入力で結果が大きく変わる操作では、
75
+ // 「できない入力」だけでは、正しい入力でどうなるかが仕様書から読めないため。
76
+ const inputOutcomesOf = (spec, action, entries, labelOf) => (spec.inputs[action] ?? []).map(([input]) => {
77
+ const mine = entries.filter((a) => a.input === input);
78
+ const transitions = uniqueBy(mine.filter((a) => a.enabled).map((a) => ({ from: labelOf(a.state), to: labelOf(a.to) })), (t) => `${t.from}→${t.to}`);
79
+ if (transitions.length > 0)
80
+ return { input, transitions, reasons: [] };
81
+ // 入力が原因の理由を優先する理由: 全員が状態や権限で止まる理由まで並べると、その入力の何がだめなのかが埋もれるため。
82
+ const byInput = inputReasonsOf(entries).filter((r) => r.input === input).map((r) => r.reason);
83
+ const reasons = byInput.length > 0 ? byInput : unique(mine.map((a) => a.reason ?? ERROR_REASON));
84
+ return { input, transitions, reasons };
85
+ });
86
+ const REST_THRESHOLD = 3;
87
+ // 一番多いまとまりを「それ以外」とまとめる理由: できないときの状態は、たいてい「できるとき」の補集合で、
88
+ // すべて並べると状態名の壁になり、何が条件なのかが読めなくなるため。少ないときはそのまま並べる。
89
+ export const presentBlocked = (blocked) => {
90
+ if (blocked.length === 0)
91
+ return [];
92
+ const largest = blocked.reduce((a, b) => (b.states.length > a.states.length ? b : a));
93
+ if (largest.states.length < REST_THRESHOLD)
94
+ return blocked;
95
+ return [...blocked.filter((b) => b !== largest), { reason: largest.reason, states: null }];
96
+ };
97
+ export const formatTransition = (t) => t.from === ANY ? `${ANY_LABEL} → ${t.to}` : t.from === t.to ? `${t.from}(変わらない)` : `${t.from} → ${t.to}`;
98
+ const effectOf = (graph, action) => {
99
+ const changed = new Map();
100
+ for (const t of graph.transitions) {
101
+ if (t.action !== action)
102
+ continue;
103
+ const from = graph.states.find((s) => s.id === t.from).values;
104
+ const to = graph.states.find((s) => s.id === t.to).values;
105
+ for (const k of Object.keys(to)) {
106
+ if (JSON.stringify(from[k]) === JSON.stringify(to[k]))
107
+ continue;
108
+ if (!changed.has(k))
109
+ changed.set(k, new Set());
110
+ changed.get(k).add(typeof to[k] === "string" ? to[k] : JSON.stringify(to[k]));
111
+ }
112
+ }
113
+ return [...changed.entries()].map(([field, values]) => ({ field, values: [...values] }));
114
+ };
115
+ const labeler = (graph) => (id) => graph.states.find((s) => s.id === id)?.label ?? id;
116
+ const unique = (xs) => [...new Set(xs)];
117
+ const uniqueBy = (xs, key) => [
118
+ ...new Map(xs.map((x) => [key(x), x])).values(),
119
+ ];
@@ -0,0 +1,3 @@
1
+ import type { SurfaceNode } from "../surface.js";
2
+ export declare const surfaceToText: (node: SurfaceNode, invalidActions: ReadonlyArray<string>) => string;
3
+ export declare const surfaceToHtml: (node: SurfaceNode, invalidActions: ReadonlyArray<string>) => string;
@@ -0,0 +1,62 @@
1
+ import { esc } from "./escape.js";
2
+ // テキストの枠線で描く理由: Markdown の仕様書は GitHub やエディタでそのまま読まれるので、
3
+ // 画像や HTML に頼らず、コードブロックの中で画面の構成(どこに何のボタンがあるか)が分かるようにする。
4
+ export const surfaceToText = (node, invalidActions) => {
5
+ if (node.kind === "code")
6
+ return node.text;
7
+ if (node.kind !== "screen")
8
+ return linesOf(node, invalidActions).join("\n");
9
+ return [`┌─ ${node.title}`, ...node.children.flatMap((c) => linesOf(c, invalidActions)).map((l) => `│ ${l}`), "└─"].join("\n");
10
+ };
11
+ const linesOf = (node, invalid) => {
12
+ switch (node.kind) {
13
+ case "screen":
14
+ case "section":
15
+ return [`▸ ${node.title}`, ...node.children.flatMap((c) => linesOf(c, invalid)).map((l) => ` ${l}`)];
16
+ case "heading":
17
+ return [`■ ${node.text}`];
18
+ case "text":
19
+ return [node.text];
20
+ case "field":
21
+ return [`${node.label}: [${node.value}]`];
22
+ case "button":
23
+ if (node.disabled === true)
24
+ return [`[${node.label}](押せない)`];
25
+ return [node.action !== undefined && invalid.includes(node.action) ? `[${node.label}] ⚠ 押しても実行できない` : `[${node.label}]`];
26
+ case "badge":
27
+ return [`(${node.text})`];
28
+ case "list":
29
+ return node.items.flatMap((i) => linesOf(i, invalid).map((l, n) => (n === 0 ? `・${l}` : ` ${l}`)));
30
+ case "code":
31
+ return node.text.split("\n");
32
+ }
33
+ };
34
+ // ワイヤーフレームの描画をサーバ側のこの関数 1 か所にまとめている理由: 状態のパネルと
35
+ // wireflow のサムネイルの両方で使うので、描画が 2 か所にあると表示がずれていくため。
36
+ export const surfaceToHtml = (node, invalidActions) => {
37
+ const children = (nodes) => nodes.map((c) => surfaceToHtml(c, invalidActions)).join("");
38
+ switch (node.kind) {
39
+ case "screen":
40
+ return `<div class="wf-screen"><div class="wf-title">${esc(node.title)}</div><div class="wf-body">${children(node.children)}</div></div>`;
41
+ case "section":
42
+ return `<div class="wf-section"><span class="wf-label">${esc(node.title)}</span>${children(node.children)}</div>`;
43
+ case "heading":
44
+ return `<div class="wf-heading">${esc(node.text)}</div>`;
45
+ case "text":
46
+ return `<p class="wf-text">${esc(node.text)}</p>`;
47
+ case "field":
48
+ return `<label class="wf-field">${esc(node.label)}<div class="wf-input">${esc(node.value)}</div></label>`;
49
+ case "button": {
50
+ const invalid = node.disabled !== true && node.action !== undefined && invalidActions.includes(node.action);
51
+ const cls = ["wf-button", node.disabled === true ? "is-disabled" : "", invalid ? "is-invalid" : ""].filter(Boolean).join(" ");
52
+ const title = invalid ? ` title="このボタンを押しても ${esc(node.action)} は実行できません"` : "";
53
+ return `<span class="${cls}"${title}>${esc(node.label)}</span>`;
54
+ }
55
+ case "badge":
56
+ return `<span class="wf-badge">${esc(node.text)}</span>`;
57
+ case "list":
58
+ return `<ul class="wf-list">${node.items.map((i) => `<li>${surfaceToHtml(i, invalidActions)}</li>`).join("")}</ul>`;
59
+ case "code":
60
+ return `<pre class="wf-code" data-language="${esc(node.language)}">${esc(node.text)}</pre>`;
61
+ }
62
+ };
@@ -0,0 +1,8 @@
1
+ export declare const EVENTS_PATH = "/__live-spec/events";
2
+ export interface SpecServer {
3
+ readonly url: string;
4
+ update(html: string): void;
5
+ close(): Promise<void>;
6
+ }
7
+ export declare const injectReload: (html: string, version: number) => string;
8
+ export declare const startServer: (port: number) => Promise<SpecServer>;