@infodb/p3 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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -2
  3. package/bin/p3.mjs +18 -0
  4. package/dist/web/apple-touch-icon.png +0 -0
  5. package/dist/web/assets/Outputs-Ni3pNuGU.js +1 -0
  6. package/dist/web/assets/RequestStatus-K8TZwpur.js +1 -0
  7. package/dist/web/assets/TagInput-BICKVH2x.js +1 -0
  8. package/dist/web/assets/TaskDrawer-BkDIstIN.js +3 -0
  9. package/dist/web/assets/_requestId-B5O_ytaq.js +1 -0
  10. package/dist/web/assets/_requestId-C66puEMO.js +30 -0
  11. package/dist/web/assets/action-CMjATXqv.js +1 -0
  12. package/dist/web/assets/board-CbfDjkls.js +1 -0
  13. package/dist/web/assets/copy-B1ZbihKL.js +2 -0
  14. package/dist/web/assets/done-CPQbCFHg.js +1 -0
  15. package/dist/web/assets/draft-dT3gLDIt.js +1 -0
  16. package/dist/web/assets/format-DuK6P1hb.js +1 -0
  17. package/dist/web/assets/index-BUcs2J6N.js +12 -0
  18. package/dist/web/assets/index-C3DkqwJ9.css +2 -0
  19. package/dist/web/assets/link-_s8ndNKS.js +1 -0
  20. package/dist/web/assets/new-T60RB7de.js +1 -0
  21. package/dist/web/assets/preload-helper-dXqN7N-I.js +1 -0
  22. package/dist/web/assets/release-notes-DxrPhDbt.js +3 -0
  23. package/dist/web/assets/requestData-D8ZiSZss.js +1 -0
  24. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  25. package/dist/web/assets/routes-D9ZxXoLk.js +2 -0
  26. package/dist/web/assets/search-CJ8MBKTz.js +1 -0
  27. package/dist/web/assets/settings-DsHVyqzJ.js +1 -0
  28. package/dist/web/assets/supersede-CLXlhCq0.js +1 -0
  29. package/dist/web/assets/ui-Cvke4y4X.js +1 -0
  30. package/dist/web/favicon.ico +0 -0
  31. package/dist/web/favicon.svg +12 -0
  32. package/dist/web/index.html +23 -0
  33. package/docs/architecture.md +591 -0
  34. package/docs/chatgpt-sign-in.md +163 -0
  35. package/docs/development.md +194 -0
  36. package/docs/how-to-use.md +524 -0
  37. package/docs/installation.md +284 -0
  38. package/docs/publishing.md +65 -0
  39. package/package.json +86 -3
  40. package/skills/p3/SKILL.md +95 -0
  41. package/src/cli/args.ts +179 -0
  42. package/src/cli/chatgpt.ts +74 -0
  43. package/src/cli/codex.ts +28 -0
  44. package/src/cli/format.ts +9 -0
  45. package/src/cli/help.ts +99 -0
  46. package/src/cli/main.ts +267 -0
  47. package/src/cli/output.ts +99 -0
  48. package/src/cli/preflightCommands.ts +237 -0
  49. package/src/cli/project.ts +508 -0
  50. package/src/cli/readOnly.ts +36 -0
  51. package/src/cli/releaseNotesCommands.ts +139 -0
  52. package/src/cli/render.ts +60 -0
  53. package/src/cli/requestCommands.ts +170 -0
  54. package/src/cli/showView.ts +110 -0
  55. package/src/cli/taskCommands.ts +167 -0
  56. package/src/cli/userConfig.ts +58 -0
  57. package/src/core/chatgpt.ts +33 -0
  58. package/src/core/context.ts +57 -0
  59. package/src/core/machineSettings.ts +207 -0
  60. package/src/core/machineSettingsEdit.ts +156 -0
  61. package/src/core/ops.ts +114 -0
  62. package/src/core/preflight/carryover.ts +133 -0
  63. package/src/core/preflight/codexEngine.ts +702 -0
  64. package/src/core/preflight/codexImage.ts +98 -0
  65. package/src/core/preflight/diagnose.ts +124 -0
  66. package/src/core/preflight/engine.ts +92 -0
  67. package/src/core/preflight/input.ts +65 -0
  68. package/src/core/preflight/launch.ts +86 -0
  69. package/src/core/preflight/launcher.mjs +75 -0
  70. package/src/core/preflight/mock-ui.html +24 -0
  71. package/src/core/preflight/mock-ui.png +0 -0
  72. package/src/core/preflight/mockEngine.ts +145 -0
  73. package/src/core/preflight/render-image/Dockerfile +23 -0
  74. package/src/core/preflight/render-image/render.mjs +53 -0
  75. package/src/core/preflight/render.ts +336 -0
  76. package/src/core/preflight/service.ts +690 -0
  77. package/src/core/preflight/uiMaterials.ts +272 -0
  78. package/src/core/preflight/uiRender.ts +84 -0
  79. package/src/core/preflight/wireframe.ts +69 -0
  80. package/src/core/preflight/xlsx.ts +328 -0
  81. package/src/core/redact.ts +31 -0
  82. package/src/core/releaseNotes/generate.ts +271 -0
  83. package/src/core/releaseNotes/material.ts +114 -0
  84. package/src/core/releaseNotes/mockSummarizer.ts +28 -0
  85. package/src/core/releaseNotes/service.ts +106 -0
  86. package/src/core/releaseNotes/store.ts +216 -0
  87. package/src/core/repoAdmin.ts +81 -0
  88. package/src/core/repoRefs.ts +90 -0
  89. package/src/core/requestOps.ts +140 -0
  90. package/src/core/requestStatus.ts +58 -0
  91. package/src/core/store/attachments.ts +228 -0
  92. package/src/core/store/collection.ts +282 -0
  93. package/src/core/store/frontmatter.ts +22 -0
  94. package/src/core/store/fsutil.ts +90 -0
  95. package/src/core/store/locate.ts +181 -0
  96. package/src/core/store/normalize.ts +155 -0
  97. package/src/core/store/noteStore.ts +56 -0
  98. package/src/core/store/preflightStore.ts +136 -0
  99. package/src/core/store/projectFile.ts +101 -0
  100. package/src/core/store/workspace.ts +328 -0
  101. package/src/core/supersede.ts +74 -0
  102. package/src/core/userConfig.ts +180 -0
  103. package/src/core/userTheme.ts +22 -0
  104. package/src/core/workTargets.ts +120 -0
  105. package/src/server/api/chatgptRoutes.ts +48 -0
  106. package/src/server/api/local.ts +33 -0
  107. package/src/server/api/manifest.ts +119 -0
  108. package/src/server/api/releaseNoteRoutes.ts +78 -0
  109. package/src/server/api/repoRoutes.ts +67 -0
  110. package/src/server/api/routes.ts +374 -0
  111. package/src/server/api/userThemeRoutes.ts +62 -0
  112. package/src/server/server.ts +49 -0
  113. package/src/shared/dates.ts +12 -0
  114. package/src/shared/preflightInput.ts +27 -0
  115. package/src/shared/refs.ts +55 -0
  116. package/src/shared/repos.ts +113 -0
  117. package/src/shared/scopeView.ts +48 -0
  118. package/src/shared/tags.ts +27 -0
  119. package/src/shared/types.ts +700 -0
  120. package/src/shared/workTarget.ts +44 -0
@@ -0,0 +1,145 @@
1
+ import { writableRepos } from "../../shared/workTarget.ts";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { join, relative } from "node:path";
4
+ import type { PreflightAssessment, ProposedTask } from "../../shared/types.ts";
5
+ import { stringifyFrontmatter } from "../store/frontmatter.ts";
6
+ import { writeFileAtomic } from "../store/fsutil.ts";
7
+ import type { EngineOutcome, PreflightEngine, PreflightJob } from "./engine.ts";
8
+
9
+ const wait = (ms: number, signal: AbortSignal) =>
10
+ new Promise<void>((res, rej) => {
11
+ const t = setTimeout(res, ms);
12
+ signal.addEventListener("abort", () => (clearTimeout(t), rej(new Error("aborted"))), { once: true });
13
+ });
14
+
15
+ /**
16
+ * Codex を使わずに preflight のファイル契約を再現するエンジン(オフライン開発・UI 確認用)。
17
+ * 要望本文の箇条書きをタスク案にし、関連項目から影響を推定するだけの単純なヒューリスティック。
18
+ * 再評価では、メモの箇条書きをタスク案に足し、前回不採用にした案(同じ題)は不採用のままにする。
19
+ * メモがあれば確認事項は答えられたものとして扱う(意味は解釈しない)。
20
+ */
21
+ export class MockEngine implements PreflightEngine {
22
+ readonly name = "mock" as const;
23
+ /** 待ち時間の倍率(画面で進み具合が見えるように少し待つ。テストでは 0) */
24
+ private delay: number;
25
+
26
+ constructor(opts: { delay?: number } = {}) {
27
+ this.delay = opts.delay ?? 1;
28
+ }
29
+
30
+ async status() {
31
+ return {
32
+ name: "mock" as const,
33
+ ok: true,
34
+ detail: "Mock(要望本文の箇条書きをそのままタスク案にする簡易評価)で実行します。P3_PREFLIGHT_ENGINE=mock か個人設定の preflight.engine: mock で選ばれています",
35
+ };
36
+ }
37
+
38
+ private sleep(ms: number, signal: AbortSignal) {
39
+ return wait(ms * this.delay, signal);
40
+ }
41
+
42
+ async run(job: PreflightJob, log: Parameters<PreflightEngine["run"]>[1], signal: AbortSignal): Promise<EngineOutcome> {
43
+ const { request } = job;
44
+ log({ kind: "info", text: "mock engine: Codex を使わずにヒューリスティックで評価します" });
45
+ await this.sleep(400, signal);
46
+ for (const r of job.refs) for (const m of r.map) log({ kind: "command", text: `$ ls ${r.name}:${m.path}` });
47
+ log({ kind: "command", text: `$ rg -l "${request.title.slice(0, 20)}" .` });
48
+ await this.sleep(400, signal);
49
+
50
+ const notes = job.carryover?.notes ?? [];
51
+ const previous = job.carryover?.previous;
52
+ if (previous) log({ kind: "command", text: `$ cat ${relative(job.dataDir, join(job.runDir, "carryover.md"))}` });
53
+ const bullets = [...new Set([request.body, ...notes.map((n) => n.body)].flatMap(bulletsOf))].slice(0, 8);
54
+ const rejected = new Set(previous?.drafts.filter((d) => !d.include).map((d) => d.title));
55
+ const items = bullets.length ? bullets : [`${request.title} の設計`, `${request.title} の実装`, `${request.title} のテスト`];
56
+ const areas = request.areas.length ? request.areas : ["src"];
57
+ const drafts: ProposedTask[] = items.map((title, i) => ({
58
+ key: `D${i + 1}`,
59
+ title,
60
+ description: `要望 ${request.id} より。\n\n## 完了条件\n- ${title} が動作すること\n- 既存機能に回帰がないこと`,
61
+ areas,
62
+ dependsOn: i === 0 ? [] : [`D${i}`],
63
+ supersedes: [],
64
+ include: !rejected.has(title),
65
+ // 作業先は作業先にできる参照先の先頭(Mock は読まないので推定しない。無ければ作業先なし)
66
+ repo: writableRepos(job.project)[0] ?? null,
67
+ }));
68
+
69
+ const clarity = Math.min(100, 40 + (request.body.length + notes.reduce((n, x) => n + x.body.length, 0)) / 8);
70
+ const carried = [previous && `前回 ${previous.id} を引き継ぎ`, notes.length && `メモ ${notes.length} 件を反映`].filter(Boolean).join("、");
71
+ const assessment: PreflightAssessment = {
72
+ summary: `「${request.title}」を ${drafts.length} 件のタスクに分割しました。${carried ? `${carried}しました。` : ""}(mock による推定)`,
73
+ verdict: clarity < 55 && !notes.length ? "clarify" : "go",
74
+ validity: { score: Math.round(clarity), reasons: ["mock: 本文の具体性から推定"] },
75
+ feasibility: { score: 80, reasons: ["mock: 固定の値"] },
76
+ risks: [],
77
+ questions: clarity < 55 && !notes.length ? ["完了条件をより具体的にしてください"] : [],
78
+ areas,
79
+ // Mock は参照先を読まないので、根拠はすべて推測
80
+ evidence: [{ claim: "mock: 要望の本文の箇条書きからタスク案を作った(コードは読んでいない)", kind: "assumed" }],
81
+ };
82
+
83
+ await writeFileAtomic(join(job.runDir, "assessment.json"), JSON.stringify(assessment, null, 2) + "\n");
84
+ for (const d of drafts) {
85
+ const { description, ...meta } = d;
86
+ await writeFileAtomic(join(job.runDir, "drafts", `${d.key}.md`), stringifyFrontmatter(meta, description));
87
+ log({ kind: "info", text: `✎ ${relative(job.dataDir, join(job.runDir, "drafts", `${d.key}.md`))}` });
88
+ await this.sleep(150, signal);
89
+ }
90
+ const ui = await writeMockUi(job, drafts);
91
+ log({ kind: "info", text: ui.length ? `✎ 画面イメージ ${ui.filter((f) => f.endsWith(".png")).length} 件(ui/)` : "画面イメージは不要としました(ui/index.json)" });
92
+ log({ kind: "message", text: assessment.summary });
93
+ return {
94
+ changed: [join(job.runDir, "assessment.json"), ...drafts.map((d) => join(job.runDir, "drafts", `${d.key}.md`)), join(job.runDir, "ui", "index.json"), ...ui],
95
+ };
96
+ }
97
+ }
98
+
99
+ /** 画面を伴う要望とみなす語 */
100
+ const UI_WORDS = /画面|UI|ボタン|一覧|表示|フォーム|入力欄|ダイアログ|メニュー/;
101
+
102
+ /**
103
+ * 画面資料(決まった日本語の例)。画面を伴う要望なら、原稿(HTML)と箱だけの PNG を書く(Mock は描画のコンテナを使わない)。
104
+ * そうでなければ不要の理由を書く。書いた画像と原稿のパスを返す
105
+ */
106
+ async function writeMockUi(job: PreflightJob, drafts: ProposedTask[]): Promise<string[]> {
107
+ const ui = join(job.runDir, "ui");
108
+ const r = job.request;
109
+ if (!drafts.length || !UI_WORDS.test(`${r.title}\n${r.body}`)) {
110
+ await writeFileAtomic(join(ui, "index.json"), JSON.stringify({ needed: false, reason: "mock: 要望に画面に関わる語が無いので、画面を伴わない変更とみなしました" }, null, 2) + "\n");
111
+ return [];
112
+ }
113
+ const target = drafts[0].key;
114
+ // 決まった原稿と、それを描画のコンテナで描いておいた画像(Mock は Docker を使わない。原稿と画像は同じもの)
115
+ await mkdir(join(ui, "src"), { recursive: true });
116
+ await writeFile(join(ui, "src", "U1.html"), await readFile(MOCK_HTML));
117
+ await writeFile(join(ui, "U1.png"), await readFile(MOCK_PNG));
118
+ const index = {
119
+ needed: true,
120
+ targets: [target],
121
+ items: [
122
+ {
123
+ id: "U1",
124
+ file: "U1.png",
125
+ html: "src/U1.html",
126
+ title: `${r.title}: 一覧と絞り込み(mock の例)`,
127
+ drafts: [target],
128
+ viewport: 960,
129
+ assumptions: ["mock: 要望の内容は読まずに決まった一覧画面の形で描いた", "表の行は仮のデータ"],
130
+ },
131
+ ],
132
+ };
133
+ await writeFileAtomic(join(ui, "index.json"), JSON.stringify(index, null, 2) + "\n");
134
+ return [join(ui, "U1.png"), join(ui, "src", "U1.html"), join(ui, "index.json")];
135
+ }
136
+
137
+ const MOCK_HTML = new URL("./mock-ui.html", import.meta.url);
138
+ const MOCK_PNG = new URL("./mock-ui.png", import.meta.url);
139
+
140
+ function bulletsOf(text: string): string[] {
141
+ return text
142
+ .split("\n")
143
+ .map((l) => /^\s*(?:[-*]|\d+\.)\s+(.+)/.exec(l)?.[1]?.trim())
144
+ .filter((s): s is string => !!s);
145
+ }
@@ -0,0 +1,23 @@
1
+ # P3 の画面イメージの描画(自己完結した HTML / CSS を PNG にする)。
2
+ #
3
+ # Codex のコンテナとは別のイメージ。P3(ホストのプロセス)が docker run で動かし、
4
+ # ネットワークなし・認証情報なし・リポジトリなしで、確かめた原稿(読むだけ)と出力のフォルダだけをマウントする。
5
+ # Playwright と Chromium(headless shell)の版は固定し、日本語のフォント(Noto CJK, SIL Open Font License 1.1)を入れる。
6
+ FROM node:22-bookworm-slim
7
+
8
+ ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \
9
+ NODE_ENV=production
10
+
11
+ WORKDIR /render
12
+ RUN npm install --no-save --no-audit --no-fund --no-package-lock playwright@1.63.0 \
13
+ && npx playwright install --with-deps --only-shell chromium \
14
+ && apt-get update \
15
+ && apt-get install -y --no-install-recommends fonts-noto-cjk \
16
+ && rm -rf /var/lib/apt/lists/* /root/.npm /tmp/* \
17
+ && useradd --create-home --uid 10001 render
18
+
19
+ COPY render.mjs /render/render.mjs
20
+
21
+ USER render
22
+ ENV HOME=/tmp
23
+ ENTRYPOINT ["node", "/render/render.mjs"]
@@ -0,0 +1,53 @@
1
+ // 原稿(/in/jobs.json と HTML)を PNG(/out/<id>.png)にする。結果は stdout に JSON で1行。
2
+ //
3
+ // スクリプトは動かさない(javaScriptEnabled: false)。ページの読み込みは setContent で行い、file:// で開かない。
4
+ // http(s) などの読み込みは全部止めて記録する(コンテナにネットワークは無いので、これは二重の囲い)。
5
+ import { readFile } from "node:fs/promises";
6
+ import { chromium } from "playwright";
7
+
8
+ const MAX_HEIGHT = Number(process.env.P3_RENDER_MAX_HEIGHT ?? 16384);
9
+ const PAGE_TIMEOUT = Number(process.env.P3_RENDER_PAGE_TIMEOUT ?? 20000);
10
+
11
+ const jobs = JSON.parse(await readFile("/in/jobs.json", "utf8"));
12
+ const browser = await chromium.launch();
13
+ const results = [];
14
+ try {
15
+ for (const job of jobs) {
16
+ const blocked = [];
17
+ const context = await browser.newContext({
18
+ javaScriptEnabled: false,
19
+ offline: true,
20
+ serviceWorkers: "block",
21
+ viewport: { width: job.width, height: 800 },
22
+ deviceScaleFactor: 1,
23
+ locale: "ja-JP",
24
+ });
25
+ try {
26
+ await context.route("**/*", (route) => {
27
+ const url = route.request().url();
28
+ if (url.startsWith("data:")) return route.continue();
29
+ blocked.push(url.slice(0, 200));
30
+ return route.abort();
31
+ });
32
+ const page = await context.newPage();
33
+ page.setDefaultTimeout(PAGE_TIMEOUT);
34
+ await page.setContent(await readFile(`/in/${job.file}`, "utf8"), { waitUntil: "load", timeout: PAGE_TIMEOUT });
35
+ const path = `/out/${job.id}.png`;
36
+ await page.screenshot({ path, fullPage: true, animations: "disabled", timeout: PAGE_TIMEOUT });
37
+ // 縦に長すぎるときは上から切る
38
+ const height = (await readFile(path)).readUInt32BE(20);
39
+ const clipped = height > MAX_HEIGHT;
40
+ if (clipped) {
41
+ await page.screenshot({ path, fullPage: true, clip: { x: 0, y: 0, width: job.width, height: MAX_HEIGHT }, animations: "disabled", timeout: PAGE_TIMEOUT });
42
+ }
43
+ results.push({ id: job.id, ok: true, clipped, blocked });
44
+ } catch (e) {
45
+ results.push({ id: job.id, ok: false, error: String(e?.message ?? e).split("\n")[0], blocked });
46
+ } finally {
47
+ await context.close();
48
+ }
49
+ }
50
+ } finally {
51
+ await browser.close();
52
+ }
53
+ process.stdout.write(JSON.stringify({ results }) + "\n");
@@ -0,0 +1,336 @@
1
+ import { spawn, execFile } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { chmod, copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { promisify } from "node:util";
7
+ import { mapPath, pathMapHowTo } from "./diagnose.ts";
8
+
9
+ const exec = promisify(execFile);
10
+
11
+ /**
12
+ * 画面イメージの描画(自己完結した HTML / CSS → PNG)。
13
+ *
14
+ * P3(ホストのプロセス)が専用のイメージ(render-image/)で docker run する。Codex のコンテナに Docker のソケットは渡さない。
15
+ * 描画のコンテナは、ネットワークなし・認証情報なし・リポジトリなしで、確かめた原稿のコピー(/in。読むだけ)と
16
+ * 出力のフォルダ(/out)だけをマウントする。ルートのファイルシステムは読むだけ、権限(capability)は全部外し、
17
+ * メモリ・CPU・プロセス数・時間に上限を付ける。Chromium の sandbox は使わない(コンテナを囲いにする)。
18
+ *
19
+ * 原稿は描画の前に確かめる(checkHtml): スクリプト・イベントの属性・javascript: URL・外のファイルや通信を指す参照・
20
+ * iframe / object / embed / link / base / meta refresh は断る。参照に使えるのは data: の画像(PNG / JPEG / GIF / WebP / SVG)・
21
+ * data: のフォント(woff2 / woff / ttf / otf)と、ページの中の #id だけ。描画するときもスクリプトは無効にし、
22
+ * data: 以外の読み込みは止めて記録する(通信を止めるのは唯一の囲いではない)。
23
+ */
24
+ export const RENDER_IMAGE_DIR = fileURLToPath(new URL("./render-image/", import.meta.url));
25
+
26
+ /** 上限 */
27
+ export const RENDER_LIMITS = {
28
+ /** 1つの原稿の大きさ */
29
+ htmlBytes: 2 * 1024 * 1024,
30
+ /** 1回の描画の数 */
31
+ pages: 20,
32
+ minWidth: 320,
33
+ maxWidth: 2560,
34
+ maxHeight: 16384,
35
+ /** 1ページあたりの時間(ブラウザの中) */
36
+ pageTimeoutMs: 20_000,
37
+ /** 1回の docker run 全体の時間 = base + ページ数 × perPage */
38
+ baseTimeoutMs: 60_000,
39
+ perPageTimeoutMs: 25_000,
40
+ memory: "1g",
41
+ cpus: "1",
42
+ pids: 256,
43
+ } as const;
44
+
45
+ export class RenderError extends Error {
46
+ constructor(
47
+ message: string,
48
+ readonly step: "check" | "docker" | "image" | "run" | "timeout" | "cancel",
49
+ ) {
50
+ super(message);
51
+ }
52
+ }
53
+
54
+ // --- 原稿の確かめ ----------------------------------------------------------
55
+
56
+ const DATA_OK = /^data:(image\/(png|jpeg|gif|webp|svg\+xml)|font\/(woff2?|ttf|otf)|application\/(font-woff2?|x-font-ttf|x-font-otf))[;,]/i;
57
+
58
+ /** 参照の値として認めるか(data: の画像・フォント、ページの中の #id) */
59
+ function refOk(v: string): boolean {
60
+ const s = v.trim().replace(/^['"]|['"]$/g, "").trim();
61
+ return !s || s.startsWith("#") || DATA_OK.test(s);
62
+ }
63
+
64
+ /**
65
+ * 原稿を確かめる。問題(理由)の一覧を返す(空なら描画してよい)。
66
+ * HTML を完全に解析するのではなく、危ないものを広めに断る(読み込みを止める囲いと、コンテナの囲いがその後ろにある)
67
+ */
68
+ export function checkHtml(html: string): string[] {
69
+ const problems: string[] = [];
70
+ const add = (p: string) => problems.includes(p) || problems.push(p);
71
+ if (Buffer.byteLength(html) > RENDER_LIMITS.htmlBytes) add(`原稿が大きすぎます(上限 ${RENDER_LIMITS.htmlBytes} バイト)`);
72
+ // コメントは参照の判定から外す(中身は描画されない)
73
+ const body = html.replace(/<!--[\s\S]*?-->/g, "");
74
+ if (/<\s*script\b/i.test(body)) add("スクリプト(<script>)は使えません");
75
+ for (const tag of ["iframe", "frame", "frameset", "object", "embed", "applet", "link", "base", "portal"]) {
76
+ if (new RegExp(`<\\s*${tag}\\b`, "i").test(body)) add(`<${tag}> は使えません`);
77
+ }
78
+ if (/<\s*meta\b[^>]*http-equiv/i.test(body)) add("<meta http-equiv> は使えません");
79
+ if (/<[^>]*\son[a-z]+\s*=/i.test(body)) add("イベントの属性(onclick など)は使えません");
80
+ if (/javascript\s*:/i.test(body) || /vbscript\s*:/i.test(body)) add("javascript: の URL は使えません");
81
+ // 属性の参照(src / href / srcset / poster / action / formaction / data / background / xlink:href)
82
+ const attr = /\s(?:xlink:)?(src|href|srcset|poster|action|formaction|data|background|manifest|ping|cite|longdesc|lowsrc|dynsrc)\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi;
83
+ for (const m of body.matchAll(attr)) {
84
+ const name = m[1].toLowerCase();
85
+ const value = m[2].replace(/^['"]|['"]$/g, "");
86
+ // srcset は「URL 記述子, URL 記述子」。data: の URL にも , が入るので、空白で分けて記述子(1x・640w)以外を見る
87
+ const values =
88
+ name === "srcset"
89
+ ? value
90
+ .split(/\s+/)
91
+ .map((x) => x.replace(/^,+|,+$/g, ""))
92
+ .filter((x) => x && !/^\d+(\.\d+)?[wx]$/.test(x))
93
+ : [value];
94
+ for (const v of values) if (!refOk(v)) add(`外のファイル・通信を指す参照は使えません: ${name}="${v.slice(0, 80)}"`);
95
+ }
96
+ // CSS の参照(url(...) と @import)
97
+ for (const m of body.matchAll(/url\(\s*("[^"]*"|'[^']*'|[^)]*)\s*\)/gi)) {
98
+ if (!refOk(m[1])) add(`外のファイル・通信を指す参照は使えません: url(${m[1].slice(0, 80)})`);
99
+ }
100
+ if (/@import\b/i.test(body)) add("@import は使えません(CSS は <style> の中に書いてください)");
101
+ if (/image-set\(|expression\(|-moz-binding|behavior\s*:/i.test(body)) add("image-set() / expression() などは使えません");
102
+ return problems;
103
+ }
104
+
105
+ // --- イメージ ----------------------------------------------------------------
106
+
107
+ /** イメージの名前(Dockerfile と描画の中身から決める。中身が変われば別の名前になり、作り直す) */
108
+ export async function renderImageTag(dir = RENDER_IMAGE_DIR): Promise<string> {
109
+ const h = createHash("sha256");
110
+ for (const f of ["Dockerfile", "render.mjs"]) h.update(await readFile(join(dir, f)));
111
+ return `infodb-p3-render:${h.digest("hex").slice(0, 12)}`;
112
+ }
113
+
114
+ export interface RenderOptions {
115
+ docker?: string;
116
+ /** このマシンのパス → Docker デーモンから見たパス(codex.pathMap) */
117
+ pathMap?: readonly [string, string][];
118
+ /** 使うイメージ(無ければ renderImageTag) */
119
+ image?: string;
120
+ signal?: AbortSignal;
121
+ onProgress?: (text: string) => void;
122
+ }
123
+
124
+ /** Docker が使えるか(使えなければ RenderError) */
125
+ export async function checkDocker(docker = "docker"): Promise<string> {
126
+ try {
127
+ const { stdout } = await exec(docker, ["version", "--format", "{{.Server.Version}}"], { timeout: 15_000 });
128
+ return stdout.trim();
129
+ } catch (e) {
130
+ const err = e as NodeJS.ErrnoException & { stderr?: string };
131
+ if (err.code === "ENOENT") throw new RenderError("docker コマンドが見つかりません。Docker をインストールしてください", "docker");
132
+ const detail = (err.stderr ?? err.message).trim().split("\n").pop();
133
+ throw new RenderError(`Docker デーモンにつながりません(${detail})。Docker を起動してください`, "docker");
134
+ }
135
+ }
136
+
137
+ /** 描画のイメージが無ければ作る。force なら作り直す。イメージの名前を返す */
138
+ export async function ensureRenderImage(opts: RenderOptions & { force?: boolean } = {}): Promise<{ image: string; built: boolean }> {
139
+ const docker = opts.docker ?? "docker";
140
+ const image = opts.image ?? (await renderImageTag());
141
+ await checkDocker(docker);
142
+ if (!opts.force) {
143
+ const has = await exec(docker, ["image", "inspect", "--format", "{{.Id}}", image], { timeout: 15_000 }).then(
144
+ () => true,
145
+ () => false,
146
+ );
147
+ if (has) return { image, built: false };
148
+ }
149
+ opts.onProgress?.(`描画のイメージ ${image} を作ります(初回は数分かかります)`);
150
+ // ビルドのコンテキストは docker の CLI が送るので、パスの対応は要らない
151
+ const out = await runProcess(docker, ["build", ...(opts.force ? ["--pull", "--no-cache"] : []), "-t", image, RENDER_IMAGE_DIR], { timeoutMs: 20 * 60_000, signal: opts.signal });
152
+ if (out.code !== 0) throw new RenderError(`描画のイメージを作れません: ${lastLine(out.stderr)}`, "image");
153
+ return { image, built: true };
154
+ }
155
+
156
+ // --- 描画 --------------------------------------------------------------------
157
+
158
+ export interface RenderJob {
159
+ /** 出力の名前(<id>.png) */
160
+ id: string;
161
+ /** 原稿の中身 */
162
+ html: string;
163
+ /** 画面の幅(px) */
164
+ width: number;
165
+ }
166
+
167
+ export interface RenderResult {
168
+ id: string;
169
+ ok: boolean;
170
+ /** できた PNG(ok のとき。出力のフォルダの中) */
171
+ file?: string;
172
+ error?: string;
173
+ /** 縦に長すぎて上から切った */
174
+ clipped?: boolean;
175
+ /** 止めた読み込み */
176
+ blocked: string[];
177
+ }
178
+
179
+ /** docker run の引数(テストで確かめる) */
180
+ export function renderArgs(p: { image: string; name: string; hostIn: string; hostOut: string }): string[] {
181
+ return [
182
+ "run",
183
+ "--rm",
184
+ "--name",
185
+ p.name,
186
+ "--network",
187
+ "none",
188
+ "--read-only",
189
+ "--cap-drop",
190
+ "ALL",
191
+ "--security-opt",
192
+ "no-new-privileges",
193
+ "--pids-limit",
194
+ String(RENDER_LIMITS.pids),
195
+ "--memory",
196
+ RENDER_LIMITS.memory,
197
+ "--cpus",
198
+ RENDER_LIMITS.cpus,
199
+ "--shm-size",
200
+ "256m",
201
+ "--tmpfs",
202
+ "/tmp:rw,size=256m",
203
+ "-e",
204
+ `P3_RENDER_MAX_HEIGHT=${RENDER_LIMITS.maxHeight}`,
205
+ "-e",
206
+ `P3_RENDER_PAGE_TIMEOUT=${RENDER_LIMITS.pageTimeoutMs}`,
207
+ "--mount",
208
+ `type=bind,src=${p.hostIn},dst=/in,readonly`,
209
+ "--mount",
210
+ `type=bind,src=${p.hostOut},dst=/out`,
211
+ p.image,
212
+ ];
213
+ }
214
+
215
+ /**
216
+ * 原稿を PNG にする。workDir(このマシンのパス。Docker デーモンから見えるところ)の下に一時のフォルダを作り、
217
+ * 終わったら(失敗・時間切れ・取消でも)コンテナを止めて消す。できた PNG は outDir に <id>.png で置く。
218
+ * 原稿に問題があるものは描画せずに結果に理由を返す
219
+ */
220
+ export async function renderHtml(jobs: RenderJob[], workDir: string, outDir: string, opts: RenderOptions = {}): Promise<RenderResult[]> {
221
+ const docker = opts.docker ?? "docker";
222
+ if (jobs.length > RENDER_LIMITS.pages) throw new RenderError(`一度に描画できるのは ${RENDER_LIMITS.pages} 枚までです`, "check");
223
+ const results = new Map<string, RenderResult>();
224
+ const ok: RenderJob[] = [];
225
+ for (const j of jobs) {
226
+ const problems = [...checkHtml(j.html)];
227
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/.test(j.id)) problems.push(`名前が使えません: ${j.id}`);
228
+ if (!Number.isInteger(j.width) || j.width < RENDER_LIMITS.minWidth || j.width > RENDER_LIMITS.maxWidth) {
229
+ problems.push(`幅は ${RENDER_LIMITS.minWidth}〜${RENDER_LIMITS.maxWidth} px にしてください: ${j.width}`);
230
+ }
231
+ if (problems.length) results.set(j.id, { id: j.id, ok: false, error: problems.join(" / "), blocked: [] });
232
+ else ok.push(j);
233
+ }
234
+ if (ok.length) {
235
+ const { image } = await ensureRenderImage({ ...opts, docker });
236
+ const tmp = join(workDir, `.render-${randomBytes(4).toString("hex")}`);
237
+ const name = `p3-render-${randomBytes(4).toString("hex")}`;
238
+ try {
239
+ await mkdir(join(tmp, "in"), { recursive: true });
240
+ await mkdir(join(tmp, "out"), { recursive: true });
241
+ // コンテナの中の利用者(root ではない)が書けるように
242
+ await chmod(join(tmp, "out"), 0o777);
243
+ for (const j of ok) await writeFile(join(tmp, "in", `${j.id}.html`), j.html);
244
+ await writeFile(join(tmp, "in", "jobs.json"), JSON.stringify(ok.map((j) => ({ id: j.id, file: `${j.id}.html`, width: j.width }))));
245
+ const host = (p: string) => mapPath(opts.pathMap ?? [], p).host;
246
+ const args = renderArgs({ image, name, hostIn: host(join(tmp, "in")), hostOut: host(join(tmp, "out")) });
247
+ opts.onProgress?.(`${ok.length} 枚を描画します`);
248
+ const timeoutMs = RENDER_LIMITS.baseTimeoutMs + ok.length * RENDER_LIMITS.perPageTimeoutMs;
249
+ const out = await runProcess(docker, args, { timeoutMs, signal: opts.signal, onStop: () => exec(docker, ["kill", name]).catch(() => {}) });
250
+ if (out.stopped === "cancel") throw new RenderError("描画を取り消しました", "cancel");
251
+ if (out.stopped === "timeout") throw new RenderError(`描画が ${Math.round(timeoutMs / 1000)} 秒で終わりませんでした`, "timeout");
252
+ if (out.code !== 0) throw new RenderError(diagnoseRender(out.stderr, opts.pathMap ?? [], workDir), "run");
253
+ const reported = parseReport(out.stdout);
254
+ await mkdir(outDir, { recursive: true });
255
+ for (const j of ok) {
256
+ const r = reported.find((x) => x.id === j.id);
257
+ if (!r?.ok) {
258
+ results.set(j.id, { id: j.id, ok: false, error: r?.error ?? "描画の結果がありません", blocked: r?.blocked ?? [] });
259
+ continue;
260
+ }
261
+ const file = join(outDir, `${j.id}.png`);
262
+ await copyFile(join(tmp, "out", `${j.id}.png`), file);
263
+ results.set(j.id, { id: j.id, ok: true, file, clipped: !!r.clipped, blocked: r.blocked ?? [] });
264
+ }
265
+ } finally {
266
+ await rm(tmp, { recursive: true, force: true });
267
+ }
268
+ }
269
+ return jobs.map((j) => results.get(j.id)!);
270
+ }
271
+
272
+ function parseReport(stdout: string): { id: string; ok: boolean; error?: string; clipped?: boolean; blocked?: string[] }[] {
273
+ const line = stdout.trim().split("\n").pop() ?? "";
274
+ try {
275
+ const r = JSON.parse(line);
276
+ return Array.isArray(r.results) ? r.results : [];
277
+ } catch {
278
+ throw new RenderError(`描画の結果が読めません: ${line.slice(0, 200)}`, "run");
279
+ }
280
+ }
281
+
282
+ const lastLine = (s: string) => s.trim().split("\n").filter(Boolean).pop() ?? "(出力なし)";
283
+
284
+ /** docker run の失敗の説明(よくある原因には次にすることを添える) */
285
+ export function diagnoseRender(stderr: string, pathMap: readonly [string, string][], workDir?: string): string {
286
+ const last = lastLine(stderr);
287
+ if (/bind source path does not exist|invalid mount config|not a directory|no such file or directory/i.test(stderr)) {
288
+ const m = workDir ? mapPath(pathMap, workDir) : undefined;
289
+ return [
290
+ `描画のコンテナに原稿のフォルダをマウントできません(${last})。DevContainer の中から使うときは、パスの対応(codex.pathMap)が要ります`,
291
+ ...pathMapHowTo(m && { label: "描画", local: workDir!, host: m.host, rule: m.rule, container: "/in" }),
292
+ ].join("\n");
293
+ }
294
+ if (/permission denied/i.test(stderr) && /docker\.sock|daemon/i.test(stderr)) return `Docker を使う権限がありません(${last})`;
295
+ if (/Unable to find image|pull access denied/i.test(stderr)) return `描画のイメージがありません(${last})。p3 render --update で作り直してください`;
296
+ return `描画に失敗しました: ${last}`;
297
+ }
298
+
299
+ interface ProcessResult {
300
+ code: number | null;
301
+ stdout: string;
302
+ stderr: string;
303
+ stopped?: "timeout" | "cancel";
304
+ }
305
+
306
+ /** 子プロセスを動かす。時間切れ・取消のときは onStop(コンテナを止める)を呼んでからプロセスを終わらせる */
307
+ function runProcess(cmd: string, args: string[], o: { timeoutMs: number; signal?: AbortSignal; onStop?: () => Promise<unknown> }): Promise<ProcessResult> {
308
+ return new Promise((resolve) => {
309
+ let stdout = "";
310
+ let stderr = "";
311
+ let stopped: ProcessResult["stopped"];
312
+ const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
313
+ child.stdout.on("data", (d) => (stdout = (stdout + d).slice(-1_000_000)));
314
+ child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-100_000)));
315
+ const stop = (why: NonNullable<ProcessResult["stopped"]>) => {
316
+ if (stopped) return;
317
+ stopped = why;
318
+ void (o.onStop?.() ?? Promise.resolve()).finally(() => child.kill("SIGKILL"));
319
+ };
320
+ const timer = setTimeout(() => stop("timeout"), o.timeoutMs);
321
+ const onAbort = () => stop("cancel");
322
+ if (o.signal?.aborted) onAbort();
323
+ o.signal?.addEventListener("abort", onAbort, { once: true });
324
+ const done = (code: number | null) => {
325
+ clearTimeout(timer);
326
+ o.signal?.removeEventListener("abort", onAbort);
327
+ resolve({ code, stdout, stderr, stopped });
328
+ };
329
+ child.on("error", (e) => {
330
+ stderr += String(e.message);
331
+ done(-1);
332
+ });
333
+ child.on("close", done);
334
+ });
335
+ }
336
+