@botiverse/stamp-cli 0.3.3 → 0.3.7

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.
@@ -0,0 +1,189 @@
1
+ import { t, prefix } from "../locale.mjs";
2
+ import { ApiError, NetworkError } from "../client.mjs";
3
+ import { AgentError, printGatewayError } from "../errors.mjs";
4
+ import { pullRequestInput, pullRequestRecovery } from "../pr/create.mjs";
5
+ import { parsePRCommentArgs, validatePRCommentResult } from "../pr/comment.mjs";
6
+ import { formatPRReview, reviewBrief } from "../pr/review.mjs";
7
+ import { parsePRApproveArgs, parsePRMergeArgs, validatePRApproveResult, validatePRMergeResult } from "../pr/write.mjs";
8
+ import {
9
+ formatPRChecks,
10
+ formatPRDetail,
11
+ formatPRDiff,
12
+ formatPRList,
13
+ formatPRListSections,
14
+ parsePRDiffArgs,
15
+ parsePRListArgs,
16
+ parsePRTargetArgs,
17
+ prChecksExitCode,
18
+ prDetailPath,
19
+ PR_SECTIONS,
20
+ prDiffPath,
21
+ prSection,
22
+ safeInline,
23
+ validatePRDetail,
24
+ validatePRDiff,
25
+ validatePRListResponse,
26
+ } from "../pr/read.mjs";
27
+
28
+ function sectionLabels(locale) {
29
+ const labels = {};
30
+ for (const name of Object.values(PR_SECTIONS)) labels[`prSection_${name}`] = t(locale, `prSection_${name}`);
31
+ return labels;
32
+ }
33
+
34
+ async function writeCommand(ctx, run) {
35
+ try {
36
+ await run();
37
+ } catch (e) {
38
+ if (e instanceof NetworkError) {
39
+ // The request left the machine, so whether the write landed is unknown:
40
+ // keep the uncertainty contract and add what we know about the transport.
41
+ ctx.err(`${prefix()}${t(ctx.locale, ctx.unknownKey)}`);
42
+ ctx.err(`${prefix()}${t(ctx.locale, e.code, e.details)}`);
43
+ return ctx.exit(1);
44
+ }
45
+ if (e instanceof AgentError) throw e;
46
+ if (e instanceof ApiError && e.status >= 400 && e.status < 500) {
47
+ ctx.err(`${prefix()}${e.message}`);
48
+ printGatewayError(e, ctx.err);
49
+ } else {
50
+ ctx.err(`${prefix()}${t(ctx.locale, ctx.unknownKey)}`);
51
+ if (e instanceof ApiError) printGatewayError(e, ctx.err);
52
+ }
53
+ return ctx.exit(1);
54
+ }
55
+ return ctx.exit(0);
56
+ }
57
+
58
+ export async function run(ctx) {
59
+ const { args, api, emit, out, err, locale, exit } = ctx;
60
+ const sub = args.shift();
61
+ if (sub === "comment") {
62
+ ctx.rejectKey = "prCommentRejected";
63
+ ctx.unknownKey = "prCommentOutcomeUnknown";
64
+ return writeCommand(ctx, async () => {
65
+ const input = parsePRCommentArgs(args);
66
+ const result = validatePRCommentResult(await api("POST", input.path, input.body), input.target);
67
+ emit(result, () => out(t(locale, "prCommentCreated", { url: result.url, actor: result.actorLogin })));
68
+ });
69
+ }
70
+ if (sub === "approve") {
71
+ ctx.rejectKey = "prApproveRejected";
72
+ ctx.unknownKey = "prApproveOutcomeUnknown";
73
+ return writeCommand(ctx, async () => {
74
+ const input = parsePRApproveArgs(args);
75
+ const result = validatePRApproveResult(await api(input.method, input.path, input.body), input.target);
76
+ emit(result, () => out(t(locale, "prApproved", { actor: result.reviewerLogin, repository: result.repository, number: result.number })));
77
+ });
78
+ }
79
+ if (sub === "merge") {
80
+ ctx.rejectKey = "prMergeRejected";
81
+ ctx.unknownKey = "prMergeOutcomeUnknown";
82
+ return writeCommand(ctx, async () => {
83
+ const input = parsePRMergeArgs(args);
84
+ const result = validatePRMergeResult(await api(input.method, input.path, input.body), input.target);
85
+ emit(result, () => out(t(locale, "prMerged", { actor: result.actorLogin, sha: result.mergeSha, repository: result.repository, number: result.number })));
86
+ });
87
+ }
88
+ if (sub === "create") {
89
+ const input = pullRequestInput(args);
90
+ try {
91
+ const d = await api("POST", "/v1/pull-requests", input);
92
+ emit(d, () => out(t(locale, d.idempotent ? "prExisting" : "prCreated", { number: d.pullNumber, url: d.url })));
93
+ } catch (e) {
94
+ if (e instanceof ApiError && e.status !== 401) {
95
+ err(`${prefix()}${e.message}`);
96
+ if (!printGatewayError(e, err)) err(t(locale, pullRequestRecovery(e.body?.error)));
97
+ return exit(1);
98
+ }
99
+ throw e;
100
+ }
101
+ return exit(0);
102
+ }
103
+ if (sub === "list" || sub === "ls") {
104
+ const { path, sections } = parsePRListArgs(args);
105
+ const paged = path.includes("limit=");
106
+ const d = validatePRListResponse(await api("GET", path), paged);
107
+ const labels = {
108
+ statusUnavailable: t(locale, "prStatusUnavailable"),
109
+ ci: t(locale, "prCIShort"),
110
+ agent: t(locale, "prAgentShort"),
111
+ ...sectionLabels(locale),
112
+ };
113
+ emit(
114
+ sections
115
+ ? { ...d, items: d.items.map((item) => ({ ...item, section: prSection(item) })) }
116
+ : d,
117
+ () => {
118
+ const lines = sections ? formatPRListSections(d, labels) : formatPRList(d, labels);
119
+ if (lines.length === 0) out(t(locale, "prListEmpty"));
120
+ else for (const line of lines) out(line);
121
+ if (d.nextCursor) out(t(locale, "prListMore", { cursor: safeInline(d.nextCursor) }));
122
+ },
123
+ );
124
+ return exit(0);
125
+ }
126
+ if (sub === "view") {
127
+ const target = parsePRTargetArgs(args, "usagePrView");
128
+ const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
129
+ emit(d, () => {
130
+ for (const line of formatPRDetail(d, {
131
+ head: t(locale, "prHeadLabel"),
132
+ checks: t(locale, "prChecksLabel"),
133
+ ciUnreadable: t(locale, "prCIUnreadable"),
134
+ review: t(locale, "prReviewLabel"),
135
+ })) out(line);
136
+ });
137
+ return exit(0);
138
+ }
139
+ if (sub === "review") {
140
+ const target = parsePRTargetArgs(args, "usagePrReview");
141
+ const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
142
+ const brief = reviewBrief(d);
143
+ emit(brief, () => {
144
+ for (const line of formatPRReview(brief, (key) => t(locale, key))) out(line);
145
+ });
146
+ // Stays exit 0 even when the CI rollup is unreadable, and that is a
147
+ // decision rather than an omission (飞牛 raised it). `pr checks` is a gate
148
+ // answering "is this green?", so it fails closed; `pr review` is a fetch
149
+ // answering "give me the brief", and the fetch succeeded. Failing it here
150
+ // would conflate "I could not build the brief" with "the brief says CI is
151
+ // unknown", and would break callers that use it to obtain a brief at all.
152
+ // The unreadability travels in the brief itself -- printed in the text and
153
+ // carried as `ciUnreadable` in --json, which is purely additive.
154
+ return exit(0);
155
+ }
156
+ if (sub === "diff") {
157
+ const target = parsePRDiffArgs(args);
158
+ const d = validatePRDiff(await api("GET", prDiffPath(target)), target);
159
+ emit(d, () => {
160
+ const chunks = formatPRDiff(d, target.nameOnly, t(locale, "prDiffUnavailable"));
161
+ if (chunks.length === 0) out(t(locale, "prDiffEmpty"));
162
+ else out(chunks.join("\n"));
163
+ });
164
+ return exit(0);
165
+ }
166
+ if (sub === "checks") {
167
+ const target = parsePRTargetArgs(args, "usagePrChecks");
168
+ const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
169
+ emit(d.checks, () => {
170
+ // BOUNDARY, deliberately not fixed here: `--json` emits the checks ARRAY,
171
+ // which has nowhere to put "the source was refused" -- an agent parsing
172
+ // stdout sees `[]` for both "no CI" and "could not read CI". Widening it
173
+ // to an object would break every agent that parses an array, which is the
174
+ // same compatibility trap as adding a ciStatus value, so the contract is:
175
+ // **the exit code is authoritative for --json callers, and `pr view
176
+ // --json` carries ciUnreadable if you need the reason.** Said out loud
177
+ // rather than left for the next person to discover (飞牛, cross).
178
+ const lines = formatPRChecks(d);
179
+ // "No checks reported." is the same lie as CI:none, just where a person
180
+ // reads it rather than in a column. An empty list because the source was
181
+ // refused must not borrow the sentence meant for a repo that has no CI.
182
+ if (d.ciUnreadable) out(t(locale, "prChecksUnreadable"));
183
+ else if (lines.length === 0) out(t(locale, "prChecksEmpty"));
184
+ else for (const line of lines) out(line);
185
+ });
186
+ return exit(prChecksExitCode(d));
187
+ }
188
+ throw new Error(t(locale, "usagePrRead"));
189
+ }
@@ -0,0 +1,16 @@
1
+ import { t } from "../locale.mjs";
2
+
3
+ export async function run(ctx) {
4
+ const sub = ctx.args.shift();
5
+ const id = ctx.args.shift();
6
+ if (sub !== "get" || !id) throw new Error(t(ctx.locale, "usageReceiptGet"));
7
+ const d = await ctx.api("GET", `/v1/receipts/${encodeURIComponent(id)}`);
8
+ ctx.emit(d, () => {
9
+ let line = `${d.id} ${d.status} ${d.repository} ${d.targetRef} published=${d.publishedSha ?? "-"}`;
10
+ if (d.publishAttempts) line += ` attempts=${d.publishAttempts}`;
11
+ if (d.nextRetryAt) line += ` nextRetry=${d.nextRetryAt}`;
12
+ ctx.out(line);
13
+ if (d.lastError) ctx.out(` last error: ${d.lastError}`);
14
+ });
15
+ return ctx.exit(0);
16
+ }
@@ -0,0 +1,78 @@
1
+ import { existsSync } from "node:fs";
2
+ import { t } from "../locale.mjs";
3
+ import { takeFlag } from "../flags.mjs";
4
+ import { gatewayCloneURL, parseRepoCloneArgs, parseRepository, runGitClone, runGitSetSSHCommand } from "../repo/clone.mjs";
5
+ import { fetchPublishedKnownHosts, resolveIdentity, resolveKnownHostsPath, sshCommandFor, writePinnedKnownHosts } from "../repo/ssh.mjs";
6
+ import { readRecordedIdentity } from "../repo/identities.mjs";
7
+
8
+ export async function run(ctx) {
9
+ if (ctx.args.shift() !== "clone") throw new Error(t(ctx.locale, "usageRepoClone"));
10
+ const identityFlag = takeFlag(ctx.args, "identity");
11
+ const knownHostsFlag = takeFlag(ctx.args, "known-hosts");
12
+ const parsed = parseRepoCloneArgs(ctx.args);
13
+ if (!parsed) throw new Error(t(ctx.locale, "usageRepoClone"));
14
+ const me = await ctx.api("GET", "/v1/me");
15
+ const repo = parseRepository(parsed.repository, me?.github?.login);
16
+ if (!repo) throw new Error(t(ctx.locale, "usageRepoClone"));
17
+ const url = gatewayCloneURL(me.sshHost, me.sshPort, repo.owner, repo.name);
18
+
19
+ // The clone carries the enrolled identity and the gateway's published host
20
+ // key itself (task #475): a bare clone must not fail with publickey, and it
21
+ // must not need a hand-exported GIT_SSH_COMMAND.
22
+ const recorded = readRecordedIdentity(ctx.env, ctx.auth.apiBase);
23
+ const { identityPath, source } = resolveIdentity(ctx.env, identityFlag, recorded);
24
+ if (!existsSync(identityPath)) {
25
+ // The recorded key is not on this machine (or moved): say which record
26
+ // pointed there, so the fix is `key enroll` here or --identity, not a
27
+ // search of ~/.ssh (task #514: never scan).
28
+ throw new Error(t(ctx.locale, source === "enrolled" ? "cloneEnrolledIdentityMissing" : "cloneIdentityMissing", { path: identityPath, origin: ctx.auth.apiBase }));
29
+ }
30
+ const knownHostsPath = resolveKnownHostsPath(ctx.env, knownHostsFlag);
31
+ const fetchImpl = ctx.opts.fetchImpl ?? fetch;
32
+ const published = await fetchPublishedKnownHosts({ apiBase: ctx.auth.apiBase, fetchImpl });
33
+ if (!published.ok) {
34
+ throw new Error(t(ctx.locale, published.invalid ? "cloneKnownHostsInvalid" : "cloneKnownHostsUnavailable", {
35
+ url: `${ctx.auth.apiBase}/.well-known/ssh-known-hosts`,
36
+ status: published.status ?? "?",
37
+ }));
38
+ }
39
+ writePinnedKnownHosts(knownHostsPath, published.pattern, published.line);
40
+ const sshCommand = sshCommandFor({ identityPath, knownHostsPath });
41
+
42
+ const git = ctx.opts.gitCloneImpl ?? runGitClone;
43
+ const result = await git({
44
+ url,
45
+ directory: parsed.directory,
46
+ gitFlags: parsed.gitFlags,
47
+ env: { ...(ctx.opts.gitEnv ?? ctx.env), GIT_SSH_COMMAND: sshCommand },
48
+ });
49
+ if (result.code !== 0) {
50
+ if (result.stderr) ctx.err(result.stderr.trimEnd());
51
+ if (/permission denied \(publickey\)/i.test(result.stderr ?? "")) {
52
+ ctx.err(t(ctx.locale, "clonePublicKeyRejected", { path: identityPath, publicKey: `${identityPath}.pub` }));
53
+ }
54
+ throw new Error(t(ctx.locale, "cloneFailed", { repository: `${repo.owner}/${repo.name}` }));
55
+ }
56
+ if (result.stderr) ctx.err(result.stderr.trimEnd());
57
+
58
+ // Make later git operations in this checkout work without any export.
59
+ const directory = parsed.directory ?? repo.name;
60
+ const pinned = await (ctx.opts.gitConfigImpl ?? runGitSetSSHCommand)({ directory, sshCommand });
61
+ ctx.emit(
62
+ { ok: true, repository: `${repo.owner}/${repo.name}`, url, directory, sshIdentity: identityPath, sshIdentitySource: source, sshPinned: pinned.ok },
63
+ () => {
64
+ ctx.out(t(ctx.locale, "cloned", { repository: `${repo.owner}/${repo.name}`, url }));
65
+ // The commit rules this gateway enforces, stated once up front (task #549):
66
+ // a pusher should not meet them for the first time as a refusal.
67
+ if (me.commitTrailers && (me.commitTrailers.signedOffBy || me.commitTrailers.coauthoredBy)) {
68
+ ctx.out(t(ctx.locale, "cloneCommitTrailers"));
69
+ if (me.commitTrailers.signedOffBy) ctx.out(` ${me.commitTrailers.signedOffBy}`);
70
+ if (me.commitTrailers.coauthoredBy) ctx.out(` ${me.commitTrailers.coauthoredBy}`);
71
+ }
72
+ ctx.out(pinned.ok
73
+ ? t(ctx.locale, "cloneIdentityPinned", { directory })
74
+ : t(ctx.locale, "cloneIdentityPinFailed", { directory, command: sshCommand }));
75
+ },
76
+ );
77
+ return ctx.exit(0);
78
+ }
@@ -0,0 +1,52 @@
1
+ import { runAgentLogin } from "../agent-login.mjs";
2
+ import { humanExpiry } from "../expiry.mjs";
3
+ import { t } from "../locale.mjs";
4
+
5
+ export async function login(ctx) {
6
+ const { auth, opts, emit, out, locale, exit } = ctx;
7
+ if (auth.mode !== "agent") {
8
+ out(t(locale, "loginHumanIntro"));
9
+ out(t(locale, "loginHumanBrowser", { url: auth.apiBase }));
10
+ out(t(locale, "loginHumanCI"));
11
+ return exit(0);
12
+ }
13
+ const loginImpl = opts.loginImpl ?? runAgentLogin;
14
+ const session = await loginImpl(auth.agentEnv, auth.apiBase, { service: auth.service, fetchImpl: opts.fetchImpl });
15
+ // JSON keeps the raw RFC3339 instant; the human line renders it for a reader
16
+ // in their own time zone with how long is left (task #436).
17
+ const expiry = humanExpiry(locale, session.access_expires_at);
18
+ emit({ ok: true, service: auth.service, api_base: auth.apiBase, access_expires_at: session.access_expires_at },
19
+ () => out(t(locale, expiry.expired ? "loginTokenExpired" : "loginAgentReady", {
20
+ service: auth.service, url: auth.apiBase, expires: expiry.text, remaining: expiry.remaining,
21
+ })));
22
+ return exit(0);
23
+ }
24
+
25
+ export async function logout(ctx) {
26
+ const p = ctx.auth.logout();
27
+ ctx.out(p ? t(ctx.locale, "logoutForgot", { path: p }) : t(ctx.locale, "logoutNothing"));
28
+ return ctx.exit(0);
29
+ }
30
+
31
+ export async function whoami(ctx) {
32
+ const me = await ctx.api("GET", "/v1/me");
33
+ ctx.emit(me, () => ctx.out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${ctx.auth.apiBase}`));
34
+ return ctx.exit(0);
35
+ }
36
+
37
+ export async function migrationHelp(ctx) {
38
+ const fetchImpl = ctx.opts.fetchImpl ?? fetch;
39
+ const res = await fetchImpl(`${ctx.auth.apiBase}/v1/migration-help`, {
40
+ headers: { "accept-language": ctx.locale === "zh-CN" ? "zh-CN" : "en" },
41
+ });
42
+ const d = await res.json();
43
+ ctx.emit(d, () => {
44
+ ctx.out(t(ctx.locale, "helpInstall", { cmds: (d.install ?? []).join(" ; ") }));
45
+ ctx.out(t(ctx.locale, "helpAgentLogin", { text: d.login?.agent ?? "" }));
46
+ for (const [from, to] of Object.entries(d.actions_to_cli ?? {})) {
47
+ const note = d.notes?.[from];
48
+ ctx.out(note ? ` ${from} → ${to} (${note})` : ` ${from} → ${to}`);
49
+ }
50
+ });
51
+ return ctx.exit(0);
52
+ }
@@ -0,0 +1,35 @@
1
+ import { t } from "../locale.mjs";
2
+ import { takeFlag, objectArgs } from "../flags.mjs";
3
+
4
+ export async function follow(ctx) {
5
+ const body = objectArgs(ctx.args, ctx.locale);
6
+ const path = ctx.cmd === "follow" ? "/v1/subscriptions/objects/follow" : "/v1/subscriptions/objects/unfollow";
7
+ const d = await ctx.api("POST", path, body);
8
+ ctx.emit(d, () => ctx.out(JSON.stringify(d)));
9
+ return ctx.exit(0);
10
+ }
11
+
12
+ export async function subscription(ctx) {
13
+ const sub = ctx.args.shift();
14
+ if (sub !== "pause" && sub !== "resume") throw new Error(t(ctx.locale, "usageSubscription"));
15
+ const body = objectArgs(ctx.args, ctx.locale);
16
+ const d = await ctx.api("POST", `/v1/subscriptions/objects/${sub}`, body);
17
+ ctx.emit(d, () => ctx.out(JSON.stringify(d)));
18
+ return ctx.exit(0);
19
+ }
20
+
21
+ export async function subscriptions(ctx) {
22
+ const d = await ctx.api("GET", "/v1/subscriptions");
23
+ ctx.emit(d, () => ctx.out(JSON.stringify(d, null, 2)));
24
+ return ctx.exit(0);
25
+ }
26
+
27
+ export async function watch(ctx) {
28
+ const repository = ctx.args.shift();
29
+ const eventType = takeFlag(ctx.args, "event");
30
+ if (!repository || !eventType) throw new Error(t(ctx.locale, "usageWatch", { cmd: ctx.cmd }));
31
+ const path = ctx.cmd === "watch" ? "/v1/subscriptions/repositories/subscribe" : "/v1/subscriptions/repositories/unsubscribe";
32
+ const d = await ctx.api("POST", path, { repository, eventType });
33
+ ctx.emit(d, () => ctx.out(JSON.stringify(d)));
34
+ return ctx.exit(0);
35
+ }
package/lib/errors.mjs CHANGED
@@ -1,24 +1,6 @@
1
- import { t } from "./locale.mjs";
1
+ import { t, prefix } from "./locale.mjs";
2
2
 
3
- const apiRecoveryKeys = new Map([
4
- ["GITHUB_IDENTITY_BINDING_REQUIRED", "apiBindIdentity"],
5
- ["REPOSITORY_NOT_INSTALLED", "apiRepositoryNotInstalled"],
6
- ["PUBLIC_CONTRIBUTION_POLICY_DENIED", "apiContributionDenied"],
7
- ["REPOSITORY_NOT_AUTHORIZED", "apiRepositoryNotAuthorized"],
8
- ["PR_NOT_FOUND", "prReadNotFound"],
9
- ["PR_HEAD_MOVED", "prReadHeadMoved"],
10
- ["PR_DIFF_INCOMPLETE", "prReadDiffIncomplete"],
11
- ["PR_DETAIL_FAILED", "prReadUnavailable"],
12
- ["PR_DIFF_FAILED", "prReadUnavailable"],
13
- ["PR_INBOX_FAILED", "prReadUnavailable"],
14
- // Cursor scope/format rejections (task #397 slice 1): the cursor is bound to
15
- // (tenant, server, viewer scope, filter); a mismatched or malformed cursor is
16
- // a recoverable user error, never a generic contract mismatch.
17
- ["PR_INBOX_CURSOR_SCOPE", "prCursorScope"],
18
- ["PR_INBOX_CURSOR_INVALID", "prCursorInvalid"],
19
- ]);
20
-
21
- /** Stable machine code on `.code`; English catalog text on `.message` for tests. */
3
+ // Local mistakes (bad flags, malformed JSON). `.code` is a locale catalog key.
22
4
  export class AgentError extends Error {
23
5
  constructor(code, details = {}) {
24
6
  super(t("en", code, details));
@@ -43,21 +25,13 @@ function stableErrorCode(value) {
43
25
  return /^[A-Z0-9_:-]{1,128}$/.test(code) ? code : "";
44
26
  }
45
27
 
46
- function boundedSuggestedAction(value) {
47
- if (typeof value !== "string") return "";
48
- return value.trim().replace(/[\r\n\t]+/g, " ").slice(0, 512);
49
- }
50
-
51
- // API authorization denials keep the compatibility `error` at the top level and
52
- // carry the actionable reason in errorCode + suggestedNextAction. Prefer a localized,
53
- // executable repair for known codes; preserve a bounded server suggestion for future
54
- // codes so a new denial does not degrade back to an opaque REPOSITORY_NOT_AUTHORIZED.
55
- export function apiErrorGuidance(locale, body) {
56
- if (!body || typeof body !== "object") return { code: "", action: "" };
57
- const code = stableErrorCode(body.errorCode ?? body.error);
58
- const key = apiRecoveryKeys.get(code);
59
- return {
60
- code,
61
- action: key ? t(locale, key) : boundedSuggestedAction(body.suggestedNextAction),
62
- };
28
+ // The gateway owns the repair: JSON { error, errorCode, suggestedNextAction }.
29
+ // The CLI prints those fields verbatim. It does not keep a second code→copy map.
30
+ export function printGatewayError(error, write) {
31
+ const body = error.body;
32
+ const code = stableErrorCode(body?.errorCode ?? body?.error);
33
+ if (code && code !== body?.error) write(`${prefix()}${code}`);
34
+ const action = typeof body?.suggestedNextAction === "string" ? body.suggestedNextAction : "";
35
+ if (action) write(`${prefix()}${action}`);
36
+ return Boolean(action);
63
37
  }
package/lib/expiry.mjs ADDED
@@ -0,0 +1,27 @@
1
+ // The access-token expiry was printed as the raw RFC3339 UTC string, which a
2
+ // reader in another time zone sees as a time earlier than their own clock and
3
+ // reads as "already expired" (task #436). The human line gets a local time plus
4
+ // how long is left; the JSON keeps the raw value for machines.
5
+
6
+ function localeTag(locale) {
7
+ return locale === "zh-CN" ? "zh-CN" : "en-US";
8
+ }
9
+
10
+ // humanExpiry formats an RFC3339 instant for the reader: local time with its
11
+ // zone, and a relative remaining time. An unparseable value is returned as-is
12
+ // (never crash on a display-only path).
13
+ export function humanExpiry(locale, iso, now = Date.now()) {
14
+ const ms = Date.parse(String(iso ?? ""));
15
+ if (!Number.isFinite(ms)) return { text: String(iso ?? ""), remaining: "", expired: false };
16
+ const tag = localeTag(locale);
17
+ // dateStyle/timeStyle cannot be combined with timeZoneName, and the zone is the
18
+ // whole point here: name the components explicitly.
19
+ const text = new Intl.DateTimeFormat(tag, {
20
+ year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", timeZoneName: "short",
21
+ }).format(ms);
22
+ const minutes = Math.round((ms - now) / 60000);
23
+ const relative = new Intl.RelativeTimeFormat(tag, { numeric: "auto" });
24
+ // Minutes are the useful unit up to 90 of them; beyond that, hours.
25
+ const remaining = Math.abs(minutes) >= 90 ? relative.format(Math.round(minutes / 60), "hour") : relative.format(minutes, "minute");
26
+ return { text, remaining, expired: minutes <= 0 };
27
+ }
package/lib/flags.mjs ADDED
@@ -0,0 +1,26 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { t } from "./locale.mjs";
3
+
4
+ export function takeFlag(args, name, dflt) {
5
+ const i = args.indexOf(`--${name}`);
6
+ if (i === -1) return dflt;
7
+ const v = args[i + 1];
8
+ args.splice(i, 2);
9
+ return v;
10
+ }
11
+
12
+ export function readPublicKey(path) {
13
+ if (path === "-") return readFileSync(0, "utf8").trim();
14
+ return readFileSync(path, "utf8").trim();
15
+ }
16
+
17
+ export function objectArgs(args, locale) {
18
+ const repository = args.shift();
19
+ const rawKind = takeFlag(args, "kind");
20
+ const kind = rawKind === "pull" ? "pull_request" : rawKind;
21
+ const number = Number(takeFlag(args, "number"));
22
+ if (!repository || !["issue", "pull_request"].includes(kind) || !Number.isInteger(number) || number <= 0) {
23
+ throw new Error(t(locale, "usageFollow"));
24
+ }
25
+ return { repository, kind, number };
26
+ }