@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,170 @@
1
+ // ターゲットファイル(deploy-target.txt / remove-target.txt)の構文チェック。シェル版の bin/sf-check.sh の移し先
2
+ // (doc/rebuild-design.md 11.2 の段階 2。仕様の正本は、移し元の冒頭コメント)。release・push・フック・ランチャーが呼ぶ。
3
+ // 外との出入りは、渡された道具の箱だけ(7.2)。作業ディレクトリは、プロジェクトのルート
4
+ //
5
+ // 【処理】
6
+ // 1. 各ターゲットファイルを 1 行ずつ検証する(CR と前後の空白を除き、空行と # の行は読み飛ばす。セクションは [files] / [members]。
7
+ // 最初のマーカーより前は [files])
8
+ // [files] : リポジトリの外を指すパス(絶対パス・.. を含むパス)・存在しないパス・認めないフォルダはエラー。
9
+ // フォルダは、lwc/<名前>・aura/<名前>・objects/<名前> だけ書ける(リリース・削除の対象が広がりすぎるため)
10
+ // [members]: 「種別名:メンバー名」の形でない(: がない・先頭か末尾が :)ときはエラー
11
+ // 2. エラーでない行について、種類の可否を確認する(metadata-capability.txt。deploy は release 列・remove は delete 列。
12
+ // ng はエラー・limited は警告)。SF_CHECK_IGNORE_CAPABILITY=1 で省略できる
13
+ // 3. テストクラス不足を確認する(警告のみ)
14
+ // 【シェル版との違い】@isTest を含む .cls の探索(Step B)は、.git と node_modules の中を見ない(速さのため。リリースの対象になる場所ではない)
15
+ import { checkCapability, typeOfPath } from "./metadata-types.js";
16
+ const stripDot = (p) => (p.startsWith("./") ? p.slice(2) : p);
17
+ function isOutsideRepo(p) {
18
+ return /^\//.test(p) || /^[A-Za-z]:[\\/]/.test(p) || p === ".." || p.startsWith("../") || p.includes("/../") || p.endsWith("/..");
19
+ }
20
+ /** 1 行の指摘を、画面の 2 行にする */
21
+ function report(box, level, file, line, content, message) {
22
+ box.output.out(` ${file}:${line === null ? "" : `${line}:`} ${level}: ${message}`);
23
+ box.output.out(` → ${content}`);
24
+ }
25
+ function capabilityCheck(c, label, lineno, content, type) {
26
+ if (c.capability === null)
27
+ return;
28
+ const r = checkCapability(c.capability, label, type, c.ignoreCapability);
29
+ if (r.level === "ok")
30
+ return;
31
+ const note = r.note === "" ? "" : `(${r.note})`;
32
+ if (r.level === "error") {
33
+ report(c.box, "error", label, lineno, content, `「${r.type}」は、API で${r.what}できないことを確認済みです${note}。組織の権限で、できる場合は、SF_CHECK_IGNORE_CAPABILITY=1 で、この確認を省略できます`);
34
+ c.errors++;
35
+ }
36
+ else {
37
+ report(c.box, "warning", label, lineno, content, `「${r.type}」は、条件によって、${r.what}できないことがあります${note}`);
38
+ }
39
+ }
40
+ function checkTargetFile(c, file, label) {
41
+ const { box } = c;
42
+ if (!box.files.exists(file)) {
43
+ box.output.err(`[INFO] ${label}: ファイルが存在しません。スキップします。(${file})`);
44
+ return;
45
+ }
46
+ box.output.err(`[INFO] ${label} を検証します: ${file}`);
47
+ const start = c.errors;
48
+ const fail = (lineno, content, message) => {
49
+ report(box, "error", label, lineno, content, message);
50
+ c.errors++;
51
+ };
52
+ let section = "files";
53
+ let entries = 0;
54
+ const lines = box.files.readText(file).split("\n");
55
+ for (let i = 0; i < lines.length; i++) {
56
+ const lineno = i + 1;
57
+ const clean = lines[i].replace(/\r/g, "").trim();
58
+ if (clean === "" || clean.startsWith("#"))
59
+ continue;
60
+ if (clean === "[files]") {
61
+ section = "files";
62
+ continue;
63
+ }
64
+ if (clean === "[members]") {
65
+ section = "members";
66
+ continue;
67
+ }
68
+ entries++;
69
+ if (section === "members") {
70
+ if (!clean.includes(":") || clean.startsWith(":") || clean.endsWith(":"))
71
+ fail(lineno, clean, "書式エラー(種別名:メンバー名)");
72
+ else
73
+ capabilityCheck(c, label, lineno, clean, clean.slice(0, clean.indexOf(":")));
74
+ }
75
+ else if (isOutsideRepo(clean)) {
76
+ fail(lineno, clean, "リポジトリの外を指すパスは使えません(絶対パス・.. を含むパス)");
77
+ }
78
+ else if (box.files.isDir(clean)) {
79
+ // フォルダは、1 つのコンポーネント・オブジェクトを丸ごと指すものだけ認める(広いフォルダは、対象が意図より広がるため)
80
+ if (/(^|\/)(lwc|aura|objects)\/[^/]+\/?$/.test(clean))
81
+ capabilityCheck(c, label, lineno, clean, typeOfPath(clean));
82
+ else
83
+ fail(lineno, clean, "フォルダは、LWC・Aura のコンポーネントとオブジェクト(lwc/<名前>・aura/<名前>・objects/<名前>)だけ書けます。ほかのフォルダは、リリース・削除の対象が広がりすぎます");
84
+ }
85
+ else if (!box.files.exists(clean)) {
86
+ fail(lineno, clean, "パスが存在しません");
87
+ }
88
+ else {
89
+ capabilityCheck(c, label, lineno, clean, typeOfPath(clean));
90
+ }
91
+ }
92
+ if (entries === 0)
93
+ box.output.err(`[WARNING] ${label}: 何も書かれていません。`);
94
+ else if (c.errors === start)
95
+ box.output.err(`[SUCCESS] ${label}: 問題なし。`);
96
+ }
97
+ /** テストクラス不足の確認(警告のみ)。deploy-target.txt の [files] の .cls のうち、@isTest のないものに、対応するテストクラスがあるか */
98
+ function checkMissingTests(box, deployList) {
99
+ if (!box.files.exists(deployList))
100
+ return;
101
+ const deployed = [];
102
+ let section = "files";
103
+ for (const raw of box.files.readText(deployList).split("\n")) {
104
+ const clean = raw.replace(/\r/g, "").trim();
105
+ if (clean === "" || clean.startsWith("#"))
106
+ continue;
107
+ if (clean === "[files]")
108
+ section = "files";
109
+ else if (clean === "[members]")
110
+ section = "members";
111
+ else if (section === "files" && clean.endsWith(".cls"))
112
+ deployed.push(clean);
113
+ }
114
+ if (deployed.length === 0)
115
+ return;
116
+ box.output.err("[INFO] テストクラス不足チェックを実行します...");
117
+ const deploySet = new Set(deployed.map(stripDot));
118
+ let tests = null; // @isTest を含む .cls(大文字・小文字を区別する)。最初に 1 回だけ読む
119
+ let warnings = 0;
120
+ for (const path of deployed) {
121
+ if (!box.files.exists(path))
122
+ continue;
123
+ if (box.files.readText(path).toLowerCase().includes("@istest"))
124
+ continue; // テストクラス自身
125
+ const name = path.split("/").pop().replace(/\.cls$/, "");
126
+ const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) || "/" : ".";
127
+ // Step A: 命名規則(同じフォルダの <名前>Test.cls / <名前>_Test.cls)
128
+ let found = [`${dir}/${name}Test.cls`, `${dir}/${name}_Test.cls`].find((p) => box.files.exists(p)) ?? "";
129
+ // Step B: 見つからなければ、@isTest を含む .cls のうち、クラス名を単語として含む最初のもの
130
+ if (found === "") {
131
+ tests ??= box.files
132
+ .walkFiles(".")
133
+ .filter((p) => p.endsWith(".cls"))
134
+ .map((p) => ({ path: p, text: box.files.readText(p) }))
135
+ .filter((t) => t.text.includes("@isTest"));
136
+ const word = new RegExp(`(^|[^A-Za-z0-9_])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^A-Za-z0-9_]|$)`);
137
+ found = tests.find((t) => word.test(t.text))?.path ?? "";
138
+ }
139
+ if (found === "")
140
+ continue;
141
+ found = stripDot(found);
142
+ if (!deploySet.has(found)) {
143
+ report(box, "warning", deployList, null, found, `${name} のテストクラスが deploy-target.txt に含まれていません(本番/Sandbox に存在する場合は無視可)`);
144
+ warnings++;
145
+ }
146
+ }
147
+ if (warnings > 0)
148
+ box.output.err(`[WARNING] テストクラス不足の可能性: ${warnings}件`);
149
+ else
150
+ box.output.err("[SUCCESS] テストクラスチェック: 問題なし。");
151
+ }
152
+ /**
153
+ * ターゲットファイルを検証する。戻り値は、エラーの数(0 = エラーなし。警告のみ・検証を飛ばした場合を含む)。
154
+ * removeList が空文字なら、deploy-target.txt だけを検証する。
155
+ * capability は、可否の表(なければ null = 可否の確認をしない)。SF_CHECK_IGNORE_CAPABILITY=1 なら、可否の確認を省略する
156
+ */
157
+ export function checkTargets(box, deployList, removeList, capability) {
158
+ box.output.err("[HEADER] デプロイターゲットファイルを検証します (sf-check)");
159
+ const c = { box, capability, ignoreCapability: box.env("SF_CHECK_IGNORE_CAPABILITY") === "1", errors: 0 };
160
+ checkTargetFile(c, deployList, "deploy-target.txt");
161
+ if (removeList !== "")
162
+ checkTargetFile(c, removeList, "remove-target.txt");
163
+ checkMissingTests(box, deployList);
164
+ if (c.errors > 0) {
165
+ box.output.out(`\nerror: ${c.errors} 件のエラーが検出されました。ターゲットファイルを修正してください。\n`);
166
+ return c.errors;
167
+ }
168
+ box.output.err("[SUCCESS] 構文チェック完了。問題はありませんでした。");
169
+ return 0;
170
+ }
@@ -0,0 +1,34 @@
1
+ // sft check の中身: 引数から、確かめるターゲットファイルを決めて、検証する(シェル版の sf-check.sh の入口。検証の本体は check-targets.ts)。
2
+ // sft push からも、同じ中身を呼ぶ
3
+ import { checkTargets } from "./check-targets.js";
4
+ import { EXIT } from "./exit-codes.js";
5
+ const BRANCH_NAME_FILE = "sf-tools/release/branch_name.txt";
6
+ /** 引数なし = branch_name.txt のブランチのファイル(なければ、警告して成功)。1 つ = deploy だけ。2 つ以上 = deploy と remove */
7
+ export function runCheck(args, box, capability) {
8
+ const paths = [];
9
+ for (const a of args) {
10
+ if (a === "-v" || a === "--verbose")
11
+ continue;
12
+ if (a.startsWith("-")) {
13
+ box.output.err(`[ERROR] 不明なオプションです: ${a}`);
14
+ return EXIT.failure;
15
+ }
16
+ paths.push(a);
17
+ }
18
+ let deploy;
19
+ let remove;
20
+ if (paths.length >= 1) {
21
+ deploy = paths[0];
22
+ remove = paths[1] ?? "";
23
+ }
24
+ else {
25
+ if (!box.files.exists(BRANCH_NAME_FILE)) {
26
+ box.output.err(`[WARNING] ブランチ情報ファイル(${BRANCH_NAME_FILE})がありません。ターゲットファイルの構文チェックを、スキップしました。`);
27
+ return EXIT.ok;
28
+ }
29
+ const branch = box.files.readText(BRANCH_NAME_FILE).replace(/[\r\n]/g, "");
30
+ deploy = `sf-tools/release/${branch}/deploy-target.txt`;
31
+ remove = `sf-tools/release/${branch}/remove-target.txt`;
32
+ }
33
+ return checkTargets(box, deploy, remove, capability) > 0 ? EXIT.failure : EXIT.ok;
34
+ }
@@ -0,0 +1,150 @@
1
+ // sft ci check-branch: wf-validate の「対象ファイル確認」ジョブの中身。templates/.github/workflows/wf-validate.yml の
2
+ // 該当ステップ(tier-switch v1 と、デプロイ対象ファイルの確認)の移し先(doc/rebuild-design.md 4.6・11.2 の段階 2)。
3
+ // 入力は環境変数 HEAD_REF(PR の元のブランチ)・BASE_REF(マージ先)。結果は GITHUB_OUTPUT に skip=true|false で書く。
4
+ // wf-release の「リリース対象確認」も、同じ手順を使う(BASE_REF = PR のマージ先。main・staging・develop のどれか)。REPOSITORY・PR_NUMBER
5
+ // (と GH_TOKEN)があれば、対象が空で skip=true のとき、PR が変えるファイルに版・ワークフロー(sf-tools/package.json・
6
+ // package-lock.json・.github/workflows/)があるかを調べ、あれば mark_only=true も書く(wf-release の「印だけ付ける」ジョブが使う。設計 4.3)。
7
+ // 終了コード: 0 = 判定できた(skip の値を見る)/ 1 = main を取得できない(段階が分からないまま進めない)
8
+ import { isToolingPath } from "./promote.js";
9
+ /** GitHub の「PR のファイルの一覧」の上限(これ以上の PR は、一覧が切れているかもしれない) */
10
+ const GITHUB_FILES_LIMIT = 3000;
11
+ /**
12
+ * PR が変えるファイルに、版・ワークフローのもの(isToolingPath。設計 4.3)があるか。入力は環境変数 REPOSITORY・PR_NUMBER
13
+ * (どちらかが空なら、判定せず "no" = これまでの動き)。gh が失敗したら "unknown"(呼ぶ側が、素通りも・印も出さない側に倒す)
14
+ */
15
+ export async function toolingChange(box) {
16
+ const repo = box.env("REPOSITORY") ?? "";
17
+ const number = box.env("PR_NUMBER") ?? "";
18
+ if (repo === "" || number === "")
19
+ return { state: "no", path: "" };
20
+ const r = await box
21
+ // 移動(rename)の前のパスも見る。この API は、3000 ファイルまでしか返さない(それ以上は、確かめられないので unknown)
22
+ .run("gh", [
23
+ "api",
24
+ "--paginate",
25
+ `repos/${repo}/pulls/${number}/files?per_page=100`,
26
+ "--jq",
27
+ ".[] | .filename, (.previous_filename // empty)",
28
+ ])
29
+ .catch(() => null);
30
+ if (r === null || r.code !== 0)
31
+ return { state: "unknown", path: "" };
32
+ const paths = r.stdout
33
+ .split("\n")
34
+ .map((l) => l.trim())
35
+ .filter((l) => l !== "");
36
+ const path = paths.find((l) => isToolingPath(l));
37
+ if (path === undefined && paths.length >= GITHUB_FILES_LIMIT)
38
+ return { state: "unknown", path: "" };
39
+ return path === undefined ? { state: "no", path: "" } : { state: "yes", path };
40
+ }
41
+ /**
42
+ * origin/main の branches.txt から、有効な段階を読む(tier-switch v1 の load_tiers)。
43
+ * 行の前後の空白と CR を除き、# の行・空行を除く。main を取得できなければ null(呼ぶ側が、ジョブを失敗にする)。
44
+ * branches.txt がなければ、known=false(tierEnabled は、今までの動きのため、常に有効を返す)
45
+ */
46
+ export async function loadTiers(box) {
47
+ const shallow = await box.run("git", ["rev-parse", "--is-shallow-repository"]).catch(() => null);
48
+ // 浅いリポジトリなら --depth=1 で軽く、全履歴なら --depth を付けない(全履歴を浅くすると、あとのマージ・祖先の確認が失敗するため)
49
+ const depth = shallow?.stdout.trim() === "true" ? ["--depth=1"] : [];
50
+ const fetched = await box.run("git", ["fetch", "origin", "main", ...depth, "-q"]).catch(() => null);
51
+ if (fetched === null || fetched.code !== 0)
52
+ return null;
53
+ const shown = await box.run("git", ["show", "FETCH_HEAD:sf-tools/config/branches.txt"]).catch(() => null);
54
+ if (shown === null || shown.code !== 0) {
55
+ return {
56
+ known: false,
57
+ tiers: [],
58
+ warnings: [
59
+ "::warning title=段階の切り替え::main に sf-tools/config/branches.txt がありません。段階の切り替えを使わず、今までの動きにします。",
60
+ ],
61
+ };
62
+ }
63
+ const tiers = shown.stdout
64
+ .split("\n")
65
+ .map((l) => l.replace(/\r/g, "").trim())
66
+ .filter((l) => l !== "" && !l.startsWith("#"));
67
+ const warnings = tiers
68
+ .filter((t) => t !== "main" && t !== "staging" && t !== "develop")
69
+ .map((t) => `::warning title=段階の切り替え::branches.txt の「${t}」は、段階の名前ではないため、無視します。`);
70
+ return { known: true, tiers, warnings };
71
+ }
72
+ /** 段階が有効か。main は常に有効。develop は、staging も有効なときだけ有効。branches.txt がなければ、常に有効(今までの動き) */
73
+ export function tierEnabled(tier, sw) {
74
+ if (tier === "main")
75
+ return true;
76
+ if (!sw.known)
77
+ return true;
78
+ if (tier !== "staging" && tier !== "develop")
79
+ return false;
80
+ if (!sw.tiers.includes(tier))
81
+ return false;
82
+ if (tier === "develop" && !sw.tiers.includes("staging"))
83
+ return false;
84
+ return true;
85
+ }
86
+ /** コメント行・空行・セクション行([files] / [members])を除いた、実質的な内容があるか */
87
+ export function hasContent(box, path) {
88
+ if (!box.files.exists(path))
89
+ return false;
90
+ return box.files
91
+ .readText(path)
92
+ .split("\n")
93
+ .some((line) => !/^\s*(#|$|\[files\]|\[members\])/.test(line));
94
+ }
95
+ export async function runCheckBranch(box) {
96
+ const head = box.env("HEAD_REF") ?? "";
97
+ const base = box.env("BASE_REF") ?? "";
98
+ const outFile = box.env("GITHUB_OUTPUT");
99
+ const say = (line) => box.output.out(line);
100
+ const setSkip = (skip) => {
101
+ const line = `skip=${skip}\n`;
102
+ if (outFile)
103
+ box.files.appendText(outFile, line);
104
+ else
105
+ say(line.trim());
106
+ };
107
+ if (head === "") {
108
+ box.output.err("[ERROR] HEAD_REF(PR の元のブランチ)が空です。");
109
+ return 1;
110
+ }
111
+ // 段階の判定(doc/tier-scaling-design.md 3.4): マージ先から、検証に使う段階を決める。
112
+ // main → 判定しない(main を取得する通信の失敗で、main への PR の必須チェックを止めないため)
113
+ // staging → staging の段階 / それ以外 → develop の段階。段階として無効なら skip=true
114
+ if (base !== "main") {
115
+ const tier = base === "staging" ? "staging" : "develop";
116
+ const sw = await loadTiers(box);
117
+ if (sw === null) {
118
+ say("::error title=段階を判定できません::main を取得できません。段階を判定できないため、止めます。");
119
+ return 1;
120
+ }
121
+ for (const w of sw.warnings)
122
+ say(w);
123
+ if (!tierEnabled(tier, sw)) {
124
+ setSkip(true);
125
+ say(`::notice title=検証しません::この PR の検証に使う ${tier} は、branches.txt にない(develop は staging もないときを含む)ため、段階として無効です。この PR は検証しません。`);
126
+ return 0;
127
+ }
128
+ }
129
+ const deploy = `sf-tools/release/${head}/deploy-target.txt`;
130
+ const remove = `sf-tools/release/${head}/remove-target.txt`;
131
+ if (!hasContent(box, deploy) && !hasContent(box, remove)) {
132
+ setSkip(true);
133
+ say(`デプロイ対象なし(${deploy} / ${remove} に内容なし)のためスキップします。`);
134
+ // 版・ワークフローだけを変える PR は、組織へは何も出さないが、次の段階が R1 で止まらないよう、リリースの印だけは付ける
135
+ // (wf-release の「印だけ付ける」ジョブが見る。REPOSITORY・PR_NUMBER があるときだけ。変更の一覧を読めなければ、印は付けない)
136
+ const tooling = await toolingChange(box);
137
+ if (tooling.state === "yes") {
138
+ if (outFile)
139
+ box.files.appendText(outFile, "mark_only=true\n");
140
+ say(`${tooling.path} を変える PR のため、組織へは出さず、リリースの印だけを付けます。`);
141
+ }
142
+ else if (tooling.state === "unknown") {
143
+ say("::warning::変更の一覧を読めないため、リリースの印は付けません(版・ワークフローの PR なら、この実行を Re-run jobs してください)。");
144
+ }
145
+ }
146
+ else {
147
+ setSkip(false);
148
+ }
149
+ return 0;
150
+ }
@@ -0,0 +1,73 @@
1
+ // wf-validate.yml・wf-release.yml・wf-metasync.yml の「接続先組織を選択」「Salesforce 組織にログイン」の移し先(sft ci select-org・login)。
2
+ // 秘密(秘密鍵・コンシューマーキー)は、環境変数でだけ受け取り、画面にもログにも出さない。
3
+ // 秘密鍵のファイルは、本人だけが読める権限で作り、ログインの成否にかかわらず(失敗しても・例外でも)、必ず消す
4
+ import { EXIT } from "./exit-codes.js";
5
+ import { maskSecrets } from "./mask.js";
6
+ /**
7
+ * 「接続先組織を選択」: マージ先のブランチから、接続先(main → PROD・staging → STG・それ以外 → DEV)を決め、
8
+ * SF_CONSUMER_KEY・SF_USERNAME・SF_INSTANCE_URL を GITHUB_ENV に書く。
9
+ * 入力: BASE_REF と、段階ごとの SF_CONSUMER_KEY_<段階>・SF_USERNAME_<段階>・SF_INSTANCE_URL_<段階>
10
+ */
11
+ export function runSelectOrg(box) {
12
+ const base = box.env("BASE_REF") ?? "";
13
+ const [suffix, label] = base === "main" ? ["PROD", "main"] : base === "staging" ? ["STG", "staging"] : ["DEV", "develop"];
14
+ const file = box.env("GITHUB_ENV");
15
+ if (!file) {
16
+ box.output.err("[ERROR] GITHUB_ENV がありません。GitHub Actions の上で動かしてください。");
17
+ return EXIT.failure;
18
+ }
19
+ const line = (name) => `${name}=${box.env(`${name}_${suffix}`) ?? ""}\n`;
20
+ box.files.appendText(file, line("SF_CONSUMER_KEY") + line("SF_USERNAME") + line("SF_INSTANCE_URL"));
21
+ box.output.out(`接続先: ${label} の組織`);
22
+ return EXIT.ok;
23
+ }
24
+ /**
25
+ * 「Salesforce 組織にログイン」: JWT Bearer Flow。入力: SF_PRIVATE_KEY(base64)・SF_CONSUMER_KEY・SF_USERNAME・SF_INSTANCE_URL・ORG_ALIAS(既定 ci-org)。
26
+ * 秘密鍵が空・base64 でなければ、ログインを試みずに失敗にする
27
+ */
28
+ export async function runLogin(box, deps) {
29
+ const encoded = (box.env("SF_PRIVATE_KEY") ?? "").trim();
30
+ if (encoded === "") {
31
+ box.output.err("[ERROR] SF_PRIVATE_KEY(秘密鍵)が空です。Secret の設定を確認してください。");
32
+ return EXIT.failure;
33
+ }
34
+ let text;
35
+ try {
36
+ text = new TextDecoder().decode(Uint8Array.from(atob(encoded.replace(/\s+/g, "")), (c) => c.charCodeAt(0)));
37
+ }
38
+ catch {
39
+ box.output.err("[ERROR] SF_PRIVATE_KEY が base64 ではありません。Secret の設定を確認してください。");
40
+ return EXIT.failure;
41
+ }
42
+ let keyPath = null;
43
+ try {
44
+ keyPath = deps.write(text);
45
+ const r = await box.run("sf", [
46
+ "org",
47
+ "login",
48
+ "jwt",
49
+ "--client-id",
50
+ box.env("SF_CONSUMER_KEY") ?? "",
51
+ "--jwt-key-file",
52
+ keyPath,
53
+ "--username",
54
+ box.env("SF_USERNAME") ?? "",
55
+ "--instance-url",
56
+ box.env("SF_INSTANCE_URL") ?? "",
57
+ "--set-default",
58
+ "--alias",
59
+ box.env("ORG_ALIAS") || "ci-org",
60
+ ]);
61
+ if (r.output !== "")
62
+ box.output.out(maskSecrets(r.output));
63
+ return r.code === 0 ? EXIT.ok : EXIT.failure;
64
+ }
65
+ catch (e) {
66
+ box.output.err(`[ERROR] ログインを実行できません: ${maskSecrets(e instanceof Error ? e.message : String(e))}`);
67
+ return EXIT.failure;
68
+ }
69
+ finally {
70
+ if (keyPath !== null)
71
+ deps.remove(keyPath);
72
+ }
73
+ }
@@ -0,0 +1,193 @@
1
+ // wf-release.yml の中のシェルの移し先(sft ci release-info・release-run・release-mark・slack-release)。
2
+ // release-mark は、MARK_ONLY=true のとき、組織へは出さずに印だけを付ける(版・ワークフローの PR。呼ぶ前に R0〜R3 を確かめること)。
3
+ // 入力は、環境変数(利用者が決められる値は、シェルに直接埋め込まず、環境変数で受け取る: 雛形の決まり)。
4
+ // 終了コード: 0 = 成功/ 1 = 失敗(release-mark は、印を付けられなかったとき。やり直しは「Re-run jobs」)
5
+ import { EXIT } from "./exit-codes.js";
6
+ import { runRelease } from "./release.js";
7
+ /** リリース先(マージ先のブランチから決める)。main → prod・staging → staging・それ以外 → develop */
8
+ export function releaseTarget(base) {
9
+ if (base === "main")
10
+ return { label: "🚀 main の組織 (prod)", alias: "prod" };
11
+ if (base === "staging")
12
+ return { label: "🧪 staging の組織 (staging)", alias: "staging" };
13
+ return { label: "🔧 develop の組織 (develop)", alias: "develop" };
14
+ }
15
+ /** 日本時間の日時(yyyy-MM-dd HH:mm:ss JST。seconds=false なら秒なし) */
16
+ export function jst(date, seconds = true) {
17
+ const parts = new Intl.DateTimeFormat("en-CA", {
18
+ timeZone: "Asia/Tokyo",
19
+ year: "numeric",
20
+ month: "2-digit",
21
+ day: "2-digit",
22
+ hour: "2-digit",
23
+ minute: "2-digit",
24
+ second: "2-digit",
25
+ hourCycle: "h23",
26
+ }).formatToParts(date);
27
+ const p = (type) => parts.find((x) => x.type === type)?.value ?? "";
28
+ const day = `${p("year")}-${p("month")}-${p("day")} ${p("hour")}:${p("minute")}`;
29
+ return `${seconds ? `${day}:${p("second")}` : day} JST`;
30
+ }
31
+ /** 「リリース先を確認」: 注記と、実行の要約(GITHUB_STEP_SUMMARY)を出す */
32
+ export function runReleaseInfo(box) {
33
+ const base = box.env("BASE_REF") ?? "";
34
+ const title = box.env("PR_TITLE_RAW") ?? "";
35
+ const number = box.env("PR_NUMBER_RAW") ?? "";
36
+ const { label } = releaseTarget(base);
37
+ box.output.out(`::notice title=リリース先::${label} | ブランチ: ${base}`);
38
+ const summary = box.env("GITHUB_STEP_SUMMARY");
39
+ if (summary) {
40
+ const rows = [
41
+ "## 🎯 Salesforce Release",
42
+ "",
43
+ "| 項目 | 値 |",
44
+ "|------|-----|",
45
+ `| リリース先 | ${label} |`,
46
+ `| ブランチ | \`${base}\` |`,
47
+ ];
48
+ if (number !== "")
49
+ rows.push(`| PR | #${number} ${title} |`);
50
+ rows.push(`| 実行日時 | ${jst(box.clock.now())} |`);
51
+ box.files.appendText(summary, `${rows.join("\n")}\n`);
52
+ }
53
+ return EXIT.ok;
54
+ }
55
+ /** 「Salesforce にリリースを実行」: branch_name.txt にソースブランチを書いて、release --release --no-open --target <別名> を動かす */
56
+ export async function runReleaseRun(box, deps) {
57
+ const source = box.env("SOURCE_BRANCH") ?? "";
58
+ if (source === "") {
59
+ box.output.err("[ERROR] SOURCE_BRANCH(PR の元のブランチ)が空です。");
60
+ return EXIT.failure;
61
+ }
62
+ const { alias } = releaseTarget(box.env("BASE_REF") ?? "");
63
+ box.files.makeDir("sf-tools/release");
64
+ box.files.writeText("sf-tools/release/branch_name.txt", `${source}\n`);
65
+ return runRelease(["--release", "--no-open", "--target", alias], box, deps);
66
+ }
67
+ /**
68
+ * 「リリースの印を付ける」: PR の先端のコミットに、commit status(context sf-tools/released-<段階>)を付ける。
69
+ * 次の段階の一方通行の確認(R1)が、この印を見る(doc/one-way-promotion-design.md 3.1)。付けられなければ 3 回まで試し、だめなら失敗にする。
70
+ * - 通常: リリースが成功したあとに呼ぶ。失敗は、組織には出ているが印がない状態(次の段階が R1 で止まる側に倒れる)。やり直しは「Re-run jobs」
71
+ * - MARK_ONLY=true: デプロイ対象がなく、版・ワークフローだけを変える PR。組織へは何も出していない。呼ぶ前に、wf-release が R0〜R3 を確かめる
72
+ * (確かめずに付けると、前の段階を通っていない PR に、印を与えてしまう)
73
+ */
74
+ export async function runReleaseMark(box) {
75
+ const repo = box.env("REPOSITORY") ?? "";
76
+ const sha = box.env("HEAD_SHA") ?? "";
77
+ const base = box.env("BASE_REF") ?? "";
78
+ const pr = box.env("PR_NUMBER") ?? "";
79
+ const runId = box.env("RUN_ID") ?? "";
80
+ if (repo === "" || sha === "" || base === "" || runId === "") {
81
+ box.output.err("[ERROR] REPOSITORY・HEAD_SHA・BASE_REF・RUN_ID のどれかが空です。");
82
+ return EXIT.failure;
83
+ }
84
+ const runUrl = `https://github.com/${repo}/actions/runs/${runId}`;
85
+ // MARK_ONLY=true: デプロイ対象がない版・ワークフローの PR。組織へは出していないが、次の段階が R1 で止まらないよう、印だけ付ける
86
+ const desc = box.env("MARK_ONLY") === "true"
87
+ ? `PR #${pr} を ${base} に取り込みました(組織へのリリースはありません: 版・ワークフローの PR。${jst(box.clock.now(), false)})`
88
+ : `PR #${pr} を ${base} の組織にリリースしました(${jst(box.clock.now(), false)})`;
89
+ for (let i = 1; i <= 3; i++) {
90
+ const r = await box
91
+ .run("gh", [
92
+ "api",
93
+ "-X",
94
+ "POST",
95
+ `repos/${repo}/statuses/${sha}`,
96
+ "-f",
97
+ "state=success",
98
+ "-f",
99
+ `context=sf-tools/released-${base}`,
100
+ "-f",
101
+ `target_url=${runUrl}`,
102
+ "-f",
103
+ `description=${desc}`,
104
+ ])
105
+ .catch(() => null);
106
+ if (r !== null && r.code === 0) {
107
+ box.output.out(`::notice title=リリースの印::${sha.slice(0, 7)} に sf-tools/released-${base} を付けました。`);
108
+ return EXIT.ok;
109
+ }
110
+ await box.clock.sleep(i * 5000);
111
+ }
112
+ box.output.out(`::error title=リリースの印を付けられません::${box.env("MARK_ONLY") === "true" ? "(組織へのリリースはありません)" : "組織へのリリースは成功しましたが、"}${sha.slice(0, 7)} に sf-tools/released-${base} を付けられませんでした。この実行を「Re-run jobs」でやり直してください。`);
113
+ return EXIT.failure;
114
+ }
115
+ /** Slack に送る文字として安全にする(制御文字の除去・Slack の特殊文字 & < > の置き換え。" と \ は、JSON にするときに処理される) */
116
+ export function slackEscape(text) {
117
+ const visible = [...text].filter((c) => c.charCodeAt(0) >= 0x20).join("");
118
+ return visible.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
119
+ }
120
+ /** Slack に送る本文(リリースの結果)。jobStatus は success か、それ以外。promoteOutcome が failure なら、一方通行の確認で止めた */
121
+ export function releaseSlackText(input) {
122
+ const { label } = releaseTarget(input.base);
123
+ let icon;
124
+ let status;
125
+ if (input.jobStatus === "success") {
126
+ icon = ":white_check_mark:";
127
+ status = "リリース成功";
128
+ }
129
+ else if (input.promoteOutcome === "failure") {
130
+ icon = ":no_entry:";
131
+ status = "リリースを止めました(一方通行の決まり: 前の段階に出していない・積み重ねの抜け・環境ブランチなど。組織は変わっていません)";
132
+ }
133
+ else {
134
+ icon = ":x:";
135
+ status = "リリース失敗";
136
+ }
137
+ const pr = input.number === "" ? "" : `\n• PR: #${slackEscape(input.number)} ${slackEscape(input.title)}`;
138
+ const runUrl = `https://github.com/${input.repo}/actions/runs/${input.runId}`;
139
+ return `${icon} *Salesforce Release ${status}*\n• リリース先: ${label}\n• ブランチ: \`${slackEscape(input.base)}\`${pr}\n• 実行日時: ${jst(input.now)}\n• <${runUrl}|Actions ログを見る>`;
140
+ }
141
+ /**
142
+ * Slack の chat.postMessage に送る。送信の失敗は ::warning を出すだけ(呼ぶ側のステップは、失敗にしない)。
143
+ * 応答の ok が true でなければ、失敗とみなす(Token の誤り・Bot がチャンネルにいないなど)。text は、slackEscape 済みの値で組む
144
+ */
145
+ export async function postSlack(box, channel, token, text) {
146
+ const payload = JSON.stringify({ channel: slackEscape(channel), text });
147
+ const r = await box
148
+ .run("curl", [
149
+ "-sS",
150
+ "-X",
151
+ "POST",
152
+ "https://slack.com/api/chat.postMessage",
153
+ "-H",
154
+ `Authorization: Bearer ${token}`,
155
+ "-H",
156
+ "Content-Type: application/json",
157
+ "-d",
158
+ payload,
159
+ ])
160
+ .catch(() => null);
161
+ const response = r?.stdout ?? "";
162
+ box.output.out(`Slack の応答: ${response}`);
163
+ let ok = false;
164
+ try {
165
+ ok = JSON.parse(response).ok === true;
166
+ }
167
+ catch {
168
+ ok = false;
169
+ }
170
+ if (!ok) {
171
+ box.output.out("::warning title=Slack 通知の失敗::Slack への通知が、失敗しました(応答の ok が true ではありません)。Secret SLACK_BOT_TOKEN・Variable SLACK_CHANNEL_ID を確認してください。");
172
+ }
173
+ }
174
+ /**
175
+ * 「Slack に結果を通知」: 送信の失敗は ::warning を出すだけで、このステップは失敗にしない(リリースの成否を、通知の失敗で変えないため)。
176
+ * 応答の ok が true でなければ、失敗とみなす(Token の誤り・Bot がチャンネルにいないなど)
177
+ */
178
+ export async function runSlackRelease(box) {
179
+ const token = box.env("SLACK_BOT_TOKEN") ?? "";
180
+ const channel = box.env("SLACK_CHANNEL_ID") ?? "";
181
+ const text = releaseSlackText({
182
+ base: box.env("BASE_REF") ?? "",
183
+ title: box.env("PR_TITLE_RAW") ?? "",
184
+ number: box.env("PR_NUMBER_RAW") ?? "",
185
+ repo: box.env("REPOSITORY") ?? "",
186
+ runId: box.env("RUN_ID") ?? "",
187
+ jobStatus: box.env("JOB_STATUS") ?? "",
188
+ promoteOutcome: box.env("PROMOTE_OUTCOME") ?? "",
189
+ now: box.clock.now(),
190
+ });
191
+ await postSlack(box, channel, token, text);
192
+ return EXIT.ok;
193
+ }