@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,684 @@
1
+ // sft metasync: 組織のメタデータを、main ブランチへ同期する(シェル版の bin/sf-metasync.sh と phases/metasync/ の移し先。
2
+ // doc/rebuild-design.md 11.2 の段階 2。仕様の正本は doc/sf-metasync-redesign.md)。
3
+ // 計画・反映・検知・指紋・秘密の検査の本体は、すでに Node の lib/metasync.js(そのまま引き継ぐ)。ここは、順序・Git・確認・終了コードを受け持つ。
4
+ // 外との出入りは、道具の箱(git・sf・gh・curl・node・ファイル)と、渡された部品(一時フォルダ・確認・設定の場所)だけを通す。
5
+ // 終了コード: 0 = 同期した・変更がなかった/ 1 = 中断/ 3 = 同期したが、削除の保留(S2・S3・S4)がある/
6
+ // 4 = 秘密の疑いで止めた/ 5 = 公開リポジトリ(または確認できない)で止めた
7
+ import { EXIT } from "./exit-codes.js";
8
+ import { maskSecrets } from "./mask.js";
9
+ import { originRepo } from "./origin.js";
10
+ export const METASYNC_EXIT = { reserved: 3, secret: 4, publicRepo: 5 };
11
+ /** 止める(シェル版の die・exit に当たる)。いちばん外で受けて、後始末のあとに、終了コードにする */
12
+ class Stop extends Error {
13
+ code;
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.code = code;
17
+ }
18
+ }
19
+ const COMMIT_SUBJECT_PREFIX = "定期更新: Salesforce変更の自動反映";
20
+ const TRANSIENT = /MetadataTransferError|UNKNOWN_EXCEPTION|ERROR_HTTP_404|ECONNRESET|ETIMEDOUT|socket hang up|fetch failed|503|Service Unavailable/;
21
+ const STATE_FILE = "sf-tools/metasync/state.json";
22
+ const FP_STATE_FILE = "sf-tools/metasync/fingerprint.json";
23
+ const METADATA_CONFIG = "./sf-tools/config/metadata.txt";
24
+ function readMode(box, name, fallback, allowed) {
25
+ const v = (box.env(name) || fallback);
26
+ if (!allowed.includes(v))
27
+ throw new Stop(EXIT.failure, `${name} は ${allowed.join(" / ")} のどれかにしてください: ${v}`);
28
+ return v;
29
+ }
30
+ /** Slack の本文として安全にする(制御文字の除去(改行・タブ以外)・Slack の特殊文字 & < > の置き換え) */
31
+ function slackSafe(text) {
32
+ const kept = [...text].filter((c) => {
33
+ const n = c.charCodeAt(0);
34
+ return n >= 0x20 || n === 0x0a || n === 0x09;
35
+ });
36
+ return kept.join("").replace(/\r/g, "").replace(/\t/g, " ").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
37
+ }
38
+ export async function runMetasync(args, box, deps) {
39
+ const log = (level, text) => box.output.err(`[${level}] ${text}`);
40
+ const isActions = box.env("GITHUB_ACTIONS") === "true";
41
+ let dryRun = false;
42
+ let assumeYes = false;
43
+ let allowMass = false;
44
+ let full = false;
45
+ let jsonEcho = false;
46
+ let applied = false;
47
+ let committed = false;
48
+ let stashUsed = false;
49
+ let stateWritten = false;
50
+ let fpWritten = false;
51
+ let workDir = "";
52
+ let pkgPath = "";
53
+ let originalBranch = "";
54
+ const git = (...a) => box.run("git", a);
55
+ const gitOk = async (...a) => (await git(...a).catch(() => null))?.code === 0;
56
+ const must = async (text, ...a) => {
57
+ const r = await git(...a).catch(() => null);
58
+ if (r === null || r.code !== 0)
59
+ throw new Stop(EXIT.failure, text);
60
+ return r.stdout;
61
+ };
62
+ /** Node の部品(lib/metasync.js)を動かす。出力は、1 行ずつ、画面に出す(先頭の [WARNING]・[ERROR] は、そのレベルで) */
63
+ const node = async (sub, a) => {
64
+ const r = await box.run(box.env("SF_METASYNC_NODE") || "node", [deps.metasyncJs, sub, ...a]);
65
+ return { code: r.code, stdout: r.output, only: r.stdout }; // only は標準出力だけ(値を受け取るときは、標準エラーを混ぜない)
66
+ };
67
+ const logNode = (text) => {
68
+ for (const line of text.split("\n")) {
69
+ if (line === "")
70
+ continue;
71
+ if (line.startsWith("[WARNING] "))
72
+ log("WARNING", line.slice(10));
73
+ else if (line.startsWith("[ERROR] "))
74
+ log("ERROR", line.slice(8));
75
+ else
76
+ log("INFO", line);
77
+ }
78
+ };
79
+ /** Slack に通知する。失敗は WARNING にとどめる(止める判断は、すでに済んでいる)。トークンは、引数に出さず、標準入力の設定で渡す */
80
+ const notifySlack = async (headline, ...lines) => {
81
+ const token = box.env("SLACK_BOT_TOKEN") ?? "";
82
+ const channel = (box.env("SLACK_CHANNEL_ID") ?? "").replace(/["\\]/g, "");
83
+ if (token === "" || channel === "") {
84
+ log("WARNING", "Slack に通知できません(SLACK_BOT_TOKEN・SLACK_CHANNEL_ID が未設定です)。");
85
+ return;
86
+ }
87
+ let text = [headline, ...lines].join("\n");
88
+ const runId = box.env("GITHUB_RUN_ID");
89
+ const repo = box.env("GITHUB_REPOSITORY");
90
+ if (runId && repo)
91
+ text += `\n実行: ${box.env("GITHUB_SERVER_URL") || "https://github.com"}/${repo}/actions/runs/${runId}`;
92
+ const r = await box
93
+ .run("curl", [
94
+ "-sS",
95
+ "--max-time",
96
+ "20",
97
+ "-K",
98
+ "-",
99
+ "-X",
100
+ "POST",
101
+ "https://slack.com/api/chat.postMessage",
102
+ "-H",
103
+ "Content-Type: application/json; charset=utf-8",
104
+ "--data",
105
+ JSON.stringify({ channel, text: slackSafe(text) }),
106
+ ], { input: `header = "Authorization: Bearer ${token}"\n` })
107
+ .catch(() => null);
108
+ const resp = r?.stdout ?? "";
109
+ if (resp.includes('"ok":true')) {
110
+ log("INFO", "Slack に通知しました。");
111
+ return;
112
+ }
113
+ const err = /"error":"([^"]*)"/.exec(resp)?.[1];
114
+ if (err !== undefined)
115
+ log("WARNING", `Slack への通知に失敗しました(${err.slice(0, 60)})。SLACK_BOT_TOKEN・SLACK_CHANNEL_ID を確認してください。`);
116
+ else
117
+ log("WARNING", `Slack への通知に失敗しました(接続または応答の異常。curl の終了: ${r !== null && r.code === 0 ? "正常" : "失敗"})。`);
118
+ };
119
+ const ask = async (question) => {
120
+ if ((await deps.confirm(question)) !== "yes")
121
+ throw new Stop(EXIT.failure, "中断しました。");
122
+ };
123
+ const cleanup = async () => {
124
+ if (applied && !committed && pkgPath !== "") {
125
+ await git("reset", "-q", "HEAD", "--", pkgPath).catch(() => null);
126
+ await git("checkout", "HEAD", "--", pkgPath).catch(() => null);
127
+ await git("clean", "-fdq", "--", pkgPath).catch(() => null);
128
+ }
129
+ for (const [written, file] of [
130
+ [stateWritten, STATE_FILE],
131
+ [fpWritten, FP_STATE_FILE],
132
+ ]) {
133
+ if (!written || committed)
134
+ continue;
135
+ await git("reset", "-q", "HEAD", "--", file).catch(() => null);
136
+ const back = await git("checkout", "HEAD", "--", file).catch(() => null);
137
+ if (back === null || back.code !== 0)
138
+ box.files.removeFile(file);
139
+ }
140
+ if (originalBranch !== "")
141
+ await git("checkout", originalBranch).catch(() => null);
142
+ if (stashUsed)
143
+ await git("stash", "pop").catch(() => null);
144
+ if (workDir !== "")
145
+ deps.removeDir(workDir);
146
+ };
147
+ try {
148
+ log("HEADER", "メタデータ同期(Salesforce -> Git)を開始します (sf-metasync)");
149
+ const version = await box.run("sf", ["--version"]).catch(() => null);
150
+ if (version === null || version.code !== 0)
151
+ throw new Stop(EXIT.failure, "sf(Salesforce CLI)を動かせません。npm 版の sf が必要です。");
152
+ for (const a of args) {
153
+ if (a === "--json" || a === "-j")
154
+ jsonEcho = true;
155
+ else if (a === "--dry-run" || a === "-n")
156
+ dryRun = true;
157
+ else if (a === "--yes" || a === "-y")
158
+ assumeYes = true;
159
+ else if (a === "--full")
160
+ full = true;
161
+ else if (a === "--allow-mass-delete")
162
+ allowMass = true;
163
+ else if (a === "--verbose" || a === "-v")
164
+ continue;
165
+ else
166
+ throw new Stop(EXIT.failure, a.startsWith("--") ? `不明なオプションです: ${a}` : `不明な引数です: ${a}`);
167
+ }
168
+ if (assumeYes && !dryRun)
169
+ throw new Stop(EXIT.failure, "-y / --yes は --dry-run と一緒にだけ指定できます。");
170
+ if (allowMass && isActions)
171
+ throw new Stop(EXIT.failure, "--allow-mass-delete は GitHub Actions 上では指定できません。");
172
+ const detectMode = readMode(box, "SF_METASYNC_DETECT", "off", ["off", "shadow", "on"]);
173
+ const fpMode = readMode(box, "SF_METASYNC_FINGERPRINT", "off", ["off", "shadow", "on"]);
174
+ const scanMode = readMode(box, "SF_METASYNC_SECRET_SCAN", "shadow", ["off", "shadow", "on"]);
175
+ const extraMode = readMode(box, "SF_METASYNC_EXTRA", "off", ["off", "on"]);
176
+ // --- 接続先の組織(main の組織) ---
177
+ let repoFull = "";
178
+ let targetOrg;
179
+ if (isActions) {
180
+ repoFull = box.env("GITHUB_REPOSITORY") ?? "";
181
+ targetOrg = "prod";
182
+ const shown = await box.run("sf", ["org", "display", "--target-org", targetOrg, "--json"], { input: "" }).catch(() => null);
183
+ if (shown === null || shown.code !== 0)
184
+ throw new Stop(EXIT.failure, `prod エイリアスの組織情報を取得できませんでした(sf org display --target-org ${targetOrg} が失敗しました)。`);
185
+ log("INFO", `接続先組織: ${targetOrg}`);
186
+ }
187
+ else {
188
+ const o = await originRepo(box);
189
+ if (o.kind !== "ok")
190
+ throw new Stop(EXIT.failure, "origin から、GitHub の owner/repo を特定できません。");
191
+ repoFull = `${o.owner}/${o.repo}`;
192
+ const idRun = await box.run("gh", ["variable", "get", "SF_ORG_ID_PROD", "-R", repoFull]).catch(() => null);
193
+ const orgId = (idRun?.code === 0 ? idRun.stdout : "").replace(/\r/g, "").trim();
194
+ if (orgId === "")
195
+ throw new Stop(EXIT.failure, `GitHub の Variable SF_ORG_ID_PROD を読み取れませんでした(${repoFull})。`);
196
+ const found = await findUsernameByOrgId(box, orgId);
197
+ if (found === null)
198
+ throw new Stop(EXIT.failure, `この PC の sf に、組織 ID ${orgId}(SF_ORG_ID_PROD。main の組織)の組織が、ログインされていません。`);
199
+ targetOrg = found;
200
+ const shown = await box.run("sf", ["org", "display", "--target-org", targetOrg, "--json"], { input: "" }).catch(() => null);
201
+ if (shown === null || shown.code !== 0)
202
+ throw new Stop(EXIT.failure, `接続先の組織情報を取得できませんでした(sf org display --target-org ${targetOrg} が失敗しました)。`);
203
+ log("INFO", `接続先組織: ${targetOrg}(組織 ID ${orgId}。GitHub の SF_ORG_ID_PROD と一致)`);
204
+ }
205
+ const head = await git("symbolic-ref", "-q", "--short", "HEAD").catch(() => null);
206
+ if (head === null || head.code !== 0 || head.stdout.trim() === "") {
207
+ throw new Stop(EXIT.failure, "現在の HEAD がブランチを指していません(detached HEAD)。元のブランチに戻れないため、中断します。");
208
+ }
209
+ originalBranch = head.stdout.trim();
210
+ if (!box.files.exists(METADATA_CONFIG))
211
+ throw new Stop(EXIT.failure, `メタデータ設定ファイルが見つかりません: ${METADATA_CONFIG}`);
212
+ const types = box.files
213
+ .readText(METADATA_CONFIG)
214
+ .split("\n")
215
+ .map((l) => l.replace(/\r$/, ""))
216
+ .filter((l) => !/^\s*#/.test(l) && l.trim() !== "");
217
+ log("INFO", `対象メタデータ (${types.length} 件): ${types.join(" ")}`);
218
+ // --- 管理者向けの警告と確認(手元のときだけ) ---
219
+ if (!isActions) {
220
+ for (const l of [
221
+ "",
222
+ "このコマンドは管理者専用です",
223
+ "管理者以外は絶対に実行しないでください",
224
+ "",
225
+ "main の Salesforce 組織からメタデータを取得し",
226
+ "main ブランチへ push します。",
227
+ ])
228
+ box.output.err(l);
229
+ if (!assumeYes)
230
+ await ask("続行しますか?");
231
+ }
232
+ // --- 公開リポジトリでは実行しない(取得の前。切り替えなし) ---
233
+ await checkVisibility();
234
+ // --- main へ切り替え・リモートの取り込み ---
235
+ if (originalBranch !== "main") {
236
+ log("INFO", `main ブランチへ切り替えます(現在: ${originalBranch})...`);
237
+ if (!(await gitOk("diff-index", "--quiet", "HEAD", "--"))) {
238
+ log("INFO", "ローカルの変更を一時退避します (git stash)...");
239
+ await must("git stash に失敗しました。", "stash");
240
+ stashUsed = true;
241
+ }
242
+ await must("main ブランチへの切替に失敗しました。", "checkout", "main");
243
+ }
244
+ log("SUCCESS", "main ブランチへの切替完了");
245
+ if (!(await gitOk("diff-index", "--quiet", "HEAD", "--"))) {
246
+ throw new Stop(EXIT.failure, "main ブランチに、追跡中のファイルの未コミットの変更があります(Salesforce 組織の内容を正として同期するため、ローカルの変更は、同期に含めません)。");
247
+ }
248
+ if (!isActions) {
249
+ const untracked = (await must("追跡していないファイルを確認できません。", "ls-files", "--others", "--exclude-standard", "--", ".", ":!sf-tools/release"))
250
+ .split("\n")
251
+ .filter((l) => l !== "")
252
+ .slice(0, 5);
253
+ if (untracked.length > 0)
254
+ throw new Stop(EXIT.failure, `main ブランチに、追跡していないファイルがあります(同期のコミットに含まれてしまうため中止します): ${untracked.join(" ")}`);
255
+ }
256
+ if (!(await gitOk("fetch", "origin")))
257
+ log("WARNING", "git fetch に失敗しました。ローカルキャッシュで続行します。");
258
+ if (!(await gitOk("pull", "origin", "main", "--rebase"))) {
259
+ await git("rebase", "--abort").catch(() => null);
260
+ throw new Stop(EXIT.failure, "Git 更新に失敗しました。");
261
+ }
262
+ log("SUCCESS", "Git 更新完了");
263
+ // --- 取得先の一時プロジェクト ---
264
+ const root = await node("root", ["--repo", "."]);
265
+ pkgPath = root.only.trim();
266
+ if (root.code !== 0 || pkgPath === "") {
267
+ if (root.stdout.trim() !== "")
268
+ logNode(root.stdout);
269
+ throw new Stop(EXIT.failure, "取得先の一時プロジェクトの準備に失敗しました。");
270
+ }
271
+ workDir = deps.makeTempDir();
272
+ const inWork = (name) => `${workDir}/${name}`;
273
+ box.files.writeText(inWork("sfdx-project.json"), box.files.readText("sfdx-project.json"));
274
+ if (box.files.exists(".forceignore"))
275
+ box.files.writeText(inWork(".forceignore"), box.files.readText(".forceignore"));
276
+ box.files.makeDir(inWork(pkgPath));
277
+ const retrieveJson = inWork("retrieve.json");
278
+ const planFile = inWork("plan.tsv");
279
+ const recentFiles = inWork("recent.txt");
280
+ log("SUCCESS", `一時プロジェクトの準備完了(パッケージのフォルダ: ${pkgPath})`);
281
+ // --- 変更の検知と一覧の指紋 ---
282
+ let detectRc = -1;
283
+ let detectStateNew = "";
284
+ if (detectMode !== "off") {
285
+ const table = `${deps.configDir}/metasync-detect.txt`;
286
+ if (!box.files.exists(table))
287
+ log("WARNING", `検知の区分の表が見つかりません(${table})。検知は行わず、全件取得します。`);
288
+ else {
289
+ detectStateNew = inWork("state.new.json");
290
+ log("INFO", `変更の検知を行います(SF_METASYNC_DETECT=${detectMode}。読み取りのみ)...`);
291
+ const r = await node("detect", [
292
+ "--org",
293
+ targetOrg,
294
+ "--types-file",
295
+ METADATA_CONFIG,
296
+ "--table",
297
+ table,
298
+ "--state",
299
+ STATE_FILE,
300
+ "--out-state",
301
+ detectStateNew,
302
+ ]);
303
+ logNode(r.stdout);
304
+ detectRc = r.code;
305
+ if (detectRc !== 0 && detectRc !== 10) {
306
+ if (detectRc !== 11)
307
+ log("WARNING", `検知が異常終了しました(終了コード ${detectRc})。不明として扱い、全件取得します。`);
308
+ detectRc = 11;
309
+ }
310
+ }
311
+ }
312
+ const extraTable = `${deps.configDir}/metasync-extra.txt`;
313
+ let fpRc = -1;
314
+ let fpStateNew = "";
315
+ let fpReport = "";
316
+ if (fpMode !== "off") {
317
+ const table = `${deps.configDir}/metasync-fingerprint.txt`;
318
+ if (!box.files.exists(table))
319
+ log("WARNING", `指紋の種類の表が見つかりません(${table})。指紋は作りません。`);
320
+ else {
321
+ fpStateNew = inWork("fp.new.json");
322
+ fpReport = inWork("fp.report.json");
323
+ log("INFO", `一覧の指紋を作ります(SF_METASYNC_FINGERPRINT=${fpMode}。読み取りのみ)...`);
324
+ const scope = ["--types-file", METADATA_CONFIG];
325
+ if (extraMode !== "off" && box.files.exists(extraTable))
326
+ scope.push("--extra-config", extraTable);
327
+ const r = await node("fingerprint", [
328
+ "--org",
329
+ targetOrg,
330
+ "--fp-config",
331
+ table,
332
+ "--repo",
333
+ ".",
334
+ ...scope,
335
+ "--state",
336
+ FP_STATE_FILE,
337
+ "--out-state",
338
+ fpStateNew,
339
+ "--out-report",
340
+ fpReport,
341
+ ]);
342
+ logNode(r.stdout);
343
+ fpRc = r.code;
344
+ if (fpRc !== 0 && fpRc !== 10) {
345
+ if (fpRc !== 11)
346
+ log("WARNING", `指紋の作成が異常終了しました(終了コード ${fpRc})。不明として扱います(取得は、省かずに行います)。`);
347
+ fpRc = 11;
348
+ }
349
+ }
350
+ }
351
+ // 取得を省くのは、on の仕組みが 1 つ以上あり、on の仕組みが「すべて」変更なし(0)のときだけ
352
+ if (detectMode === "on" || fpMode === "on") {
353
+ let skipOk = true;
354
+ if (detectMode === "on" && detectRc !== 0)
355
+ skipOk = false;
356
+ if (fpMode === "on" && fpRc !== 0)
357
+ skipOk = false;
358
+ const by = detectMode === "on" && fpMode === "on" ? "検知と一覧の指紋" : detectMode === "on" ? "検知" : "一覧の指紋";
359
+ if (!skipOk && detectMode === "on" && fpMode === "on" && (detectRc === 0 || fpRc === 0)) {
360
+ log("INFO", `検知と一覧の指紋の結果が分かれたため(検知: ${detectRc} / 指紋: ${fpRc}。0 = 変更なし)、全件取得します。`);
361
+ }
362
+ if (skipOk) {
363
+ const ahead = (await git("rev-list", "--count", "origin/main..HEAD").catch(() => null))?.stdout.trim() ?? "0";
364
+ if (full)
365
+ log("INFO", `--full が指定されているため、${by}の結果にかかわらず、全件取得します。`);
366
+ else if (dryRun)
367
+ log("INFO", `--dry-run のため、${by}の結果にかかわらず、全件取得して計画を作ります(本番の実行では、取得を省きます)。`);
368
+ else if (/^\d+$/.test(ahead) && Number(ahead) > 0)
369
+ log("INFO", `未プッシュのコミットがあるため、${by}の結果にかかわらず、全件取得します。`);
370
+ else {
371
+ if (fpMode === "shadow" && fpRc === 10)
372
+ log("WARNING", "指紋は『変更あり』ですが、検知は『変更なし』でした。検知の見逃しの可能性があります(今回は取得を省きます。毎日の --full で反映されます)。");
373
+ if (detectMode === "shadow" && detectRc === 10)
374
+ log("WARNING", "検知は『変更あり』ですが、指紋は『変更なし』でした。指紋の見逃しの可能性があります(今回は取得を省きます。毎日の --full で反映されます)。");
375
+ log("SUCCESS", `完了: ${by}の結果、Salesforce 組織側に変更はありませんでした(全件取得を省きました)。`);
376
+ return EXIT.ok;
377
+ }
378
+ }
379
+ }
380
+ // --- 組織から取得 ---
381
+ const retryWait = Number(box.env("SF_METASYNC_RETRY_WAIT") || "60");
382
+ const retrieve = async (label, extraArgs, jsonFile) => {
383
+ for (let attempt = 1; attempt <= 2; attempt++) {
384
+ log("INFO", `${label}(試行 ${attempt}/2)...`);
385
+ const r = await box
386
+ .run("sf", ["project", "retrieve", "start", "--target-org", targetOrg, "--ignore-conflicts", "--json", ...extraArgs], {
387
+ cwd: workDir,
388
+ })
389
+ .catch(() => null);
390
+ box.files.writeText(jsonFile, r?.stdout ?? "");
391
+ if (jsonEcho)
392
+ log("INFO", `取得の応答(先頭 2000 文字): ${maskSecrets((r?.stdout ?? "").slice(0, 2000))}`);
393
+ if (r !== null && r.code === 0)
394
+ return true;
395
+ const detail = maskSecrets(`${r?.stderr ?? ""}`.slice(0, 600) + (r?.stdout ?? "").slice(0, 600)).replace(/\n/g, " ");
396
+ log("WARNING", `取得が失敗しました(終了コード ${r?.code ?? "起動できません"}): ${detail}`);
397
+ if (attempt === 1 && TRANSIENT.test(`${r?.stdout ?? ""}${r?.stderr ?? ""}`)) {
398
+ log("WARNING", `一時的なエラーの可能性があるため、${retryWait} 秒待って 1 回だけやり直します。`);
399
+ await box.clock.sleep(retryWait * 1000);
400
+ continue;
401
+ }
402
+ break;
403
+ }
404
+ return false;
405
+ };
406
+ const typeArgs = types.flatMap((t) => ["--metadata", t]);
407
+ if (!(await retrieve(`組織からメタデータを取得します(一時プロジェクトへ。種類 ${types.length} 件)`, typeArgs, retrieveJson))) {
408
+ throw new Stop(EXIT.failure, "メタデータの取得に失敗しました。");
409
+ }
410
+ log("SUCCESS", "メタデータ取得完了");
411
+ // --- 追加の取得(失敗しても止めない) ---
412
+ let extraState = "off";
413
+ const extraJson = inWork("extra.retrieve.json");
414
+ const extraManifest = inWork("extra.package.xml");
415
+ if (extraMode === "on") {
416
+ extraState = "failed";
417
+ if (!box.files.exists(extraTable)) {
418
+ log("WARNING", `追加の取得の表が見つかりません(${extraTable})。追加の取得は行いません(その種類の削除は保留します)。`);
419
+ }
420
+ else {
421
+ log("INFO", `追加の取得: 名前を集めます(SF_METASYNC_EXTRA=${extraMode}。読み取りのみ)...`);
422
+ const m = await node("manifest", ["--org", targetOrg, "--extra-config", extraTable, "--repo", ".", "--out", extraManifest]);
423
+ logNode(m.stdout);
424
+ if (m.code === 12) {
425
+ extraState = "ok";
426
+ log("INFO", "追加の取得: 取る部品がありません。");
427
+ }
428
+ else if (m.code !== 0) {
429
+ log("WARNING", "追加の取得: 名前を集められませんでした。今回は取りません(その種類と標準オブジェクトの部品の削除は保留します)。");
430
+ }
431
+ else if (await retrieve("追加の取得: 組織から取得します(package.xml)", ["--manifest", extraManifest], extraJson)) {
432
+ extraState = "ok";
433
+ log("SUCCESS", "追加の取得: 完了");
434
+ }
435
+ else {
436
+ log("WARNING", "追加の取得は行えませんでした。その種類と標準オブジェクトの部品の削除は保留します。");
437
+ }
438
+ }
439
+ }
440
+ // --- 直近のマージされたファイル(S5 用)。失敗しても、空の一覧にして続ける ---
441
+ const recent = await git("log", "--first-parent", "-m", "--since=24 hours ago", "--invert-grep", `--grep=^${COMMIT_SUBJECT_PREFIX}`, "--name-only", "--format=", "HEAD", "--", pkgPath).catch(() => null);
442
+ box.files.writeText(recentFiles, recent !== null && recent.code === 0 ? recent.stdout : "");
443
+ // --- 計画 ---
444
+ const dirsTable = `${deps.configDir}/metadata-dirs.txt`;
445
+ const planArgs = [
446
+ "--repo",
447
+ ".",
448
+ "--fetched",
449
+ workDir,
450
+ "--types-file",
451
+ METADATA_CONFIG,
452
+ "--dirs-table",
453
+ dirsTable,
454
+ "--out",
455
+ planFile,
456
+ "--recent-files",
457
+ recentFiles,
458
+ "--retrieve-json",
459
+ retrieveJson,
460
+ ];
461
+ if (allowMass)
462
+ planArgs.push("--allow-mass-delete");
463
+ if (extraMode === "on" && !box.files.exists(extraTable)) {
464
+ throw new Stop(EXIT.failure, `追加の取得の表が見つかりません(${extraTable})。標準オブジェクトの部品を守れないため、計画を作りません(sf-tools の更新を確認してください)。`);
465
+ }
466
+ if (box.files.exists(extraTable)) {
467
+ if (extraMode === "on") {
468
+ planArgs.push("--extra-config", extraTable, "--extra-json", extraJson, "--extra-state", extraState);
469
+ if (extraState === "ok" && box.files.exists(extraManifest))
470
+ planArgs.push("--extra-manifest", extraManifest);
471
+ }
472
+ else
473
+ planArgs.push("--extra-config", extraTable, "--extra-state", "off");
474
+ }
475
+ const planned = await node("plan", planArgs);
476
+ logNode(planned.stdout);
477
+ if (planned.code !== 0 && planned.code !== METASYNC_EXIT.reserved)
478
+ throw new Stop(EXIT.failure, "計画の作成に失敗しました。");
479
+ const planRc = planned.code;
480
+ const rows = box.files
481
+ .readText(planFile)
482
+ .split("\n")
483
+ .filter((l) => l !== "")
484
+ .map((l) => l.split("\t"));
485
+ const count = (k) => rows.filter((r) => r[0] === k).length;
486
+ const planCounts = `追加 ${count("A")} 件 / 変更 ${count("M")} 件 / 削除 ${count("D")} 件 / 削除の保留 ${count("H")} 件`;
487
+ const planChanges = count("A") + count("M") + count("D");
488
+ log("SUCCESS", `計画の作成完了(${planCounts})`);
489
+ if (detectRc === 0 && planChanges > 0) {
490
+ log("WARNING", `検知は「変更なし」でしたが、実際は ${planChanges} 件の変更がありました(区分 C の種類の変更を含む)。先頭 10 件:`);
491
+ for (const r of rows.filter((x) => x[0] === "A" || x[0] === "M" || x[0] === "D").slice(0, 10))
492
+ log("WARNING", ` ${r[0]} ${r[1]}`);
493
+ }
494
+ if (fpMode !== "off" && fpRc >= 0 && fpReport !== "" && box.files.exists(fpReport)) {
495
+ const cmp = await node("fpcompare", [
496
+ "--report",
497
+ fpReport,
498
+ "--plan",
499
+ planFile,
500
+ "--fp-config",
501
+ `${deps.configDir}/metasync-fingerprint.txt`,
502
+ "--dirs-table",
503
+ dirsTable,
504
+ ]);
505
+ if (cmp.code !== 0)
506
+ log("WARNING", "指紋の影の比較に失敗しました(同期には影響しません)。");
507
+ if (cmp.stdout !== "")
508
+ logNode(cmp.stdout);
509
+ }
510
+ // --- 秘密情報の検査 ---
511
+ if (scanMode !== "off")
512
+ await secretScan(scanMode, planFile, inWork("scan.report.tsv"));
513
+ if (dryRun) {
514
+ log("SUCCESS", "完了: --dry-run のため、計画の表示までで終了します(作業ツリー・コミット・push は行いません)。");
515
+ return EXIT.ok;
516
+ }
517
+ if (!isActions && planChanges > 0)
518
+ await ask("上記の計画を main に反映して、コミット&プッシュします。よろしいですか?");
519
+ // --- 反映 ---
520
+ applied = true;
521
+ const ap = await node("apply", ["--plan", planFile, "--repo", ".", "--fetched", workDir]);
522
+ if (ap.code !== 0) {
523
+ log("ERROR", ap.stdout);
524
+ throw new Stop(EXIT.failure, "計画の反映に失敗しました。");
525
+ }
526
+ log("INFO", ap.stdout);
527
+ if (detectMode !== "off" && (detectRc === 10 || detectRc === 11) && detectStateNew !== "" && box.files.exists(detectStateNew)) {
528
+ stateWritten = true;
529
+ box.files.makeDir("sf-tools/metasync");
530
+ box.files.writeText(STATE_FILE, box.files.readText(detectStateNew));
531
+ log("INFO", `検知の状態を更新しました: ${STATE_FILE}`);
532
+ }
533
+ if (fpMode !== "off" && (fpRc === 10 || fpRc === 11) && fpStateNew !== "" && box.files.exists(fpStateNew)) {
534
+ fpWritten = true;
535
+ box.files.makeDir("sf-tools/metasync");
536
+ box.files.writeText(FP_STATE_FILE, box.files.readText(fpStateNew));
537
+ log("INFO", `指紋の状態を更新しました: ${FP_STATE_FILE}`);
538
+ }
539
+ // --- Git へ反映 ---
540
+ log("INFO", "Git リポジトリへ反映中...");
541
+ const addPaths = [pkgPath, ...(stateWritten ? [STATE_FILE] : []), ...(fpWritten ? [FP_STATE_FILE] : [])];
542
+ await must("Git への同期中にエラーが発生しました(git add)。", "add", "-A", "--", ...addPaths);
543
+ if (await gitOk("diff-index", "--quiet", "HEAD", "--")) {
544
+ const ahead = (await git("rev-list", "--count", "origin/main..HEAD").catch(() => null))?.stdout.trim() ?? "0";
545
+ if (/^\d+$/.test(ahead) && Number(ahead) > 0) {
546
+ log("INFO", `未プッシュのコミットが ${ahead} 件あります(前回の同期のコミットの push が、失敗した可能性があります)。push だけ行います。`);
547
+ if (!isActions) {
548
+ const list = await git("log", "--oneline", "origin/main..HEAD").catch(() => null);
549
+ if (list !== null)
550
+ box.output.err(list.stdout.trimEnd());
551
+ await ask("上記のコミットを main にプッシュします。よろしいですか?");
552
+ }
553
+ await must("Git への同期中にエラーが発生しました(push)。", "push", "--no-verify", "origin", "main");
554
+ log("SUCCESS", "完了: リポジトリを最新に更新しました。");
555
+ }
556
+ else {
557
+ log("SUCCESS", "完了: Salesforce 組織側に変更はありませんでした。");
558
+ }
559
+ }
560
+ else {
561
+ let body = planCounts;
562
+ if (stateWritten || fpWritten) {
563
+ const label = fpWritten ? (stateWritten ? "検知・指紋の状態" : "指紋の状態") : "検知の状態";
564
+ body += planChanges === 0 ? `(${label}の更新のみ)` : `(${label}も更新)`;
565
+ }
566
+ await must("Git への同期中にエラーが発生しました(commit)。", "commit", "-m", `${COMMIT_SUBJECT_PREFIX} (${deps.today()})`, "-m", body);
567
+ committed = true;
568
+ await must("Git への同期中にエラーが発生しました(push)。", "push", "--no-verify", "origin", "main");
569
+ log("SUCCESS", "完了: リポジトリを最新に更新しました。");
570
+ log("INFO", "main の変更は、staging・develop のブランチへは伝播しません(開発のブランチが、sf-push.sh で main を取り込みます)。");
571
+ }
572
+ if (planRc === METASYNC_EXIT.reserved) {
573
+ log("WARNING", "削除を保留したものがあります(ファイルは残しています)。原因を確かめてください(手元で --dry-run、必要なら --allow-mass-delete)。");
574
+ return METASYNC_EXIT.reserved;
575
+ }
576
+ return EXIT.ok;
577
+ // ---- ここから、内側の関数 ----
578
+ async function checkVisibility() {
579
+ let vis = "";
580
+ const noToken = isActions && !box.env("GH_TOKEN") && !box.env("GITHUB_TOKEN");
581
+ if (repoFull !== "" && !noToken) {
582
+ for (let attempt = 1; attempt <= 3; attempt++) {
583
+ const r = await box.run("gh", ["api", `repos/${repoFull}`, "--jq", ".visibility"]).catch(() => null);
584
+ const v = (r?.code === 0 ? r.stdout : "").replace(/\r/g, "").trim();
585
+ if (v === "private" || v === "internal" || v === "public") {
586
+ vis = v;
587
+ break;
588
+ }
589
+ if (attempt < 3)
590
+ await box.clock.sleep(Number(box.env("SF_METASYNC_VIS_RETRY_WAIT") || "3") * 1000);
591
+ }
592
+ }
593
+ if (vis === "private" || vis === "internal") {
594
+ log("INFO", `リポジトリの公開範囲: ${vis}(${repoFull})`);
595
+ return;
596
+ }
597
+ let why;
598
+ if (vis === "public")
599
+ why = "リポジトリが公開(public)です";
600
+ else if (noToken)
601
+ why =
602
+ "リポジトリの公開・非公開を確認できませんでした(GH_TOKEN が渡されていません。wf-metasync.yml が古い可能性があります。sf-update-workflows.sh で更新してください)";
603
+ else
604
+ why = `リポジトリの公開・非公開を確認できませんでした(${repoFull || "不明"})`;
605
+ log("ERROR", `${why}。Salesforce 組織の開発物を外部にさらさないため、取得せずに止めます。非公開(private)のリポジトリで実行してください。`);
606
+ if (!dryRun)
607
+ await notifySlack(`:no_entry: [metasync] 同期を止めました: ${repoFull || "不明"}`, `理由: ${why}(取得は行っていません)`);
608
+ throw new Stop(METASYNC_EXIT.publicRepo, "");
609
+ }
610
+ async function secretScan(mode, plan, report) {
611
+ const allow = "./sf-tools/config/metasync-secret-allow.txt";
612
+ const a = ["--plan", plan, "--repo", ".", "--fetched", workDir, "--out-report", report];
613
+ if (box.files.exists(allow))
614
+ a.push("--allow", allow);
615
+ const r = await node("scan", a);
616
+ logNode(r.stdout);
617
+ if (r.code === 0)
618
+ return;
619
+ if (r.code !== 10) {
620
+ if (mode === "on") {
621
+ log("ERROR", `秘密情報の検査に失敗しました(終了コード ${r.code})。検査していない内容はコミットしないため、何もコミット・push せずに止めます。`);
622
+ if (!dryRun) {
623
+ await notifySlack(`:rotating_light: [metasync] 秘密情報の検査に失敗したため、同期を止めました: ${repoFull || "不明"}`, "理由: 検査そのものが失敗しました(許可の一覧 sf-tools/config/metasync-secret-allow.txt の書式の誤りなど)。コミット・push は行っていません。", "確認: 実行のログを見て、原因を直してください。");
624
+ }
625
+ throw new Stop(METASYNC_EXIT.secret, "");
626
+ }
627
+ log("WARNING", `秘密情報の検査に失敗しました(終了コード ${r.code})。shadow のため、止めません。`);
628
+ return;
629
+ }
630
+ if (mode === "shadow") {
631
+ log("WARNING", `秘密の疑いがあります(shadow のため、止めません)。誤検知なら ${allow} に「規則 パス [キー]」を足し(パスに空白があるときは * で書く)、本物なら組織側で取り除いてください(規則が scan-error のものは、検査できなかったファイル。上の行の案内を参照)。`);
632
+ return;
633
+ }
634
+ log("ERROR", `秘密の疑いがあるため、何もコミット・push せずに止めます。本物なら組織側で取り除き、誤検知なら ${allow} に「規則 パス [キー]」を足し(パスに空白があるときは * で書く)てください(値は表示しません。規則が scan-error のものは、検査できなかったファイル。上の行の案内を参照)。`);
635
+ if (!dryRun) {
636
+ const lines = (box.files.exists(report) ? box.files.readText(report) : "")
637
+ .split("\n")
638
+ .map((l) => l.split("\t"))
639
+ .filter((c) => (c[0] ?? "") !== "")
640
+ .slice(0, 10)
641
+ .map((c) => `・${c[0]} ${c[1] ?? ""}${c[3] ? `(${c[3]})` : ""}`);
642
+ await notifySlack(`:rotating_light: [metasync] 秘密の疑いのため、同期を止めました: ${repoFull || "不明"}`, "理由: 組織から取得した内容に、秘密情報の疑いがあります(コミット・push は行っていません)。", ...lines, "確認: 本物なら組織側で取り除く。誤検知なら sf-tools/config/metasync-secret-allow.txt に「規則 パス [キー]」を足す(パスの空白は * で書く)。規則が scan-error のものは、検査できなかった規則(キー)があるファイルで、中身を確かめ、問題なければ「scan-error パス キー」を足す。");
643
+ }
644
+ throw new Stop(METASYNC_EXIT.secret, "");
645
+ }
646
+ }
647
+ catch (e) {
648
+ if (e instanceof Stop) {
649
+ if (e.message !== "")
650
+ log("ERROR", e.message);
651
+ return e.code;
652
+ }
653
+ throw e;
654
+ }
655
+ finally {
656
+ await cleanup();
657
+ }
658
+ }
659
+ /** この PC の sf にログイン済みの組織から、組織 ID(上位 15 文字)が一致するものを探して、ユーザー名を返す。なければ null */
660
+ export async function findUsernameByOrgId(box, orgId) {
661
+ const want = orgId.slice(0, 15);
662
+ if (want.length !== 15)
663
+ return null;
664
+ const r = await box.run("sf", ["org", "list", "--json"], { input: "" }).catch(() => null);
665
+ if (r === null || r.code !== 0)
666
+ return null;
667
+ let data;
668
+ try {
669
+ data = JSON.parse(r.stdout);
670
+ }
671
+ catch {
672
+ return null;
673
+ }
674
+ for (const k of ["nonScratchOrgs", "sandboxes", "devHubs", "scratchOrgs", "other"]) {
675
+ const list = data.result?.[k];
676
+ if (!Array.isArray(list))
677
+ continue;
678
+ for (const o of list) {
679
+ if (typeof o.orgId === "string" && typeof o.username === "string" && o.orgId.slice(0, 15) === want && o.username !== "")
680
+ return o.username;
681
+ }
682
+ }
683
+ return null;
684
+ }