@tamai/hub-cli 0.1.10 → 0.1.12

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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @tamai/hub-cli
2
2
 
3
- hub(tamai個人のパーソナルハブ)のタスク看板、プロジェクト、インフラ資産を操作する CLI。
3
+ hub(tamai個人のパーソナルハブ)のタスク看板、プロジェクト、インフラ資産、デプロイ先を操作する CLI。
4
4
  状態の正本は hub の D1 であり、この CLI はそれを読み書きする唯一の道具である。
5
5
  依存ゼロ(`node:` のみ)。**認証は tamai の Cloudflare Access service token が要る**ので、
6
6
  それを持っていない環境では何もできない。API の契約・権限・エラーの意味は
@@ -64,11 +64,13 @@ hub --help
64
64
  hub task help
65
65
  hub project help
66
66
  hub infra help
67
+ hub deploy help
67
68
  ```
68
69
 
69
70
  動詞は `task` が `new` / `add` / `claim` / `next` / `show` / `report` / `note` / `list` / `audit` / `brief`、
70
71
  `project` が `list` / `show` / `create` / `update` / `move`、
71
- `infra` が `list` / `show` / `update` / `note` / `link` / `unlink`。
72
+ `infra` が `list` / `new` / `show` / `update` / `note` / `link` / `unlink`、
73
+ `deploy` が `list` / `show` / `link` / `unlink`。
72
74
  **正確なオプションは常に `--help` を見る**(ここにも、スキルにも写経しない)。
73
75
  全動詞が `--json` を受ける。機械が読むときは必ず `--json` を使い、人向けの整形を parse しない。
74
76
 
@@ -150,13 +152,29 @@ hub task brief 183 --role review --worker codex1 --out /tmp/brief-183.md --sandb
150
152
  警告が出て「対象は依頼者から受け取る」と書かれる。案件が引けないときは案件の節を省いて警告し、
151
153
  依頼書そのものは出す(看板が引けないときだけ何も出さない)。
152
154
 
155
+ ### デプロイ先を読む・案件に紐付ける
156
+
157
+ ```bash
158
+ hub deploy list --platform cloudflare_workers --project hub
159
+ hub deploy show hub-dash
160
+ hub deploy link hub-dash --project hub
161
+ hub deploy unlink hub-dash --project hub
162
+ ```
163
+
164
+ `show` / `link` / `unlink` は名前の完全一致またはIDで指定する。同名の対象が複数あるときは、
165
+ 候補のplatform・アカウント・IDを見てIDで指定する。`link` は現在の集合へ追加し、`unlink` は
166
+ 指定した案件だけを外す。両方とも `--project` が必須で、繰り返し指定できる。
167
+ 最新のversionをGETして全置換PUTへ渡す。409は自動再送せず、APIのエラーをそのまま返す。
168
+ これはhubに記録したデプロイ先の操作であり、providerへデプロイするコマンドではない。
169
+
153
170
  ### インフラ資産を読む・更新する
154
171
 
155
172
  ```bash
156
173
  hub infra list # 自分で管理する資産だけ(既定)
157
174
  hub infra list --management all # 他社管理を含む全件
175
+ hub infra new --kind domain --name example.jp --provider xserver --renewal-policy undecided
158
176
  hub infra show example.jp
159
- hub infra update example.jp --status to_cancel --reason '11/30までに解約と決めた'
177
+ hub infra update example.jp --renewal-policy let_expire --reason '11/30までに解約と決めた'
160
178
  hub infra update example.jp --prod-platform none # 本番の置き場なし(確定値)
161
179
  hub infra update example.jp --renew-source bundled --bundle-server motokura
162
180
  hub infra update example.jp --transfer-to cloudflare --transfer-stage awaiting_approval \
@@ -174,6 +192,12 @@ hub infra unlink example.jp # 紐付けを全部外す
174
192
  1回だけ再試行する。`link` は現在の紐付けへ追加、`unlink` は指定分を削除し、APIへはどちらも
175
193
  `PUT /:id/projects` の全置換として送る。
176
194
 
195
+ `--status` は契約の**現在**(`active`=契約中 / `cancelled`=終了 / `needs_review`=要確認)で、
196
+ `--renewal-policy` が継続の**意思**(`renew` / `let_expire` / `cancel_now` / `while_bundled` / `undecided`)を持つ。
197
+ `--status to_cancel` と `--migration-plan cancel` は**APIを呼ぶ前にCLIが拒否**する——どちらも意思なので
198
+ `--renewal-policy` へ移った(台帳に残っている行はデータ移行で消える)。`--renewal-policy none` は
199
+ `undecided` へ戻す(NOT NULLの列なので空にはしない)。
200
+
177
201
  `--renew-source` は更新の**方式**(`paid` / `bundled`)で、`--auto-renew`(確認できた更新状態)とは
178
202
  **別の軸**である。特典ドメインでも `on` には化けない——特典元のサーバー契約が解約されれば更新は止まる。
179
203
  `--bundle-server` は特典元のサーバーで、`bundled` のときだけ持てる(`--hosted-on` と同じく名前かIDで指定する)。
@@ -214,8 +238,13 @@ hub infra note example.jp --note '…' --operation-id 01M33H236V8MACB2DFR641ATK3
214
238
  `none`で未記入(`null`)へ戻せる。`--prod-platform none`だけは「本番の置き場は無い」という
215
239
  確定済みのenum値を送り、未記入には戻さない。
216
240
 
217
- 資産の作成と削除はCLIに持たせない。正確なオプションとserver資産へ指定できない項目は
218
- `hub infra help` を正本とする。
241
+ `new` は `--kind domain|server`、`--name`、`--provider` が必須。
242
+ その他のフィールドオプションは `update` と同じ変換を使い、省略値はAPIの既定に任せる。
243
+ `--append-note` は初期noteになるが、廃止予告は更新時と同じ。
244
+ `--reason` は既存の作成APIが受け付けないため、CLIも書き込み前に拒否する。
245
+ 経緯は作成後に `hub infra note` で足す。
246
+ 作成は通信エラーでも409でも自動再送しない。結果を `show` / `list` で確認してから判断する。
247
+ 削除動詞は作らない。正確なオプションとserver資産へ指定できない項目は `hub infra help` を正本とする。
219
248
 
220
249
  ### `--repo-card` の出力先は cwd 基準
221
250
 
@@ -0,0 +1,20 @@
1
+ import { requireSinglePositional } from "../lib/args.mjs";
2
+ import { deployProjectSlugs, getDeployTarget, requiredProjectSlugs, requireDeployVersion } from "../lib/deploy.mjs";
3
+ import { printDeployResult } from "../lib/format.mjs";
4
+
5
+ export const deployLinkCommand = {
6
+ name: "link",
7
+ options: { allowed: ["project"], repeatable: ["project"] },
8
+ async run({ options, positional, dependencies, api }) {
9
+ const reference = requireSinglePositional(positional, "デプロイ先名またはid");
10
+ const selected = requiredProjectSlugs(options);
11
+ const current = await getDeployTarget(reference, api);
12
+ const currentSlugs = deployProjectSlugs(current.item);
13
+ const slugs = [...new Set([...currentSlugs, ...selected])];
14
+ const payload = await api(`/api/deploy/targets/${encodeURIComponent(current.item.id)}/projects`, {
15
+ method: "PUT",
16
+ body: JSON.stringify({ version: requireDeployVersion(current.item), project_slugs: slugs }),
17
+ });
18
+ printDeployResult(payload, options.json, dependencies.stdout, "projects");
19
+ },
20
+ };
@@ -0,0 +1,16 @@
1
+ import { usageError } from "../lib/args.mjs";
2
+ import { printDeployResult } from "../lib/format.mjs";
3
+
4
+ export const deployListCommand = {
5
+ name: "list",
6
+ options: { allowed: ["platform", "project"] },
7
+ async run({ options, positional, flags, dependencies, api }) {
8
+ if (positional.length !== 0) throw usageError("listに位置引数は指定できません");
9
+ const query = new URLSearchParams();
10
+ if (flags.platform) query.set("platform", options.platform);
11
+ if (flags.project) query.set("project", options.project);
12
+ const suffix = query.size === 0 ? "" : `?${query.toString()}`;
13
+ const payload = await api(`/api/deploy/targets${suffix}`);
14
+ printDeployResult(payload, options.json, dependencies.stdout, "list");
15
+ },
16
+ };
@@ -0,0 +1,13 @@
1
+ import { requireSinglePositional } from "../lib/args.mjs";
2
+ import { getDeployTarget } from "../lib/deploy.mjs";
3
+ import { printDeployResult } from "../lib/format.mjs";
4
+
5
+ export const deployShowCommand = {
6
+ name: "show",
7
+ options: {},
8
+ async run({ options, positional, dependencies, api }) {
9
+ const reference = requireSinglePositional(positional, "デプロイ先名またはid");
10
+ const payload = await getDeployTarget(reference, api);
11
+ printDeployResult(payload, options.json, dependencies.stdout, "show");
12
+ },
13
+ };
@@ -0,0 +1,20 @@
1
+ import { requireSinglePositional } from "../lib/args.mjs";
2
+ import { deployProjectSlugs, getDeployTarget, requiredProjectSlugs, requireDeployVersion } from "../lib/deploy.mjs";
3
+ import { printDeployResult } from "../lib/format.mjs";
4
+
5
+ export const deployUnlinkCommand = {
6
+ name: "unlink",
7
+ options: { allowed: ["project"], repeatable: ["project"] },
8
+ async run({ options, positional, dependencies, api }) {
9
+ const reference = requireSinglePositional(positional, "デプロイ先名またはid");
10
+ const selected = requiredProjectSlugs(options);
11
+ const current = await getDeployTarget(reference, api);
12
+ const currentSlugs = deployProjectSlugs(current.item);
13
+ const slugs = currentSlugs.filter((slug) => !selected.includes(slug));
14
+ const payload = await api(`/api/deploy/targets/${encodeURIComponent(current.item.id)}/projects`, {
15
+ method: "PUT",
16
+ body: JSON.stringify({ version: requireDeployVersion(current.item), project_slugs: slugs }),
17
+ });
18
+ printDeployResult(payload, options.json, dependencies.stdout, "projects");
19
+ },
20
+ };
@@ -0,0 +1,37 @@
1
+ import { usageError } from "../lib/args.mjs";
2
+ import { printInfraResult } from "../lib/format.mjs";
3
+ import {
4
+ APPEND_NOTE_DEPRECATION,
5
+ INFRA_WRITE_OPTIONS,
6
+ prepareInfraFields,
7
+ rejectLegacyValues,
8
+ rejectServerOptions,
9
+ } from "../lib/infra-input.mjs";
10
+
11
+ export const infraNewCommand = {
12
+ name: "new",
13
+ options: { allowed: ["kind", "name", ...INFRA_WRITE_OPTIONS] },
14
+ async run({ options, positional, flags, dependencies, api }) {
15
+ if (positional.length !== 0) throw usageError("newに位置引数は指定できません(--name を使ってください)");
16
+ for (const field of ["kind", "name", "provider"]) {
17
+ if (!flags[field] || options[field].trim() === "") throw usageError(`--${field} が必要です`);
18
+ }
19
+ const kind = options.kind.trim();
20
+ if (kind !== "domain" && kind !== "server") throw usageError("--kind は domain または server を指定してください");
21
+ if (flags.reason) {
22
+ throw usageError("作成APIは --reason を受け付けません。現在の補足は --note、経緯は作成後に hub infra note で記録してください");
23
+ }
24
+ if (flags.note && flags["append-note"]) throw usageError("--note と --append-note は同時に指定できません");
25
+ rejectLegacyValues(options, flags);
26
+ rejectServerOptions(kind, flags);
27
+ if (flags["append-note"]) dependencies.stderr.write(APPEND_NOTE_DEPRECATION);
28
+ const { prepared, appendNote } = await prepareInfraFields(options, flags, api);
29
+ if (appendNote !== null) prepared.note = appendNote;
30
+ // 作成は冪等な操作IDを持たない。通信エラーも含め自動再送しない。
31
+ const payload = await api("/api/infra/assets", {
32
+ method: "POST",
33
+ body: JSON.stringify({ kind, name: options.name.trim(), ...prepared }),
34
+ });
35
+ printInfraResult(payload, options.json, dependencies.stdout, "new");
36
+ },
37
+ };
@@ -1,45 +1,19 @@
1
1
  import { isConflictError, withGuidance } from "../lib/api.mjs";
2
- import { cliError, requireSinglePositional, usageError } from "../lib/args.mjs";
2
+ import { requireSinglePositional, usageError } from "../lib/args.mjs";
3
+ import {
4
+ APPEND_NOTE_DEPRECATION,
5
+ INFRA_WRITE_OPTIONS,
6
+ prepareInfraFields,
7
+ rejectLegacyValues,
8
+ rejectServerOptions,
9
+ } from "../lib/infra-input.mjs";
3
10
  import { printInfraResult } from "../lib/format.mjs";
4
11
  import {
5
- INFRA_DOMAIN_ONLY_OPTIONS,
6
12
  getInfraAsset,
7
13
  getInfraAssetById,
8
14
  requireInfraVersion,
9
15
  } from "../lib/infra.mjs";
10
16
 
11
- const OPTION_FIELDS = {
12
- status: "status",
13
- "auto-renew": "auto_renew",
14
- expires: "expires_on",
15
- "dns-host": "dns_host",
16
- "mail-host": "mail_host",
17
- "migration-plan": "migration_plan",
18
- management: "management",
19
- purpose: "purpose",
20
- provider: "provider",
21
- "prod-platform": "prod_platform",
22
- "prod-ref": "prod_ref",
23
- contract: "contract",
24
- amount: "amount_yen",
25
- payer: "payer",
26
- holder: "holder",
27
- account: "account",
28
- "account-ref": "account_ref",
29
- note: "note",
30
- "hosted-on-basis": "hosted_on_basis",
31
- // 特典と移管(記録191 / migration 0029)。`--bundle-server` だけは名前解決が要るので
32
- // ここには入れず、`--hosted-on` と同じ扱いで別に処理する
33
- "renew-source": "renew_source",
34
- "transfer-to": "transfer_to",
35
- "transfer-stage": "transfer_stage",
36
- "transfer-due": "transfer_due_at",
37
- };
38
-
39
- const ALLOWED_OPTIONS = [
40
- ...Object.keys(OPTION_FIELDS), "append-note", "hosted-on", "reason", "bundle-server",
41
- ];
42
-
43
17
  /**
44
18
  * 移管の3項目を含む更新は **409 で自動再送しない**(所見 Medium 2・記録191)。
45
19
  *
@@ -52,40 +26,12 @@ const TRANSFER_OPTIONS = ["transfer-to", "transfer-stage", "transfer-due"];
52
26
  const TRANSFER_CONFLICT_GUIDANCE =
53
27
  "移管の更新は自動で再送しません。最新の段階を確認してからもう一度実行してください";
54
28
 
55
- /**
56
- * `--append-note` は次の版で外す(記録188 §3.5)。既存noteの末尾へ「 / 」で足す作りは、
57
- * 「現在の補足」と「経緯」を1つの列に混ぜる——経緯は `hub infra note` が別の表へ積む。
58
- * 打つたびに出す(1回だけの告知だと、使い続けている人には届かない)。
59
- */
60
- const APPEND_NOTE_DEPRECATION =
61
- "警告: --append-note は次の版で外します。経緯は hub infra note <name|id> --note <text> へ。\n";
62
-
63
29
  /**
64
30
  * 理由は**読んだ状態に依存する**ので、409で自動的に取り直して再送しない(所見 Medium 2)。
65
31
  * 「A を B にした理由」を書いたあとに他人が A を C へ変えていたら、その理由はもう合わない。
66
32
  */
67
33
  const REASON_CONFLICT_GUIDANCE =
68
34
  "理由つきの更新は自動で再送しません。最新の内容を確認し、理由を書き直してからもう一度実行してください";
69
- const NULLABLE_VALUE_OPTIONS = new Set([
70
- "dns-host",
71
- "mail-host",
72
- "migration-plan",
73
- "contract",
74
- "hosted-on-basis",
75
- "renew-source",
76
- "transfer-to",
77
- "transfer-stage",
78
- "transfer-due",
79
- ]);
80
-
81
- function amountValue(value) {
82
- if (value === "none") return null;
83
- if (!/^\d+$/.test(value)) throw usageError("--amount は0以上の整数か none を指定してください");
84
- const parsed = Number(value);
85
- if (!Number.isSafeInteger(parsed)) throw usageError("--amount は安全な整数の範囲で指定してください");
86
- return parsed;
87
- }
88
-
89
35
  function bodyFor(current, prepared, appendNote, reason) {
90
36
  const body = { version: requireInfraVersion(current), ...prepared };
91
37
  if (appendNote !== null) {
@@ -96,98 +42,65 @@ function bodyFor(current, prepared, appendNote, reason) {
96
42
  return body;
97
43
  }
98
44
 
45
+ /** 理由だけ・空の理由を、台帳を読む前に拒否する。 */
46
+ function updateReason(options, flags) {
47
+ if (!flags.reason) return null;
48
+ if (!INFRA_WRITE_OPTIONS.some((name) => name !== "reason" && flags[name])) {
49
+ throw usageError("--reason は値の変更と一緒に指定してください(経緯だけを足すときは hub infra note)");
50
+ }
51
+ const reason = options.reason.trim();
52
+ if (reason === "") throw usageError("--reason に空文字は指定できません");
53
+ return reason;
54
+ }
55
+
56
+ /** nullなら1回だけ再送可。理由と移管を両方指定した場合も、従来どおり理由の案内を優先する。 */
57
+ function conflictGuidance(flags, reason) {
58
+ if (reason !== null) return REASON_CONFLICT_GUIDANCE;
59
+ if (TRANSFER_OPTIONS.some((name) => flags[name])) return TRANSFER_CONFLICT_GUIDANCE;
60
+ return null;
61
+ }
62
+
63
+ /** 再送のたびに最新versionとnoteから本文を組む。再取得自体の失敗は再送しない。 */
64
+ async function patchWithRetry(api, current, update) {
65
+ for (let attempt = 0; attempt < 2; attempt += 1) {
66
+ try {
67
+ return await api(`/api/infra/assets/${encodeURIComponent(current.id)}`, {
68
+ method: "PATCH",
69
+ body: JSON.stringify(bodyFor(current, update.prepared, update.appendNote, update.reason)),
70
+ });
71
+ } catch (error) {
72
+ if (!isConflictError(error)) throw error;
73
+ if (update.conflictGuidance !== null) throw withGuidance(error, update.conflictGuidance);
74
+ if (attempt === 1) {
75
+ throw withGuidance(error, "再取得後にも競合しました。最新の内容を確認してから、もう一度実行してください");
76
+ }
77
+ current = (await getInfraAssetById(current.id, api)).item;
78
+ }
79
+ }
80
+ }
81
+
99
82
  export const infraUpdateCommand = {
100
83
  name: "update",
101
- options: { allowed: ALLOWED_OPTIONS },
84
+ options: { allowed: INFRA_WRITE_OPTIONS },
102
85
  async run({ options, positional, flags, dependencies, api }) {
103
86
  const reference = requireSinglePositional(positional, "資産名またはid");
104
- if (!ALLOWED_OPTIONS.some((name) => flags[name])) {
105
- throw usageError(`更新するオプションを指定してください: ${ALLOWED_OPTIONS.map((name) => `--${name}`).join(" / ")}`);
87
+ if (!INFRA_WRITE_OPTIONS.some((name) => flags[name])) {
88
+ throw usageError(`更新するオプションを指定してください: ${INFRA_WRITE_OPTIONS.map((name) => `--${name}`).join(" / ")}`);
106
89
  }
107
90
  if (flags.note && flags["append-note"]) {
108
91
  throw usageError("--note と --append-note は同時に指定できません");
109
92
  }
110
- // 理由だけの更新はAPIが400にする(経緯は `hub infra note`)。往復する前にここで案内する
111
- let reason = null;
112
- if (flags.reason) {
113
- if (!ALLOWED_OPTIONS.some((name) => name !== "reason" && flags[name])) {
114
- throw usageError("--reason は値の変更と一緒に指定してください(経緯だけを足すときは hub infra note)");
115
- }
116
- reason = options.reason.trim();
117
- if (reason === "") throw usageError("--reason に空文字は指定できません");
118
- }
93
+ const reason = updateReason(options, flags);
94
+ rejectLegacyValues(options, flags);
119
95
  if (flags["append-note"]) dependencies.stderr.write(APPEND_NOTE_DEPRECATION);
120
96
 
121
- let currentPayload = await getInfraAsset(reference, api);
122
- let current = currentPayload.item;
123
- const forbidden = INFRA_DOMAIN_ONLY_OPTIONS.filter((name) => flags[name]);
124
- if (current.kind === "server" && forbidden.length > 0) {
125
- throw usageError(`server資産にはドメイン専用オプションを指定できません: ${forbidden.map((name) => `--${name}`).join(" / ")}`);
126
- }
127
-
128
- const prepared = {};
129
- for (const [option, field] of Object.entries(OPTION_FIELDS)) {
130
- if (!flags[option] || option === "note") continue;
131
- const value = options[option].trim();
132
- if (option === "expires") prepared[field] = value === "none" ? null : value;
133
- else if (option === "amount") prepared[field] = amountValue(value);
134
- else if (NULLABLE_VALUE_OPTIONS.has(option) && value === "none") prepared[field] = null;
135
- else prepared[field] = value;
136
- }
137
- if (flags.note) prepared.note = options.note.trim();
138
-
139
- let appendNote = null;
140
- if (flags["append-note"]) {
141
- appendNote = options["append-note"].trim();
142
- if (appendNote === "") throw usageError("--append-note に空文字は指定できません");
143
- }
97
+ const { item: current } = await getInfraAsset(reference, api);
98
+ rejectServerOptions(current.kind, flags);
99
+ const { prepared, appendNote } = await prepareInfraFields(options, flags, api);
144
100
 
145
- if (flags["hosted-on"]) {
146
- const hostReference = options["hosted-on"].trim();
147
- if (hostReference === "none") {
148
- prepared.hosted_on = null;
149
- } else {
150
- const host = await getInfraAsset(hostReference, api, { kind: "server" });
151
- if (host.item.kind !== "server") throw cliError("--hosted-on にはserver資産の名前またはidを指定してください");
152
- prepared.hosted_on = host.item.id;
153
- }
154
- }
155
-
156
- // 特典元も server の名前かidで指定する(`--hosted-on` と同じ解決。記録191)
157
- if (flags["bundle-server"]) {
158
- const bundleReference = options["bundle-server"].trim();
159
- if (bundleReference === "none") {
160
- prepared.bundle_server = null;
161
- } else {
162
- const bundle = await getInfraAsset(bundleReference, api, { kind: "server" });
163
- if (bundle.item.kind !== "server") throw cliError("--bundle-server にはserver資産の名前またはidを指定してください");
164
- prepared.bundle_server = bundle.item.id;
165
- }
166
- }
167
-
168
- for (let attempt = 0; attempt < 2; attempt += 1) {
169
- try {
170
- const payload = await api(`/api/infra/assets/${encodeURIComponent(current.id)}`, {
171
- method: "PATCH",
172
- body: JSON.stringify(bodyFor(current, prepared, appendNote, reason)),
173
- });
174
- printInfraResult(payload, options.json, dependencies.stdout, "update");
175
- return;
176
- } catch (error) {
177
- if (!isConflictError(error)) throw error;
178
- // 理由つきは取り直して送り直さない。**書いた理由が古い前提のままになる**ので、
179
- // 人が最新を読んで理由を書き直す(所見 Medium 2・記録188 §3.5)
180
- if (reason !== null) throw withGuidance(error, REASON_CONFLICT_GUIDANCE);
181
- // 移管も同じ(記録191)。段階は外の出来事を見て人が書く値なので巻き戻さない
182
- if (TRANSFER_OPTIONS.some((name) => flags[name])) {
183
- throw withGuidance(error, TRANSFER_CONFLICT_GUIDANCE);
184
- }
185
- if (attempt === 1) {
186
- throw withGuidance(error, "再取得後にも競合しました。最新の内容を確認してから、もう一度実行してください");
187
- }
188
- currentPayload = await getInfraAssetById(current.id, api);
189
- current = currentPayload.item;
190
- }
191
- }
101
+ const payload = await patchWithRetry(api, current, {
102
+ prepared, appendNote, reason, conflictGuidance: conflictGuidance(flags, reason),
103
+ });
104
+ printInfraResult(payload, options.json, dependencies.stdout, "update");
192
105
  },
193
106
  };
@@ -1,6 +1,7 @@
1
- import { cliError, requireSinglePositional } from "../lib/args.mjs";
2
- import { describeFailure } from "../lib/api.mjs";
1
+ import { cliError, requireSinglePositional, usageError } from "../lib/args.mjs";
2
+ import { ApiError, describeFailure, isConflictError, withGuidance } from "../lib/api.mjs";
3
3
  import { taskLines } from "../lib/format.mjs";
4
+ import { newUlid } from "../lib/ulid.mjs";
4
5
  import {
5
6
  DEFAULT_RECORD_DIR,
6
7
  requireRecordSlug,
@@ -9,15 +10,50 @@ import {
9
10
  writeRepoRecord,
10
11
  } from "../lib/records.mjs";
11
12
 
13
+ function operationIdFrom(value) {
14
+ if (value === undefined) return newUlid();
15
+ const id = value.trim().toUpperCase();
16
+ if (!/^[0-9A-HJKMNP-TV-Z]{26}$/.test(id)) {
17
+ throw usageError("--operation-id にはULID(26文字のCrockford Base32)を指定してください");
18
+ }
19
+ return id;
20
+ }
21
+
22
+ /** infra noteと同様、応答を失った場合だけ同じ操作ID・本文で1回再送する。 */
23
+ async function postTask(api, body) {
24
+ const init = { method: "POST", body: JSON.stringify(body) };
25
+ for (let attempt = 0; ; attempt += 1) {
26
+ try {
27
+ return await api("/api/tasks", init);
28
+ } catch (error) {
29
+ // 409は「同じ操作IDが別の内容で使われている」。再送ではないので送り直しを勧めない
30
+ // ——同じIDを付け直しても結果は変わらず、既存タスクを自分の起票と取り違える
31
+ if (isConflictError(error)) {
32
+ throw withGuidance(error,
33
+ `別の操作の id です(操作ID: ${body.id})。\n`
34
+ + "この起票には --operation-id を外して新しく採番するか、別のULIDを指定してください。"
35
+ + `\n同じIDのタスクは hub task show ${body.id} で確かめられます。`);
36
+ }
37
+ const unknownOutcome = !(error instanceof ApiError) && error?.code !== "cli_error";
38
+ if (attempt === 0 && unknownOutcome) continue;
39
+ throw withGuidance(error,
40
+ `操作ID: ${body.id}\n`
41
+ + `同じ起票を送り直すときは --operation-id ${body.id} を付けてください。`
42
+ + (unknownOutcome ? "届いたかどうかは分かりません。" : ""));
43
+ }
44
+ }
45
+ }
46
+
12
47
  export const taskNewCommand = {
13
48
  name: "new",
14
49
  options: {
15
- allowed: ["project", "due", "body-file", "repo-card", "slug", "force"],
50
+ allowed: ["project", "due", "body-file", "repo-card", "slug", "force", "operation-id"],
16
51
  optionalValue: ["repo-card"],
17
52
  boolean: ["force"],
18
53
  },
19
54
  async run({ options, positional, flags, dependencies, api }) {
20
55
  const title = requireSinglePositional(positional, "タイトル");
56
+ const operationId = operationIdFrom(options["operation-id"]);
21
57
  const recordSlug = flags["repo-card"]
22
58
  ? requireRecordSlug(options.slug ?? title, { explicit: options.slug !== undefined })
23
59
  : null;
@@ -31,7 +67,7 @@ export const taskNewCommand = {
31
67
  dependencies.stderr.write(`記録の出力先: ${target.absoluteDir}\n`);
32
68
  }
33
69
 
34
- const body = { title };
70
+ const body = { id: operationId, title };
35
71
  const project = await resolveTaskProject(options.project, {
36
72
  force: flags.force === true,
37
73
  api,
@@ -41,15 +77,18 @@ export const taskNewCommand = {
41
77
  if (options.due) body.due = options.due;
42
78
  if (options["body-file"]) body.body = await dependencies.readFileImpl(options["body-file"], "utf8");
43
79
 
44
- const created = await api("/api/tasks", { method: "POST", body: JSON.stringify(body) });
80
+ const created = await postTask(api, body);
45
81
  const item = created?.item;
46
- if (typeof item?.id !== "string") throw cliError("API応答のタスクIDが不正です");
82
+ if (typeof item?.id !== "string") throw cliError(`API応答のタスクIDが不正です。操作ID: ${operationId}`);
47
83
 
48
84
  let record = null;
49
85
  if (target === null) {
50
86
  dependencies.stderr.write(
51
87
  `注意: --repo-card が無いため ${DEFAULT_RECORD_DIR} に記録は作られません(判断を残すタスクなら --repo-card を付ける)。\n`,
52
88
  );
89
+ } else if (typeof item.context_ref === "string" && item.context_ref.trim() !== "") {
90
+ // 手動再送で既存の記録を別ファイルへ付け替えない。ファイル自体の復旧は別操作。
91
+ dependencies.stderr.write(`既存の記録 ${item.context_ref} との紐付けを維持します。\n`);
53
92
  } else {
54
93
  try {
55
94
  record = await writeRepoRecord({ target, slug: recordSlug, item, dependencies });
package/lib/args.mjs CHANGED
@@ -46,7 +46,7 @@ export const TASK_USAGE = `使い方:
46
46
  hub task note <id> (--note <text> | --note-file <path>) [--json]
47
47
  hub task add <title> [--project <name>] [--force] [--due <YYYY-MM-DD>] [--body-file <path>] [--json]
48
48
  hub task new <title> [--project <name>] [--due <YYYY-MM-DD>] [--body-file <path>]
49
- [--repo-card [<dir>]] [--slug <slug>] [--force] [--json]
49
+ [--repo-card [<dir>]] [--slug <slug>] [--force] [--operation-id <ULID>] [--json]
50
50
  hub task list [--status <s>] [--project <name>] [--owner <name>] [--q <text>] [--json]
51
51
  hub task audit [--json]
52
52
  hub task brief <id> [--role implement|review|design] [--worker <name>] [--commits <range>]
@@ -54,6 +54,7 @@ export const TASK_USAGE = `使い方:
54
54
 
55
55
  show / claim / report / note の <id> には記録番号(150 / #150)も指定できる(context_ref が docs/records/150-… のタスクを一覧から引く。番号はrepoごとの採番なので、複数一致は作業ツリーに記録ファイルがある1件で割る。0件・それでも割れない複数一致はエラー)。
56
56
  hub task new は「D1へ起票 → repoに記録の雛形を作成 → context_ref で紐付け」を1コマンドで行う。
57
+ 通信切断時は同じ操作IDで1回再送する。手動再送は失敗時に出た --operation-id <ULID> を指定する。
57
58
  記録には status / owner / priority を書かない(状態の正本はD1だけ)。
58
59
  --repo-card はリポジトリ相対のディレクトリのみ。context_ref にはリポジトリルート相対のパスが入る。
59
60
  --repo-card で題名からslugを作れない場合は、3文字以上のkebab-caseで --slug <slug> が必要(例: --slug project-detail-pc-layout)。
@@ -104,11 +105,29 @@ export const PROJECT_USAGE = `使い方:
104
105
  オプションは --name=value の形でも書ける(値が -- で始まるときはこの形で渡す)。
105
106
  `;
106
107
 
108
+ export const DEPLOY_USAGE = `使い方:
109
+ hub deploy list [--platform <platform>] [--project <slug>] [--json]
110
+ hub deploy show <name|id> [--json]
111
+ hub deploy link <name|id> --project <slug> [--project <slug>]... [--json]
112
+ hub deploy unlink <name|id> --project <slug> [--project <slug>]... [--json]
113
+
114
+ platform は cloudflare_workers / cloudflare_pages / vercel / xserver / other。
115
+ list はplatform・アカウント・名前の順。絞り込みはANDで合成する。
116
+ show / link / unlink は名前の完全一致またはidで指定する。同名が複数あるときはidで指定する。
117
+ link は現在の紐付けへ追加し、unlink は指定した紐付けだけを外す(--project は必須)。
118
+ version競合時は自動再送しない。最新の紐付けを確認してからもう一度実行する。
119
+ 台帳の紐付けを変えるコマンドであり、providerへのデプロイ操作は行わない。
120
+ オプションは --name=value の形でも書ける。
121
+ `;
122
+
107
123
  export const INFRA_USAGE = `使い方:
108
124
  hub infra list [--kind server|domain] [--status <status[,status...]>] [--management self|external|all]
109
125
  [--project <slug>] [--q <text>] [--json]
126
+ hub infra new --kind domain|server --name <name> --provider <provider> [更新と同じフィールドオプション] [--json]
110
127
  hub infra show <name|id> [--json]
111
- hub infra update <name|id> [--status <status>] [--auto-renew on|off|unknown]
128
+ hub infra update <name|id> [--status active|cancelled|needs_review]
129
+ [--renewal-policy renew|let_expire|cancel_now|while_bundled|undecided|none]
130
+ [--auto-renew on|off|unknown]
112
131
  [--expires YYYY-MM-DD|none] [--dns-host <value>|none]
113
132
  [--mail-host <value>|none] [--migration-plan <value>|none]
114
133
  [--management self|external] [--purpose <text>]
@@ -134,6 +153,10 @@ export const INFRA_USAGE = `使い方:
134
153
  list の --status はカンマ区切りで複数指定できる。
135
154
  show / update / link / unlink の資産は名前の完全一致またはidで指定する。
136
155
  update は指定した項目だけを更新する。version競合時は最新を取り直して1回だけ再試行する。
156
+ --status は契約の**現在**(active=契約中 / cancelled=終了 / needs_review=要確認)。
157
+ --renewal-policy は継続の**意思**(更新するか)。--status to_cancel と
158
+ --migration-plan cancel は書けない(どちらも意思なので --renewal-policy へ移す)。
159
+ --renewal-policy none は要判断(undecided)へ戻す(NOT NULLの列なので空にはしない)。
137
160
  --reason は更新の理由(500文字まで)。値の変更と一緒に指定する(理由だけの更新はできない)。
138
161
  **--reason を含む更新は409で自動再送しない**(理由は読んだ状態に依存するため、
139
162
  最新を確認して書き直す)。
@@ -159,7 +182,11 @@ export const INFRA_USAGE = `使い方:
159
182
  prod-platform / prod-ref / renew-source / bundle-server / transfer-to / transfer-stage /
160
183
  transfer-due を指定できない。
161
184
  link は現在の紐付けへ追加し、unlink は指定分を外す。unlink の --project 省略は全解除。
162
- 作成・削除はCLIから行えない。
185
+ new は台帳へ1件作成する。kind / name / provider は必須。他のフィールドは update と同じ。
186
+ 省略した値の既定はAPIが決める。--append-note は初期noteに入る(廃止予告はupdateと同じ)。
187
+ --reason は更新専用で、作成APIには送れない。経緯は作成後に note で足す。
188
+ 作成は通信エラーや409でも自動再送しない。結果を show / list で確認する。
189
+ 削除はCLIから行えない。
163
190
  オプションは --name=value の形でも書ける(値が -- で始まるときはこの形で渡す)。
164
191
  `;
165
192
 
@@ -168,8 +195,10 @@ export const USAGE = `使い方:
168
195
  hub task help
169
196
  hub project <verb> ... プロジェクト操作(list / show / create / update / move)
170
197
  hub project help
171
- hub infra <verb> ... インフラ資産操作(list / show / update / note / link / unlink)
198
+ hub infra <verb> ... インフラ資産操作(list / new / show / update / note / link / unlink)
172
199
  hub infra help
200
+ hub deploy <verb> ... デプロイ先操作(list / show / link / unlink)
201
+ hub deploy help
173
202
  hub --version 入っているCLIの版を出す(hub version も同じ)
174
203
 
175
204
  環境変数:
@@ -206,7 +235,7 @@ export function usageError(message) {
206
235
  }
207
236
 
208
237
  export function usageLineFor(group, verb) {
209
- const usage = group === "task" ? TASK_USAGE : group === "project" ? PROJECT_USAGE : INFRA_USAGE;
238
+ const usage = { task: TASK_USAGE, project: PROJECT_USAGE, infra: INFRA_USAGE, deploy: DEPLOY_USAGE }[group] ?? "";
210
239
  const lines = usage.split("\n");
211
240
  const prefix = ` hub ${group} ${verb}`;
212
241
  const start = lines.findIndex((line) => line === prefix || line.startsWith(`${prefix} `));
package/lib/cli.mjs CHANGED
@@ -4,6 +4,7 @@
4
4
  //
5
5
  // hub task <verb> ... タスク操作
6
6
  // hub project <verb> ... プロジェクト操作(読み取り + 作成・更新)
7
+ // hub deploy <verb> ... デプロイ先操作(読み取り + 紐付け)
7
8
  // hub infra <verb> ... インフラ資産操作(読み取り + 更新・経緯・紐付け)
8
9
  //
9
10
  // 全サブコマンドが `--json` を受け付け、付けると生のAPI応答をそのまま出力する。
@@ -23,6 +24,7 @@ import {
23
24
  redactSecrets,
24
25
  } from "./api.mjs";
25
26
  import {
27
+ DEPLOY_USAGE,
26
28
  INFRA_USAGE,
27
29
  PROJECT_USAGE,
28
30
  TASK_USAGE,
@@ -31,8 +33,13 @@ import {
31
33
  parseCommandArgs,
32
34
  usageLineFor,
33
35
  } from "./args.mjs";
36
+ import { deployLinkCommand } from "../commands/deploy-link.mjs";
37
+ import { deployListCommand } from "../commands/deploy-list.mjs";
38
+ import { deployShowCommand } from "../commands/deploy-show.mjs";
39
+ import { deployUnlinkCommand } from "../commands/deploy-unlink.mjs";
34
40
  import { infraLinkCommand } from "../commands/infra-link.mjs";
35
41
  import { infraListCommand } from "../commands/infra-list.mjs";
42
+ import { infraNewCommand } from "../commands/infra-new.mjs";
36
43
  import { infraNoteCommand } from "../commands/infra-note.mjs";
37
44
  import { infraShowCommand } from "../commands/infra-show.mjs";
38
45
  import { infraUnlinkCommand } from "../commands/infra-unlink.mjs";
@@ -99,10 +106,15 @@ const COMMAND_GROUPS = {
99
106
  projectUpdateCommand,
100
107
  ]),
101
108
  },
109
+ deploy: {
110
+ usage: DEPLOY_USAGE,
111
+ commands: commandMap([deployListCommand, deployShowCommand, deployLinkCommand, deployUnlinkCommand]),
112
+ },
102
113
  infra: {
103
114
  usage: INFRA_USAGE,
104
115
  commands: commandMap([
105
116
  infraListCommand,
117
+ infraNewCommand,
106
118
  infraShowCommand,
107
119
  infraUpdateCommand,
108
120
  infraNoteCommand,
package/lib/deploy.mjs ADDED
@@ -0,0 +1,60 @@
1
+ import { cliError, usageError } from "./args.mjs";
2
+
3
+ const ULID_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
4
+ const oneLine = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
5
+
6
+ /** 名前は全件中の完全一致だけ。platform・アカウントが違う同名対象はIDで選ぶ。 */
7
+ export async function getDeployTarget(reference, api) {
8
+ const target = reference.trim();
9
+ if (target === "") throw usageError("デプロイ先名またはidを指定してください");
10
+ let id = target.toUpperCase();
11
+ if (!ULID_PATTERN.test(target)) {
12
+ const payload = await api("/api/deploy/targets");
13
+ if (!Array.isArray(payload?.items)) throw cliError("deploy一覧のAPI応答が不正です");
14
+ const items = payload.items.filter((item) => item !== null && typeof item === "object"
15
+ && typeof item.id === "string" && typeof item.name === "string");
16
+ const query = target.toLowerCase();
17
+ const exact = items.filter((item) => item.name.toLowerCase() === query);
18
+ if (exact.length !== 1) {
19
+ const candidates = (exact.length > 1 ? exact : items)
20
+ .map((item) => ({ item, near: item.name.toLowerCase().includes(query) ? 0 : 1 }))
21
+ .sort((left, right) => left.near - right.near || left.item.name.localeCompare(right.item.name, "ja"))
22
+ .slice(0, 3)
23
+ .map(({ item }) => `- ${oneLine(item.name)} [${oneLine(item.platform)}/${oneLine(item.account_key)}] (${oneLine(item.id)})`);
24
+ const reason = exact.length > 1 ? "同名のデプロイ先が複数あります。idで指定してください" : "デプロイ先が見つかりません";
25
+ throw cliError(`${reason}: ${target}\n候補:\n${candidates.join("\n") || "- 該当なし"}`);
26
+ }
27
+ id = exact[0].id;
28
+ }
29
+ const payload = await api(`/api/deploy/targets/${encodeURIComponent(id)}`);
30
+ const item = payload?.item;
31
+ if (item === null || typeof item !== "object" || Array.isArray(item)
32
+ || typeof item.id !== "string" || typeof item.name !== "string") {
33
+ throw cliError("deploy API応答のitemが不正です");
34
+ }
35
+ return payload;
36
+ }
37
+
38
+ export function requireDeployVersion(item) {
39
+ if (!Number.isSafeInteger(item?.version) || item.version < 1) {
40
+ throw cliError("deploy API応答のversionが不正です");
41
+ }
42
+ return item.version;
43
+ }
44
+
45
+ /** 全置換PUTの前に既存集合を検査する。不正な応答から空集合を作らない。 */
46
+ export function deployProjectSlugs(item) {
47
+ if (!Array.isArray(item?.projects) || item.projects.some((project) =>
48
+ typeof project?.slug !== "string" || project.slug.trim() === "")) {
49
+ throw cliError("deploy API応答のprojectsが不正です");
50
+ }
51
+ return [...new Set(item.projects.map((project) => project.slug))];
52
+ }
53
+
54
+ export function requiredProjectSlugs(options) {
55
+ const slugs = options.project.map((slug) => slug.trim());
56
+ if (slugs.length === 0 || slugs.some((slug) => slug === "")) {
57
+ throw usageError("--project <slug> を1つ以上指定してください");
58
+ }
59
+ return [...new Set(slugs)];
60
+ }
package/lib/format.mjs CHANGED
@@ -243,6 +243,22 @@ function bundleMark(item) {
243
243
  * 移管中の印(記録191)。`rejected` / `cancelled` は「移管しなかった」なので
244
244
  * 移管先を出さない——出すと、まだ動いているように読める。
245
245
  */
246
+ /**
247
+ * 継続方針(記録192)。**`renew` は出さない**——一覧の大半がそれになり、密度だけ食う
248
+ * (SPAのバッジと同じ流儀)。`undecided` は出す(意思を決めていない行は拾いたい)。
249
+ */
250
+ const RENEWAL_POLICY_MARKS = {
251
+ let_expire: "期限で終了",
252
+ cancel_now: "解約手続き中",
253
+ while_bundled: "特典が続く間",
254
+ undecided: "要判断",
255
+ };
256
+
257
+ function policyMark(item) {
258
+ const mark = RENEWAL_POLICY_MARKS[item?.renewal_policy];
259
+ return mark === undefined ? "" : ` [方針:${mark}]`;
260
+ }
261
+
246
262
  function transferMark(item) {
247
263
  const stage = item?.transfer_stage;
248
264
  if (stage === null || stage === undefined) return "";
@@ -265,7 +281,7 @@ export function infraListLine(item, now = new Date()) {
265
281
  displayValue(item?.name),
266
282
  `[${displayValue(item?.kind)}]`,
267
283
  `provider:${displayValue(item?.provider)}`,
268
- `status:${displayValue(item?.status)}`,
284
+ `status:${displayValue(item?.status)}${policyMark(item)}`,
269
285
  `auto-renew:${displayValue(item?.auto_renew)}${bundleMark(item)}`,
270
286
  `expires:${displayValue(item?.expires_on)} (${remainingDays(item?.expires_on, now)})`,
271
287
  `projects:${projects.join(",") || "-"}${external}${transferMark(item)}`,
@@ -274,7 +290,7 @@ export function infraListLine(item, now = new Date()) {
274
290
 
275
291
  export function infraAssetLines(item) {
276
292
  const fields = [
277
- "id", "provider", "status", "management", "auto_renew", "expires_on", "purpose",
293
+ "id", "provider", "status", "renewal_policy", "management", "auto_renew", "expires_on", "purpose",
278
294
  "dns_host", "mail_host", "migration_plan", "hosted_on_basis", "prod_platform", "prod_ref",
279
295
  "contract", "amount_yen", "payer", "holder", "account", "account_ref", "note",
280
296
  "renew_source", "transfer_to", "transfer_stage", "transfer_due_at", "version",
@@ -368,3 +384,31 @@ function infraEventSummary(event) {
368
384
  : `${field}: ${formatEventValue(from[field])} → ${formatEventValue(to[field])}`))
369
385
  .join(" / ");
370
386
  }
387
+
388
+
389
+ export function printDeployResult(payload, json, stdout, kind) {
390
+ if (json) {
391
+ stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
392
+ return;
393
+ }
394
+ if (kind === "list") {
395
+ const items = payload?.items ?? [];
396
+ const lines = items.map((item) => `${deployLine(item)} projects:${(item.projects ?? []).map((project) => displayValue(project.slug)).join(",") || "-"} (${displayValue(item.id)})`);
397
+ stdout.write(lines.length === 0 ? "デプロイ先はありません。\n" : `${lines.join("\n")}\n`);
398
+ return;
399
+ }
400
+ const item = payload?.item;
401
+ const lines = [deployLine(item)];
402
+ for (const field of ["id", "platform", "account_key", "account_label", "platform_ref", "target_kind", "state", "url", "repo", "repo_path", "note", "version", "created_at", "updated_at"]) {
403
+ lines.push(`${field}: ${displayValue(item?.[field])}`);
404
+ }
405
+ lines.push(`projects: ${(item?.projects ?? []).map((project) => displayValue(project.slug)).join(", ") || "-"}`);
406
+ if (kind === "show" && Array.isArray(payload?.events) && payload.events.length > 0) {
407
+ lines.push("", "events:");
408
+ for (const event of payload.events) {
409
+ const note = event.note ? ` — ${displayValue(event.note)}` : "";
410
+ lines.push(`- ${displayValue(event.at)} ${displayValue(event.kind)} (${displayValue(event.actor)})${note}`);
411
+ }
412
+ }
413
+ stdout.write(`${lines.join("\n")}\n`);
414
+ }
@@ -0,0 +1,142 @@
1
+ import { cliError, usageError } from "./args.mjs";
2
+ import { INFRA_DOMAIN_ONLY_OPTIONS, getInfraAsset } from "./infra.mjs";
3
+
4
+ const OPTION_FIELDS = {
5
+ status: "status",
6
+ "auto-renew": "auto_renew",
7
+ expires: "expires_on",
8
+ "dns-host": "dns_host",
9
+ "mail-host": "mail_host",
10
+ "migration-plan": "migration_plan",
11
+ management: "management",
12
+ purpose: "purpose",
13
+ provider: "provider",
14
+ "prod-platform": "prod_platform",
15
+ "prod-ref": "prod_ref",
16
+ contract: "contract",
17
+ amount: "amount_yen",
18
+ payer: "payer",
19
+ holder: "holder",
20
+ account: "account",
21
+ "account-ref": "account_ref",
22
+ note: "note",
23
+ "hosted-on-basis": "hosted_on_basis",
24
+ // 特典と移管(記録191 / migration 0029)。`--bundle-server` だけは名前解決が要るので
25
+ // ここには入れず、`--hosted-on` と同じ扱いで別に処理する
26
+ "renew-source": "renew_source",
27
+ "transfer-to": "transfer_to",
28
+ "transfer-stage": "transfer_stage",
29
+ "transfer-due": "transfer_due_at",
30
+ // 継続の意思(記録192 / migration 0030)。`status`(契約の現在)とは別の軸
31
+ "renewal-policy": "renewal_policy",
32
+ };
33
+
34
+ /**
35
+ * 互換で残した値(記録192)。APIも400にするが、**往復する前にCLIが止める**——
36
+ * 打ち間違いではなく「古い言い方が手に残っている」ので、案内を先に出す方が早い。
37
+ */
38
+ const LEGACY_VALUES = {
39
+ status: {
40
+ to_cancel: "status に to_cancel は書けません。継続の意思は --renewal-policy let_expire / cancel_now で指定します",
41
+ },
42
+ "migration-plan": {
43
+ cancel: "migration-plan に cancel は書けません。継続の意思は --renewal-policy let_expire / cancel_now で指定します",
44
+ },
45
+ };
46
+
47
+ export const INFRA_WRITE_OPTIONS = [
48
+ ...Object.keys(OPTION_FIELDS), "append-note", "hosted-on", "reason", "bundle-server",
49
+ ];
50
+
51
+
52
+ /**
53
+ * `--append-note` は次の版で外す(記録188 §3.5)。既存noteの末尾へ「 / 」で足す作りは、
54
+ * 「現在の補足」と「経緯」を1つの列に混ぜる——経緯は `hub infra note` が別の表へ積む。
55
+ * 打つたびに出す(1回だけの告知だと、使い続けている人には届かない)。
56
+ */
57
+ export const APPEND_NOTE_DEPRECATION =
58
+ "警告: --append-note は次の版で外します。経緯は hub infra note <name|id> --note <text> へ。\n";
59
+
60
+ const NULLABLE_VALUE_OPTIONS = new Set([
61
+ "dns-host",
62
+ "mail-host",
63
+ "migration-plan",
64
+ "contract",
65
+ "hosted-on-basis",
66
+ "renew-source",
67
+ "transfer-to",
68
+ "transfer-stage",
69
+ "transfer-due",
70
+ ]);
71
+
72
+ function amountValue(value) {
73
+ if (value === "none") return null;
74
+ if (!/^\d+$/.test(value)) throw usageError("--amount は0以上の整数か none を指定してください");
75
+ const parsed = Number(value);
76
+ if (!Number.isSafeInteger(parsed)) throw usageError("--amount は安全な整数の範囲で指定してください");
77
+ return parsed;
78
+ }
79
+
80
+ /** 互換値は引数だけで判定できるので、認証や接続に先立って案内する(記録192)。 */
81
+ export function rejectLegacyValues(options, flags) {
82
+ for (const [option, values] of Object.entries(LEGACY_VALUES)) {
83
+ if (!flags[option]) continue;
84
+ const value = options[option].trim();
85
+ if (Object.hasOwn(values, value)) throw usageError(values[value]);
86
+ }
87
+ }
88
+
89
+ export function rejectServerOptions(kind, flags) {
90
+ const forbidden = INFRA_DOMAIN_ONLY_OPTIONS.filter((name) => flags[name]);
91
+ if (kind === "server" && forbidden.length > 0) {
92
+ throw usageError(`server資産にはドメイン専用オプションを指定できません: ${forbidden.map((name) => `--${name}`).join(" / ")}`);
93
+ }
94
+
95
+ }
96
+
97
+ /** 作成と更新で同じCLI値を同じAPIフィールドへ写す。既定値はWorkerが持つ。 */
98
+ export async function prepareInfraFields(options, flags, api) {
99
+ const prepared = {};
100
+ for (const [option, field] of Object.entries(OPTION_FIELDS)) {
101
+ if (!flags[option] || option === "note") continue;
102
+ const value = options[option].trim();
103
+ // 継続方針は NOT NULL の列なので、`none` は null ではなく `undecided` へ戻す
104
+ if (option === "renewal-policy") prepared[field] = value === "none" ? "undecided" : value;
105
+ else if (option === "expires") prepared[field] = value === "none" ? null : value;
106
+ else if (option === "amount") prepared[field] = amountValue(value);
107
+ else if (NULLABLE_VALUE_OPTIONS.has(option) && value === "none") prepared[field] = null;
108
+ else prepared[field] = value;
109
+ }
110
+ if (flags.note) prepared.note = options.note.trim();
111
+
112
+ let appendNote = null;
113
+ if (flags["append-note"]) {
114
+ appendNote = options["append-note"].trim();
115
+ if (appendNote === "") throw usageError("--append-note に空文字は指定できません");
116
+ }
117
+
118
+ if (flags["hosted-on"]) {
119
+ const hostReference = options["hosted-on"].trim();
120
+ if (hostReference === "none") {
121
+ prepared.hosted_on = null;
122
+ } else {
123
+ const host = await getInfraAsset(hostReference, api, { kind: "server" });
124
+ if (host.item.kind !== "server") throw cliError("--hosted-on にはserver資産の名前またはidを指定してください");
125
+ prepared.hosted_on = host.item.id;
126
+ }
127
+ }
128
+
129
+ // 特典元も server の名前かidで指定する(`--hosted-on` と同じ解決。記録191)
130
+ if (flags["bundle-server"]) {
131
+ const bundleReference = options["bundle-server"].trim();
132
+ if (bundleReference === "none") {
133
+ prepared.bundle_server = null;
134
+ } else {
135
+ const bundle = await getInfraAsset(bundleReference, api, { kind: "server" });
136
+ if (bundle.item.kind !== "server") throw cliError("--bundle-server にはserver資産の名前またはidを指定してください");
137
+ prepared.bundle_server = bundle.item.id;
138
+ }
139
+ }
140
+
141
+ return { prepared, appendNote };
142
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tamai/hub-cli",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "description": "CLI for the hub personal dashboard: D1-backed task board and project registry.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",