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

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 +368 -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,256 @@
1
+ // sft ci release / sft release: ターゲットファイルから、組織へ検証(既定)またはリリースする。シェル版の bin/sf-release.sh の移し先
2
+ // (doc/rebuild-design.md 11.2 の段階 2。仕様の正本は、移し元の冒頭コメント)。
3
+ //
4
+ // 【使い方】 release [--validate|--dry-run] [-r|--release] [-n|--no-open] [-f|--force] [-t|--target ALIAS] [-j|--json] [-v]
5
+ // 既定は検証モード(sf project deploy start --dry-run)。-r で、実際に組織へ反映する。
6
+ //
7
+ // 【安全ガード】(落とさないこと。doc/dev-reference.md の「共有環境の保護」)
8
+ // - 本物の GitHub Actions の外では、接続先が予約名(prod / staging / develop / main)なら、検証でも中断する。
9
+ // 名前を付け替えた本番組織も止めるため、組織の種類も確認し、本番・種類を確認できない組織は、中断する(止める側に倒す)
10
+ // - 本物の Actions の外で、-r(リリース)のとき(SF_DEPLOY_CONFIRMED=1 でなければ)、確認(Y/N/q)を出す。
11
+ // AI 操作(SF_TOOLS_AI=1)では、確認の答えを受け取る仕組みが、まだないため、聞かずに終了コード 20(確認待ち)で止まる
12
+ //
13
+ // 【処理の流れ】
14
+ // 1. sf が動くことを確かめる 2. 接続先を決める(引数 > SF_TARGET_ORG > sf org display)3. 保護ガード 4. 確認
15
+ // 5. sf-tools/release/branch_name.txt のブランチの deploy-target.txt・remove-target.txt を、checkTargets で検査する
16
+ // 6. @isTest のテストクラスを検出して表示する(あれば、9 で RunSpecifiedTests にする。マニフェストの作成の前に行う)
17
+ // 7. マニフェストを作る(対象が 1 件もなければ、何もせず 0 で終わる)。反映と削除の両方にあるものがあれば、中断する
18
+ // 8. 削除の対象のうち、組織にないもの(すでに消えたもの)を外す(# @ignore-missing があれば、しない)
19
+ // 9. sf project deploy start を実行する
20
+ // 終了コード: 0 = 成功(対象なしを含む)/ 1 = 中断・失敗/ 20 = 確認待ち(AI 操作)
21
+ import { isReservedOrgAlias } from "./branches.js";
22
+ import { checkTargets } from "./check-targets.js";
23
+ import { EXIT } from "./exit-codes.js";
24
+ import { buildManifest, parseTargetList } from "./manifest-build.js";
25
+ import { getTargetOrg, isRealGithubActions, orgLocalReleaseCheck } from "./org.js";
26
+ import { manifestDropPairs, manifestMissingInOrg, manifestOverlap, manifestPairs } from "./package-xml.js";
27
+ const FOLDERED_TYPES = new Set(["Report", "Dashboard", "Document", "EmailTemplate"]);
28
+ /** 組織にある名前の一覧(種類ごと)。取れなければ null(ある、とみなして、削除の対象から外さない) */
29
+ async function listOrgNames(box, org, type) {
30
+ const r = await box
31
+ .run("sf", ["org", "list", "metadata", "--metadata-type", type, "--target-org", org, "--json"], { input: "" })
32
+ .catch(() => null);
33
+ if (r === null || r.code !== 0)
34
+ return null;
35
+ try {
36
+ const data = JSON.parse(r.stdout);
37
+ if (String(data.status) !== "0")
38
+ return null;
39
+ const items = Array.isArray(data.result) ? data.result : data.result ? [data.result] : [];
40
+ return items.map((i) => String(i.fullName ?? "")).filter((n) => n !== "");
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ export async function runRelease(args, box, deps) {
47
+ const log = (level, text) => box.output.err(`[${level}] ${text}`);
48
+ const die = (text) => {
49
+ log("ERROR", text);
50
+ return EXIT.failure;
51
+ };
52
+ // --- 引数(既定は、最も安全な設定: 検証のみ・ブラウザを開く) ---
53
+ let validate = true;
54
+ let open = true;
55
+ let force = false;
56
+ let target = "";
57
+ let json = false;
58
+ for (let i = 0; i < args.length; i++) {
59
+ const a = args[i];
60
+ if (a === "--validate" || a === "--dry-run")
61
+ validate = true;
62
+ else if (a === "--release" || a === "-r")
63
+ validate = false;
64
+ else if (a === "--no-open" || a === "-n")
65
+ open = false;
66
+ else if (a === "--force" || a === "-f")
67
+ force = true;
68
+ else if (a === "--json" || a === "-j")
69
+ json = true;
70
+ else if (a === "--verbose" || a === "-v")
71
+ continue;
72
+ else if (a === "--target" || a === "-t") {
73
+ const v = args[i + 1] ?? "";
74
+ if (v === "" || v.startsWith("-"))
75
+ return die("-t / --target の値(組織のエイリアス)がない、または - で始まっています。");
76
+ target = v;
77
+ i++;
78
+ }
79
+ else
80
+ return die(a.startsWith("--") ? `不明なオプションです: ${a}` : `不明な引数です: ${a}`);
81
+ }
82
+ const extra = json ? ["--json"] : [];
83
+ log("HEADER", "リリース・検証処理を開始します (sf-release)");
84
+ const version = await box.run("sf", ["--version"]).catch(() => null);
85
+ if (version === null || version.code !== 0)
86
+ return die("sf(Salesforce CLI)を動かせません。npm 版の sf が必要です。");
87
+ const org = await getTargetOrg(box, target);
88
+ if (org === null)
89
+ return die("接続先の組織エイリアスを特定できません。");
90
+ log("INFO", `接続先組織: ${org}`);
91
+ // --- 保護組織へのローカル直接実行を禁止(共有環境と本番は、GitHub Actions 専用) ---
92
+ const real = isRealGithubActions(box);
93
+ if (!real) {
94
+ if (isReservedOrgAlias(org))
95
+ return die(`${org} は共有環境(予約名)のため、ローカルから実行できません。`);
96
+ const kind = await orgLocalReleaseCheck(box, org);
97
+ if (kind === 1)
98
+ return die(`${org} は本番組織のため、ローカルから実行できません。`);
99
+ if (kind === 2)
100
+ return die(`${org} の組織の種類を確認できないため、ローカルから実行できません。`);
101
+ }
102
+ // --- ローカルでのリリースの確認 ---
103
+ if (!real && !validate && box.env("SF_DEPLOY_CONFIRMED") !== "1") {
104
+ if (force)
105
+ log("WARNING", "--force(--ignore-conflicts)が指定されています。コンフリクトは強制上書きされます。");
106
+ if (box.env("SF_TOOLS_AI") === "1") {
107
+ box.output.err("[ERROR] 確認待ち: リリースを実行します(実際に、組織へ反映されます)。続行しますか?(AI 操作では、答えを渡す仕組みが、まだありません)");
108
+ return EXIT.needAnswer;
109
+ }
110
+ const answer = await deps.confirm("リリースを実行します(実際に、組織へ反映されます)。続行しますか?");
111
+ if (answer !== "yes")
112
+ return die("中断しました。");
113
+ }
114
+ // --- パス ---
115
+ const branchFile = "sf-tools/release/branch_name.txt";
116
+ if (!box.files.exists(branchFile))
117
+ return die(`ブランチ情報ファイルが見つかりません (${branchFile})。`);
118
+ const branch = box.files.readText(branchFile).replace(/[\r\n]/g, "");
119
+ const dir = `sf-tools/release/${branch}`;
120
+ const deployList = `${dir}/deploy-target.txt`;
121
+ const removeList = `${dir}/remove-target.txt`;
122
+ const deployXml = `${dir}/package.xml`;
123
+ const removeXml = `${dir}/destructiveChanges.xml`;
124
+ log("INFO", `リリース処理開始 (Target: ${org}, Branch: ${branch})`);
125
+ // --- CHECK ---
126
+ box.files.makeDir(dir);
127
+ for (const f of [deployList, removeList]) {
128
+ if (!box.files.exists(f))
129
+ return die(`ターゲットファイルが見つかりません: ${f}`);
130
+ }
131
+ if (checkTargets(box, deployList, removeList, deps.loadCapability()) > 0)
132
+ return die("ターゲットファイルの検証(sf-check)でエラーがありました。");
133
+ log("SUCCESS", "対象リストの確認完了");
134
+ // --- MANIFEST ---
135
+ const tests = [];
136
+ for (const item of parseTargetList(box.files.readText(deployList))) {
137
+ if (item.kind !== "source-dir" || !item.value.endsWith(".cls") || !box.files.exists(item.value))
138
+ continue;
139
+ if (!box.files.readText(item.value).toLowerCase().includes("@istest"))
140
+ continue;
141
+ const name = item.value.split("/").pop().replace(/\.cls$/, "");
142
+ tests.push(name);
143
+ log("INFO", ` テストクラス検出: ${name}`);
144
+ }
145
+ if (tests.length > 0)
146
+ log("INFO", `テストクラス合計: ${tests.length}件 → --tests に自動設定します`);
147
+ const built = await buildManifest(box, ".", dir, dir, extra);
148
+ if (built.kind === "nochange") {
149
+ log("WARNING", `デプロイ対象がありません。${deployList} または ${removeList} にパスを記入してください。`);
150
+ log("SUCCESS", "デプロイ対象なし。正常終了します。");
151
+ return EXIT.ok;
152
+ }
153
+ if (built.kind === "error") {
154
+ log("ERROR", built.message);
155
+ return die("マニフェスト生成に失敗しました。");
156
+ }
157
+ log("SUCCESS", "マニフェスト生成完了");
158
+ let destructive = built.destructiveXml;
159
+ // 反映と削除の両方に同じものがあれば、止める(先に消して、反映で作り直す。項目なら、データだけが黙って消える)
160
+ if (destructive !== null) {
161
+ const overlap = manifestOverlap(built.packageXml, destructive);
162
+ if (overlap.length > 0) {
163
+ log("ERROR", "反映(package.xml)と削除(destructiveChanges.xml)の両方に、同じものがあります:");
164
+ for (const item of overlap)
165
+ log("ERROR", ` ${item}`);
166
+ log("ERROR", "このまま進めると、削除のあとの反映で、作り直されます(項目なら、中のデータだけが消えます)。");
167
+ log("ERROR", "deploy-target.txt に書いたオブジェクトの本体(*.object-meta.xml)やフォルダは、配下の項目などを、すべて反映に含めます。");
168
+ return die("マニフェスト生成に失敗しました。");
169
+ }
170
+ }
171
+ // --- PRUNE: 削除の対象のうち、組織にないものを外す(remove-target.txt に「# @ignore-missing」があれば、しない) ---
172
+ const pruned = [];
173
+ const report = (summary) => {
174
+ if (pruned.length === 0)
175
+ return;
176
+ log("WARNING", `組織(${org})にないため、削除の対象から外しました(すでに消えているもの): ${pruned.length} 件`);
177
+ for (const p of pruned)
178
+ log("WARNING", ` ${p}`);
179
+ log("WARNING", " remove-target.txt の [members] の名前の書き間違いも、ここに出ます。消したいものが、ここにないかを確かめてください。");
180
+ const summaryFile = box.env("GITHUB_STEP_SUMMARY");
181
+ if (summary && summaryFile) {
182
+ try {
183
+ box.files.appendText(summaryFile, `### 削除の対象から外したもの(組織 ${org} にないため)\n\n${pruned.map((p) => `- \`${p}\``).join("\n")}\n\nremove-target.txt の [members] の名前の書き間違いも、ここに出ます。\n\n`);
184
+ }
185
+ catch {
186
+ // 要約に書けなくても、リリースは進める
187
+ }
188
+ }
189
+ };
190
+ const ignoreMissing = /^\s*#\s*@ignore-missing/m.test(box.files.readText(removeList));
191
+ if (destructive !== null && !ignoreMissing) {
192
+ log("INFO", `削除の対象が、組織(${org})にあるかを確かめます...`);
193
+ const names = new Map();
194
+ for (const type of new Set(manifestPairs(destructive).map((p) => p.slice(0, p.indexOf(":"))))) {
195
+ if (FOLDERED_TYPES.has(type))
196
+ continue;
197
+ log("CMD", `[sf-release.sh] sf org list metadata --metadata-type ${type} --target-org ${org} --json`);
198
+ const list = await listOrgNames(box, org, type);
199
+ if (list === null)
200
+ log("WARNING", ` ${type}: 組織にあるかを確かめられませんでした(一覧が取れません)。削除の対象から外しません。`);
201
+ names.set(type, list);
202
+ }
203
+ const missing = manifestMissingInOrg(destructive, (type) => names.get(type) ?? null);
204
+ if (missing.length === 0) {
205
+ log("SUCCESS", "削除の対象は、すべて組織にあります(確かめられなかったものは、上の WARNING)。");
206
+ }
207
+ else {
208
+ destructive = manifestDropPairs(destructive, missing);
209
+ box.files.writeText(removeXml, destructive);
210
+ pruned.push(...missing);
211
+ report(true);
212
+ if (!destructive.includes("<members>")) {
213
+ box.files.removeFile(removeXml);
214
+ destructive = null;
215
+ log("INFO", "削除の対象が、すべて組織にないため、削除は行いません(--pre-destructive-changes を付けません)。");
216
+ if (!built.packageXml.includes("<members>")) {
217
+ log("SUCCESS", "反映・削除するものがありません(削除の対象は、すべて組織にありません)。正常終了します。");
218
+ return EXIT.ok;
219
+ }
220
+ }
221
+ }
222
+ }
223
+ // --- RELEASE ---
224
+ const deploy = ["project", "deploy", "start", "--target-org", org, "--manifest", deployXml, ...extra];
225
+ if (destructive !== null)
226
+ deploy.push("--pre-destructive-changes", removeXml);
227
+ if (force)
228
+ deploy.push("--ignore-conflicts");
229
+ if (ignoreMissing) {
230
+ deploy.push("--ignore-warnings");
231
+ log("INFO", "remove-target.txt に @ignore-missing があるため、存在しない削除対象は、エラーにしません(--ignore-warnings)");
232
+ }
233
+ if (tests.length > 0) {
234
+ deploy.push("--test-level", "RunSpecifiedTests", ...tests.flatMap((t) => ["--tests", t]));
235
+ log("INFO", `テスト実行: --test-level RunSpecifiedTests ${tests.map((t) => `--tests ${t}`).join(" ")}`);
236
+ }
237
+ if (validate) {
238
+ log("INFO", "検証モード (Dry-Run) を開始します");
239
+ deploy.push("--dry-run");
240
+ }
241
+ else {
242
+ log("INFO", "組織へのリリースを実行します!");
243
+ }
244
+ if (open) {
245
+ log("INFO", "リリース状況画面をブラウザで表示します...");
246
+ await box.run("sf", ["org", "open", "--target-org", org, "--path", "lightning/setup/DeployStatus/home", ...extra]).catch(() => null);
247
+ log("INFO", "ブラウザ描画待機 (5秒)");
248
+ await box.clock.sleep(5000);
249
+ }
250
+ const result = await box.run("sf", deploy, { onChunk: (text) => box.output.out(text.replace(/\n$/, "")) }).catch(() => null);
251
+ report(false); // 外したものは、最後にもう一度表示する(デプロイの出力の上に流れて、見落とさないように)
252
+ if (result === null || result.code !== 0)
253
+ return die("Salesforce へのデプロイ/検証の実行に失敗しました。");
254
+ log("SUCCESS", "デプロイ/検証が完了しました。");
255
+ return EXIT.ok;
256
+ }
@@ -0,0 +1,29 @@
1
+ /** 絶対のパスか(/ で始まる・Windows のドライブ C:\ や C:/・\\ で始まる) */
2
+ export const isAbsolutePath = (p) => /^([A-Za-z]:)?[\\/]/.test(p);
3
+ /** dir と p をつなぐ(p が絶対ならそのまま。. は dir) */
4
+ export function joinPath(dir, p) {
5
+ if (isAbsolutePath(p))
6
+ return p;
7
+ if (p === "" || p === ".")
8
+ return dir;
9
+ return `${dir.replace(/[\\/]+$/, "")}/${p.replace(/^\.\//, "")}`;
10
+ }
11
+ export function scopeBox(box, dir) {
12
+ const at = (p) => joinPath(dir, p);
13
+ const f = box.files;
14
+ return {
15
+ ...box,
16
+ run: (command, args, options) => box.run(command, args, { ...options, cwd: at(options?.cwd ?? ".") }),
17
+ files: {
18
+ readText: (p) => f.readText(at(p)),
19
+ writeText: (p, t) => f.writeText(at(p), t),
20
+ appendText: (p, t) => f.appendText(at(p), t),
21
+ exists: (p) => f.exists(at(p)),
22
+ makeDir: (p) => f.makeDir(at(p)),
23
+ removeFile: (p) => f.removeFile(at(p)),
24
+ isDir: (p) => f.isDir(at(p)),
25
+ walkFiles: (p) => f.walkFiles(at(p)),
26
+ listDir: (p) => f.listDir(at(p)),
27
+ },
28
+ };
29
+ }
@@ -0,0 +1,155 @@
1
+ // sft(引数なし・force-* の中)の起動の準備。bin/sf-start.sh の移し先(doc/rebuild-design.md 2 章: 「組織に接続し、手元の準備をして、ランチャーを開く」)。
2
+ // 1. 接続の確認: .sf/config.json があり、やり直しの指定(forceRelogin)がなければ、sf org display --json。エイリアスが取れ、組織 ID が
3
+ // 00D で始まれば接続済み(ログインを省く)。connectedStatus が認証の期限切れ・取り消しなら、WARNING でログインし直す。
4
+ // sf の失敗・JSON でないときは、未接続として扱う。通信の失敗など、ほかの connectedStatus は接続済みとして進む
5
+ // 2. 未接続(またはやり直し)のログイン(loginOrg): エイリアスの入力(空は聞き直し・q と入力の終わりで中断)→
6
+ // sf alias unset vscodeOrg(失敗は無視)→ ログイン先の選択(login-url.ts。環境変数 SF_INIT_LOGIN_URL_START で指定できる)→
7
+ // sf org logout(失敗は無視)→ sf org login web --set-default(ブラウザ。失敗したら中断し、設定ファイルは書かない)
8
+ // 3. .sf/config.json({"target-org": エイリアス})と .sfdx/sfdx-config.json({"defaultusername": エイリアス})を書く。
9
+ // VS Code(code .)を起動する(なければ WARNING)。AI 向けの案内(CLAUDE.md の「@~/sf-tools/doc/ai-dev-loop.md」・AGENTS.md の
10
+ // 「~/sf-tools/doc/ai-dev-loop.md」)がなければ WARNING(ファイルは書き換えない。未コミットの変更を作らないため)
11
+ // 4. 手元の準備(sft doctor。今の sf-refresh.sh の代わり。裏ではなく、ランチャーの前に動かす。失敗しても WARNING で進む)
12
+ // 5. デバッグログの自動の取り始め(log-session.ts の beginLog。答えがなければ聞く。取るなら、ランチャーの裏で取り続ける)
13
+ // 6. ランチャーを開く。中で組織を切り替えたら、デバッグログを新しい組織に移す(前の組織は leave、新しい組織で取り始め)。
14
+ // 閉じたら、デバッグログの後始末(leave)。終了コードは、ランチャーによらず 0(中断・ログインの失敗は 1)
15
+ // なくしたもの: sf-tools の git pull と、24 時間ごとの CLI の更新(版の固定・人が sft update-cli を動かす: 設計 1.2 の 5・2.4)。
16
+ // WSL の wslview の補い(WSL は force-* の対象外: CLAUDE.md 4.1)。
17
+ // sf の確認は、シェル版の sf-refresh.sh と同じく、doctor が毎回確かめる(Java は 24 時間省く)
18
+ import { chooseLoginUrl } from "./login-url.js";
19
+ /** sf の出力が、保存した認証の期限切れ・取り消しを示すか(lib/org.sh の org_is_auth_expired と同じ) */
20
+ export function isAuthExpired(text) {
21
+ return /expired access\/refresh token|invalid_grant|RefreshTokenAuthError/.test(text);
22
+ }
23
+ /** 接続済みなら、そのエイリアス。未接続・期限切れなら null */
24
+ export async function connectedAlias(box) {
25
+ const r = await box.run("sf", ["org", "display", "--json"]).catch(() => null);
26
+ if (r === null)
27
+ return null;
28
+ let data;
29
+ try {
30
+ data = JSON.parse(r.stdout);
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ const alias = typeof data.result?.alias === "string" ? data.result.alias : "";
36
+ const id = typeof data.result?.id === "string" ? data.result.id : "";
37
+ if (alias === "" || alias === "null" || !id.startsWith("00D"))
38
+ return null;
39
+ const status = typeof data.result?.connectedStatus === "string" ? data.result.connectedStatus : "";
40
+ if (isAuthExpired(status)) {
41
+ box.output.err(`[WARNING] 組織 (${alias}) の認証が切れています。ログインし直してください(q で中断)。`);
42
+ return null;
43
+ }
44
+ box.output.err(`[INFO] 組織 (${alias}) に接続済みです。`);
45
+ return alias;
46
+ }
47
+ /** エイリアスを聞いてログインし、接続設定を書く(sft switch-org のやり直しも使う)。成功ならエイリアス、中断・失敗なら null */
48
+ export async function loginOrg(box, deps) {
49
+ const err = (l) => box.output.err(l);
50
+ const alias = await deps.prompts.text("接続する組織のエイリアスを入力してください [q で中断]: ");
51
+ if (alias === "quit") {
52
+ err("[ERROR] 中断しました。");
53
+ return null;
54
+ }
55
+ await box.run("sf", ["alias", "unset", "vscodeOrg", "--json"]).catch(() => null); // 古い VS Code 向けの設定(失敗しても続ける)
56
+ const chosen = await chooseLoginUrl(box, deps.prompts, { label: `組織 ${alias}`, tier: "main", envName: "SF_INIT_LOGIN_URL_START" });
57
+ if ("quit" in chosen) {
58
+ err("[ERROR] 中断しました。");
59
+ return null;
60
+ }
61
+ if ("error" in chosen) {
62
+ err(`[ERROR] ${chosen.error}`);
63
+ return null;
64
+ }
65
+ err("[INFO] ブラウザでログインして接続を許可してください...");
66
+ await box.run("sf", ["org", "logout", "--target-org", alias, "--no-prompt"]).catch(() => null);
67
+ // ブラウザでのログイン。応答は、そのまま画面に流す(ブラウザが開かないときの URL の案内を見せるため)
68
+ const login = await box
69
+ .run("sf", ["org", "login", "web", "--set-default", "--alias", alias, "--instance-url", chosen.url], {
70
+ onChunk: (text) => box.output.err(text.replace(/\n$/, "")),
71
+ })
72
+ .catch(() => null);
73
+ if (login === null || login.code !== 0) {
74
+ err(`[ERROR] Salesforce へのログインに失敗しました(エイリアス: ${alias})。`);
75
+ return null;
76
+ }
77
+ writeOrgConfig(box, alias);
78
+ err("[SUCCESS] 接続完了!");
79
+ return alias;
80
+ }
81
+ /** VS Code の Salesforce 拡張と sf が読む接続設定を書く */
82
+ export function writeOrgConfig(box, alias) {
83
+ box.files.makeDir(".sf");
84
+ box.files.makeDir(".sfdx");
85
+ box.files.writeText(".sf/config.json", `${JSON.stringify({ "target-org": alias })}\n`);
86
+ box.files.writeText(".sfdx/sfdx-config.json", `${JSON.stringify({ defaultusername: alias })}\n`);
87
+ }
88
+ function aiGuidanceMissing(box) {
89
+ const has = (path, needle) => {
90
+ try {
91
+ return box.files.exists(path) && box.files.readText(path).includes(needle);
92
+ }
93
+ catch {
94
+ return false;
95
+ }
96
+ };
97
+ const missing = [];
98
+ if (!has("CLAUDE.md", "@~/sf-tools/doc/ai-dev-loop.md"))
99
+ missing.push("CLAUDE.md");
100
+ if (!has("AGENTS.md", "~/sf-tools/doc/ai-dev-loop.md"))
101
+ missing.push("AGENTS.md");
102
+ return missing;
103
+ }
104
+ export async function runStart(box, deps) {
105
+ const err = (l) => box.output.err(l);
106
+ if (!deps.folderName.startsWith("force-")) {
107
+ err("[ERROR] force-* フォルダで実行してください。");
108
+ return 1;
109
+ }
110
+ err("=== 開発タスクのスタートアップを開始します (sft) ===");
111
+ err("[INFO] Salesforce 接続確認中...");
112
+ let alias = box.files.exists(".sf/config.json") ? await connectedAlias(box) : null;
113
+ if (alias === null) {
114
+ alias = await loginOrg(box, deps);
115
+ if (alias === null)
116
+ return 1;
117
+ }
118
+ else {
119
+ writeOrgConfig(box, alias);
120
+ }
121
+ err("[SUCCESS] Salesforce に接続しました");
122
+ err("[INFO] VS Code を起動中...");
123
+ const code = await box.run("code", ["."], { allowCmdShell: true }).catch(() => null);
124
+ if (code !== null && code.code === 0)
125
+ err("[SUCCESS] VS Code を起動しました。");
126
+ else
127
+ err("[WARNING] 'code' コマンドが見つかりません。VS Code を手動で起動してください。");
128
+ const missing = aiGuidanceMissing(box);
129
+ if (missing.length > 0) {
130
+ const names = missing.join("・");
131
+ err(`[WARNING] AI 向けの案内(${names} の、手順書 ~/sf-tools/doc/ai-dev-loop.md を指す行)がありません。AI が sf-tools の使い方を知らないまま作業します。`);
132
+ err(`[WARNING] ~/sf-tools/templates/ の ${names} の行を、プロジェクトのルートの同じ名前のファイルに足して(ファイルがなければコピーして)、コミットしてください。`);
133
+ }
134
+ if ((await deps.doctor()) !== 0)
135
+ err("[WARNING] 手元の準備に、うまくいかないところがありました(上の表示を確認してください)。");
136
+ // デバッグログ(自動の取り始め): 取るなら、ランチャーの裏で取り続け、閉じたら後始末する
137
+ let session = deps.log ? await deps.log(alias).catch(() => null) : null;
138
+ // ランチャーの中で組織を切り替えたら、前の組織の取得を後始末して(TraceFlag を消す)、新しい組織で取り始める
139
+ // (シェル版は、sf-switch-org.sh が sf-start.sh を動かし直して、同じことになる)
140
+ const orgSwitched = async () => {
141
+ const next = await connectedAlias(box);
142
+ if (next === null || next === alias || !deps.log)
143
+ return;
144
+ await session?.leave();
145
+ alias = next;
146
+ session = await deps.log(next).catch(() => null);
147
+ };
148
+ try {
149
+ await deps.launcher(orgSwitched);
150
+ }
151
+ finally {
152
+ await session?.leave();
153
+ }
154
+ return 0;
155
+ }
@@ -0,0 +1,49 @@
1
+ const CONFIGS = [".sf/config.json", ".sfdx/sfdx-config.json"];
2
+ export async function runSwitchOrg(args, box, deps) {
3
+ const rest = args.filter((a) => a !== "-v" && a !== "--verbose");
4
+ if (rest.length > 0) {
5
+ box.output.err(`[ERROR] 不明なオプションです: ${rest[0]}`);
6
+ return 1;
7
+ }
8
+ if (!deps.folderName.startsWith("force-")) {
9
+ box.output.err(`[ERROR] force-* フォルダで実行してください(今いるフォルダ: ${deps.folderName})。`);
10
+ return 1;
11
+ }
12
+ const { files } = box;
13
+ // 退避(メモリに読む)。読めなければ、何も消さずに中断する(戻せなくなるため)
14
+ const saved = new Map();
15
+ for (const path of CONFIGS) {
16
+ if (!files.exists(path))
17
+ continue;
18
+ try {
19
+ saved.set(path, files.readText(path));
20
+ }
21
+ catch {
22
+ box.output.err(`[ERROR] 接続設定(${path})を退避できません。`);
23
+ return 1;
24
+ }
25
+ }
26
+ box.output.out("[INFO] 現在のローカル接続設定をクリアしています...");
27
+ for (const path of CONFIGS)
28
+ files.removeFile(path);
29
+ const code = (await deps.relogin(args)) ?? 1;
30
+ if (code !== 0) {
31
+ let restored = false;
32
+ for (const [path, text] of saved) {
33
+ if (files.exists(path))
34
+ continue; // 新しい設定が書かれていれば、そのまま
35
+ try {
36
+ files.makeDir(path.slice(0, path.lastIndexOf("/")));
37
+ files.writeText(path, text);
38
+ restored = true;
39
+ }
40
+ catch {
41
+ box.output.err(`[WARNING] 元の接続設定(${path})を戻せませんでした。`);
42
+ }
43
+ }
44
+ if (restored) {
45
+ box.output.err("[WARNING] ログインのやり直しが失敗したため、元の接続設定(.sf/config.json・.sfdx/sfdx-config.json)を戻しました。");
46
+ }
47
+ }
48
+ return code;
49
+ }