@yutaura/live-spec 0.0.0-stage → 0.2.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 (67) hide show
  1. package/.claude-plugin/plugin.json +12 -0
  2. package/LICENSE +21 -0
  3. package/README.md +205 -2
  4. package/dist/cli.d.ts +20 -0
  5. package/dist/cli.js +219 -0
  6. package/dist/diff.d.ts +123 -0
  7. package/dist/diff.js +178 -0
  8. package/dist/ensure-scope.d.ts +9 -0
  9. package/dist/ensure-scope.js +81 -0
  10. package/dist/ensure.d.ts +9 -0
  11. package/dist/ensure.js +35 -0
  12. package/dist/explore.d.ts +25 -0
  13. package/dist/explore.js +292 -0
  14. package/dist/generate.d.ts +21 -0
  15. package/dist/generate.js +159 -0
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.js +2 -0
  18. package/dist/load.d.ts +58 -0
  19. package/dist/load.js +79 -0
  20. package/dist/model.d.ts +487 -0
  21. package/dist/model.js +209 -0
  22. package/dist/mutation.d.ts +3 -0
  23. package/dist/mutation.js +51 -0
  24. package/dist/omission.d.ts +6 -0
  25. package/dist/omission.js +177 -0
  26. package/dist/project-diff.d.ts +24 -0
  27. package/dist/project-diff.js +76 -0
  28. package/dist/render/collapse.d.ts +4 -0
  29. package/dist/render/collapse.js +22 -0
  30. package/dist/render/diff-html.d.ts +2 -0
  31. package/dist/render/diff-html.js +148 -0
  32. package/dist/render/diff-markdown.d.ts +11 -0
  33. package/dist/render/diff-markdown.js +70 -0
  34. package/dist/render/ensures.d.ts +2 -0
  35. package/dist/render/ensures.js +21 -0
  36. package/dist/render/escape.d.ts +1 -0
  37. package/dist/render/escape.js +2 -0
  38. package/dist/render/html.d.ts +13 -0
  39. package/dist/render/html.js +717 -0
  40. package/dist/render/layout.d.ts +39 -0
  41. package/dist/render/layout.js +74 -0
  42. package/dist/render/markdown.d.ts +20 -0
  43. package/dist/render/markdown.js +248 -0
  44. package/dist/render/review.d.ts +17 -0
  45. package/dist/render/review.js +17 -0
  46. package/dist/render/summary.d.ts +62 -0
  47. package/dist/render/summary.js +119 -0
  48. package/dist/render/union.d.ts +23 -0
  49. package/dist/render/union.js +43 -0
  50. package/dist/render/wireframe.d.ts +3 -0
  51. package/dist/render/wireframe.js +62 -0
  52. package/dist/serve.d.ts +8 -0
  53. package/dist/serve.js +71 -0
  54. package/dist/skills.d.ts +8 -0
  55. package/dist/skills.js +20 -0
  56. package/dist/spec-loader.d.ts +2 -0
  57. package/dist/spec-loader.js +24 -0
  58. package/dist/static.d.ts +15 -0
  59. package/dist/static.js +151 -0
  60. package/dist/surface.d.ts +59 -0
  61. package/dist/surface.js +44 -0
  62. package/dist/watch.d.ts +10 -0
  63. package/dist/watch.js +47 -0
  64. package/package.json +60 -4
  65. package/skills/live-spec-authoring/SKILL.md +190 -0
  66. package/skills/live-spec-from-code/SKILL.md +93 -0
  67. package/skills/live-spec-review/SKILL.md +71 -0
@@ -0,0 +1,43 @@
1
+ // 状態は値で突き合わせる(ID は探索順で、名前は initial の書き順で変わりうる)。
2
+ // 自分自身に戻る遷移は、通常の図と同じく描かない。
3
+ export const unionGraph = (before, after) => {
4
+ const keyOf = (s) => JSON.stringify(s.values);
5
+ const labelsOf = (g) => new Map((g?.states ?? []).map((s) => [s.id, keyOf(s)]));
6
+ const lb = labelsOf(before);
7
+ const la = labelsOf(after);
8
+ const beforeKeys = new Set(lb.values());
9
+ const afterKeys = new Set(la.values());
10
+ const ordered = [...new Set([...afterKeys, ...beforeKeys])];
11
+ // 変更後の名前を優先する理由: レビューする人が読むのは変更後の spec なので。
12
+ const names = new Map([...(before?.states ?? []), ...(after?.states ?? [])].map((s) => [keyOf(s), s.label]));
13
+ const initialState = (after ?? before)?.states.find((s) => s.initial);
14
+ const initialKey = initialState === undefined ? undefined : keyOf(initialState);
15
+ const nodes = ordered.map((key, i) => ({
16
+ id: `n${i}`,
17
+ label: names.get(key) ?? key,
18
+ status: !beforeKeys.has(key) ? "added" : !afterKeys.has(key) ? "removed" : "kept",
19
+ initial: key === initialKey,
20
+ }));
21
+ const idOf = new Map(ordered.map((key, i) => [key, nodes[i].id]));
22
+ const actorsByKey = (g, labels) => {
23
+ const map = new Map();
24
+ for (const t of (g?.transitions ?? []).filter((t) => t.from !== t.to)) {
25
+ const key = JSON.stringify([labels.get(t.from), t.action, labels.get(t.to)]);
26
+ map.set(key, new Set([...(map.get(key) ?? []), ...t.actors]));
27
+ }
28
+ return map;
29
+ };
30
+ const kb = actorsByKey(before, lb);
31
+ const ka = actorsByKey(after, la);
32
+ const edges = [...new Set([...ka.keys(), ...kb.keys()])].map((key) => {
33
+ const [from, action, to] = JSON.parse(key);
34
+ const b = kb.get(key);
35
+ const a = ka.get(key);
36
+ const actorsAdded = b === undefined || a === undefined ? [] : [...a].filter((x) => !b.has(x));
37
+ const actorsRemoved = b === undefined || a === undefined ? [] : [...b].filter((x) => !a.has(x));
38
+ const status = b === undefined ? "added" : a === undefined ? "removed" : actorsAdded.length + actorsRemoved.length > 0 ? "changed" : "kept";
39
+ return { from: idOf.get(from), to: idOf.get(to), action, status, actorsAdded, actorsRemoved };
40
+ });
41
+ return { nodes, edges };
42
+ };
43
+ export const edgeLabel = (e) => [e.action, ...e.actorsAdded.map((a) => `+${a}`), ...e.actorsRemoved.map((a) => `-${a}`)].join(" ");
@@ -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>;
package/dist/serve.js ADDED
@@ -0,0 +1,71 @@
1
+ import { createServer } from "node:http";
2
+ export const EVENTS_PATH = "/__live-spec/events";
3
+ // 再読み込みのスクリプトを生成時ではなく配信時に差し込む理由: --out で書き出すファイルは
4
+ // サーバなしで開いても動く単体の HTML のままにしておきたいため。
5
+ // ページに版数を埋め込み、通知の接続がつながったときにサーバの版数と比べる理由:
6
+ // ページを読み込んでから接続がつながるまでの間に生成し直されると、その時点で接続がないので
7
+ // reload の通知を受け取れない。接続時に版数を確かめれば、その間の更新も取りこぼさない。
8
+ export const injectReload = (html, version) => html.replace("</body>", `<script>(function () {
9
+ var version = ${version};
10
+ var es = new EventSource("${EVENTS_PATH}");
11
+ es.onmessage = function (e) {
12
+ if (e.data === "reload" || (e.data.indexOf("version ") === 0 && e.data !== "version " + version)) location.reload();
13
+ };
14
+ // 接続が切れたことを表示する理由: サーバを止めると、開いたままのタブは何も知らせずに古い仕様書を
15
+ // 表示し続けていた(specs/browser-tab.spec.ts の未決事項だったもの)。つなぎ直せたら消す。
16
+ var banner = null;
17
+ es.onerror = function () {
18
+ if (banner) return;
19
+ banner = document.createElement("div");
20
+ banner.textContent = "サーバとの接続が切れました。この仕様書は最新ではないかもしれません。";
21
+ banner.setAttribute("style", "position:fixed;top:0;left:0;right:0;z-index:100;padding:8px 16px;background:#b3501a;color:#fff;font:14px system-ui,sans-serif;text-align:center");
22
+ document.body.append(banner);
23
+ };
24
+ es.onopen = function () { if (banner) { banner.remove(); banner = null; } };
25
+ })();</script>\n</body>`);
26
+ const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost"]);
27
+ export const startServer = (port) => new Promise((resolve, reject) => {
28
+ let html = "<!doctype html><html><body><p>仕様書を生成しています…</p></body></html>";
29
+ let version = 0;
30
+ const clients = new Set();
31
+ const server = createServer((req, res) => {
32
+ // Host ヘッダを確かめる理由: DNS リバインディングで外部のサイトが自分のドメイン名を
33
+ // 127.0.0.1 に向け直すと、このサーバの内容をブラウザ経由で読み取れてしまうため。
34
+ const host = (req.headers.host ?? "").replace(/:\d+$/, "");
35
+ if (!LOCAL_HOSTS.has(host)) {
36
+ res.writeHead(403).end();
37
+ return;
38
+ }
39
+ if (req.url === "/") {
40
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
41
+ res.end(injectReload(html, version));
42
+ return;
43
+ }
44
+ if (req.url === EVENTS_PATH) {
45
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
46
+ res.write(`: connected\n\ndata: version ${version}\n\n`);
47
+ clients.add(res);
48
+ req.on("close", () => clients.delete(res));
49
+ return;
50
+ }
51
+ res.writeHead(404).end();
52
+ });
53
+ server.on("error", reject);
54
+ server.listen(port, "127.0.0.1", () => {
55
+ const { port: actual } = server.address();
56
+ resolve({
57
+ url: `http://127.0.0.1:${actual}/`,
58
+ update(next) {
59
+ html = next;
60
+ version += 1;
61
+ for (const client of clients)
62
+ client.write("data: reload\n\n");
63
+ },
64
+ close() {
65
+ for (const client of clients)
66
+ client.end();
67
+ return new Promise((done) => server.close(() => done()));
68
+ },
69
+ });
70
+ });
71
+ });
@@ -0,0 +1,8 @@
1
+ export declare const bundledSkills: () => Array<string>;
2
+ export interface InstallResult {
3
+ readonly name: string;
4
+ readonly status: "installed" | "updated" | "skipped";
5
+ }
6
+ export declare const installSkills: (targetDir: string, options?: {
7
+ readonly force?: boolean;
8
+ }) => Array<InstallResult>;
package/dist/skills.js ADDED
@@ -0,0 +1,20 @@
1
+ import { cpSync, existsSync, mkdirSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ // 配布物では skills/(skills-npm などの慣習の置き場所。ビルドで .claude/skills からコピーする)、
5
+ // このリポジトリで直接動かすときは原本の .claude/skills から読む。src/ からも dist/ からも 1 つ上がルート。
6
+ const candidates = ["../skills/", "../.claude/skills/"].map((p) => fileURLToPath(new URL(p, import.meta.url)));
7
+ const SKILLS_DIR = candidates.find((dir) => existsSync(dir)) ?? candidates[1];
8
+ export const bundledSkills = () => readdirSync(SKILLS_DIR, { withFileTypes: true })
9
+ .filter((d) => d.isDirectory() && existsSync(join(SKILLS_DIR, d.name, "SKILL.md")))
10
+ .map((d) => d.name)
11
+ .sort();
12
+ export const installSkills = (targetDir, options = {}) => bundledSkills().map((name) => {
13
+ const dest = join(targetDir, name, "SKILL.md");
14
+ const exists = existsSync(dest);
15
+ if (exists && options.force !== true)
16
+ return { name, status: "skipped" };
17
+ mkdirSync(join(targetDir, name), { recursive: true });
18
+ cpSync(join(SKILLS_DIR, name, "SKILL.md"), dest);
19
+ return { name, status: exists ? "updated" : "installed" };
20
+ });
@@ -0,0 +1,2 @@
1
+ export declare const isSpecModuleUrl: (url: string) => boolean;
2
+ export declare const registerSpecLoader: () => void;
@@ -0,0 +1,24 @@
1
+ import { registerHooks } from "node:module";
2
+ // ファイル名に .spec. を含む .ts。差分やミューテーションで書き出す一時ファイル(.order.spec.live-spec-base.ts など)も含む。
3
+ export const isSpecModuleUrl = (url) => {
4
+ if (!url.startsWith("file:"))
5
+ return false;
6
+ const path = new URL(url).pathname;
7
+ const base = path.slice(path.lastIndexOf("/") + 1);
8
+ return base.endsWith(".ts") && base.includes(".spec.");
9
+ };
10
+ let registered = false;
11
+ // spec を TypeScript の ES module として読むよう Node に伝える。
12
+ // 伝えないと、package.json に "type": "module" が無いプロジェクト(pnpm workspace のルートなど)では、
13
+ // Node が CommonJS として読もうとして失敗し、spec ごとに MODULE_TYPELESS_PACKAGE_JSON の警告を出す。
14
+ // 利用者に package.json を足してもらう回避策にしない理由: ルートに "type" を足すと、既存の CommonJS の設定ファイルを壊しうる。
15
+ export const registerSpecLoader = () => {
16
+ if (registered)
17
+ return;
18
+ registered = true;
19
+ registerHooks({
20
+ load(url, context, nextLoad) {
21
+ return nextLoad(url, isSpecModuleUrl(url) ? { ...context, format: "module-typescript" } : context);
22
+ },
23
+ });
24
+ };
@@ -0,0 +1,15 @@
1
+ export type FieldValue = string | boolean;
2
+ export interface StaticInfo {
3
+ readonly order: ReadonlyArray<string>;
4
+ readonly docs: Readonly<Record<string, string>>;
5
+ readonly fields: Readonly<Record<string, ReadonlyArray<FieldValue>>>;
6
+ readonly stateDoc: string | null;
7
+ readonly fieldDocs: Readonly<Record<string, string>>;
8
+ readonly evidence: Readonly<Record<string, ReadonlyArray<string>>>;
9
+ readonly ensures: Readonly<Record<string, ReadonlyArray<EnsureCall>>>;
10
+ }
11
+ export interface EnsureCall {
12
+ readonly reason: string;
13
+ readonly line: number;
14
+ }
15
+ export declare const analyze: (source: string) => StaticInfo;
package/dist/static.js ADDED
@@ -0,0 +1,151 @@
1
+ import { parse } from "@babel/parser";
2
+ const EVIDENCE = /^\s*根拠[::]\s*(.+?)\s*$/;
3
+ // TypeScript の型チェッカーではなく構文解析にとどめる理由:
4
+ // TypeScript 7 の JS API は typescript/unstable/sync しかなく、まだ不安定。
5
+ // 構文だけでも「同じファイルの type / interface に書かれたリテラル union」と JSDoc は読める。
6
+ // import した型や型の別名をまたぐ解決が必要になったら、この関数だけを差し替える。
7
+ export const analyze = (source) => {
8
+ const file = parse(source, { sourceType: "module", plugins: ["typescript"] });
9
+ const body = file.program.body;
10
+ const comments = file.comments ?? [];
11
+ const evidence = {};
12
+ const ensures = {};
13
+ const order = [];
14
+ const docs = {};
15
+ const types = new Map();
16
+ let initialType = null;
17
+ for (const node of body) {
18
+ const decl = node.type === "ExportNamedDeclaration" ? node.declaration : node;
19
+ const doc = summaryOf(node.leadingComments);
20
+ if (decl == null)
21
+ continue;
22
+ if (decl.type === "TSTypeAliasDeclaration" && decl.typeAnnotation.type === "TSTypeLiteral") {
23
+ types.set(decl.id.name, { members: decl.typeAnnotation.members, doc });
24
+ }
25
+ if (decl.type === "TSInterfaceDeclaration")
26
+ types.set(decl.id.name, { members: decl.body.body, doc });
27
+ for (const [name, typeName] of valueNamesOf(decl)) {
28
+ if (name === "initial")
29
+ initialType = typeName;
30
+ if (node.type !== "ExportNamedDeclaration")
31
+ continue;
32
+ order.push(name);
33
+ if (doc !== null)
34
+ docs[name] = doc;
35
+ // 関数の範囲にある「// 根拠:」をその操作の根拠とする。spec とコードを突き合わせられるように、
36
+ // 書き起こした人が残した場所を仕様書にも出すため。
37
+ const found = comments
38
+ .filter((c) => c.type === "CommentLine" && c.start >= decl.start && c.end <= decl.end)
39
+ .flatMap((c) => {
40
+ const m = EVIDENCE.exec(c.value);
41
+ return m === null ? [] : [m[1]];
42
+ });
43
+ if (found.length > 0)
44
+ evidence[name] = found;
45
+ const calls = ensureCallsIn(decl);
46
+ if (calls.length > 0)
47
+ ensures[name] = calls;
48
+ }
49
+ }
50
+ const stateType = initialType === null ? undefined : types.get(initialType);
51
+ return {
52
+ order,
53
+ docs,
54
+ fields: stateType === undefined ? {} : fieldsOf(stateType.members),
55
+ stateDoc: stateType?.doc ?? null,
56
+ fieldDocs: stateType === undefined ? {} : fieldDocsOf(stateType.members),
57
+ evidence,
58
+ ensures,
59
+ };
60
+ };
61
+ // 理由が文字列リテラル(または式を含まないテンプレート)の ensure だけを集める。
62
+ // 理由を式で組み立てている ensure は、どの理由のときに外せばよいかを実行前に決められないため。
63
+ const ensureCallsIn = (root) => {
64
+ const calls = [];
65
+ const visit = (node) => {
66
+ if (Array.isArray(node))
67
+ return node.forEach(visit);
68
+ if (typeof node !== "object" || node === null || !("type" in node))
69
+ return;
70
+ const n = node;
71
+ if (n.type === "CallExpression" && n.callee.type === "Identifier" && n.callee.name === "ensure") {
72
+ const arg = n.arguments[1];
73
+ const reason = arg?.type === "StringLiteral"
74
+ ? arg.value
75
+ : arg?.type === "TemplateLiteral" && arg.expressions.length === 0
76
+ ? arg.quasis.map((q) => q.value.cooked ?? "").join("")
77
+ : null;
78
+ if (reason !== null && n.loc != null)
79
+ calls.push({ reason, line: n.loc.start.line });
80
+ }
81
+ for (const [key, value] of Object.entries(n)) {
82
+ if (key === "loc" || key.endsWith("Comments"))
83
+ continue;
84
+ visit(value);
85
+ }
86
+ };
87
+ visit(root);
88
+ return calls;
89
+ };
90
+ const valueNamesOf = (decl) => {
91
+ if (decl.type === "FunctionDeclaration" && decl.id != null)
92
+ return [[decl.id.name, null]];
93
+ if (decl.type !== "VariableDeclaration")
94
+ return [];
95
+ return decl.declarations.flatMap((d) => {
96
+ if (d.id.type !== "Identifier")
97
+ return [];
98
+ const ann = d.id.typeAnnotation;
99
+ const ref = ann?.type === "TSTypeAnnotation" && ann.typeAnnotation.type === "TSTypeReference" ? ann.typeAnnotation : null;
100
+ const typeName = ref !== null && ref.typeName.type === "Identifier" ? ref.typeName.name : null;
101
+ return [[d.id.name, typeName]];
102
+ });
103
+ };
104
+ const fieldsOf = (members) => {
105
+ const fields = {};
106
+ for (const m of members) {
107
+ if (m.type !== "TSPropertySignature" || m.typeAnnotation == null)
108
+ continue;
109
+ const key = m.key.type === "Identifier" ? m.key.name : m.key.type === "StringLiteral" ? m.key.value : null;
110
+ const values = finiteValuesOf(m.typeAnnotation.typeAnnotation);
111
+ if (key !== null && values !== null)
112
+ fields[key] = values;
113
+ }
114
+ return fields;
115
+ };
116
+ const fieldDocsOf = (members) => {
117
+ const docs = {};
118
+ for (const m of members) {
119
+ if (m.type !== "TSPropertySignature")
120
+ continue;
121
+ const key = m.key.type === "Identifier" ? m.key.name : m.key.type === "StringLiteral" ? m.key.value : null;
122
+ const doc = summaryOf(m.leadingComments);
123
+ if (key !== null && doc !== null)
124
+ docs[key] = doc;
125
+ }
126
+ return docs;
127
+ };
128
+ const finiteValuesOf = (type) => {
129
+ if (type.type === "TSBooleanKeyword")
130
+ return [false, true];
131
+ const members = type.type === "TSUnionType" ? type.types : [type];
132
+ const values = members.map((m) => (m.type === "TSLiteralType" && m.literal.type === "StringLiteral" ? m.literal.value : null));
133
+ return values.every((v) => v !== null) ? values : null;
134
+ };
135
+ // 最初の段落(空行まで)を説明文にする理由: 1 行目だけを取ると、複数行にわたる文が途中で切れてしまうため。
136
+ const summaryOf = (comments) => {
137
+ const jsdoc = comments?.findLast((c) => c.type === "CommentBlock" && c.value.startsWith("*"));
138
+ if (jsdoc === undefined)
139
+ return null;
140
+ const lines = jsdoc.value
141
+ .slice(1)
142
+ .split("\n")
143
+ .map((line) => line.replace(/^\s*\*?\s?/, "").trim());
144
+ const start = lines.findIndex((line) => line !== "");
145
+ if (start === -1)
146
+ return null;
147
+ const end = lines.indexOf("", start);
148
+ return (end === -1 ? lines.slice(start) : lines.slice(start, end)).reduce((text, line) => isCjk(text.at(-1)) || isCjk(line[0]) ? text + line : `${text} ${line}`);
149
+ };
150
+ // 日本語の行のあいだに空白を入れない理由: JSDoc の折り返しは表示上の都合なので、日本語では空白が入ると文が不自然に途切れる。
151
+ const isCjk = (ch) => ch !== undefined && (ch.codePointAt(0) ?? 0) > 0x2e7f;
@@ -0,0 +1,59 @@
1
+ export type SurfaceNode = {
2
+ readonly kind: "screen";
3
+ readonly title: string;
4
+ readonly children: ReadonlyArray<SurfaceNode>;
5
+ } | {
6
+ readonly kind: "section";
7
+ readonly title: string;
8
+ readonly children: ReadonlyArray<SurfaceNode>;
9
+ } | {
10
+ readonly kind: "heading";
11
+ readonly text: string;
12
+ } | {
13
+ readonly kind: "text";
14
+ readonly text: string;
15
+ } | {
16
+ readonly kind: "field";
17
+ readonly label: string;
18
+ readonly value: string;
19
+ } | {
20
+ readonly kind: "button";
21
+ readonly label: string;
22
+ readonly action?: string;
23
+ readonly disabled?: true;
24
+ } | {
25
+ readonly kind: "badge";
26
+ readonly text: string;
27
+ } | {
28
+ readonly kind: "list";
29
+ readonly items: ReadonlyArray<SurfaceNode>;
30
+ } | {
31
+ readonly kind: "code";
32
+ readonly language: string;
33
+ readonly text: string;
34
+ };
35
+ export type Child = SurfaceNode | false | null | undefined;
36
+ type AnyAction = (...args: never) => unknown;
37
+ export declare const ui: {
38
+ screen: (title: string, ...children: ReadonlyArray<Child>) => SurfaceNode;
39
+ section: (title: string, ...children: ReadonlyArray<Child>) => SurfaceNode;
40
+ heading: (text: string) => SurfaceNode;
41
+ text: (text: string) => SurfaceNode;
42
+ field: (label: string, value?: string) => SurfaceNode;
43
+ button: (label: string, action?: AnyAction, options?: {
44
+ readonly disabled?: boolean;
45
+ }) => SurfaceNode;
46
+ badge: (text: string) => SurfaceNode;
47
+ list: (...items: ReadonlyArray<Child>) => SurfaceNode;
48
+ };
49
+ export declare const api: {
50
+ request: (method: string, path: string, body?: unknown) => SurfaceNode;
51
+ response: (status: number, body?: unknown) => SurfaceNode;
52
+ };
53
+ export declare const cli: {
54
+ output: (text: string) => SurfaceNode;
55
+ };
56
+ export declare const buttonsOf: (node: SurfaceNode) => Array<Extract<SurfaceNode, {
57
+ kind: "button";
58
+ }>>;
59
+ export {};
@@ -0,0 +1,44 @@
1
+ const present = (children) => children.filter((c) => c !== false && c !== null && c !== undefined);
2
+ export const ui = {
3
+ screen: (title, ...children) => ({ kind: "screen", title, children: present(children) }),
4
+ section: (title, ...children) => ({
5
+ kind: "section",
6
+ title,
7
+ children: present(children),
8
+ }),
9
+ heading: (text) => ({ kind: "heading", text }),
10
+ text: (text) => ({ kind: "text", text }),
11
+ field: (label, value = "") => ({ kind: "field", label, value }),
12
+ button: (label, action, options = {}) => ({
13
+ kind: "button",
14
+ label,
15
+ ...(action === undefined ? {} : { action: action.name }),
16
+ ...(options.disabled === true ? { disabled: true } : {}),
17
+ }),
18
+ badge: (text) => ({ kind: "badge", text }),
19
+ list: (...items) => ({ kind: "list", items: present(items) }),
20
+ };
21
+ export const api = {
22
+ request: (method, path, body) => ({
23
+ kind: "code",
24
+ language: "http",
25
+ text: body === undefined ? `${method} ${path}` : `${method} ${path}\n${JSON.stringify(body, null, 2)}`,
26
+ }),
27
+ response: (status, body) => ({
28
+ kind: "code",
29
+ language: "http",
30
+ text: body === undefined ? `HTTP ${status}` : `HTTP ${status}\n${JSON.stringify(body, null, 2)}`,
31
+ }),
32
+ };
33
+ export const cli = {
34
+ output: (text) => ({ kind: "code", language: "terminal", text }),
35
+ };
36
+ export const buttonsOf = (node) => {
37
+ if (node.kind === "button")
38
+ return [node];
39
+ if (node.kind === "screen" || node.kind === "section")
40
+ return node.children.flatMap(buttonsOf);
41
+ if (node.kind === "list")
42
+ return node.items.flatMap(buttonsOf);
43
+ return [];
44
+ };
@@ -0,0 +1,10 @@
1
+ import { type FSWatcher } from "node:fs";
2
+ import { type OutputFormat } from "./generate.js";
3
+ export interface WatchOptions {
4
+ readonly paths: ReadonlyArray<string>;
5
+ readonly format: OutputFormat;
6
+ readonly out: string | null;
7
+ readonly title?: string | null;
8
+ readonly onBuilt?: (output: string) => void;
9
+ }
10
+ export declare const watchSpec: (options: WatchOptions, log?: (message: string) => void) => ReadonlyArray<FSWatcher>;
package/dist/watch.js ADDED
@@ -0,0 +1,47 @@
1
+ import { watch } from "node:fs";
2
+ import { basename, dirname, resolve } from "node:path";
3
+ import { expandSpecPaths, failureOutput, generateProject, writeProjectOutput } from "./generate.js";
4
+ // 保存後に少し待ってから生成する理由: エディタは 1 回の保存で複数の変更イベントを出すことが多く、
5
+ // そのたびに生成すると書きかけの内容を読んだり、同じ生成を何度も走らせたりするため。
6
+ const DEBOUNCE_MS = 80;
7
+ export const watchSpec = (options, log = console.error) => {
8
+ let timer;
9
+ let queue = Promise.resolve();
10
+ const rebuild = () => {
11
+ queue = queue.then(async () => {
12
+ const started = performance.now();
13
+ // 生成のたびにディレクトリを展開し直す理由: 監視中に spec ファイルが増えても、次の保存で拾えるようにするため。
14
+ const paths = expandSpecPaths(options.paths);
15
+ try {
16
+ const output = await generateProject(paths, options.format, options.title ?? undefined);
17
+ if (options.out !== null)
18
+ await writeProjectOutput(options.out, output);
19
+ if (output.kind === "text")
20
+ options.onBuilt?.(output.content);
21
+ const ms = Math.round(performance.now() - started);
22
+ log(options.out === null ? `✓ 生成しました(${ms}ms)` : `✓ ${options.out} を生成しました(${ms}ms)`);
23
+ }
24
+ catch (e) {
25
+ log(`✗ 生成に失敗しました: ${e instanceof Error ? e.message : String(e)}`);
26
+ // 失敗しても監視は続ける。書きかけの spec が一時的に壊れているのはよくあることなので。
27
+ const failure = failureOutput(options.format, paths, e);
28
+ if (options.out !== null)
29
+ await writeProjectOutput(options.out, failure);
30
+ if (failure.kind === "text")
31
+ options.onBuilt?.(failure.content);
32
+ }
33
+ });
34
+ };
35
+ // ファイルではなくディレクトリを監視する理由: 多くのエディタは「別ファイルに書いてから名前を差し替える」
36
+ // 方式で保存するので、ファイル自体を監視すると最初の保存で追跡が切れる。
37
+ const dirs = [...new Set(expandSpecPaths(options.paths).map((p) => dirname(resolve(p))).concat(options.paths.filter((p) => !p.endsWith(".ts")).map((p) => resolve(p))))];
38
+ const watchers = dirs.map((dir) => watch(dir, { recursive: true }, (_event, filename) => {
39
+ if (filename === null || !basename(filename).endsWith(".spec.ts"))
40
+ return;
41
+ clearTimeout(timer);
42
+ timer = setTimeout(rebuild, DEBOUNCE_MS);
43
+ }));
44
+ log(`${options.paths.join(", ")} を監視しています(Ctrl+C で終了)`);
45
+ rebuild();
46
+ return watchers;
47
+ };
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@yutaura/live-spec",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "description": "AI が書き、人が見て理解できる「生きた仕様書」を作るツール。素の TypeScript で書いた仕様を実行し、状態遷移図・画面・できる/できない理由・検査結果をまとめた仕様書を生成する",
7
+ "keywords": [
8
+ "specification",
9
+ "living-documentation",
10
+ "state-machine",
11
+ "spec-driven-development",
12
+ "wireframe"
13
+ ],
14
+ "homepage": "https://github.com/yutaura-dev/live-spec#readme",
15
+ "bugs": "https://github.com/yutaura-dev/live-spec/issues",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/yutaura-dev/live-spec.git"
19
+ },
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ }
25
+ },
26
+ "bin": {
27
+ "live-spec": "dist/cli.js"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "skills/*/SKILL.md",
32
+ ".claude-plugin/plugin.json",
33
+ "README.md"
34
+ ],
35
+ "engines": {
36
+ "node": ">=22.18"
37
+ },
38
+ "scripts": {
39
+ "test": "vitest run",
40
+ "test:watch": "vitest",
41
+ "typecheck": "tsc --noEmit",
42
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && node scripts/rewrite-dts-extensions.mjs dist && node scripts/copy-skills.mjs skills",
43
+ "prepack": "pnpm build",
44
+ "spec": "node src/cli.ts"
45
+ },
46
+ "packageManager": "pnpm@12.23.0",
47
+ "dependencies": {
48
+ "@babel/parser": "8.1.3",
49
+ "effect": "4.1.5",
50
+ "elkjs": "0.12.1"
51
+ },
52
+ "devDependencies": {
53
+ "@babel/types": "8.1.3",
54
+ "@effect/vitest": "4.1.5",
55
+ "@types/node": "^24.19.2",
56
+ "typescript": "7.0.2",
57
+ "vitest": "5.1.1"
58
+ },
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }