@hive3/cli 0.1.1-beta.0 → 0.2.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.
package/README.md CHANGED
@@ -33,6 +33,16 @@ Useful environment overrides:
33
33
  - `HIVE_APP_URL`: browser approval app URL, default `https://app.hive3.tech`
34
34
  - `HIVE_CONFIG_HOME`: test/custom config directory
35
35
 
36
+ ## Updating
37
+
38
+ The CLI checks npm for a new stable release at most once every 24 hours during interactive use. If an update is available, it prints a short notice after the command finishes. Update with:
39
+
40
+ ```bash
41
+ hive update
42
+ ```
43
+
44
+ Use `hive update --check` to check without installing. Set `HIVE_NO_UPDATE_CHECK=1` to disable the automatic daily check. The check only requests public package metadata from npm and never sends Hive credentials.
45
+
36
46
  ## Scopes
37
47
 
38
48
  Most users should use the login approval page's Read Only or Full Access choice:
package/bin/hive.js CHANGED
@@ -1,5 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { main } from "../src/commands.js";
4
+ import { maybeNotifyUpdate } from "../src/update.js";
4
5
 
5
- process.exitCode = await main(process.argv.slice(2));
6
+ const argv = process.argv.slice(2);
7
+ const exitCode = await main(argv);
8
+ if (exitCode === 0 && argv[0] !== "update") await maybeNotifyUpdate();
9
+ process.exitCode = exitCode;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hive3/cli",
3
- "version": "0.1.1-beta.0",
3
+ "version": "0.2.1",
4
4
  "description": "Command-line client for Hive's public API.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -17,7 +17,7 @@
17
17
  "access": "public"
18
18
  },
19
19
  "scripts": {
20
- "check": "node --check bin/hive.js && node --check src/api-client.js && node --check src/commands.js && node --check src/config.js && node --check src/extended-commands.js && node --check src/login.js",
20
+ "check": "node --check bin/hive.js && node --check src/api-client.js && node --check src/commands.js && node --check src/config.js && node --check src/extended-commands.js && node --check src/login.js && node --check src/update.js && node --check src/usage.js",
21
21
  "test": "node --test test/*.test.mjs"
22
22
  },
23
23
  "engines": {
package/src/api-client.js CHANGED
@@ -196,6 +196,9 @@ export function createApiClient(options) {
196
196
  requestAccountExport() {
197
197
  return request("POST", "/account/export");
198
198
  },
199
+ revokeCurrentKey() {
200
+ return request("DELETE", "/account/keys/current");
201
+ },
199
202
  saveBuilder(kind, config) {
200
203
  return request("PATCH", `/profile/${kind}`, { body: { config } });
201
204
  },
package/src/commands.js CHANGED
@@ -7,58 +7,7 @@ import { createApiClient, HiveApiError, isResourceKind } from "./api-client.js";
7
7
  import { clearConfig, loadConfig } from "./config.js";
8
8
  import { runExtendedCommand } from "./extended-commands.js";
9
9
  import { login, loginUsage, parseLoginArgs } from "./login.js";
10
-
11
- function usage() {
12
- return [
13
- "Usage: hive <command> [options]",
14
- "",
15
- "Commands:",
16
- " login Connect this CLI through browser approval",
17
- " logout Remove the stored local credential",
18
- " whoami Show the authenticated Hive account",
19
- " capabilities List community targets available to this account",
20
- " profile <action> Manage profile text, media IDs, access, and builders",
21
- " upload <file> Upload an allowed image or document and print its storage ID",
22
- " account <action> Manage account preferences, exports, and deletion requests",
23
- " wallets <action> Manage linked wallet visibility/default selection",
24
- " nfts <action> Manage public NFT exposure",
25
- " notifications <action> Manage notifications and notification mutes",
26
- " comments <action> Manage post comments",
27
- " communities <action> Manage community membership and role-derived admin actions",
28
- " posts <action> Manage posts",
29
- " events <action> Manage events",
30
- " courses <action> Manage courses",
31
- " content <action> Manage content",
32
- " quests <action> Manage quests",
33
- " jobs <action> Manage jobs",
34
- "",
35
- "Resource CRUD actions:",
36
- " list [--limit n] [--cursor c] [--owner-type person|community] [--community-id id]",
37
- " create [--title t] [--body b] [--description d] [--content-type t] [--visibility v]",
38
- " update <id> [--title t] [--body b] [--description d] [--content-type t] [--visibility v]",
39
- " archive <id> (workflow subcommands include participants, enrollments, evidence, applications)",
40
- ].join("\n");
41
- }
42
-
43
- function resourceUsage(kind) {
44
- return [
45
- `Usage: hive ${kind} <list|create|update|archive> [options]`,
46
- "",
47
- "Create/update fields:",
48
- " --title <text>",
49
- " --body <text>",
50
- " --description <text>",
51
- " --content-type <type>",
52
- " --image-url <url>",
53
- " --visibility <public|protected|private>",
54
- " --file <json>",
55
- "",
56
- "Create owner fields:",
57
- " --owner-type <person|community>",
58
- " --community-id <id>",
59
- " --idempotency-key <key>",
60
- ].join("\n");
61
- }
10
+ import { resourceUsage, usage } from "./usage.js";
62
11
 
63
12
  function defaultDeps(overrides = {}) {
64
13
  return {
@@ -424,8 +373,9 @@ async function runUpload(args, deps) {
424
373
  const fileName = path.basename(filePath);
425
374
  const client = await authenticatedClient(deps);
426
375
  const issued = await client.createUploadUrl({ byteSize: fileStat.size, contentType, fileName, purpose });
376
+ const { uploadUrl, ...issuedSafe } = issued.data;
427
377
  const bytes = await readFile(filePath);
428
- const response = await deps.fetch(issued.data.uploadUrl, {
378
+ const response = await deps.fetch(uploadUrl, {
429
379
  body: new Blob([bytes], { type: contentType }),
430
380
  headers: { "Content-Type": contentType },
431
381
  method: "POST",
@@ -435,7 +385,7 @@ async function runUpload(args, deps) {
435
385
  if (!response.ok) {
436
386
  throw new HiveApiError(`Upload failed with status ${response.status}`, { code: "upload_failed", status: response.status });
437
387
  }
438
- writeJson(deps.stdout, { data: { ...issued.data, ...parsed } });
388
+ writeJson(deps.stdout, { data: { ...issuedSafe, ...parsed } });
439
389
  }
440
390
 
441
391
  async function runAccount(args, deps) {
@@ -551,6 +501,22 @@ export async function main(argv, overrides = {}) {
551
501
  return 0;
552
502
  }
553
503
  if (command === "logout") {
504
+ try {
505
+ const config = await loadConfig({ env: deps.env, homeDir: deps.homeDir, platform: deps.platform });
506
+ if (config?.apiKey) {
507
+ await createApiClient({
508
+ apiBaseUrl: config.apiBaseUrl,
509
+ apiKey: config.apiKey,
510
+ fetch: deps.fetch,
511
+ }).revokeCurrentKey();
512
+ writeLine(deps.stdout, "Revoked the server credential.");
513
+ }
514
+ } catch {
515
+ writeLine(
516
+ deps.stderr,
517
+ "Warning: could not revoke the server credential. Revoke it at Settings → Developer credentials.",
518
+ );
519
+ }
554
520
  const file = await clearConfig({ env: deps.env, homeDir: deps.homeDir, platform: deps.platform });
555
521
  writeLine(deps.stdout, `Removed Hive CLI credential at ${file}.`);
556
522
  return 0;
package/src/config.js CHANGED
@@ -78,8 +78,9 @@ export async function saveCredential(credential, options, overrides = {}) {
78
78
  keyPrefix: credential.keyPrefix,
79
79
  scopes: credential.scopes,
80
80
  };
81
- await fs.writeFile(file, `${JSON.stringify(body, null, 2)}\n`, { mode: 0o600 });
82
- await fs.chmod(file, 0o600);
81
+ const tmp = `${file}.${process.pid}.tmp`;
82
+ await fs.writeFile(tmp, `${JSON.stringify(body, null, 2)}\n`, { mode: 0o600 });
83
+ await fs.rename(tmp, file);
83
84
  return file;
84
85
  }
85
86
 
@@ -4,6 +4,7 @@ import { readFile } from "node:fs/promises";
4
4
 
5
5
  import { createApiClient, HiveApiError } from "./api-client.js";
6
6
  import { loadConfig } from "./config.js";
7
+ import { runUpdateCommand } from "./update.js";
7
8
 
8
9
  function writeLine(stream, message = "") {
9
10
  stream.write(`${message}\n`);
@@ -472,6 +473,10 @@ async function runCommunities(args, deps) {
472
473
  }
473
474
 
474
475
  export async function runExtendedCommand(command, args, deps) {
476
+ if (command === "update") {
477
+ await (deps.runUpdateCommand ?? runUpdateCommand)(args, deps);
478
+ return true;
479
+ }
475
480
  if (command === "notifications") {
476
481
  await runNotifications(args, deps);
477
482
  return true;
package/src/update.js ADDED
@@ -0,0 +1,199 @@
1
+ // @ts-check
2
+
3
+ import { spawn } from "node:child_process";
4
+ import { readFileSync } from "node:fs";
5
+ import { promises as fs } from "node:fs";
6
+ import path from "node:path";
7
+
8
+ import { configDirectory } from "./config.js";
9
+
10
+ export const PACKAGE_NAME = "@hive3/cli";
11
+ export const REGISTRY_LATEST_URL = "https://registry.npmjs.org/@hive3%2Fcli/latest";
12
+ export const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
13
+ export const CURRENT_VERSION = JSON.parse(
14
+ readFileSync(new URL("../package.json", import.meta.url), "utf8"),
15
+ ).version;
16
+
17
+ const VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?$/;
18
+
19
+ function writeLine(stream, message = "") {
20
+ stream.write(`${message}\n`);
21
+ }
22
+
23
+ function parseVersion(value) {
24
+ if (typeof value !== "string") throw new Error("Invalid Hive CLI version.");
25
+ const match = VERSION_PATTERN.exec(value);
26
+ if (!match) throw new Error(`Invalid Hive CLI version: ${value}`);
27
+ return {
28
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
29
+ prerelease: match[4]?.split(".") ?? [],
30
+ };
31
+ }
32
+
33
+ function comparePrerelease(left, right) {
34
+ if (left.length === 0 || right.length === 0) {
35
+ if (left.length === right.length) return 0;
36
+ return left.length === 0 ? 1 : -1;
37
+ }
38
+ const length = Math.max(left.length, right.length);
39
+ for (let index = 0; index < length; index += 1) {
40
+ const leftPart = left[index];
41
+ const rightPart = right[index];
42
+ if (leftPart === undefined || rightPart === undefined) {
43
+ if (leftPart === rightPart) return 0;
44
+ return leftPart === undefined ? -1 : 1;
45
+ }
46
+ if (leftPart === rightPart) continue;
47
+ const leftNumeric = /^\d+$/.test(leftPart);
48
+ const rightNumeric = /^\d+$/.test(rightPart);
49
+ if (leftNumeric && rightNumeric) return Number(leftPart) > Number(rightPart) ? 1 : -1;
50
+ if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
51
+ return leftPart > rightPart ? 1 : -1;
52
+ }
53
+ return 0;
54
+ }
55
+
56
+ export function compareVersions(leftValue, rightValue) {
57
+ const left = parseVersion(leftValue);
58
+ const right = parseVersion(rightValue);
59
+ for (let index = 0; index < left.core.length; index += 1) {
60
+ if (left.core[index] !== right.core[index]) return left.core[index] > right.core[index] ? 1 : -1;
61
+ }
62
+ return comparePrerelease(left.prerelease, right.prerelease);
63
+ }
64
+
65
+ export async function fetchLatestVersion(overrides = {}) {
66
+ const fetchImpl = overrides.fetch ?? globalThis.fetch;
67
+ const timeoutMs = overrides.timeoutMs ?? 1500;
68
+ const controller = new AbortController();
69
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
70
+ try {
71
+ const response = await fetchImpl(REGISTRY_LATEST_URL, {
72
+ headers: { Accept: "application/json" },
73
+ signal: controller.signal,
74
+ });
75
+ if (!response.ok) throw new Error(`npm registry returned HTTP ${response.status}.`);
76
+ const body = await response.json();
77
+ const version = body && typeof body === "object" && !Array.isArray(body) ? body.version : undefined;
78
+ parseVersion(version);
79
+ return version;
80
+ } finally {
81
+ clearTimeout(timeout);
82
+ }
83
+ }
84
+
85
+ function updateCheckPath(env, platform, homeDir) {
86
+ return path.join(configDirectory(env, platform, homeDir), "update-check.json");
87
+ }
88
+
89
+ async function loadUpdateCache(file) {
90
+ try {
91
+ const parsed = JSON.parse(await fs.readFile(file, "utf8"));
92
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
93
+ return parsed;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ async function saveUpdateCache(file, cache) {
100
+ const directory = path.dirname(file);
101
+ await fs.mkdir(directory, { mode: 0o700, recursive: true });
102
+ const temporaryFile = `${file}.${process.pid}.tmp`;
103
+ await fs.writeFile(temporaryFile, `${JSON.stringify(cache)}\n`, { mode: 0o600 });
104
+ await fs.rename(temporaryFile, file);
105
+ }
106
+
107
+ export async function maybeNotifyUpdate(overrides = {}) {
108
+ const env = overrides.env ?? process.env;
109
+ const stderr = overrides.stderr ?? process.stderr;
110
+ if (stderr?.isTTY !== true || env.CI || env.HIVE_NO_UPDATE_CHECK === "1" || env.HIVE_NO_UPDATE_CHECK === "true") {
111
+ return null;
112
+ }
113
+
114
+ const now = (overrides.now ?? Date.now)();
115
+ const file = updateCheckPath(env, overrides.platform ?? process.platform, overrides.homeDir);
116
+ const cache = await loadUpdateCache(file);
117
+ if (
118
+ typeof cache?.checkedAt === "number" &&
119
+ now >= cache.checkedAt &&
120
+ now - cache.checkedAt < UPDATE_CHECK_INTERVAL_MS
121
+ ) {
122
+ return null;
123
+ }
124
+
125
+ let latestVersion;
126
+ try {
127
+ latestVersion = await fetchLatestVersion({ fetch: overrides.fetch, timeoutMs: overrides.timeoutMs });
128
+ } catch {
129
+ try {
130
+ await saveUpdateCache(file, { checkedAt: now });
131
+ } catch {
132
+ // Update checks must never break a CLI command.
133
+ }
134
+ return null;
135
+ }
136
+
137
+ try {
138
+ await saveUpdateCache(file, { checkedAt: now, latestVersion });
139
+ } catch {
140
+ // A read-only notification is still useful if the cache is unavailable.
141
+ }
142
+ const currentVersion = overrides.currentVersion ?? CURRENT_VERSION;
143
+ if (compareVersions(latestVersion, currentVersion) <= 0) return null;
144
+
145
+ writeLine(stderr, `Hive CLI update available: ${currentVersion} → ${latestVersion}`);
146
+ writeLine(stderr, "Run `hive update` to install it.");
147
+ return latestVersion;
148
+ }
149
+
150
+ export function installLatest(overrides = {}) {
151
+ const spawnImpl = overrides.spawn ?? spawn;
152
+ const command = (overrides.platform ?? process.platform) === "win32" ? "npm.cmd" : "npm";
153
+ return new Promise((resolve, reject) => {
154
+ const child = spawnImpl(command, ["install", "--global", `${PACKAGE_NAME}@latest`], {
155
+ shell: false,
156
+ stdio: "inherit",
157
+ });
158
+ child.once("error", reject);
159
+ child.once("exit", (code, signal) => {
160
+ if (code === 0) resolve(undefined);
161
+ else reject(new Error(`npm update failed${signal ? ` with signal ${signal}` : ` with exit code ${code}`}.`));
162
+ });
163
+ });
164
+ }
165
+
166
+ export async function runUpdateCommand(args, overrides = {}) {
167
+ const stdout = overrides.stdout ?? process.stdout;
168
+ if (args.length > 1 || (args.length === 1 && !["--check", "--help", "-h"].includes(args[0]))) {
169
+ throw new Error(`Unknown update option: ${args[0] ?? ""}`.trim());
170
+ }
171
+ if (args[0] === "--help" || args[0] === "-h") {
172
+ writeLine(stdout, "Usage: hive update [--check]");
173
+ return;
174
+ }
175
+
176
+ let latestVersion;
177
+ try {
178
+ latestVersion = await fetchLatestVersion({ fetch: overrides.fetch, timeoutMs: overrides.timeoutMs });
179
+ } catch (error) {
180
+ const detail = error instanceof Error ? error.message : "Unknown registry error.";
181
+ throw new Error(`Unable to check for Hive CLI updates: ${detail}`);
182
+ }
183
+
184
+ const currentVersion = overrides.currentVersion ?? CURRENT_VERSION;
185
+ if (compareVersions(latestVersion, currentVersion) <= 0) {
186
+ writeLine(stdout, `Hive CLI ${currentVersion} is already the latest version.`);
187
+ return;
188
+ }
189
+
190
+ if (args[0] === "--check") {
191
+ writeLine(stdout, `Hive CLI update available: ${currentVersion} → ${latestVersion}`);
192
+ writeLine(stdout, "Run `hive update` to install it.");
193
+ return;
194
+ }
195
+
196
+ writeLine(stdout, `Updating Hive CLI ${currentVersion} → ${latestVersion}...`);
197
+ await (overrides.install ?? installLatest)({ platform: overrides.platform, spawn: overrides.spawn });
198
+ writeLine(stdout, `Hive CLI ${latestVersion} installed. Run \`hive --help\` to verify it.`);
199
+ }
package/src/usage.js ADDED
@@ -0,0 +1,54 @@
1
+ // @ts-check
2
+
3
+ export function usage() {
4
+ return [
5
+ "Usage: hive <command> [options]",
6
+ "",
7
+ "Commands:",
8
+ " login Connect this CLI through browser approval",
9
+ " logout Remove the stored local credential",
10
+ " update [--check] Install or check for the latest Hive CLI",
11
+ " whoami Show the authenticated Hive account",
12
+ " capabilities List community targets available to this account",
13
+ " profile <action> Manage profile text, media IDs, access, and builders",
14
+ " upload <file> Upload an allowed image or document and print its storage ID",
15
+ " account <action> Manage account preferences, exports, and deletion requests",
16
+ " wallets <action> Manage linked wallet visibility/default selection",
17
+ " nfts <action> Manage public NFT exposure",
18
+ " notifications <action> Manage notifications and notification mutes",
19
+ " comments <action> Manage post comments",
20
+ " communities <action> Manage community membership and role-derived admin actions",
21
+ " posts <action> Manage posts",
22
+ " events <action> Manage events",
23
+ " courses <action> Manage courses",
24
+ " content <action> Manage content",
25
+ " quests <action> Manage quests",
26
+ " jobs <action> Manage jobs",
27
+ "",
28
+ "Resource CRUD actions:",
29
+ " list [--limit n] [--cursor c] [--owner-type person|community] [--community-id id]",
30
+ " create [--title t] [--body b] [--description d] [--content-type t] [--visibility v]",
31
+ " update <id> [--title t] [--body b] [--description d] [--content-type t] [--visibility v]",
32
+ " archive <id> (workflow subcommands include participants, enrollments, evidence, applications)",
33
+ ].join("\n");
34
+ }
35
+
36
+ export function resourceUsage(kind) {
37
+ return [
38
+ `Usage: hive ${kind} <list|create|update|archive> [options]`,
39
+ "",
40
+ "Create/update fields:",
41
+ " --title <text>",
42
+ " --body <text>",
43
+ " --description <text>",
44
+ " --content-type <type>",
45
+ " --image-url <url>",
46
+ " --visibility <public|protected|private>",
47
+ " --file <json>",
48
+ "",
49
+ "Create owner fields:",
50
+ " --owner-type <person|community>",
51
+ " --community-id <id>",
52
+ " --idempotency-key <key>",
53
+ ].join("\n");
54
+ }