@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,259 @@
1
+ import { chooseLoginUrl } from "./login-url.js";
2
+ import { orgKind, parseOrgInfo } from "./org.js";
3
+ import { orgKindLabel } from "./project-status.js";
4
+ import { orgGuardProblem } from "./update-secret.js";
5
+ export class EcaStop extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.code = code;
10
+ }
11
+ }
12
+ /** sf-project が作るアプリの名前(SF_TOOLS_ + リポジトリ名の英数字以外を _ に) */
13
+ export const ecaName = (repoName) => `SF_TOOLS_${repoName.replace(/[^A-Za-z0-9]/g, "_")}`;
14
+ const xmlEscape = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
15
+ /** ECA のメタデータ(作業フォルダからの相対パスと本文)。certPem は PEM(BEGIN・END の行は除いて入れる) */
16
+ export function ecaMetadata(app, email, profile, certPem) {
17
+ const cert = certPem
18
+ .replace(/\r/g, "")
19
+ .split("\n")
20
+ .filter((l) => !l.includes("-----"))
21
+ .join("\n")
22
+ .replace(/\n+$/, "");
23
+ const b = "force-app/main/default";
24
+ const x = (...l) => `${['<?xml version="1.0" encoding="UTF-8"?>', ...l].join("\n")}\n`;
25
+ return [
26
+ {
27
+ path: "sfdx-project.json",
28
+ text: '{"packageDirectories":[{"path":"force-app","default":true}],"namespace":"","sourceApiVersion":"64.0"}\n',
29
+ },
30
+ {
31
+ path: `${b}/externalClientApps/${app}.eca-meta.xml`,
32
+ text: x('<ExternalClientApplication xmlns="http://soap.sforce.com/2006/04/metadata">', ` <contactEmail>${xmlEscape(email)}</contactEmail>`, " <distributionState>Local</distributionState>", " <isProtected>false</isProtected>", ` <label>${app}</label>`, "</ExternalClientApplication>"),
33
+ },
34
+ {
35
+ path: `${b}/extlClntAppGlobalOauthSets/${app}_glbloauth.ecaGlblOauth-meta.xml`,
36
+ text: x('<ExtlClntAppGlobalOauthSettings xmlns="http://soap.sforce.com/2006/04/metadata">', " <callbackUrl>https://login.salesforce.com/services/oauth2/callback</callbackUrl>", ` <certificate>${cert}</certificate>`, ` <externalClientApplication>${app}</externalClientApplication>`, " <isClientCredentialsFlowEnabled>false</isClientCredentialsFlowEnabled>", " <isCodeCredFlowEnabled>false</isCodeCredFlowEnabled>", " <isCodeCredPostOnly>false</isCodeCredPostOnly>", " <isConsumerSecretOptional>true</isConsumerSecretOptional>", " <isDeviceFlowEnabled>false</isDeviceFlowEnabled>", " <isIntrospectAllTokens>false</isIntrospectAllTokens>", " <isNamedUserJwtEnabled>false</isNamedUserJwtEnabled>", " <isPkceRequired>true</isPkceRequired>", " <isRefreshTokenRotationEnabled>true</isRefreshTokenRotationEnabled>", " <isSecretRequiredForRefreshToken>false</isSecretRequiredForRefreshToken>", " <isSecretRequiredForTokenExchange>true</isSecretRequiredForTokenExchange>", " <isTokenExchangeEnabled>false</isTokenExchangeEnabled>", ` <label>${app}_glbloauth</label>`, " <shouldRotateConsumerKey>false</shouldRotateConsumerKey>", " <shouldRotateConsumerSecret>false</shouldRotateConsumerSecret>", "</ExtlClntAppGlobalOauthSettings>"),
37
+ },
38
+ {
39
+ path: `${b}/extlClntAppOauthSettings/${app}_oauth.ecaOauth-meta.xml`,
40
+ text: x('<ExtlClntAppOauthSettings xmlns="http://soap.sforce.com/2006/04/metadata">', " <commaSeparatedOauthScopes>Full, RefreshToken</commaSeparatedOauthScopes>", ` <externalClientApplication>${app}</externalClientApplication>`, " <isFirstPartyAppEnabled>false</isFirstPartyAppEnabled>", ` <label>${app}_oauth</label>`, "</ExtlClntAppOauthSettings>"),
41
+ },
42
+ {
43
+ path: `${b}/extlClntAppOauthPolicies/${app}_oauthPlcy.ecaOauthPlcy-meta.xml`,
44
+ text: x('<ExtlClntAppOauthConfigurablePolicies xmlns="http://soap.sforce.com/2006/04/metadata">', ` <commaSeparatedProfile>${xmlEscape(profile)}</commaSeparatedProfile>`, ` <externalClientApplication>${app}</externalClientApplication>`, " <ipRelaxationPolicyType>Enforce</ipRelaxationPolicyType>", " <isClientCredentialsFlowEnabled>false</isClientCredentialsFlowEnabled>", " <isGuestCodeCredFlowEnabled>false</isGuestCodeCredFlowEnabled>", " <isTokenExchangeFlowEnabled>false</isTokenExchangeFlowEnabled>", ` <label>${app}_oauthPlcy</label>`, " <permittedUsersPolicyType>AdminApprovedPreAuthorized</permittedUsersPolicyType>", " <refreshTokenPolicyType>SpecificInactivity</refreshTokenPolicyType>", " <refreshTokenValidityPeriod>30</refreshTokenValidityPeriod>", " <refreshTokenValidityUnit>Days</refreshTokenValidityUnit>", " <requiredSessionLevel>STANDARD</requiredSessionLevel>", "</ExtlClntAppOauthConfigurablePolicies>"),
45
+ },
46
+ {
47
+ path: `${b}/extlClntAppPolicies/${app}_plcy.ecaPlcy-meta.xml`,
48
+ text: x('<ExtlClntAppConfigurablePolicies xmlns="http://soap.sforce.com/2006/04/metadata">', ` <externalClientApplication>${app}</externalClientApplication>`, " <isEnabled>true</isEnabled>", " <isOauthPluginEnabled>true</isOauthPluginEnabled>", ` <label>${app}_plcy</label>`, " <startPage>None</startPage>", "</ExtlClntAppConfigurablePolicies>"),
49
+ },
50
+ ];
51
+ }
52
+ function jsonPath(text, path) {
53
+ try {
54
+ let v = JSON.parse(text);
55
+ for (const k of path)
56
+ v = v?.[k];
57
+ return typeof v === "string" ? v : "";
58
+ }
59
+ catch {
60
+ return "";
61
+ }
62
+ }
63
+ const envInt = (box, name, def, min) => {
64
+ const v = box.env(name) ?? "";
65
+ return /^[0-9]+$/.test(v) && Number(v) >= min ? Number(v) : def;
66
+ };
67
+ /** アプリを作り、JWT の認証情報を登録する。戻り値: 読めた組織の情報(読めなければ null)。止めるときは EcaStop */
68
+ export async function registerJwtSecretEca(box, deps, ask, o) {
69
+ const err = (l) => box.output.err(l);
70
+ const tmpAlias = `sf-tools-${o.suffix}`;
71
+ const app = ecaName(o.repo.split("/")[1] ?? o.repo);
72
+ const retries = envInt(box, "SF_INIT_JWT_RETRIES", 20, 1);
73
+ const interval = envInt(box, "SF_INIT_JWT_INTERVAL", 30, 0);
74
+ err(`=== ${o.label}(SF_*_${o.suffix})の設定(外部クライアントアプリを自動作成) ===`);
75
+ // 1・2. ログイン先とブラウザでのログイン
76
+ const chosen = await chooseLoginUrl(box, deps.prompts, { label: o.label, tier: o.tier, envName: `SF_INIT_LOGIN_URL_${o.suffix}` });
77
+ if ("quit" in chosen)
78
+ throw new EcaStop(1, "中断しました。");
79
+ if ("error" in chosen)
80
+ throw new EcaStop(1, chosen.error);
81
+ const url = chosen.url;
82
+ err(`[INFO] 接続 URL: ${url}`);
83
+ err(`[INFO] ブラウザが開きます。${o.label}に、接続ユーザー(管理者権限)でログインしてください。`);
84
+ err("[WARNING] ※ ブラウザでのログインは、約 2 分で時間切れになります。ブラウザが開いたら、すぐに、ログインしてください。");
85
+ const unalias = () => box.run("sf", ["alias", "unset", tmpAlias]).catch(() => null);
86
+ await unalias(); // 前回の古い認証が残っていて「ログイン済み」と取り違えないため
87
+ const login = await box.run("sf", ["org", "login", "web", "--instance-url", url, "--alias", tmpAlias]).catch(() => null);
88
+ if (login === null || login.code !== 0)
89
+ throw new EcaStop(1, `${o.label}へのログインに失敗しました。`);
90
+ // 3〜5. ここからの失敗は、一時エイリアスを外し・一時フォルダを消してから止める
91
+ let work = "";
92
+ let consumerKey = "";
93
+ let info = null;
94
+ let username = "";
95
+ try {
96
+ const disp = await box.run("sf", ["org", "display", "--target-org", tmpAlias, "--json"]).catch(() => null);
97
+ if (disp === null || disp.code !== 0)
98
+ throw new EcaStop(1, `${o.label}の接続情報を取得できませんでした。`);
99
+ username = jsonPath(disp.stdout, ["result", "username"]);
100
+ if (username === "")
101
+ throw new EcaStop(1, `${o.label}の接続ユーザー名を取得できませんでした。`);
102
+ err("[INFO] ログインに成功しました。");
103
+ err(`[INFO] 接続ユーザー: ${username}`);
104
+ // 組織の種類(アプリを作る前に。本番に誤って作らないため)
105
+ const q = await box
106
+ .run("sf", [
107
+ "data",
108
+ "query",
109
+ "--query",
110
+ "SELECT Id, Name, IsSandbox, OrganizationType, TrialExpirationDate FROM Organization LIMIT 1",
111
+ "--target-org",
112
+ tmpAlias,
113
+ "--json",
114
+ ])
115
+ .catch(() => null);
116
+ info = q !== null && q.code === 0 ? parseOrgInfo(q.stdout) : null;
117
+ if (info === null)
118
+ err("[WARNING] 組織の種類を、組織から読み取れませんでした(権限・通信など)。");
119
+ const kind = orgKind(info);
120
+ err(`[INFO] ログインした組織: ${info?.name || "(名前を取得できません)"}(${orgKindLabel(kind)}${info ? ` / 組織 ID ${info.id}` : ""})`);
121
+ const problem = orgGuardProblem(o.tier, o.label, kind);
122
+ if (problem !== null) {
123
+ err(`[ERROR] ${problem}`);
124
+ throw new EcaStop(1, `${o.label}(${o.tier})に、Salesforce の本番組織、または、種類を判定できない組織は、つなげません(本番組織は main のみです)。`);
125
+ }
126
+ if (kind === "unknown")
127
+ err("[WARNING] 組織の種類を判定できませんでした(main のため、このまま続行します)。");
128
+ const prof = await box
129
+ .run("sf", [
130
+ "data",
131
+ "query",
132
+ "--query",
133
+ `SELECT Profile.Name FROM User WHERE Username='${username}'`,
134
+ "--target-org",
135
+ tmpAlias,
136
+ "--json",
137
+ ])
138
+ .catch(() => null);
139
+ const profile = prof !== null && prof.code === 0 ? jsonPath(prof.stdout, ["result", "records", 0, "Profile", "Name"]) : "";
140
+ if (profile === "")
141
+ throw new EcaStop(1, "接続ユーザーのプロファイル名を取得できませんでした。");
142
+ err(`[INFO] プロファイル: ${profile}`);
143
+ // 4. アプリを作る
144
+ work = deps.makeTempDir();
145
+ let cert = "";
146
+ try {
147
+ cert = box.files.readText(o.certFile);
148
+ }
149
+ catch {
150
+ throw new EcaStop(1, "外部クライアントアプリのメタデータを生成できませんでした。");
151
+ }
152
+ for (const f of ecaMetadata(app, username, profile, cert)) {
153
+ const dir = f.path.includes("/") ? `${work}/${f.path.slice(0, f.path.lastIndexOf("/"))}` : work;
154
+ box.files.makeDir(dir);
155
+ box.files.writeText(`${work}/${f.path}`, f.text);
156
+ }
157
+ err(`[INFO] 外部クライアントアプリ(${app})を作成します(メタデータの deploy)...`);
158
+ const dep = await box
159
+ .run("sf", ["project", "deploy", "start", "--source-dir", "force-app", "--target-org", tmpAlias], { cwd: work })
160
+ .catch(() => null);
161
+ if (dep === null || dep.code !== 0)
162
+ throw new EcaStop(1, "外部クライアントアプリの作成(deploy)に失敗しました。");
163
+ // 5. コンシューマー鍵(値は出さない)
164
+ const ret = await box
165
+ .run("sf", ["project", "retrieve", "start", "--metadata", `ExtlClntAppGlobalOauthSettings:${app}_glbloauth`, "--target-org", tmpAlias], {
166
+ cwd: work,
167
+ })
168
+ .catch(() => null);
169
+ if (ret === null || ret.code !== 0)
170
+ throw new EcaStop(1, "コンシューマー鍵の取得(retrieve)に失敗しました。");
171
+ const keyXml = `${work}/force-app/main/default/extlClntAppGlobalOauthSets/${app}_glbloauth.ecaGlblOauth-meta.xml`;
172
+ try {
173
+ consumerKey = /<consumerKey>(.*)<\/consumerKey>/.exec(box.files.readText(keyXml))?.[1] ?? "";
174
+ }
175
+ catch {
176
+ consumerKey = "";
177
+ }
178
+ }
179
+ finally {
180
+ if (work !== "")
181
+ deps.removeDir(work);
182
+ await unalias(); // sf org logout は、同じユーザー名の全エイリアスの認証を消すため使わない
183
+ }
184
+ if (consumerKey === "")
185
+ throw new EcaStop(1, "コンシューマー鍵を取得できませんでした。");
186
+ err("[INFO] コンシューマー鍵を取得しました。");
187
+ // 6. JWT の接続テスト(一時的なホームの中: エイリアスが増えず、同じユーザーの既存の認証も置き換わらない)
188
+ err(`[INFO] JWT 接続テストを実行中...(反映待ちのため、成功するまで最大 ${retries} 回リトライします)`);
189
+ const mask = (s) => s.split(consumerKey).join("***masked***");
190
+ let ok = false;
191
+ let last = "";
192
+ for (let i = 1; i <= retries; i++) {
193
+ const home = deps.makeTempDir();
194
+ try {
195
+ const env = { HOME: home, USERPROFILE: home };
196
+ if (deps.platform !== "win32")
197
+ env.SF_USE_GENERIC_UNIX_KEYCHAIN = "true";
198
+ const r = await box
199
+ .run("sf", [
200
+ "org",
201
+ "login",
202
+ "jwt",
203
+ "--client-id",
204
+ consumerKey,
205
+ "--jwt-key-file",
206
+ o.keyFile,
207
+ "--username",
208
+ username,
209
+ "--instance-url",
210
+ url,
211
+ "--alias",
212
+ o.alias,
213
+ ], { env })
214
+ .catch(() => null);
215
+ last = r?.output ?? "sf を起動できません";
216
+ ok = r !== null && r.code === 0;
217
+ }
218
+ finally {
219
+ deps.removeDir(home);
220
+ }
221
+ if (ok || i >= retries)
222
+ break;
223
+ err(`[INFO] Salesforce の反映を待っています(${i} / ${retries} 回目・最大 約 ${Math.floor(((retries - 1) * interval + 59) / 60)} 分)。${interval} 秒後に、もう一度、確認します...`);
224
+ await box.clock.sleep(interval * 1000);
225
+ }
226
+ if (ok)
227
+ err("[SUCCESS] JWT 接続テスト成功。");
228
+ else {
229
+ err(`[ERROR] [jwt error] ${mask(last).trim()}`);
230
+ err("[WARNING] JWT 接続テストに成功しませんでした(反映待ち・ユーザーのプロファイル・組織の種類などを確認してください)。");
231
+ const a = await ask("", "接続テストをスキップして GitHub Secrets への登録のみ行いますか?(GitHub Actions で後でテストできます)");
232
+ if (a === "need")
233
+ throw new EcaStop(20, "");
234
+ if (a !== "yes")
235
+ throw new EcaStop(1, "JWT 接続テストに失敗しました。");
236
+ err("[WARNING] 接続テストをスキップします。GitHub Actions で動作を確認してください。");
237
+ }
238
+ // 7. 登録(コンシューマー鍵は標準入力で渡す)
239
+ const gh = (args, input) => box.run("gh", args, input !== undefined ? { input } : {}).then((r) => r.code === 0, () => false);
240
+ if (!(await gh(["secret", "set", `SF_CONSUMER_KEY_${o.suffix}`, "-R", o.repo], consumerKey)))
241
+ throw new EcaStop(1, `SF_CONSUMER_KEY_${o.suffix} の登録に失敗しました。`);
242
+ if (!(await gh(["variable", "set", `SF_USERNAME_${o.suffix}`, "--body", username, "-R", o.repo])))
243
+ throw new EcaStop(1, `SF_USERNAME_${o.suffix} の登録に失敗しました。`);
244
+ if (!(await gh(["variable", "set", `SF_INSTANCE_URL_${o.suffix}`, "--body", url, "-R", o.repo])))
245
+ throw new EcaStop(1, `SF_INSTANCE_URL_${o.suffix} の登録に失敗しました。`);
246
+ err(`[SUCCESS] SF_CONSUMER_KEY_${o.suffix}(Secret)/ SF_USERNAME_${o.suffix}(Variable)/ SF_INSTANCE_URL_${o.suffix}(Variable)を登録しました。`);
247
+ if (info !== null) {
248
+ const values = [
249
+ [`SF_ORG_ID_${o.suffix}`, info.id],
250
+ [`SF_ORG_NAME_${o.suffix}`, info.name],
251
+ [`SF_ORG_KIND_${o.suffix}`, orgKind(info)],
252
+ [`SF_ORG_CHECKED_${o.suffix}`, deps.nowText()],
253
+ ];
254
+ for (const [name, value] of values)
255
+ if (!(await gh(["variable", "set", name, "--body", value, "-R", o.repo])))
256
+ err(`[WARNING] ${name} を保存できませんでした。`);
257
+ }
258
+ return info;
259
+ }
@@ -0,0 +1,12 @@
1
+ // 全体で共通の終了コード(doc/rebuild-design.md 5.1)。
2
+ // ほかの意味のあるコードは、コマンドごとに、サブコマンドの定義(command.ts の exitCodes)に書く
3
+ export const EXIT = {
4
+ /** 成功 */
5
+ ok: 0,
6
+ /** 失敗 */
7
+ failure: 1,
8
+ /** AI 操作の確認待ち */
9
+ needAnswer: 20,
10
+ /** Ctrl+C での中断 */
11
+ interrupted: 130,
12
+ };
@@ -0,0 +1,46 @@
1
+ // gh のログインからの、オーナーとプロジェクトの候補。シェル版の lib/identity.sh の gh_owner_candidates・gh_existing_projects の移し先
2
+ // (doc/rebuild-design.md 11.2 の段階 1)。gh が使えない・未認証・失敗のときは、何も出さない(呼ぶ側が、入力に切り替える)
3
+ async function ghLines(box, args) {
4
+ try {
5
+ const r = await box.run("gh", args);
6
+ if (r.code !== 0)
7
+ return [];
8
+ return r.stdout
9
+ .split("\n")
10
+ .map((l) => l.replace(/\r$/, ""))
11
+ .filter((l) => l.trim() !== "");
12
+ }
13
+ catch {
14
+ return []; // gh を起動できない
15
+ }
16
+ }
17
+ /**
18
+ * オーナーの候補(組織 → 自分のアカウントの順。重複なし)。
19
+ * admin = 自分が管理者(admin かつ active)の組織(sf-project 用) / member = 自分が所属する組織(sf-job 用)
20
+ */
21
+ export async function ghOwnerCandidates(box, kind = "member") {
22
+ const orgs = kind === "admin"
23
+ ? await ghLines(box, [
24
+ "api",
25
+ "user/memberships/orgs",
26
+ "--jq",
27
+ '.[] | select(.role=="admin" and .state=="active") | .organization.login',
28
+ ])
29
+ : await ghLines(box, ["api", "user/orgs", "--jq", ".[].login"]);
30
+ const me = await ghLines(box, ["api", "user", "--jq", ".login"]);
31
+ return [...new Set([...orgs, ...me])];
32
+ }
33
+ /** そのオーナーにある force-* リポジトリの、XXXX(force- を除いた名前)。gh repo list の最大 200 件から探す */
34
+ export async function ghExistingProjects(box, owner) {
35
+ return ghLines(box, [
36
+ "repo",
37
+ "list",
38
+ owner,
39
+ "--limit",
40
+ "200",
41
+ "--json",
42
+ "name",
43
+ "--jq",
44
+ '.[].name | select(startswith("force-")) | sub("^force-";"")',
45
+ ]);
46
+ }
@@ -0,0 +1,130 @@
1
+ /** フックが呼ぶ、凍結した入口(プロジェクトのルートからの相対パス。設計 4.6・5.7) */
2
+ export const HOOK_ENTRY = "sf-tools/node_modules/@tama-create/sf-tools/bin/sft.js";
3
+ /** sf-tools が入れたフックの目印(lib/common.sh の SF_HOOK_MARKER と同じ文言。シェル版の sf-unhook.sh も、これで見分ける) */
4
+ export const HOOK_MARKER = "# Generated by sf-tools: wrapper for pre-push hook";
5
+ /** sh の単一引用符の中に入れる文字(' を '\'' にする) */
6
+ function shQuote(s) {
7
+ return `'${s.replace(/'/g, "'\\''")}'`;
8
+ }
9
+ /** フックの中身(sh。Windows でも git が付属の sh で動かす) */
10
+ export function hookScript(which, nodePath) {
11
+ const tag = which === "pre-commit" ? "PRE-COMMIT" : "PRE-PUSH";
12
+ return [
13
+ "#!/bin/sh",
14
+ HOOK_MARKER,
15
+ `# sft hook install が入れた ${which} フック。node で sft の凍結した入口を呼ぶだけ(本体は sft hook run ${which})。`,
16
+ "# node は、PATH のものを先に使い、なければ、入れたときに記録した絶対パスを使う(GUI の Git・nvm への備え)",
17
+ `ENTRY="${HOOK_ENTRY}"`,
18
+ `NODE_RECORDED=${shQuote(nodePath)}`,
19
+ 'if [ ! -f "$ENTRY" ]; then',
20
+ ` echo "[${tag}][ERROR] sft が見つかりません: $ENTRY(sf-tools フォルダで npm ci を実行してください)" >&2`,
21
+ " exit 1",
22
+ "fi",
23
+ "if command -v node >/dev/null 2>&1; then",
24
+ " NODE=node",
25
+ 'elif [ -x "$NODE_RECORDED" ]; then',
26
+ ' NODE="$NODE_RECORDED"',
27
+ "else",
28
+ ` echo "[${tag}][ERROR] node が見つかりません(PATH にも、記録した場所 $NODE_RECORDED にもありません)" >&2`,
29
+ " exit 1",
30
+ "fi",
31
+ `exec "$NODE" "$ENTRY" hook run ${which} "$@"`,
32
+ "",
33
+ ].join("\n");
34
+ }
35
+ async function gitConfig(box, args) {
36
+ const r = await box.run("git", ["config", ...args]).catch(() => null);
37
+ return r !== null && r.code === 0 ? r.stdout.trim() : "";
38
+ }
39
+ export async function runHookInstall(box, deps) {
40
+ const err = (s) => box.output.err(s);
41
+ if (!box.files.isDir(".git")) {
42
+ err("[ERROR] カレントフォルダに .git ディレクトリがありません(Git リポジトリのルートではありません)。");
43
+ return 1;
44
+ }
45
+ if (!box.files.exists(HOOK_ENTRY)) {
46
+ err(`[ERROR] sft の凍結した入口がありません: ${HOOK_ENTRY}。フックを入れると、コミット・プッシュが止まるため、入れません。`);
47
+ return 1;
48
+ }
49
+ const local = await gitConfig(box, ["--local", "core.hooksPath"]);
50
+ if (local.includes("husky")) {
51
+ err(`[WARNING] core.hooksPath が '${local}' に設定されています。削除します...`);
52
+ const r = await box.run("git", ["config", "--local", "--unset", "core.hooksPath"]).catch(() => null);
53
+ if (r === null || r.code !== 0) {
54
+ err("[ERROR] core.hooksPath の削除に失敗しました。");
55
+ return 1;
56
+ }
57
+ }
58
+ const other = await gitConfig(box, ["core.hooksPath"]);
59
+ if (other !== "") {
60
+ err(`[WARNING] core.hooksPath が '${other}' に設定されているため、git は .git/hooks/ を使いません。入れたフックは、動きません。`);
61
+ }
62
+ box.files.makeDir(".git/hooks");
63
+ for (const which of ["pre-commit", "pre-push"]) {
64
+ const dest = `.git/hooks/${which}`;
65
+ box.files.writeText(dest, hookScript(which, deps.nodePath));
66
+ deps.makeExecutable(dest);
67
+ box.output.out(`[SUCCESS] ${which} フックを強制適用しました。`);
68
+ }
69
+ box.output.out(other === ""
70
+ ? "[INFO] 次回以降の git commit / push 時に自動的に検証が実行されます。"
71
+ : "[WARNING] core.hooksPath が設定されているため、入れたフックは、git commit / push で動きません。");
72
+ return 0;
73
+ }
74
+ export function runHookRemove(box) {
75
+ const dest = ".git/hooks/pre-push";
76
+ if (!box.files.isDir(".git")) {
77
+ box.output.err("[ERROR] カレントフォルダに .git ディレクトリがありません(Git リポジトリのルートではありません)。");
78
+ return 1;
79
+ }
80
+ if (!box.files.exists(dest)) {
81
+ box.output.out("[INFO] フックはすでに無効化されています(ファイルが存在しません)。");
82
+ return 0;
83
+ }
84
+ if (!box.files.readText(dest).includes(HOOK_MARKER)) {
85
+ box.output.err(`[WARNING] sf-tools が管理するフックではないためスキップしました: ${dest}`);
86
+ return 0;
87
+ }
88
+ box.files.removeFile(dest);
89
+ box.output.out("[SUCCESS] pre-push フックを無効化しました。次回以降の git push 時には、自動検証は行われません。");
90
+ return 0;
91
+ }
92
+ /**
93
+ * フックの実行時の版の確認(設計 5.7)。フックは全体の sft を通らないため、ここで、固定の版(sf-tools/package-lock.json)と、
94
+ * 入っている版(sf-tools/node_modules/@tama-create/sf-tools/package.json)を比べる。違えば、事実を出して止める(git pull で固定の版が
95
+ * 変わったあとに、古い版で動き続けないため)。固定の記録(package-lock.json の項目)がなければ、比べない(版を固定していないプロジェクト)。
96
+ * 戻り値: null = 進んでよい/文字列 = 止める理由
97
+ */
98
+ export function hookVersionProblem(box) {
99
+ const lockPath = "sf-tools/package-lock.json";
100
+ const installedPath = "sf-tools/node_modules/@tama-create/sf-tools/package.json";
101
+ const readJson = (path) => {
102
+ if (!box.files.exists(path))
103
+ return null;
104
+ try {
105
+ const v = JSON.parse(box.files.readText(path));
106
+ return typeof v === "object" && v !== null && !Array.isArray(v) ? v : "broken";
107
+ }
108
+ catch {
109
+ return "broken";
110
+ }
111
+ };
112
+ const lock = readJson(lockPath);
113
+ if (lock === null)
114
+ return null;
115
+ if (lock === "broken")
116
+ return `${lockPath} を JSON として読めません。`;
117
+ const packages = lock.packages;
118
+ const locked = packages?.["node_modules/@tama-create/sf-tools"]?.version;
119
+ if (typeof locked !== "string")
120
+ return null;
121
+ const installed = readJson(installedPath);
122
+ if (installed === null)
123
+ return `固定の版は ${locked} ですが、${installedPath} がありません(sf-tools フォルダで npm ci を実行してください)。`;
124
+ if (installed === "broken")
125
+ return `${installedPath} を JSON として読めません。`;
126
+ if (installed.version !== locked) {
127
+ return `固定の版は ${locked} ですが、入っている版は ${String(installed.version)} です(sf-tools フォルダで npm ci を実行してください)。`;
128
+ }
129
+ return null;
130
+ }
@@ -0,0 +1,116 @@
1
+ // git フックの本体(sft hook run pre-commit / pre-push)。シェル版の phases/hook/precommit.sh・prepush.sh の移し先。
2
+ // フックは、凍結した入口を node で呼ぶ数行だけ(doc/rebuild-design.md 5.7)。ここが、判断を受け持つ。終了コード 0 以外 = コミット・プッシュを中止する。
3
+ import { branchList, isProtectedBranch } from "./branches.js";
4
+ import { runCheck } from "./check.js";
5
+ import { EXIT } from "./exit-codes.js";
6
+ /** pre-commit: ターゲットファイルを検証して、エラーならコミットを中止する */
7
+ export function runPreCommit(box, deps) {
8
+ box.output.err("[HEADER] コミット前チェックを開始します (sf-hook pre-commit)");
9
+ box.output.err("[INFO] ターゲットファイルを検証します。");
10
+ if (runCheck([], box, deps.capability()) !== 0) {
11
+ box.output.err("[ERROR] ターゲットファイルの検証に失敗しました。コミットを中止します。");
12
+ return EXIT.failure;
13
+ }
14
+ box.output.err("[SUCCESS] チェック完了。コミットを続行します。");
15
+ return EXIT.ok;
16
+ }
17
+ /** branches.txt のブランチを、fetch してよい名前に絞る(英数字で始まり、英数字・. _ / - だけ。branches.txt はリポジトリで共有されるため) */
18
+ export function isFetchableName(name) {
19
+ return /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(name);
20
+ }
21
+ /**
22
+ * pre-push: 保護ブランチの上からのプッシュ・保護ブランチへのプッシュを拒否し、ターゲットファイルを検証して、
23
+ * origin/<自ブランチ> と origin/main の未取り込みのコミットを merge で取り込む。取り込んだら、そのプッシュを中止する(もう一度プッシュすると通る)
24
+ */
25
+ export async function runPrePush(box, deps) {
26
+ const log = (level, text) => box.output.err(`[${level}] ${text}`);
27
+ const die = (text) => {
28
+ log("ERROR", text);
29
+ return EXIT.failure;
30
+ };
31
+ const git = (...a) => box.run("git", a).catch(() => ({ code: 1, stdout: "", stderr: "", output: "" }));
32
+ log("HEADER", "main 同期チェックを開始します (sf-hook pre-push)");
33
+ const refs = await deps.readPushRefs();
34
+ const sym = await git("symbolic-ref", "-q", "--short", "HEAD");
35
+ if (sym.code !== 0 || sym.stdout.trim() === "")
36
+ return die("現在の HEAD がブランチを指していません(detached HEAD)。プッシュを中止しました。");
37
+ const current = sym.stdout.trim();
38
+ const listFile = "sf-tools/config/branches.txt";
39
+ const list = branchList(box.files.exists(listFile) ? box.files.readText(listFile) : null);
40
+ if (isProtectedBranch(current, list.branches))
41
+ return die(`${current} ブランチ(保護ブランチ)からの直接プッシュは禁止されています。`);
42
+ for (const line of refs.split("\n")) {
43
+ const remoteRef = line.trim().split(/\s+/)[2] ?? "";
44
+ if (!remoteRef.startsWith("refs/heads/"))
45
+ continue;
46
+ const target = remoteRef.slice("refs/heads/".length);
47
+ if (isProtectedBranch(target, list.branches))
48
+ return die(`${target} ブランチへの直接プッシュは禁止されています(プッシュ先: ${remoteRef})。`);
49
+ }
50
+ if (runCheck([], box, deps.capability()) !== 0)
51
+ return die("ターゲットファイルの検証でエラーがありました。プッシュを中断しました。");
52
+ // --- 最新の取得(現在のブランチ・保護ブランチ。origin にあるものだけ) ---
53
+ log("INFO", "リモート(origin)の最新情報を確認中...");
54
+ const onOrigin = async (b) => (await git("ls-remote", "--exit-code", "origin", b)).code === 0;
55
+ const targets = [];
56
+ const ownOnOrigin = await onOrigin(current);
57
+ if (ownOnOrigin)
58
+ targets.push(current);
59
+ for (const raw of list.branches) {
60
+ const b = raw.trim();
61
+ if (b === "")
62
+ continue;
63
+ if (!isFetchableName(b)) {
64
+ log("WARNING", `branches.txt に、使えないブランチ名があります(取得しません): ${b}`);
65
+ continue;
66
+ }
67
+ if (!(await onOrigin(b))) {
68
+ log("WARNING", `branches.txt のブランチが、origin に、まだありません(取得しません): ${b}`);
69
+ continue;
70
+ }
71
+ targets.push(b);
72
+ }
73
+ if (targets.length > 0 && (await git("fetch", "-q", "origin", "--", ...targets)).code !== 0)
74
+ return die("リモート情報の取得に失敗しました。");
75
+ // --- 取り込み(自ブランチ → main の順) ---
76
+ let merged = false;
77
+ const pull = async (remote, own) => {
78
+ const missing = await git("log", `${current}..origin/${remote}`, "--oneline");
79
+ if (missing.code !== 0)
80
+ return die(`origin/${remote} との差分を確認できませんでした(git log ${current}..origin/${remote} が失敗しました)。プッシュを中止しました。`);
81
+ const commits = missing.stdout.trim();
82
+ if (commits === "") {
83
+ log(own ? "INFO" : "SUCCESS", own ? `${current} ブランチはリモートと同期されています。` : "main ブランチと同期されています。");
84
+ return null;
85
+ }
86
+ log("WARNING", own
87
+ ? `リモートの ${current} ブランチが更新されています。自動的に取り込みます...`
88
+ : "リモートの main ブランチが更新されています。自動的に取り込みます...");
89
+ log("INFO", "取り込むコミット:");
90
+ box.output.err("--------------------------------------------------");
91
+ box.output.err(commits);
92
+ box.output.err("--------------------------------------------------");
93
+ if ((await git("merge", `origin/${remote}`)).code !== 0) {
94
+ await git("merge", "--abort");
95
+ return die(`origin/${remote} の自動取り込み(git merge)に失敗しました。プッシュを中止しました。`);
96
+ }
97
+ log("SUCCESS", own ? `${current} ブランチのリモート変更を取り込みました。` : "main ブランチの変更を自動的に取り込みました。");
98
+ merged = true;
99
+ return null;
100
+ };
101
+ if (ownOnOrigin) {
102
+ const r = await pull(current, true);
103
+ if (r !== null)
104
+ return r;
105
+ }
106
+ else {
107
+ log("INFO", `リモートに ${current} ブランチがまだ存在しません。スキップします。`);
108
+ }
109
+ const r2 = await pull("main", false);
110
+ if (r2 !== null)
111
+ return r2;
112
+ if (merged)
113
+ return die("リモートの変更を、現在のブランチに取り込みました(早送りを含む)。このプッシュには、取り込みが含まれないため、中止しました。");
114
+ log("SUCCESS", "すべてのチェックが完了しました。プッシュを継続します。");
115
+ return EXIT.ok;
116
+ }
@@ -0,0 +1,48 @@
1
+ // プロジェクトの特定のうち、判定だけの部分(GitHub の URL の読み取り・プロジェクト名の正規化)。
2
+ // シェル版の lib/identity.sh の parse_github_remote・normalize_project_name の移し先(doc/rebuild-design.md 11.2 の段階 1)。
3
+ // git・gh を呼ぶ部分は、道具の箱を使うので、あとで別のモジュールに足す
4
+ /**
5
+ * GitHub の URL から owner と repo を取り出す。対応: https://github.com/o/r(.git)・https://user@github.com/o/r・
6
+ * http://github.com/o/r・git@github.com:o/r(.git)・ssh://git@github.com/o/r(末尾の / と .git は除く)。
7
+ * GitHub の URL でない・owner/repo の 2 階層でないときは null
8
+ */
9
+ export function parseGithubRemote(url) {
10
+ let rest;
11
+ if (/^https:\/\/github\.com\//.test(url) || /^https:\/\/[^/]*@github\.com\//.test(url) || /^http:\/\/github\.com\//.test(url)) {
12
+ rest = url.slice(url.indexOf("github.com/") + "github.com/".length);
13
+ }
14
+ else if (url.startsWith("git@github.com:")) {
15
+ rest = url.slice("git@github.com:".length);
16
+ }
17
+ else if (url.startsWith("ssh://git@github.com/")) {
18
+ rest = url.slice("ssh://git@github.com/".length);
19
+ }
20
+ else {
21
+ return null;
22
+ }
23
+ if (rest.endsWith("/"))
24
+ rest = rest.slice(0, -1);
25
+ if (rest.endsWith(".git"))
26
+ rest = rest.slice(0, -4);
27
+ const parts = rest.split("/");
28
+ if (parts.length !== 2 || parts[0] === "" || parts[1] === "")
29
+ return null;
30
+ return { owner: parts[0], repo: parts[1] };
31
+ }
32
+ /**
33
+ * 入力から XXXX(リポジトリ名 force-XXXX の、force- の後ろ)を取り出す。前後の空白と、先頭の force-(大文字小文字を問わない)を除く。
34
+ * 使える文字は英数字と - _ .(英数字の間に 1 つだけ)。50 文字まで。末尾の .git は不可。
35
+ * 理由: 外部クライアントアプリの名前が、Salesforce の API 名の制約(連続した _・末尾の _ は不可。80 文字まで)を満たすため。不正なら null
36
+ */
37
+ export function normalizeProjectName(input) {
38
+ let name = input.trim();
39
+ if (/^force-/i.test(name))
40
+ name = name.slice(6);
41
+ if (name.length > 50)
42
+ return null;
43
+ if (!/^[A-Za-z0-9]+([._-][A-Za-z0-9]+)*$/.test(name))
44
+ return null;
45
+ if (name.endsWith(".git"))
46
+ return null;
47
+ return name;
48
+ }