@tama-create/sf-tools 0.0.0-stage → 1.4.0-dev.2

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 (118) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +212 -2
  3. package/bin/sft.js +22 -0
  4. package/dist/cli.js +35 -0
  5. package/dist/commands/admin.js +46 -0
  6. package/dist/commands/check.js +20 -0
  7. package/dist/commands/ci.js +123 -0
  8. package/dist/commands/deploy.js +31 -0
  9. package/dist/commands/doctor.js +11 -0
  10. package/dist/commands/dryrun.js +17 -0
  11. package/dist/commands/hook.js +46 -0
  12. package/dist/commands/index.js +36 -0
  13. package/dist/commands/job.js +31 -0
  14. package/dist/commands/launcher.js +40 -0
  15. package/dist/commands/log.js +58 -0
  16. package/dist/commands/metasync.js +21 -0
  17. package/dist/commands/pr.js +32 -0
  18. package/dist/commands/project.js +93 -0
  19. package/dist/commands/push.js +16 -0
  20. package/dist/commands/release.js +19 -0
  21. package/dist/commands/start.js +19 -0
  22. package/dist/commands/switch-org.js +12 -0
  23. package/dist/commands/update-cli.js +11 -0
  24. package/dist/commands/version.js +18 -0
  25. package/dist/core/admin-clone.js +79 -0
  26. package/dist/core/ai-answers.js +40 -0
  27. package/dist/core/branches.js +88 -0
  28. package/dist/core/check-targets.js +170 -0
  29. package/dist/core/check.js +34 -0
  30. package/dist/core/ci-check-branch.js +150 -0
  31. package/dist/core/ci-login-steps.js +73 -0
  32. package/dist/core/ci-release-steps.js +193 -0
  33. package/dist/core/ci-sequence-steps.js +188 -0
  34. package/dist/core/ci-validate-steps.js +140 -0
  35. package/dist/core/command.js +25 -0
  36. package/dist/core/create-connect.js +519 -0
  37. package/dist/core/create-setup.js +314 -0
  38. package/dist/core/create-state.js +82 -0
  39. package/dist/core/delegate.js +45 -0
  40. package/dist/core/deploy.js +66 -0
  41. package/dist/core/diag.js +200 -0
  42. package/dist/core/doctor.js +211 -0
  43. package/dist/core/eca.js +259 -0
  44. package/dist/core/exit-codes.js +12 -0
  45. package/dist/core/gh-identity.js +46 -0
  46. package/dist/core/hook-install.js +130 -0
  47. package/dist/core/hook.js +116 -0
  48. package/dist/core/identity.js +48 -0
  49. package/dist/core/job.js +243 -0
  50. package/dist/core/launcher-status.js +184 -0
  51. package/dist/core/lines.js +25 -0
  52. package/dist/core/log-auto.js +56 -0
  53. package/dist/core/log-box.js +85 -0
  54. package/dist/core/log-collector.js +370 -0
  55. package/dist/core/log-format.js +44 -0
  56. package/dist/core/log-pull.js +565 -0
  57. package/dist/core/log-select.js +126 -0
  58. package/dist/core/log-session.js +362 -0
  59. package/dist/core/log-start.js +421 -0
  60. package/dist/core/log-status.js +223 -0
  61. package/dist/core/log-summarize.js +127 -0
  62. package/dist/core/logger.js +71 -0
  63. package/dist/core/login-url.js +50 -0
  64. package/dist/core/manifest-build.js +118 -0
  65. package/dist/core/mask.js +70 -0
  66. package/dist/core/metadata-types.js +79 -0
  67. package/dist/core/metasync.js +684 -0
  68. package/dist/core/org.js +115 -0
  69. package/dist/core/origin.js +62 -0
  70. package/dist/core/package-xml.js +157 -0
  71. package/dist/core/pr.js +199 -0
  72. package/dist/core/project-create.js +733 -0
  73. package/dist/core/project-reconnect.js +126 -0
  74. package/dist/core/project-status.js +235 -0
  75. package/dist/core/project-tier.js +374 -0
  76. package/dist/core/project-verify.js +517 -0
  77. package/dist/core/promote-check.js +380 -0
  78. package/dist/core/promote.js +141 -0
  79. package/dist/core/push.js +152 -0
  80. package/dist/core/release.js +256 -0
  81. package/dist/core/scoped-box.js +29 -0
  82. package/dist/core/start.js +155 -0
  83. package/dist/core/switch-org.js +49 -0
  84. package/dist/core/test-types.js +212 -0
  85. package/dist/core/toolbox.js +4 -0
  86. package/dist/core/update-cli.js +156 -0
  87. package/dist/core/update-secret.js +301 -0
  88. package/dist/core/update-workflows.js +132 -0
  89. package/dist/core/verify-gh.js +286 -0
  90. package/dist/core/verify-samples.js +152 -0
  91. package/dist/core/windows-shim.js +21 -0
  92. package/dist/io/capability-file.js +11 -0
  93. package/dist/io/create-deps.js +68 -0
  94. package/dist/io/doctor-deps.js +32 -0
  95. package/dist/io/hook-install-deps.js +11 -0
  96. package/dist/io/job-deps.js +31 -0
  97. package/dist/io/key-file.js +17 -0
  98. package/dist/io/keys.js +161 -0
  99. package/dist/io/log-deps.js +106 -0
  100. package/dist/io/metasync-deps.js +21 -0
  101. package/dist/io/open-browser.js +21 -0
  102. package/dist/io/package-version.js +10 -0
  103. package/dist/io/pinned-project.js +111 -0
  104. package/dist/io/promote-deps.js +27 -0
  105. package/dist/io/push-refs.js +20 -0
  106. package/dist/io/resolve.js +74 -0
  107. package/dist/io/run.js +201 -0
  108. package/dist/io/switch-org-deps.js +10 -0
  109. package/dist/io/temp-dir.js +10 -0
  110. package/dist/io/tool-versions.js +14 -0
  111. package/dist/io/toolbox.js +68 -0
  112. package/dist/io/update-cli-deps.js +75 -0
  113. package/dist/io/update-secret-deps.js +27 -0
  114. package/dist/launch.js +152 -0
  115. package/dist/ui/confirm.js +18 -0
  116. package/dist/ui/launcher.js +132 -0
  117. package/dist/ui/prompt.js +66 -0
  118. package/package.json +37 -4
@@ -0,0 +1,200 @@
1
+ // セットアップの状態の診断(sft project status・verify が使う)。シェル版の lib/diag.sh の移し先(doc/rebuild-design.md 11.2)。
2
+ // リポジトリのセットアップが、どこまで正しくできているかを、GitHub から読み取って、項目ごとに表示する。何も変更しない(読み取りのみ)。
3
+ // 記号: ✓ できている / ✗ 不足(直し方を、すぐ下に出す。不足の数に数える)/ ! 注意(数えない)/ ? 確認できなかった(数えない)。
4
+ // 確認する項目(「段階」は、渡したブランチ名。PROD / STG / DEV の接尾辞は main / staging / develop だけ):
5
+ // 1. リポジトリ: GitHub にあるか / 段階のブランチ / ワークフロー 4 本。廃止した wf-propagate.yml が残っていれば !
6
+ // 2. Secrets: PAT_TOKEN / SLACK_BOT_TOKEN / SF_PRIVATE_KEY / 段階ごとの SF_CONSUMER_KEY_*
7
+ // 3. Variables: SLACK_CHANNEL_ID / 段階ごとの SF_USERNAME_* / SF_INSTANCE_URL_*(SF_ORG_ID_* がなければ !)
8
+ // 4. ブランチ保護: Ruleset protect-main / protect-staging の必須チェックの名前が、requiredStatusCheckNames と過不足なく一致するか
9
+ // (Ruleset がない・読めないときは ?)
10
+ // 5. 直近の実行: wf-metasync / wf-release / wf-validate の直近 1 回(成功 ✓、成功以外の完了 !、未実行・実行中・失敗 ?)
11
+ // Salesforce 側(JWT 接続)は、ログインが必要なため、ここでは確かめない。表示は、すべて標準エラー(色は付けない)
12
+ import { requiredStatusCheckNames } from "./branches.js";
13
+ const SYMBOL = { ok: "✓", ng: "✗", warn: "!", unknown: "?" };
14
+ /** 段階(ブランチ名)→ Secrets / Variables の接尾辞(main / staging / develop 以外は空) */
15
+ export function tierSuffix(tier) {
16
+ return tier === "main" ? "PROD" : tier === "staging" ? "STG" : tier === "develop" ? "DEV" : "";
17
+ }
18
+ /** gh を呼び、成功なら行(CR と空の行を除く)、失敗・起動できないなら null */
19
+ async function ghLinesOrNull(box, args) {
20
+ try {
21
+ const r = await box.run("gh", args);
22
+ if (r.code !== 0)
23
+ return null;
24
+ return r.stdout
25
+ .split("\n")
26
+ .map((l) => l.replace(/\r$/, ""))
27
+ .filter((l) => l.trim() !== "");
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ /** 診断を実行して表示し、不足(✗)の数を返す */
34
+ export async function runDiag(box, repo, tiers) {
35
+ let ng = 0;
36
+ const err = (l) => box.output.err(l);
37
+ const line = (state, label, hint = "") => {
38
+ err(` ${SYMBOL[state]} ${label}`);
39
+ if (state === "ng") {
40
+ ng++;
41
+ if (hint !== "")
42
+ err(` 直し方: ${hint}`);
43
+ }
44
+ };
45
+ const need = (names, name, hint) => {
46
+ if (names.includes(name))
47
+ line("ok", name);
48
+ else
49
+ line("ng", `${name} がありません`, hint);
50
+ };
51
+ err("");
52
+ err(" 【セットアップの状態】(✓ できている / ✗ 不足 / ! 注意 / ? 確認できず)");
53
+ // --- 1. リポジトリ ---
54
+ err(" リポジトリ");
55
+ if ((await ghLinesOrNull(box, ["repo", "view", repo, "--json", "name"])) !== null) {
56
+ line("ok", `GitHub に、リポジトリがあります(${repo})`);
57
+ }
58
+ else {
59
+ line("ng", `GitHub に、リポジトリが見つかりません(${repo})`, "リポジトリの作成からやり直す: プロジェクトのフォルダで sf-project.sh");
60
+ }
61
+ const branches = await ghLinesOrNull(box, ["api", `repos/${repo}/branches`, "--paginate", "--jq", ".[].name"]);
62
+ if (branches !== null) {
63
+ for (const tier of tiers) {
64
+ if (branches.includes(tier))
65
+ line("ok", `ブランチ ${tier} があります`);
66
+ else
67
+ line("ng", `ブランチ ${tier} がありません`, `force-* の中で sf-project.sh --add-tier ${tier}`);
68
+ }
69
+ }
70
+ else {
71
+ line("unknown", "ブランチの一覧を、確認できませんでした");
72
+ }
73
+ const workflows = await ghLinesOrNull(box, ["api", `repos/${repo}/contents/.github/workflows`, "--jq", ".[].name"]);
74
+ if (workflows !== null) {
75
+ for (const wf of ["wf-metasync.yml", "wf-release.yml", "wf-sequence.yml", "wf-validate.yml"]) {
76
+ if (workflows.includes(wf))
77
+ line("ok", `ワークフロー ${wf} があります`);
78
+ else
79
+ line("ng", `ワークフロー ${wf} がありません`, "force-* の中で sf-update-workflows.sh");
80
+ }
81
+ if (workflows.includes("wf-propagate.yml")) {
82
+ line("warn", "廃止したワークフロー wf-propagate.yml が残っています(force-* の中で sf-update-workflows.sh --remove wf-propagate.yml で消します)");
83
+ }
84
+ }
85
+ else {
86
+ line("unknown", "ワークフローの一覧を、確認できませんでした");
87
+ }
88
+ // --- 2. Secrets ---
89
+ err(" Secrets(登録した値の名前。値そのものは、読めません)");
90
+ const secrets = await ghLinesOrNull(box, ["secret", "list", "-R", repo, "--json", "name", "--jq", ".[].name"]);
91
+ if (secrets !== null) {
92
+ need(secrets, "PAT_TOKEN", "force-* の中で gh secret set PAT_TOKEN(Classic Token: repo・workflow)");
93
+ need(secrets, "SLACK_BOT_TOKEN", "force-* の中で gh secret set SLACK_BOT_TOKEN");
94
+ need(secrets, "SF_PRIVATE_KEY", "force-* の中で sf-update-secret.sh(メニュー 1: 秘密鍵)");
95
+ for (const tier of tiers) {
96
+ const sfx = tierSuffix(tier);
97
+ if (sfx !== "")
98
+ need(secrets, `SF_CONSUMER_KEY_${sfx}`, `force-* の中で sf-project.sh --reconnect ${tier}`);
99
+ }
100
+ }
101
+ else {
102
+ line("unknown", "Secrets の一覧を、確認できませんでした(権限がない、または、通信エラー)");
103
+ }
104
+ // --- 3. Variables ---
105
+ err(" Variables");
106
+ const vars = await ghLinesOrNull(box, ["variable", "list", "-R", repo, "--json", "name", "--jq", ".[].name"]);
107
+ if (vars !== null) {
108
+ need(vars, "SLACK_CHANNEL_ID", "force-* の中で gh variable set SLACK_CHANNEL_ID --body <チャンネル ID>");
109
+ for (const tier of tiers) {
110
+ const sfx = tierSuffix(tier);
111
+ if (sfx === "")
112
+ continue;
113
+ need(vars, `SF_USERNAME_${sfx}`, `force-* の中で sf-project.sh --reconnect ${tier}`);
114
+ need(vars, `SF_INSTANCE_URL_${sfx}`, `force-* の中で sf-project.sh --reconnect ${tier}`);
115
+ if (!vars.includes(`SF_ORG_ID_${sfx}`)) {
116
+ line("warn", `SF_ORG_ID_${sfx} がありません(組織の種類が、記録されていません)。force-* の中で sf-project.sh --reconnect ${tier} で、記録できます`);
117
+ }
118
+ }
119
+ }
120
+ else {
121
+ line("unknown", "Variables の一覧を、確認できませんでした(権限がない、または、通信エラー)");
122
+ }
123
+ // --- 4. ブランチ保護(Ruleset)の必須チェックの名前 ---
124
+ err(" ブランチ保護(Ruleset)の必須チェック");
125
+ const rulesets = await ghLinesOrNull(box, ["api", `repos/${repo}/rulesets`, "--jq", '.[] | "\\(.id) \\(.name)"']);
126
+ if (rulesets === null) {
127
+ line("unknown", "Ruleset の一覧を、確認できませんでした(権限がない・プランが対応していない・通信エラーのどれか)");
128
+ }
129
+ else {
130
+ const expected = requiredStatusCheckNames();
131
+ for (const rs of ["protect-main", "protect-staging"]) {
132
+ const id = rulesets.map((l) => l.split(" ")).find((f) => f[1] === rs)?.[0];
133
+ if (id === undefined) {
134
+ line("unknown", `Ruleset ${rs} が、ありません(無料プランの非公開リポジトリでは、設定できません)`);
135
+ continue;
136
+ }
137
+ const got = await ghLinesOrNull(box, [
138
+ "api",
139
+ `repos/${repo}/rulesets/${id}`,
140
+ "--jq",
141
+ '[.rules[] | select(.type == "required_status_checks") | .parameters.required_status_checks[].context] | .[]',
142
+ ]);
143
+ if (got === null) {
144
+ line("unknown", `Ruleset ${rs} の内容を、確認できませんでした`);
145
+ continue;
146
+ }
147
+ const missing = expected.filter((n) => !got.includes(n)).join("・");
148
+ const extra = got.filter((n) => !expected.includes(n)).join("・");
149
+ if (missing === "" && extra === "") {
150
+ line("ok", `Ruleset ${rs}: 必須チェックの名前が、ワークフローのジョブ名と合っています`);
151
+ }
152
+ else {
153
+ line("ng", `Ruleset ${rs}: 必須チェックの名前が、ワークフローのジョブ名と合っていません。このままでは、条件が満たされず、PR をマージできません(余分: ${extra || "なし"} / 足りない: ${missing || "なし"})`, `GitHub の Settings → Rules → Rulesets → ${rs} の「Require status checks to pass」を、${expected.join("・")} だけにする(ワークフロー名は付けない)`);
154
+ }
155
+ }
156
+ }
157
+ // --- 5. 直近のワークフローの実行(参考) ---
158
+ err(" 直近のワークフローの実行(成功していれば、Salesforce への JWT 接続も、できています)");
159
+ for (const wf of ["wf-metasync.yml", "wf-release.yml", "wf-validate.yml"]) {
160
+ const out = await ghLinesOrNull(box, [
161
+ "run",
162
+ "list",
163
+ "-R",
164
+ repo,
165
+ "--workflow",
166
+ wf,
167
+ "--limit",
168
+ "1",
169
+ "--json",
170
+ "status,conclusion,createdAt",
171
+ "--jq",
172
+ 'if length==0 then "none" else .[0] | "\\(.status) \\(if (.conclusion // "") == "" then "-" else .conclusion end) \\(.createdAt)" end',
173
+ ]);
174
+ if (out === null) {
175
+ line("unknown", `${wf}: 直近の実行を、確認できませんでした`);
176
+ continue;
177
+ }
178
+ const first = out[0] ?? "";
179
+ if (first === "" || first === "none") {
180
+ line("unknown", `${wf}: まだ、実行されていません`);
181
+ continue;
182
+ }
183
+ const [status = "", rawConcl = "", rawAt = ""] = first.trim().split(/\s+/);
184
+ const concl = rawConcl === "-" ? "" : rawConcl;
185
+ const at = `${rawAt.replace("T", " ").slice(0, 16)} UTC`;
186
+ if (status === "completed" && concl === "success")
187
+ line("ok", `${wf}: 直近の実行は、成功です(${at})`);
188
+ else if (status === "completed") {
189
+ line("warn", `${wf}: 直近の実行は、成功していません(${concl || "不明"}。${at})。GitHub の Actions で、ログを確認してください`);
190
+ }
191
+ else
192
+ line("unknown", `${wf}: 実行中、または、待機中です(${at})`);
193
+ }
194
+ err("");
195
+ if (ng === 0)
196
+ err(" ✓ セットアップに、不足はありません。");
197
+ else
198
+ err(` ✗ 不足が ${ng} 件あります。上の「直し方」を実行してください。`);
199
+ return ng;
200
+ }
@@ -0,0 +1,211 @@
1
+ // sft doctor: 手元の準備と確認(bin/sf-refresh.sh の移し先。設計 2.4.1)。止めるのは設定ファイルがないときだけで、ほかは警告して続ける。
2
+ // 1. sf-tools/config/metadata.txt・branches.txt がなければ止める(プロジェクトの破損。生成はしない)
3
+ // 2. sf の確認(npm 版か: sf --version の終了コード。入れ替えが途中で切れた印も表示)・Java 17 以上の確認(警告のみ。Actions 上は省く)。
4
+ // Java の成功は、記録のファイル(~/.sf-tools-java-check)に、調べたもの(java の場所と PATH)を書き、同じなら 24 時間は確認を省く
5
+ // (シェル版の sf-refresh.sh の check_java_cli --cache と同じ。失敗は記録せず、毎回確認する)。sf は、シェル版と同じく毎回確かめる
6
+ // 3. フック: 入っているものが、この版のフックと違えば入れ直す(sft の凍結した入口がなければ、入れない)
7
+ // 4. release/ と release/<ブランチ>/(deploy-target.txt・remove-target.txt・README.md。あるものは上書きしない)と branch_name.txt。
8
+ // main・detached HEAD では、release/<ブランチ>/ を作らない
9
+ // 5. LWC の部品(force-* の package.json): node_modules/.package-lock.json が package-lock.json より古ければ npm install
10
+ // なくしたもの(設計 2.4.1): ~/sf-tools の git pull(版の固定)・24 時間ごとの裏の sf-update-cli.sh(自動の更新はしない)。
11
+ // 未了: コピー元(config/install/release/)を npm の公開物に入れる(公開の直前)
12
+ import { HOOK_ENTRY, hookScript, runHookInstall } from "./hook-install.js";
13
+ const DAY_MS = 86_400_000;
14
+ /** 記録が、同じものについて 24 時間以内の成功か */
15
+ function recentlyOk(box, deps, stamp, key) {
16
+ if (stamp === undefined || !box.files.exists(stamp))
17
+ return false;
18
+ try {
19
+ return box.files.readText(stamp) === key && box.clock.now().getTime() - deps.mtime(stamp) < DAY_MS;
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ function rememberOk(box, stamp, key) {
26
+ if (stamp === undefined)
27
+ return;
28
+ try {
29
+ box.files.writeText(stamp, key);
30
+ }
31
+ catch {
32
+ // 書けなくても続ける(次回も確認するだけ)
33
+ }
34
+ }
35
+ /** java -version の出力から、主なバージョン(1.8.0_351 → 8・17.0.2 → 17・17-ea → 17)。読めなければ null */
36
+ export function javaMajor(output) {
37
+ const m = /version "([^"]*)"/.exec(output.replace(/\r/g, ""));
38
+ if (!m)
39
+ return null;
40
+ let ver = m[1];
41
+ if (/^1\./.test(ver))
42
+ ver = ver.slice(2);
43
+ const n = /^(\d+)/.exec(ver);
44
+ return n ? Number(n[1]) : null;
45
+ }
46
+ function javaGuidance(box, min, platform, level) {
47
+ const w = (s) => box.output.err(`[${level}] ${s}`);
48
+ w(" このままだと、Apex の言語サーバーが起動せず、VS Code に「telemetry handler is null」などのエラーが出ます。");
49
+ w(` 対処: JDK ${min} 以上(例: Microsoft OpenJDK ${min})をインストールし、環境変数 JAVA_HOME に、そのフォルダを設定してください。`);
50
+ if (platform === "win32") {
51
+ w(" 管理者権限が使えないときは、zip 版を展開し、ユーザーの環境変数に設定できます(管理者権限は不要)。");
52
+ w(` 例: setx JAVA_HOME 'C:\\Users\\(ユーザー名)\\tools\\jdk-${min}'(設定後に開く、新しいターミナルと VS Code から有効)`);
53
+ }
54
+ else if (platform === "darwin") {
55
+ w(` macOS: ~/.zshrc に export JAVA_HOME=$(/usr/libexec/java_home -v ${min}) を書き、ターミナルを開き直してください。`);
56
+ }
57
+ else {
58
+ w(" ~/.bashrc などに export JAVA_HOME=(JDK のフォルダ)を書き、ターミナルを開き直してください。");
59
+ }
60
+ w(" VS Code の設定(salesforcedx-vscode-apex.java.home)で別の JDK を指していて、この確認を省くときは、環境変数 SF_TOOLS_SKIP_JAVA_CHECK=1 を設定します。");
61
+ }
62
+ async function checkSf(box, deps) {
63
+ if (box.files.exists(deps.sfBrokenMark)) {
64
+ box.output.err("[WARNING] Salesforce CLI の入れ替えが、途中で切れています(sf-update-cli が見つけました):");
65
+ for (const line of box.files.readText(deps.sfBrokenMark).split("\n")) {
66
+ // 表示を崩す制御文字を除く
67
+ const clean = [...line].filter((ch) => ch.charCodeAt(0) >= 0x20 && ch.charCodeAt(0) !== 0x7f).join("");
68
+ if (clean !== "")
69
+ box.output.err(`[WARNING] ${clean}`);
70
+ }
71
+ box.output.err("[WARNING] 直し方: 退避された元の版(.cli-* のフォルダ)を cli に名前を戻すか、npm install -g @salesforce/cli で入れ直してください");
72
+ }
73
+ const r = await box.run("sf", ["--version"]).catch(() => null);
74
+ if (r === null)
75
+ return; // sf が入っていない(各コマンドの確認が扱う)
76
+ if (r.code === 0)
77
+ return;
78
+ box.output.err(`[ERROR] sf(Salesforce CLI)の終了コードが 0 ではありません(sf --version: 終了コード ${r.code})。`);
79
+ const first = r.output.split("\n")[0] ?? "";
80
+ if (first !== "")
81
+ box.output.err(`[ERROR] 出力: ${first}`);
82
+ box.output.err("[ERROR] sf-tools は、npm 版の Salesforce CLI を前提としています(Windows の公式インストーラー版は、成功しても終了コード 1 になります)。");
83
+ box.output.err("[ERROR] 対処: インストーラー版をアンインストールし、npm install -g @salesforce/cli で入れ直してください。");
84
+ }
85
+ /**
86
+ * Java が min 以上か(SF_TOOLS_SKIP_JAVA_CHECK=1 で省く)。足りなければ、案内を level で出して false。sft project create は ERROR で使う。
87
+ * mtime と javaCheckStamp を渡すと、24 時間以内の成功の記録があれば確かめない
88
+ */
89
+ export async function checkJava(box, deps, level = "WARNING") {
90
+ if (box.env("SF_TOOLS_SKIP_JAVA_CHECK") === "1")
91
+ return true;
92
+ const e = (s) => box.output.err(`[${level}] ${s}`);
93
+ const min = Number.parseInt(box.env("SF_TOOLS_JAVA_MIN_MAJOR") ?? "17", 10) || 17;
94
+ const home = box.env("JAVA_HOME") ?? "";
95
+ // Windows の実体は java.exe(シェルの -x は .exe を補うが、Node の確認は補わない)
96
+ const homeJava = deps.platform === "win32" ? `${home}/bin/java.exe` : `${home}/bin/java`;
97
+ const java = home !== "" && deps.isExecutable(homeJava) ? homeJava : "java";
98
+ // 同じ java の場所・同じ PATH なら、同じ Java とみなす
99
+ const stamp = deps.mtime ? deps.javaCheckStamp : undefined;
100
+ const key = `${java}\n${box.env("PATH") ?? ""}`;
101
+ if (deps.mtime && recentlyOk(box, { mtime: deps.mtime }, stamp, key))
102
+ return true;
103
+ const r = await box.run(java, ["-version"]).catch(() => null);
104
+ if (r === null) {
105
+ e(`Java が見つかりません。Salesforce の Apex 拡張(VS Code)は、Java ${min} 以上が必要です。`);
106
+ javaGuidance(box, min, deps.platform, level);
107
+ return false;
108
+ }
109
+ const major = javaMajor(r.output);
110
+ if (major === null) {
111
+ e(`Java のバージョンを判定できませんでした(${java})。Apex 拡張は、Java ${min} 以上が必要です。`);
112
+ javaGuidance(box, min, deps.platform, level);
113
+ return false;
114
+ }
115
+ if (major < min) {
116
+ e(`Java ${major} が使われます(${java})。Salesforce の Apex 拡張(VS Code)は、Java ${min} 以上が必要です。`);
117
+ javaGuidance(box, min, deps.platform, level);
118
+ return false;
119
+ }
120
+ rememberOk(box, stamp, key);
121
+ return true;
122
+ }
123
+ /** フック: 入っているものが、この版のフックと違えば入れ直す(sft project create も使う) */
124
+ export async function setupHooks(box, deps) {
125
+ if (!box.files.exists(HOOK_ENTRY)) {
126
+ box.output.err(`[INFO] sft の凍結した入口(${HOOK_ENTRY})がないため、フックは入れ替えません。`);
127
+ return;
128
+ }
129
+ const same = ["pre-commit", "pre-push"].every((w) => {
130
+ const p = `.git/hooks/${w}`;
131
+ return box.files.exists(p) && box.files.readText(p) === hookScript(w, deps.nodePath);
132
+ });
133
+ if (same)
134
+ return;
135
+ if ((await runHookInstall(box, deps)) !== 0)
136
+ box.output.err("[WARNING] Git フックのインストールに失敗しました(続行します)");
137
+ }
138
+ /** release/ と release/<ブランチ>/ の準備(sft project create も使う) */
139
+ export async function setupReleaseDir(box, deps) {
140
+ const r = await box.run("git", ["symbolic-ref", "-q", "--short", "HEAD"]).catch(() => null);
141
+ const branch = r !== null && r.code === 0 ? r.stdout.trim() : "";
142
+ if (branch === "") {
143
+ box.output.err("[WARNING] 現在のブランチ名を取得できませんでした(detached HEAD など)。リリース管理ディレクトリの準備をスキップします。");
144
+ return;
145
+ }
146
+ const { files } = box;
147
+ // 作れなくても、警告にして続ける(シェル版と同じ)
148
+ try {
149
+ files.makeDir("sf-tools/release");
150
+ }
151
+ catch {
152
+ box.output.err("[WARNING] sf-tools/release を作れませんでした(続行します)");
153
+ return;
154
+ }
155
+ if (branch === "main")
156
+ return; // main はリリースの対象外
157
+ const dir = `sf-tools/release/${branch}`;
158
+ try {
159
+ files.makeDir(dir);
160
+ }
161
+ catch {
162
+ box.output.err(`[WARNING] ${dir} を作れませんでした(続行します)`);
163
+ return;
164
+ }
165
+ try {
166
+ for (const name of ["deploy-target.txt", "remove-target.txt", "README.md"]) {
167
+ // あるものは上書きしない(書いた内容を消さないため)
168
+ if (!files.exists(`${dir}/${name}`))
169
+ files.writeText(`${dir}/${name}`, files.readText(`${deps.releaseTemplateDir}/${name}`));
170
+ }
171
+ files.writeText("sf-tools/release/branch_name.txt", `${branch}\n`);
172
+ }
173
+ catch {
174
+ box.output.err("[WARNING] リリース管理ディレクトリの準備に失敗しました(続行します)");
175
+ return;
176
+ }
177
+ box.output.err(`[INFO] ブランチ: ${branch} / branch_name.txt を保存しました`);
178
+ }
179
+ async function npmInstall(box, deps) {
180
+ if (!box.files.exists("package.json"))
181
+ return;
182
+ const lock = deps.mtime("package-lock.json");
183
+ if (lock > 0 && deps.mtime("node_modules/.package-lock.json") >= lock)
184
+ return;
185
+ box.output.err("[INFO] npm install を実行します...");
186
+ const r = await box.run("npm", ["install"]).catch(() => null);
187
+ if (r === null || r.code !== 0)
188
+ box.output.err("[WARNING] npm install に失敗しました(続行します)");
189
+ }
190
+ export async function runDoctor(args, box, deps) {
191
+ const rest = args.filter((a) => a !== "-v" && a !== "--verbose");
192
+ if (rest.length > 0) {
193
+ box.output.err(`[ERROR] 不明なオプションです: ${rest[0]}`);
194
+ return 1;
195
+ }
196
+ for (const cfg of ["sf-tools/config/metadata.txt", "sf-tools/config/branches.txt"]) {
197
+ if (!box.files.exists(cfg)) {
198
+ box.output.err(`[ERROR] 設定ファイルが見つかりません: ${cfg}`);
199
+ return 1;
200
+ }
201
+ }
202
+ if (box.env("GITHUB_ACTIONS") !== "true") {
203
+ await checkSf(box, deps);
204
+ await checkJava(box, deps);
205
+ }
206
+ await setupHooks(box, deps);
207
+ await setupReleaseDir(box, deps);
208
+ await npmInstall(box, deps);
209
+ box.output.out("[SUCCESS] 手元の準備と確認が完了しました。");
210
+ return 0;
211
+ }