@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,127 @@
1
+ // sft log summarize: 手元の目録(logs/apex/.index)にあるログから、AI が最初に読む要約(logs/apex/latest.md)を作る。
2
+ // sf-log.sh pull の後半(phases/log/pull.sh の 8 章の「要約のロックから、要約を書くまで」)の移し先。組織には触れない(読み取りのみ)。
3
+ // 要約を書く部分(writeSummary)は、sft log pull(移植中)からも使えるように分けた。組織からの取得・取得役への依頼・要約のロック・拾い直しは、log-pull.ts(sft log pull)。
4
+ // ロックを取らないため、しおり(LAST_READ_LINE・LAST_READ_ID)は進めない(ロックが取れないときのシェル版と同じ。同じ範囲を、もう一度要約できる)
5
+ import { ID_RE, indexMark, kvGet, kvSet, migrateOldMark, parseIndex, selectLogs } from "./log-select.js";
6
+ const APEX_DIR = "logs/apex";
7
+ export function parseSummaryArgs(args) {
8
+ let max = 50;
9
+ let since = null;
10
+ for (let i = 0; i < args.length; i++) {
11
+ const a = args[i];
12
+ const v = args[i + 1] ?? "";
13
+ if (a === "--max" || a === "--since") {
14
+ if (!/^[0-9]+$/.test(v) || Number(v) < 1)
15
+ return `${a} は 1 以上の整数です: ${v}`;
16
+ if (a === "--max")
17
+ max = Number(v);
18
+ else
19
+ since = Number(v);
20
+ i++;
21
+ }
22
+ else {
23
+ return `不明なオプションです: ${a}`;
24
+ }
25
+ }
26
+ return { max, since };
27
+ }
28
+ function nowZ(box) {
29
+ return box.clock
30
+ .now()
31
+ .toISOString()
32
+ .replace(/\.\d{3}Z$/, "Z");
33
+ }
34
+ /** PC のタイムゾーンの YYYYMMDD_HHMMSS(要約のファイル名) */
35
+ function localStamp(d) {
36
+ const p = (n) => String(n).padStart(2, "0");
37
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}_${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
38
+ }
39
+ /** 目録からログを選び、要約(summaries/<時刻>.md と latest.md)を書いて、1 行目とパスを表示する(sft log pull も使う) */
40
+ export async function writeSummary(box, deps, opts) {
41
+ const { files } = box;
42
+ const indexPath = `${APEX_DIR}/.index`;
43
+ const statePath = `${APEX_DIR}/.state`;
44
+ const state = files.exists(statePath) ? files.readText(statePath) : "";
45
+ const lines = parseIndex(files.exists(indexPath) ? files.readText(indexPath) : "");
46
+ const now = nowZ(box);
47
+ let lastReadId = kvGet(state, "LAST_READ_ID");
48
+ let lastReadLine = kvGet(state, "LAST_READ_LINE");
49
+ if (opts.since === null && lastReadLine === "") {
50
+ // 古い .state(シェル版の前の形)からの移し替え。進めるときに、新しい形で書く
51
+ const old = migrateOldMark(lines, kvGet(state, "LAST_READ"), kvGet(state, "LAST_READ_IDS"));
52
+ if (old !== null) {
53
+ lastReadLine = String(old.line);
54
+ lastReadId = old.id;
55
+ box.output.err(`[INFO] 要約のしおりを、新しい形(目録の ${old.line} 行目)に移しました。`);
56
+ }
57
+ }
58
+ const sel = selectLogs({
59
+ lines,
60
+ lastReadLine,
61
+ lastReadId: ID_RE.test(lastReadId) || lastReadId === "" ? lastReadId : "",
62
+ sinceMin: opts.since,
63
+ now,
64
+ max: opts.max,
65
+ });
66
+ for (const w of sel.warnings)
67
+ box.output.err(`[WARNING] ${w}`);
68
+ const notes = [...opts.notes, ...sel.notes];
69
+ const listPath = `${APEX_DIR}/.summarize.list`;
70
+ files.writeText(listPath, sel.entries.map((l) => `${l}\n`).join(""));
71
+ let r;
72
+ try {
73
+ r = await box.run("node", [
74
+ deps.apexlogJs,
75
+ "summarize",
76
+ "--list",
77
+ listPath,
78
+ "--base",
79
+ ".",
80
+ "--now",
81
+ now,
82
+ ...notes.flatMap((n) => ["--note", n]),
83
+ ]);
84
+ }
85
+ finally {
86
+ files.removeFile(listPath);
87
+ }
88
+ if (r.code !== 0) {
89
+ box.output.err("[ERROR] 要約を作れませんでした。");
90
+ return 1;
91
+ }
92
+ const dir = `${APEX_DIR}/summaries`;
93
+ files.makeDir(dir);
94
+ const outMd = `${dir}/${localStamp(box.clock.now())}.md`;
95
+ files.writeText(outMd, r.stdout);
96
+ files.writeText(`${APEX_DIR}/latest.md`, r.stdout);
97
+ if (opts.advance && sel.advance) {
98
+ // 読んだ目録の最後の行(要約のロックの中で読み直す。ほかの pull が先に進めていないことは、ロックが守る)
99
+ const mark = indexMark(lines);
100
+ const updates = { LAST_READ_LINE: String(mark.line), LAST_READ_ID: mark.id, LAST_READ: "", LAST_READ_IDS: "" };
101
+ if (opts.writeState) {
102
+ // 取得役も .state を書くので、状態のロックの中で書く(書けなければ、しおりを進めない)
103
+ if (!(await opts.writeState(updates)))
104
+ box.output.err("[WARNING] しおりを進められませんでした(次の要約に、同じログが入ることがあります)。");
105
+ }
106
+ else {
107
+ const cur = files.exists(statePath) ? files.readText(statePath) : "";
108
+ files.writeText(statePath, kvSet(cur, updates));
109
+ }
110
+ }
111
+ const header = (r.stdout.split("\n")[0] ?? "").replace(/^# /, "");
112
+ box.output.out(header);
113
+ box.output.out(`${APEX_DIR}/latest.md`);
114
+ return 0;
115
+ }
116
+ export async function runLogSummarize(args, box, deps) {
117
+ const parsed = parseSummaryArgs(args);
118
+ if (typeof parsed === "string") {
119
+ box.output.err(`[ERROR] ${parsed}`);
120
+ return 1;
121
+ }
122
+ return writeSummary(box, deps, {
123
+ ...parsed,
124
+ notes: ["取得は行っていません(手元の目録にある分だけで要約しました。新しいログは sft log pull で取ります)"],
125
+ advance: false,
126
+ });
127
+ }
@@ -0,0 +1,71 @@
1
+ // ログと、ログに残すコマンドの実行(今の lib/common.sh の log・run を引き継ぐ)。
2
+ // - 成否は、終了コードだけで決める。ただし、出力に「変更なし」の印があれば、終了コードより優先して「変更なし」
3
+ // - コマンドの出力は [OUT] の行でログに残す。失敗は、同じフォルダの error.log にも追記し、道具の版を 1 回だけ書く
4
+ // - 伏せ字は、コマンドの行にも出力にもかける(今のシェル版はコマンドの行だけ。漏れを減らすために広げた)
5
+ // 出入りは道具の箱を使う(core は Node 専用の機能を使わない)
6
+ import { createLineWriter } from "./lines.js";
7
+ import { fileLine, prefixLines, screenLines, stripTermCodes, timestamp } from "./log-format.js";
8
+ import { maskSecrets } from "./mask.js";
9
+ const noChangeMarks = ["NothingToDeploy", "No local changes to deploy"];
10
+ export function createLogger(box, options) {
11
+ const folder = options.file.replace(/[^\\/]*$/, "");
12
+ if (folder !== "")
13
+ box.files.makeDir(folder);
14
+ if (options.mode === "new")
15
+ box.files.writeText(options.file, "");
16
+ let versionsWritten = false;
17
+ const now = () => timestamp(box.clock.now());
18
+ const log = (level, message) => {
19
+ const safe = maskSecrets(message);
20
+ box.files.appendText(options.file, fileLine(now(), level, safe));
21
+ for (const line of screenLines(level, safe, options.color ?? false))
22
+ box.output.err(line);
23
+ };
24
+ const writeVersions = async () => {
25
+ if (versionsWritten || !options.toolVersions)
26
+ return;
27
+ versionsWritten = true;
28
+ // 版の確認に失敗しても、もとの失敗の記録は残す
29
+ const line = await options.toolVersions().catch(() => "不明");
30
+ box.files.appendText(options.file, `[${now()}] [ENV] ${line}\n`);
31
+ };
32
+ const run = async (command, args, runOptions = {}) => {
33
+ const { logOutput = true, ...rest } = runOptions;
34
+ const shown = maskSecrets([command, ...args].join(" "));
35
+ log("CMD", `[${options.name}] ${shown}`);
36
+ // 画面へは、行がそろってから、伏せ字にして出す。標準出力と標準エラーは別々にまとめる。
37
+ // 出力をログに残さない指定(秘密を含む応答)は、--verbose でも画面に出さない
38
+ const screen = options.verbose && logOutput;
39
+ const writers = {
40
+ stdout: createLineWriter((line) => box.output.err(line)),
41
+ stderr: createLineWriter((line) => box.output.err(line)),
42
+ };
43
+ let result;
44
+ try {
45
+ result = await box.run(command, args, screen ? { ...rest, onChunk: (text, stream) => writers[stream].push(text) } : rest);
46
+ }
47
+ catch (error) {
48
+ log("ERROR", error instanceof Error ? error.message : String(error));
49
+ await writeVersions();
50
+ throw error;
51
+ }
52
+ writers.stdout.flush();
53
+ writers.stderr.flush();
54
+ // 時間切れ・中断は、出力に「変更なし」の印があっても、失敗
55
+ const stopped = result.timedOut || result.aborted;
56
+ const noChange = !stopped && noChangeMarks.some((mark) => result.output.includes(mark));
57
+ const status = noChange ? "noChange" : result.code === 0 ? "ok" : "failed";
58
+ if (noChange)
59
+ log("WARNING", "組織との差分が検出されませんでした (NothingToDeploy)。ローカルのソースはすでに組織と一致しています。");
60
+ const clean = logOutput ? maskSecrets(stripTermCodes(result.output)) : "";
61
+ const ts = now();
62
+ box.files.appendText(options.file, prefixLines(`[${ts}] [OUT] `, clean));
63
+ if (status === "failed") {
64
+ const header = `====== [${ts}] ERROR: [${options.name}] ${shown} ======\n`;
65
+ box.files.appendText(`${folder}error.log`, header + prefixLines(" ", clean));
66
+ await writeVersions();
67
+ }
68
+ return { ...result, status };
69
+ };
70
+ return { log, run };
71
+ }
@@ -0,0 +1,50 @@
1
+ export const LOGIN_URL = "https://login.salesforce.com";
2
+ export const TEST_URL = "https://test.salesforce.com";
3
+ const URL_RE = /^https:\/\/[A-Za-z0-9.-]+\.(salesforce\.com|force\.com)(\/\S*)?$/;
4
+ export async function chooseLoginUrl(box, prompts, target) {
5
+ const err = (l) => box.output.err(l);
6
+ const preset = box.env(target.envName) ?? "";
7
+ if (preset !== "") {
8
+ const url = preset === "login" ? LOGIN_URL : preset === "test" ? TEST_URL : preset.replace(/\/$/, "");
9
+ if (!URL_RE.test(url))
10
+ return { error: `${target.envName} の値が、Salesforce のログイン先として正しくありません: ${preset}` };
11
+ err(`[INFO] ${target.label}のログイン先: ${url}(環境変数 ${target.envName} の指定)`);
12
+ return { url };
13
+ }
14
+ const hint = target.tier === "main" ? "本番・Developer Edition・Trial など" : "Developer Edition・Trial など(※ Salesforce の本番は、main のみ)";
15
+ for (const l of [
16
+ "",
17
+ ` ▶ ${target.label}(${target.tier})には、どこからログインしますか?`,
18
+ ` [1] ${LOGIN_URL} ${hint}`,
19
+ ` [2] ${TEST_URL} Sandbox ← 安全なおすすめ(本番に影響しません)`,
20
+ " [3] 組織の URL を入力する My Domain(例: https://会社名.my.salesforce.com)",
21
+ ])
22
+ err(l);
23
+ for (;;) {
24
+ const ans = await prompts.line(" ▶ 番号を選んでください [Enter=2 / 1 / 3 / q=中断]: ");
25
+ if (ans === null || ans === "q" || ans === "Q")
26
+ return { quit: true };
27
+ let url = "";
28
+ if (ans === "" || ans === "2")
29
+ url = TEST_URL;
30
+ else if (ans === "1")
31
+ url = LOGIN_URL;
32
+ else if (ans === "3") {
33
+ for (;;) {
34
+ const v = await prompts.text(" 組織の URL(q で中断): ");
35
+ if (v === "quit")
36
+ return { quit: true };
37
+ url = v.replace(/\/$/, "");
38
+ if (URL_RE.test(url))
39
+ break;
40
+ err(`[WARNING] 「${url}」は、Salesforce のログイン先の形式ではありません(https:// で始まり、salesforce.com または force.com のドメインです)。`);
41
+ }
42
+ }
43
+ else {
44
+ err(" 1・2・3 のいずれかを入力してください(Enter は 2)。");
45
+ continue;
46
+ }
47
+ err(`[INFO] ${target.label}のログイン先: ${url}`);
48
+ return { url };
49
+ }
50
+ }
@@ -0,0 +1,118 @@
1
+ // ターゲットファイル(deploy-target.txt / remove-target.txt)から、マニフェストを作る。シェル版の lib/manifest.sh
2
+ // (manifest_parse_list・manifest_generate・manifest_build)の移し先(doc/rebuild-design.md 11.2 の段階 2)。
3
+ // release(組織へ出す)と promote-check(一方通行の確認の R2)が共有する。sf は、渡された道具の箱だけで呼ぶ(7.2)。
4
+ //
5
+ // 【決まり】(シェル版から移したもの。動きは変えない)
6
+ // - リストの行: [files] セクション(既定)は --source-dir、[members] セクションは --metadata。# で始まる行・空行は無視。
7
+ // 行末の CR と前後の空白は除く
8
+ // - [files] と [members] は、別々に sf project generate manifest で作り、統合する
9
+ // (両方を同時に渡すと、sf は共通部分だけ(重なりがなければ空)を返し、しかも成功として終わるため)
10
+ // - 作ったものにメンバーが 1 つもなければ、失敗にする(NothingToDeploy の成功扱いで、見落とさないため)
11
+ // - deploy-target.txt が空で remove-target.txt にだけ対象があるときは、メンバーのない package.xml(version 60.0)を作る
12
+ // - 反映と削除の重なりの確認・組織にない削除の対象を外す処理は、組織に出すときの処理なので、ここではしない
13
+ import { mergePackageXml } from "./package-xml.js";
14
+ /** リストを読み、sf の引数にする([files] は --source-dir・[members] は --metadata) */
15
+ export function parseTargetList(text) {
16
+ const args = [];
17
+ let section = "files";
18
+ for (const raw of text.split("\n")) {
19
+ const line = raw.replace(/\r/g, "").trim();
20
+ if (line === "[files]")
21
+ section = "files";
22
+ else if (line === "[members]")
23
+ section = "members";
24
+ else if (line !== "" && !line.startsWith("#"))
25
+ args.push({ kind: section === "files" ? "source-dir" : "metadata", value: line });
26
+ }
27
+ return args;
28
+ }
29
+ const EMPTY_PACKAGE = '<?xml version="1.0" encoding="UTF-8"?><Package xmlns="http://soap.sforce.com/2006/04/metadata"><version>60.0</version></Package>\n';
30
+ async function generate(box, dir, out, name, args, label, extra) {
31
+ const base = name.replace(/\.xml$/, "");
32
+ const parts = [];
33
+ const groups = [
34
+ ["files", args.filter((a) => a.kind === "source-dir")],
35
+ ["members", args.filter((a) => a.kind === "metadata")],
36
+ ];
37
+ for (const [group, items] of groups) {
38
+ if (items.length === 0)
39
+ continue;
40
+ const partName = `${base}.${group}.xml`;
41
+ const flag = group === "files" ? "--source-dir" : "--metadata";
42
+ const sfArgs = [
43
+ "project",
44
+ "generate",
45
+ "manifest",
46
+ ...items.flatMap((a) => [flag, a.value]),
47
+ "--output-dir",
48
+ out,
49
+ "--name",
50
+ partName,
51
+ ...extra,
52
+ ];
53
+ const r = await box.run("sf", sfArgs, { cwd: dir });
54
+ if (r.code !== 0)
55
+ return { error: `sf project generate manifest が失敗しました(${partName})。` };
56
+ parts.push(`${out}/${partName}`);
57
+ }
58
+ if (parts.length === 0)
59
+ return { error: `${name}: 生成する対象がありません。` };
60
+ const merged = mergePackageXml(parts.map((p) => box.files.readText(p)));
61
+ for (const p of parts)
62
+ box.files.removeFile(p); // 統合前の一時ファイルの除去
63
+ if (!merged.includes("<members>")) {
64
+ return {
65
+ error: `${name} に、メンバーが 1 つも含まれていません(ターゲットファイルの記述が、マニフェストに反映されていません)。${label.deploy} / ${label.remove} の、パス・種別名:メンバー名を確認してください。`,
66
+ };
67
+ }
68
+ box.files.writeText(`${out}/${name}`, merged);
69
+ return merged;
70
+ }
71
+ /**
72
+ * リリースのフォルダ reldir(dir からの相対)のターゲットファイルから、out に package.xml・destructiveChanges.xml を作る。
73
+ * dir は、プロジェクトのルート(sf project generate manifest が sfdx-project.json を読むため)。out は、書き込める場所
74
+ * (sf の --output-dir にそのまま渡す)。out の古い package.xml・destructiveChanges.xml は、先に消す。
75
+ * extra は、sf に足す引数(release の --json など)
76
+ */
77
+ export async function buildManifest(box, dir, reldir, out, extra = []) {
78
+ const deployList = `${reldir}/deploy-target.txt`;
79
+ const removeList = `${reldir}/remove-target.txt`;
80
+ box.files.makeDir(out);
81
+ box.files.removeFile(`${out}/package.xml`);
82
+ box.files.removeFile(`${out}/destructiveChanges.xml`);
83
+ const read = (rel) => {
84
+ const path = dir === "." ? rel : `${dir}/${rel}`;
85
+ return box.files.exists(path) ? box.files.readText(path) : null;
86
+ };
87
+ const deployText = read(deployList);
88
+ if (deployText === null)
89
+ return { kind: "error", message: `ターゲットファイルが見つかりません: ${deployList}` };
90
+ const removeText = read(removeList);
91
+ if (removeText === null)
92
+ return { kind: "error", message: `ターゲットファイルが見つかりません: ${removeList}` };
93
+ const deploy = parseTargetList(deployText);
94
+ const remove = parseTargetList(removeText);
95
+ if (deploy.length === 0 && remove.length === 0)
96
+ return { kind: "nochange" };
97
+ const label = { deploy: deployList, remove: removeList };
98
+ let packageXml;
99
+ if (deploy.length > 0) {
100
+ const made = await generate(box, dir, out, "package.xml", deploy, label, extra);
101
+ if (typeof made !== "string")
102
+ return { kind: "error", message: made.error };
103
+ packageXml = made;
104
+ }
105
+ else {
106
+ // 対象ゼロでも CLI エラーを防ぐために最小構成の XML を作る
107
+ packageXml = EMPTY_PACKAGE;
108
+ box.files.writeText(`${out}/package.xml`, packageXml);
109
+ }
110
+ let destructiveXml = null;
111
+ if (remove.length > 0) {
112
+ const made = await generate(box, dir, out, "destructiveChanges.xml", remove, label, extra);
113
+ if (typeof made !== "string")
114
+ return { kind: "error", message: made.error };
115
+ destructiveXml = made;
116
+ }
117
+ return { kind: "ok", packageXml, destructiveXml };
118
+ }
@@ -0,0 +1,70 @@
1
+ // 秘密の値を、画面とログに出さないための伏せ字(今の lib/common.sh の _mask_secrets を引き継ぎ、広げたもの)。
2
+ // 知っている形だけを伏せる。形の分からない秘密は伏せられないので、秘密を含む応答は、ログに出さない指定(logOutput: false)を使う
3
+ const MASK = "***masked***";
4
+ const keyBegin = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;
5
+ const keyEnd = /-----END [A-Z0-9 ]*PRIVATE KEY-----/;
6
+ const rules = [
7
+ // 秘密鍵の本体(終わりの行がなければ、最後まで)
8
+ [/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g, MASK],
9
+ // GitHub・Slack・npm のトークン
10
+ [/(gh[pousr]_)[A-Za-z0-9]+/g, `$1${MASK}`],
11
+ [/github_pat_[A-Za-z0-9_]+/g, `github_pat_${MASK}`],
12
+ [/(xox[abeoprs]-|xapp-)[A-Za-z0-9-]+/g, `$1${MASK}`],
13
+ [/(hooks\.slack\.com\/services\/)[A-Za-z0-9/_-]+/g, `$1${MASK}`],
14
+ [/npm_[A-Za-z0-9]{20,}/g, `npm_${MASK}`],
15
+ // Salesforce のアクセストークン(組織の ID + ! + 本体)と、認証の URL(更新トークンを含む)
16
+ [/(00D[A-Za-z0-9]{12,15}!)[A-Za-z0-9._]+/g, `$1${MASK}`],
17
+ [/force:\/\/[^\s"']+/g, `force://${MASK}`],
18
+ // JSON の中の、秘密を入れる名前の値
19
+ [
20
+ /("(?:accessToken|refreshToken|access_token|refresh_token|clientSecret|client_secret|sfdxAuthUrl|password)"\s*:\s*")[^"]+/g,
21
+ `$1${MASK}`,
22
+ ],
23
+ // HTTP の認証の見出し・URL の中の認証情報
24
+ [/(authorization\s*:\s*(?:basic|bearer|token)\s+)[^\s"']+/gi, `$1${MASK}`],
25
+ // 長さの上限は、記号の多い長い文で時間がかからないようにするため
26
+ [/\b([a-z][a-z0-9+.-]{0,30}:\/\/)(?!\*\*\*)[^/\s"'@]{1,1000}@/gi, `$1${MASK}@`],
27
+ ];
28
+ /** JWT の 1 つ目と 2 つ目の区切りの、eyJ から後ろの最小の長さ(eyJ + 8 文字) */
29
+ const JWT_PART = 11;
30
+ /**
31
+ * JWT になりうる文字の並び(英数字・_・-・.)の 1 つを、. で分けて調べる。「…eyJ…」「eyJ…」「何か」と続く所を伏せる。
32
+ * 直前に英数字や _ - が続いていても(URL の %3D の直後など)、1 つ目の区切りの最初の eyJ から後ろを伏せる。
33
+ * 正規表現の 1 回の照合で調べないのは、長い並びで、時間が長さの 2 乗になったり、例外(呼び出しの積み過ぎ)で落ちたりするため
34
+ */
35
+ function maskJwtRun(run) {
36
+ if (!run.includes(".eyJ"))
37
+ return run;
38
+ const parts = run.split(".");
39
+ const out = [];
40
+ for (let i = 0; i < parts.length; i += 1) {
41
+ const head = parts[i] ?? "";
42
+ const at = head.indexOf("eyJ");
43
+ const body = parts[i + 1] ?? "";
44
+ const signature = parts[i + 2] ?? "";
45
+ if (at >= 0 && head.length - at >= JWT_PART && body.startsWith("eyJ") && body.length >= JWT_PART && signature !== "") {
46
+ out.push(head.slice(0, at) + MASK);
47
+ i += 2;
48
+ }
49
+ else {
50
+ out.push(head);
51
+ }
52
+ }
53
+ return out.join(".");
54
+ }
55
+ export function maskSecrets(text) {
56
+ const masked = rules.reduce((t, [pattern, replacement]) => t.replace(pattern, replacement), text);
57
+ return masked.replace(/[A-Za-z0-9_.-]+/g, maskJwtRun);
58
+ }
59
+ /** 1 行ずつ出すときの伏せ字。何行にもわたる秘密鍵は、終わりの行まで出さない(null = この行は出さない) */
60
+ export function createLineMasker() {
61
+ let insideKey = false;
62
+ return (line) => {
63
+ if (insideKey) {
64
+ insideKey = !keyEnd.test(line);
65
+ return null;
66
+ }
67
+ insideKey = keyBegin.test(line) && !keyEnd.test(line);
68
+ return maskSecrets(line);
69
+ };
70
+ }
@@ -0,0 +1,79 @@
1
+ // メタデータの種類の表。シェル版の config/metadata-capability.txt(bin/sf-check.sh の lookup_capability・type_of_path・
2
+ // check_capability)・config/metadata-dirs.txt・config/changeset-types.txt の読み取りと検索の移し先
3
+ // (doc/rebuild-design.md 11.2 の段階 1)。core は Node 専用の機能を使わないので、ファイルは読まず、中身の文字列を受け取る
4
+ /** 可否の表(タブ区切り: 種類 / release / delete / 備考)を読む。同じ種類が複数あれば、最初の行を使う */
5
+ export function parseCapabilityTable(text) {
6
+ const table = new Map();
7
+ for (const raw of text.split("\n")) {
8
+ if (raw.startsWith("#"))
9
+ continue;
10
+ const cols = raw.split("\t").map((c) => c.replace(/\r/g, ""));
11
+ const type = cols[0] ?? "";
12
+ if (type === "" || table.has(type))
13
+ continue;
14
+ table.set(type, { release: cols[1] ?? "", delete: cols[2] ?? "", note: cols[3] ?? "" });
15
+ }
16
+ return table;
17
+ }
18
+ /** [files] のパスから、種類を推定する(確認済みの NG がありうる主な種類だけ)。分からなければ null */
19
+ export function typeOfPath(path) {
20
+ if (/\/flows\/.*\.flow-meta\.xml$/.test(path))
21
+ return "Flow";
22
+ if (/\/classes\/.*\.cls$/.test(path))
23
+ return "ApexClass";
24
+ if (/\/triggers\/.*\.trigger$/.test(path))
25
+ return "ApexTrigger";
26
+ if (/\/lwc\//.test(path))
27
+ return "LightningComponentBundle";
28
+ if (/\/aura\//.test(path))
29
+ return "AuraDefinitionBundle";
30
+ if (/\/servicePresenceStatuses\//.test(path))
31
+ return "ServicePresenceStatus";
32
+ if (/\/standardValueSets\//.test(path))
33
+ return "StandardValueSet";
34
+ return null;
35
+ }
36
+ /**
37
+ * 種類の可否の確認。deploy-target.txt(label が remove で始まらない)は release を、remove-target.txt は delete を見る。
38
+ * ng はエラー・limited は警告・それ以外(表にない・unknown)は何もしない。
39
+ * ignore(SF_CHECK_IGNORE_CAPABILITY=1)なら、確認しない
40
+ */
41
+ export function checkCapability(table, label, type, ignore = false) {
42
+ if (type === null || type === "" || ignore)
43
+ return { level: "ok" };
44
+ const row = table.get(type);
45
+ if (!row)
46
+ return { level: "ok" };
47
+ const removing = label.startsWith("remove");
48
+ const status = removing ? row.delete : row.release;
49
+ const what = removing ? "削除" : "リリース";
50
+ if (status === "ng")
51
+ return { level: "error", type, what, note: row.note };
52
+ if (status === "limited")
53
+ return { level: "warning", type, what, note: row.note };
54
+ return { level: "ok" };
55
+ }
56
+ /** 種類 → force-app/main/default の下のフォルダ名の表(config/metadata-dirs.txt。1 行に「種類名 フォルダ名」。空白区切り) */
57
+ export function parseMetadataDirs(text) {
58
+ const dirs = new Map();
59
+ for (const raw of text.split("\n")) {
60
+ const line = raw.replace(/\r$/, "").trim();
61
+ if (line === "" || line.startsWith("#"))
62
+ continue;
63
+ const [type, dir] = line.split(/\s+/);
64
+ if (type && dir && !dirs.has(type))
65
+ dirs.set(type, dir);
66
+ }
67
+ return dirs;
68
+ }
69
+ /** 1 行 1 種類の一覧(config/changeset-types.txt)。# で始まる行と空行は無視 */
70
+ export function parseTypeList(text) {
71
+ const types = [];
72
+ for (const raw of text.split("\n")) {
73
+ const line = raw.replace(/\r$/, "").trim();
74
+ if (line === "" || line.startsWith("#"))
75
+ continue;
76
+ types.push(line);
77
+ }
78
+ return types;
79
+ }