@networkbase/cli 2.1.1 → 2.1.3
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/bin/nb.mjs +24 -1
- package/lib/api.mjs +8 -2
- package/lib/commands/assignments.mjs +39 -4
- package/lib/commands/browse.mjs +139 -3
- package/lib/commands/complete.mjs +72 -0
- package/lib/commands/docs.mjs +143 -5
- package/lib/commands/extras.mjs +18 -1
- package/lib/commands/files.mjs +34 -3
- package/lib/commands/inbox.mjs +71 -3
- package/lib/commands/misc.mjs +108 -6
- package/lib/commands/resolve.mjs +30 -1
- package/lib/commands/table.mjs +60 -13
- package/lib/commands/tasks.mjs +100 -11
- package/lib/commands/undo.mjs +12 -3
- package/lib/commands/watch.mjs +5 -2
- package/lib/commands/work.mjs +65 -3
- package/lib/config.mjs +2 -0
- package/lib/context.mjs +4 -1
- package/lib/dates.mjs +24 -0
- package/lib/error-fixes.mjs +2 -0
- package/lib/errors.mjs +1 -0
- package/lib/help-topics.mjs +47 -0
- package/lib/network.mjs +27 -0
- package/lib/print/notices.mjs +3 -0
- package/lib/print/out.mjs +21 -3
- package/lib/sync/transfer.mjs +10 -4
- package/lib/whats-new.mjs +8 -0
- package/package.json +1 -1
package/lib/commands/tasks.mjs
CHANGED
|
@@ -29,7 +29,7 @@ export async function resolveTask(ctx, ref, { brief = false } = {}) {
|
|
|
29
29
|
if (error instanceof CliError && (error.status === 404 || error.code === "NOT_FOUND")) throw new CliError("TASK_NOT_FOUND", `No task ${ref} in this workspace`, { hint: "See nb task list" });
|
|
30
30
|
throw error;
|
|
31
31
|
}));
|
|
32
|
-
return { ...detail.task, subtasks: detail.subtasks ?? [], files: detail.files ?? [], comments: detail.comments ?? [], pushes: detail.pushes ?? [] };
|
|
32
|
+
return { ...detail.task, subtasks: detail.subtasks ?? [], files: detail.files ?? [], comments: detail.comments ?? [], pushes: detail.pushes ?? [], meta: detail.meta ?? null };
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
/**
|
|
@@ -92,7 +92,8 @@ export async function list(ctx) {
|
|
|
92
92
|
const { applySavedFilter } = await import("./extras.mjs");
|
|
93
93
|
applySavedFilter(ctx);
|
|
94
94
|
const workspaceId = ctx.requireWorkspace();
|
|
95
|
-
|
|
95
|
+
// A label or your stars pick tasks on their own, so they look at everyone's (M4b live check).
|
|
96
|
+
const scope = ctx.flags.all || ctx.flags.to || ctx.flags.label || ctx.flags.starred ? "all" : "mine";
|
|
96
97
|
const wanted = ctx.flags.status ? new Set(String(ctx.flags.status).split(",").map((s) => s.trim())) : null;
|
|
97
98
|
const limit = ctx.flags.limit ? Number(ctx.flags.limit) : 50;
|
|
98
99
|
// Filters run on the server (C2), so open work never falls off a page of done tasks.
|
|
@@ -110,11 +111,13 @@ export async function list(ctx) {
|
|
|
110
111
|
if (ctx.flags.sprint) query.sprint = await resolveSprint(ctx, String(ctx.flags.sprint));
|
|
111
112
|
if (ctx.flags.priority) query.priority = String(ctx.flags.priority);
|
|
112
113
|
if (ctx.flags.sort) query.sort = String(ctx.flags.sort);
|
|
114
|
+
if (ctx.flags.label) query.label = String(ctx.flags.label).toLowerCase();
|
|
115
|
+
if (ctx.flags.starred) query.starred = "1";
|
|
113
116
|
const { tasks } = /** @type {any} */ (await ctx.api.get("/api/v1/extension/workspace-tasks", { query }));
|
|
114
117
|
let rows = tasks.filter((/** @type {any} */ t) => (wanted ? wanted.has(t.status) || (wanted.has("review") && t.reviewStatus === "pending") : true));
|
|
115
118
|
const more = Math.max(0, rows.length - limit);
|
|
116
119
|
rows = rows.slice(0, limit);
|
|
117
|
-
const data = { scope, tasks: rows.map((/** @type {any} */ t) => ({ id: t.id, number: t.taskNumber, title: t.title, status: t.status, reviewStatus: t.reviewStatus ?? null, priority: t.priority ?? null, dueDate: t.dueDate ?? null, assignee: t.assigneeUsername ?? t.assigneeName ?? null, subtasks: t.subtaskSummary ?? null })), more };
|
|
120
|
+
const data = { scope, tasks: rows.map((/** @type {any} */ t) => ({ id: t.id, number: t.taskNumber, title: t.title, status: t.status, reviewStatus: t.reviewStatus ?? null, priority: t.priority ?? null, dueDate: t.dueDate ?? null, assignee: t.assigneeUsername ?? t.assigneeName ?? null, labels: t.labels ?? [], subtasks: t.subtaskSummary ?? null })), more };
|
|
118
121
|
ctx.out.result("nb.task.list/1", data, (d) => {
|
|
119
122
|
if (!d.tasks.length) return scope === "mine" ? "No open tasks assigned to you · nb task list --all for everyone's" : "No open tasks";
|
|
120
123
|
const started = ctx.project?.startedTask?.id;
|
|
@@ -122,7 +125,7 @@ export async function list(ctx) {
|
|
|
122
125
|
...ctx.out.table([
|
|
123
126
|
// The started task gets a marker and a space, so plain output never reads as "-1" (C16 #4).
|
|
124
127
|
{ title: "#", value: (t) => `${t.id === started ? ctx.out.c.brand(ctx.out.sym.cursor) : " "} ${t.number ?? ""}`, align: "right" },
|
|
125
|
-
{ title: "Task", value: (t) => safe(t.title)
|
|
128
|
+
{ title: "Task", value: (t) => `${safe(t.title)}${t.labels?.length ? ` ${ctx.out.c.accent(t.labels.map((/** @type {string} */ l) => `[${safe(l)}]`).join(" "))}` : ""}`, flex: true },
|
|
126
129
|
{ title: "Status", value: (t) => statusWord(t) },
|
|
127
130
|
{ title: "Due", value: (t) => (t.dueDate ? formatDate(t.dueDate) : "—"), optional: true },
|
|
128
131
|
{ title: "Assignee", value: (t) => (t.assignee ? `@${safe(t.assignee)}` : "—"), optional: true },
|
|
@@ -174,10 +177,21 @@ export function formatDate(iso) {
|
|
|
174
177
|
if (days === 0) return "today";
|
|
175
178
|
if (days === 1) return "tomorrow";
|
|
176
179
|
if (days === -1) return "yesterday";
|
|
177
|
-
|
|
180
|
+
// Relative within a week (C11): "in 3 days", "4 days ago"; exact dates stay in --json.
|
|
181
|
+
if (days > 1 && days < 7) return `in ${days} days`;
|
|
182
|
+
if (days < -1 && days > -7) return `${-days} days ago`;
|
|
178
183
|
return d.toLocaleDateString(undefined, { day: "numeric", month: "short" });
|
|
179
184
|
}
|
|
180
185
|
|
|
186
|
+
/** When something happened (C11): "just now", "5 min ago", "3 h ago", then as formatDate. @param {string} iso */
|
|
187
|
+
export function formatWhen(iso) {
|
|
188
|
+
const ms = Date.now() - new Date(iso).getTime();
|
|
189
|
+
if (ms >= 0 && ms < 60_000) return "just now";
|
|
190
|
+
if (ms >= 0 && ms < 3_600_000) return `${Math.floor(ms / 60_000)} min ago`;
|
|
191
|
+
if (ms >= 0 && ms < 86_400_000) return `${Math.floor(ms / 3_600_000)} h ago`;
|
|
192
|
+
return formatDate(iso);
|
|
193
|
+
}
|
|
194
|
+
|
|
181
195
|
/** "How many tasks do I have?" (report §18.2). @param {Context} ctx */
|
|
182
196
|
export async function count(ctx) {
|
|
183
197
|
const counts = /** @type {any} */ (await ctx.api.get("/api/v1/tasks/count"));
|
|
@@ -202,16 +216,29 @@ export async function view(ctx) {
|
|
|
202
216
|
assignee: task.assignee?.username ?? task.assignee?.name ?? null, sprint: task.sprint?.name ?? null, description: task.description ?? "",
|
|
203
217
|
subtasks: task.subtasks.map((/** @type {any} */ s, /** @type {number} */ i) => ({ n: s.index ?? i + 1, id: s.id, title: s.title, done: Boolean(s.completed) })),
|
|
204
218
|
files: task.files.map((/** @type {any} */ f) => ({ path: f.path ?? f.name, as: ROLE[f.role] ?? "draft", version: f.currentVersion ?? null })),
|
|
219
|
+
// The one-screen view (C11): labels, what it waits on and what waits on it, links, the latest 3 comments.
|
|
220
|
+
labels: task.meta?.labels ?? task.labels ?? [],
|
|
221
|
+
blockedBy: (task.meta?.blockedBy ?? []).map((/** @type {any} */ t) => ({ number: t.number, title: t.title, status: t.status })),
|
|
222
|
+
blocking: (task.meta?.blocking ?? []).map((/** @type {any} */ t) => ({ number: t.number, title: t.title, status: t.status })),
|
|
223
|
+
links: task.meta?.links ?? [],
|
|
224
|
+
watching: Boolean(task.meta?.watching),
|
|
225
|
+
starred: Boolean(task.meta?.starred),
|
|
226
|
+
comments: task.comments.slice(0, 3).map((/** @type {any} */ cm) => ({ by: cm.authorUsername ?? cm.authorName ?? null, text: cm.content, at: cm.createdAt })),
|
|
205
227
|
};
|
|
206
228
|
const { c, sym } = ctx.out;
|
|
207
229
|
const slug = ctx.project?.slug ?? ctx.flags.workspace;
|
|
208
230
|
const taskUrl = slug ? `${ctx.profile.origin}/workspaces/${encodeURIComponent(String(slug))}?tab=tasks&task=${data.number}` : null;
|
|
209
231
|
ctx.out.result("nb.task.view/1", data, (d) => [
|
|
210
232
|
`${c.brand(sym.brand)} ${taskUrl ? ctx.out.link(`#${d.number}`, taskUrl, ctx.profile.origin) : `#${d.number}`} ${c.bold(safe(d.title))}`,
|
|
211
|
-
` ${statusWord(d)}${d.priority ? ` · ${d.priority}` : ""}${d.assignee ? ` · @${safe(d.assignee)}` : ""}${d.sprint ? ` · ${safe(d.sprint)}` : ""}`,
|
|
233
|
+
` ${statusWord(d)}${d.priority ? ` · ${d.priority}` : ""}${d.assignee ? ` · @${safe(d.assignee)}` : ""}${d.sprint ? ` · ${safe(d.sprint)}` : ""}${d.starred ? ` · ${c.warning("★")}` : ""}${d.watching ? c.muted(" · watching") : ""}`,
|
|
234
|
+
...(d.labels.length ? [` ${d.labels.map((/** @type {string} */ l) => c.accent(`[${safe(l)}]`)).join(" ")}`] : []),
|
|
235
|
+
...(d.blockedBy.length ? [` ${c.warning("Waiting on")} ${d.blockedBy.map((/** @type {any} */ t) => `#${t.number} ${safe(t.title)}${t.status === "done" ? c.muted(" (done)") : ""}`).join(", ")}`] : []),
|
|
236
|
+
...(d.blocking.length ? [` ${c.muted("Blocks")} ${d.blocking.map((/** @type {any} */ t) => `#${t.number}`).join(", ")}`] : []),
|
|
212
237
|
...(d.description.trim() ? ["", ...safe(d.description.trim()).split("\n").map((l) => ` ${l}`)] : []),
|
|
213
238
|
...(d.subtasks.length ? ["", ` Subtasks (${d.subtasks.filter((/** @type {any} */ s) => s.done).length}/${d.subtasks.length})`, ...d.subtasks.map((/** @type {any} */ s) => ` ${s.done ? c.success("[x]") : "[ ]"} ${s.n}. ${safe(s.title)}`)] : []),
|
|
214
239
|
...(d.files.length ? ["", " Files", ...d.files.map((/** @type {any} */ f) => ` ${safe(f.path)} ${c.muted(`${f.as}${f.version ? ` · v${f.version}` : ""}`)}`)] : []),
|
|
240
|
+
...(d.links.length ? ["", " Links", ...d.links.map((/** @type {any} */ l) => ` ${l.kind === "pull_request" ? "PR " : l.kind === "issue" ? "Issue " : ""}${l.title ? `${safe(l.title)} ${c.muted(safe(l.url))}` : safe(l.url)}`)] : []),
|
|
241
|
+
...(d.comments.length ? ["", " Latest comments", ...d.comments.map((/** @type {any} */ cm) => ` ${cm.by ? `@${safe(cm.by)}` : "someone"}: ${commentText(cm.text).replace(/\n/g, " ").slice(0, 160)}`)] : []),
|
|
215
242
|
], { page: true });
|
|
216
243
|
}
|
|
217
244
|
|
|
@@ -494,11 +521,73 @@ export const subtaskUncheck = (ctx) => setSubtasks(ctx, false);
|
|
|
494
521
|
|
|
495
522
|
/** @param {Context} ctx */
|
|
496
523
|
export async function commentAdd(ctx) {
|
|
524
|
+
// A comment on a doc is a comment on its file (C4): nb comment add --doc readme -m "…".
|
|
525
|
+
if (ctx.flags.doc) {
|
|
526
|
+
const { docs } = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/docs`));
|
|
527
|
+
const doc = docs.find((/** @type {any} */ d) => d.slug === String(ctx.flags.doc).toLowerCase());
|
|
528
|
+
if (!doc?.nodePath) throw new CliError("DOC_NOT_FOUND", doc ? `${doc.slug} has no file yet` : `No doc called ${ctx.flags.doc}`, { hint: "nb doc list" });
|
|
529
|
+
ctx.flags.file = `${doc.nodePath.replace(/^\//, "")}:1`;
|
|
530
|
+
}
|
|
497
531
|
if (ctx.flags.file) return (await import("./work.mjs")).commentOnFile(ctx);
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
const
|
|
501
|
-
|
|
502
|
-
|
|
532
|
+
// `nb comment add 4 "looks good"`: a leading task number, when text follows it or comes with -m.
|
|
533
|
+
const lead = !ctx.flags.task && /^#?\d+$/.test(ctx.positionals[0] ?? "") && (ctx.flags.message !== undefined || ctx.positionals.length > 1);
|
|
534
|
+
const words = lead ? ctx.positionals.slice(1) : ctx.positionals;
|
|
535
|
+
const raw = String(ctx.flags.message ?? words.join(" ")).trim();
|
|
536
|
+
if (!raw) throw usage('nb comment add <task> "<text>" [--reply <id>]');
|
|
537
|
+
const task = await resolveTask(ctx, lead ? ctx.positionals[0].replace("#", "") : taskRef(ctx, undefined));
|
|
538
|
+
const text = await withMentions(ctx, raw);
|
|
539
|
+
const replyTo = ctx.flags.reply ? commentIdOf(task, String(ctx.flags.reply)) : null;
|
|
540
|
+
await ctx.api.post("/api/v1/extension/comments", { kind: "task", projectId: ctx.requireWorkspace(), taskId: task.id, text, ...(replyTo ? { replyTo } : {}) });
|
|
541
|
+
ctx.out.result("nb.comment.add/1", { number: task.taskNumber, reply: Boolean(replyTo) }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${d.reply ? "Replied" : "Commented"} on #${d.number}`);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* `@sam` in a comment becomes a real mention (C4), so Sam is told, as in the app. A name that isn't a member of the
|
|
546
|
+
* workspace is an error that says so, never a mention that quietly goes nowhere.
|
|
547
|
+
* @param {Context} ctx @param {string} text
|
|
548
|
+
*/
|
|
549
|
+
export async function withMentions(ctx, text) {
|
|
550
|
+
const names = [...new Set([...text.matchAll(/(?<![\w@{])@([a-z0-9_.-]{2,40})\b/gi)].map((m) => m[1].toLowerCase()))];
|
|
551
|
+
if (!names.length) return text;
|
|
552
|
+
const { members } = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/members`));
|
|
553
|
+
let out = text;
|
|
554
|
+
for (const name of names) {
|
|
555
|
+
const m = members.find((/** @type {any} */ x) => String(x.username ?? "").toLowerCase() === name);
|
|
556
|
+
if (!m) throw new CliError("NOT_FOUND", `@${name} isn't in this workspace, so they wouldn't be told`, { hint: "nb member list" });
|
|
557
|
+
out = out.replace(new RegExp(`(?<![\\w@{])@${name.replace(/[.]/g, "\\.")}\\b`, "gi"), `@{${m.id}|${String(m.fullName ?? m.username).replace(/[|}]/g, "")}}`);
|
|
558
|
+
}
|
|
559
|
+
return out;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** A comment by the id shown in nb comment list (its first characters are enough). @param {any} task @param {string} ref */
|
|
563
|
+
function commentIdOf(task, ref) {
|
|
564
|
+
const hits = task.comments.filter((/** @type {any} */ c) => String(c.id).startsWith(ref.toLowerCase()));
|
|
565
|
+
if (hits.length !== 1) throw new CliError("NOT_FOUND", hits.length ? `${ref} matches more than one comment` : `No comment ${ref} on #${task.taskNumber}`, { hint: `nb comment list --task ${task.taskNumber}` });
|
|
566
|
+
return hits[0].id;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** `nb comment edit <id> -m "…"` and `nb comment delete <id>` (C4): your own task comments. @param {Context} ctx @param {"edit" | "delete"} what */
|
|
570
|
+
async function ownComment(ctx, what) {
|
|
571
|
+
const ref = ctx.positionals[0];
|
|
572
|
+
if (!ref) throw usage(what === "edit" ? 'nb comment edit <id> -m "new text" [--task 4]' : "nb comment delete <id> [--task 4]", "The ids are in nb comment list");
|
|
573
|
+
// A full id is enough on its own; the short one from nb comment list is found on the task.
|
|
574
|
+
const full = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(ref) && !ctx.flags.task;
|
|
575
|
+
if (!full && !ctx.flags.task && !ctx.project?.startedTask && !branchTask(ctx.root)) throw usage(`Which task is comment ${ref} on? Add --task <n>`, "Or pass the full comment id from nb comment list --json");
|
|
576
|
+
const task = full ? null : await resolveTask(ctx, taskRef(ctx, undefined));
|
|
577
|
+
const commentId = task ? commentIdOf(task, ref) : ref;
|
|
578
|
+
if (what === "edit") {
|
|
579
|
+
const raw = String(ctx.flags.message ?? ctx.positionals.slice(1).join(" ")).trim();
|
|
580
|
+
if (!raw) throw usage('nb comment edit <id> -m "new text"');
|
|
581
|
+
await ctx.api.patch("/api/v1/extension/comments", { projectId: ctx.requireWorkspace(), commentId, text: await withMentions(ctx, raw) });
|
|
582
|
+
} else {
|
|
583
|
+
const { confirm } = await import("../tui/ask.mjs");
|
|
584
|
+
if (!(await confirm(ctx, { key: "delete", question: `Delete your comment ${ref}${task ? ` on #${task.taskNumber}` : ""}?`, yesLabel: "Delete", defaultYes: false }))) return 130;
|
|
585
|
+
await ctx.api.request("DELETE", "/api/v1/extension/comments", { body: { projectId: ctx.requireWorkspace(), commentId } });
|
|
586
|
+
}
|
|
587
|
+
ctx.out.result(`nb.comment.${what}/1`, { number: task?.taskNumber ?? null, commentId }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${what === "edit" ? "Edited" : "Deleted"} your comment${d.number ? ` on #${d.number}` : ""}`);
|
|
503
588
|
}
|
|
589
|
+
/** @param {Context} ctx */
|
|
590
|
+
export const commentEdit = (ctx) => ownComment(ctx, "edit");
|
|
591
|
+
/** @param {Context} ctx */
|
|
592
|
+
export const commentDelete = (ctx) => ownComment(ctx, "delete");
|
|
504
593
|
|
package/lib/commands/undo.mjs
CHANGED
|
@@ -15,8 +15,15 @@ const WHAT = /** @type {Record<string, string>} */ ({
|
|
|
15
15
|
export async function undo(ctx) {
|
|
16
16
|
const log = readUndoLog(ctx.env, ctx.profile.origin);
|
|
17
17
|
if (ctx.flags.list) {
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
// What each would undo, in the server's words (C10), newest first; nb undo <n> picks one.
|
|
19
|
+
const recent = log.slice().reverse().slice(0, 20);
|
|
20
|
+
const summaries = await Promise.all(recent.map((e) => ctx.api.get(`/api/v1/undo/${encodeURIComponent(e.token)}`).then((/** @type {any} */ r) => String(r.summary), () => null)));
|
|
21
|
+
const changes = recent.map((e, i) => ({ n: i + 1, token: e.token, at: new Date(e.at).toISOString(), what: summaries[i] ?? WHAT[e.path] ?? e.path, available: summaries[i] !== null }));
|
|
22
|
+
const { formatWhen } = await import("./tasks.mjs");
|
|
23
|
+
return ctx.out.result("nb.undo.list/1", { changes }, (d) =>
|
|
24
|
+
d.changes.length
|
|
25
|
+
? [...d.changes.map((c) => ` ${String(c.n).padStart(2)}. ${ctx.out.c.muted(formatWhen(c.at).padEnd(10))} ${safe(c.what)}${c.available ? "" : ctx.out.c.muted(" (can't be undone any more)")}`), ctx.out.c.muted(" nb undo <n> undoes that one")]
|
|
26
|
+
: "Nothing to undo from the last 24 hours");
|
|
20
27
|
}
|
|
21
28
|
if (ctx.flags.session) {
|
|
22
29
|
// Everything this agent session did, newest first (report A7.7): `nb mcp` tags its changes with a session id.
|
|
@@ -39,7 +46,9 @@ export async function undo(ctx) {
|
|
|
39
46
|
return results.every((r) => r.ok) ? 0 : 4;
|
|
40
47
|
}
|
|
41
48
|
const given = ctx.positionals[0];
|
|
42
|
-
|
|
49
|
+
// A number is a line of nb undo --list (newest first); anything else is a token or its start.
|
|
50
|
+
const numbered = given && /^\d{1,2}$/.test(given) ? log.slice().reverse()[Number(given) - 1] : null;
|
|
51
|
+
const entry = numbered ?? (given ? log.find((e) => e.token.startsWith(given)) ?? { token: given } : log.at(-1));
|
|
43
52
|
if (!entry) throw new CliError("NOT_FOUND", "Nothing to undo from the last 24 hours on this machine", { hint: "nb undo --list" });
|
|
44
53
|
try {
|
|
45
54
|
const res = /** @type {any} */ (await ctx.api.post(`/api/v1/undo/${encodeURIComponent(entry.token)}`, {}));
|
package/lib/commands/watch.mjs
CHANGED
|
@@ -47,9 +47,12 @@ export async function watch(ctx) {
|
|
|
47
47
|
let backoff = 1000;
|
|
48
48
|
while (!stopping) {
|
|
49
49
|
try {
|
|
50
|
-
const res = /** @type {any} */ (await ctx.api.get("/api/v1/events", { query: { since, workspace: project.workspaceId, inbox: 0 }, timeoutMs: 40_000 }));
|
|
50
|
+
const res = /** @type {any} */ (await ctx.api.get("/api/v1/events", { query: { since, workspace: project.workspaceId, inbox: ctx.flags.inbox ? 1 : 0 }, timeoutMs: 40_000 }));
|
|
51
51
|
since = res.cursor;
|
|
52
52
|
backoff = 1000;
|
|
53
|
+
// --inbox (C13): your notifications as they happen, one line each; your settings and quiet hours already apply.
|
|
54
|
+
if (ctx.flags.inbox) for (const n of res.notifications ?? []) ctx.out.note(`${ctx.out.c.brand(ctx.out.sym.brand)} ${safe(n.title ?? "")}${n.body ? ctx.out.c.muted(` · ${safe(String(n.body)).replace(/\s+/g, " ").slice(0, 100)}`) : ""}`);
|
|
55
|
+
if (ctx.flags["no-pull"]) continue;
|
|
53
56
|
const theirs = [...new Set(res.files.filter((/** @type {any} */ f) => !f.mine).map((/** @type {any} */ f) => toRelative(project.remoteRoot, f.path)).filter(Boolean))];
|
|
54
57
|
if (!theirs.length || stopping) continue;
|
|
55
58
|
while (busy) await new Promise((r) => setTimeout(r, 200));
|
|
@@ -68,7 +71,7 @@ export async function watch(ctx) {
|
|
|
68
71
|
}
|
|
69
72
|
}
|
|
70
73
|
};
|
|
71
|
-
if (!ctx.flags["no-pull"]) void livePull();
|
|
74
|
+
if (!ctx.flags["no-pull"] || ctx.flags.inbox) void livePull();
|
|
72
75
|
|
|
73
76
|
/** One batch: files whose last change is older than the quiet window. */
|
|
74
77
|
async function flush() {
|
package/lib/commands/work.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { CliError, EXIT, usage } from "../errors.mjs";
|
|
|
8
8
|
import { commentText, safe } from "../print/style.mjs";
|
|
9
9
|
import { confirm } from "../tui/ask.mjs";
|
|
10
10
|
import { parseDate } from "../dates.mjs";
|
|
11
|
-
import { bulkChange, resolveTask, taskRef } from "./tasks.mjs";
|
|
11
|
+
import { bulkChange, formatWhen, resolveTask, taskRef } from "./tasks.mjs";
|
|
12
12
|
|
|
13
13
|
/** @typedef {import("../context.mjs").Context} Context */
|
|
14
14
|
|
|
@@ -32,7 +32,28 @@ export async function taskEdit(ctx) {
|
|
|
32
32
|
if (due !== "none" && !date) throw usage(`--due ${due} isn't a date I know`, "Use today, tomorrow, friday, next week, in 3 days, 2026-12-01, or none");
|
|
33
33
|
changes.push(["dueDate", date]);
|
|
34
34
|
}
|
|
35
|
-
|
|
35
|
+
// Labels, "blocked by" and links (C2, C12, 0087) go to the task's meta route.
|
|
36
|
+
const list = (/** @type {unknown} */ v) => (v === undefined ? [] : /** @type {string[]} */ ([v].flat()).flatMap((x) => String(x).split(",")).map((x) => x.trim()).filter(Boolean));
|
|
37
|
+
const labelAdd = list(ctx.flags.label).map((l) => l.toLowerCase()), labelRemove = list(ctx.flags.unlabel).map((l) => l.toLowerCase()), blockAdd = list(ctx.flags["blocked-by"]), blockRemove = list(ctx.flags["not-blocked-by"]), linkAdd = list(ctx.flags.link);
|
|
38
|
+
const metaWanted = labelAdd.length || labelRemove.length || blockAdd.length || blockRemove.length || linkAdd.length;
|
|
39
|
+
if (!changes.length && !metaWanted) throw usage("nb task edit <task…> [--title text] [-m description] [--priority high] [--due friday|none] [--label bug] [--blocked-by 7] [--link url]");
|
|
40
|
+
if (metaWanted) {
|
|
41
|
+
if (ctx.positionals.length > 1) throw usage("Labels, blocked-by and links change one task at a time");
|
|
42
|
+
const task = await resolveTask(ctx, taskRef(ctx, ctx.positionals[0]), { brief: true });
|
|
43
|
+
const ids = async (/** @type {string[]} */ refs) => Promise.all(refs.map(async (r) => (await resolveTask(ctx, r, { brief: true })).id));
|
|
44
|
+
const meta = /** @type {any} */ (await ctx.api.patch(`/api/v1/tasks/${task.id}/meta`, {
|
|
45
|
+
...(labelAdd.length || labelRemove.length ? { labels: { ...(labelAdd.length ? { add: labelAdd } : {}), ...(labelRemove.length ? { remove: labelRemove } : {}) } } : {}),
|
|
46
|
+
...(blockAdd.length || blockRemove.length ? { blockedBy: { ...(blockAdd.length ? { add: await ids(blockAdd) } : {}), ...(blockRemove.length ? { remove: await ids(blockRemove) } : {}) } } : {}),
|
|
47
|
+
...(linkAdd.length ? { links: { add: linkAdd.map((url) => ({ url })) } } : {}),
|
|
48
|
+
}));
|
|
49
|
+
for (const [field, value] of changes) await update(ctx, { kind: "edit", taskId: task.id, field, value });
|
|
50
|
+
return ctx.out.result("nb.task.edit/1", { number: task.taskNumber, changed: changes.map(([f]) => f), labels: meta.labels, blockedBy: meta.blockedBy.map((/** @type {any} */ t) => t.number), links: meta.links }, (d) => [
|
|
51
|
+
`${ctx.out.c.success(ctx.out.sym.done)} Changed #${d.number}${d.changed.length ? `: ${d.changed.join(", ")}` : ""}`,
|
|
52
|
+
...(d.labels.length ? [` labels ${d.labels.map((/** @type {string} */ l) => `[${safe(l)}]`).join(" ")}`] : []),
|
|
53
|
+
...(d.blockedBy.length ? [` waiting on ${d.blockedBy.map((/** @type {number} */ n) => `#${n}`).join(", ")}`] : []),
|
|
54
|
+
...(d.links.length ? [` links ${d.links.map((/** @type {any} */ l) => safe(l.title ?? l.url)).join(", ")}`] : []),
|
|
55
|
+
]);
|
|
56
|
+
}
|
|
36
57
|
if (ctx.positionals.length > 1) {
|
|
37
58
|
if (changes.some(([f]) => f === "title" || f === "description")) throw usage("Several tasks take --priority and --due; change a title one task at a time");
|
|
38
59
|
let numbers = [];
|
|
@@ -70,6 +91,47 @@ async function pickPerson(ctx) {
|
|
|
70
91
|
] });
|
|
71
92
|
}
|
|
72
93
|
|
|
94
|
+
/** Watching and starring are your own (C2, 0087): `nb task watch 4`, `nb task star 4`, and `--off`. @param {Context} ctx @param {"watch" | "star"} what */
|
|
95
|
+
async function personal(ctx, what) {
|
|
96
|
+
const task = await resolveTask(ctx, taskRef(ctx, ctx.positionals[0]), { brief: true });
|
|
97
|
+
const on = !ctx.flags.off;
|
|
98
|
+
await ctx.api.patch(`/api/v1/tasks/${task.id}/meta`, { [what]: on });
|
|
99
|
+
ctx.out.result(`nb.task.${what}/1`, { number: task.taskNumber, [what === "watch" ? "watching" : "starred"]: on }, () =>
|
|
100
|
+
`${ctx.out.c.success(ctx.out.sym.done)} ${what === "watch" ? (on ? `Watching #${task.taskNumber}: you'll hear when it changes` : `Stopped watching #${task.taskNumber}`) : on ? `Starred #${task.taskNumber} · nb task list --starred` : `Unstarred #${task.taskNumber}`}`);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* `nb task remind 4 "tomorrow 9am" [-m note]` (C2, 0088): your own reminder, delivered to your inbox (and push or
|
|
104
|
+
* email as your settings say). `--list` shows yours on the task; `--off` cancels them.
|
|
105
|
+
* @param {Context} ctx
|
|
106
|
+
*/
|
|
107
|
+
export async function taskRemind(ctx) {
|
|
108
|
+
const [ref, ...words] = ctx.positionals;
|
|
109
|
+
if (!ref) throw usage('nb task remind <task> "tomorrow 9am" [-m note]', "Or --list to see yours, --off to cancel them");
|
|
110
|
+
const task = await resolveTask(ctx, ref, { brief: true });
|
|
111
|
+
const path = `/api/v1/tasks/${task.id}/reminders`;
|
|
112
|
+
if (ctx.flags.off) {
|
|
113
|
+
const { cancelled } = /** @type {any} */ (await ctx.api.request("DELETE", path));
|
|
114
|
+
return ctx.out.result("nb.task.remind/1", { number: task.taskNumber, cancelled }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Cancelled ${d.cancelled} reminder${d.cancelled === 1 ? "" : "s"} on #${d.number}`);
|
|
115
|
+
}
|
|
116
|
+
if (ctx.flags.list || !words.length) {
|
|
117
|
+
const { reminders } = /** @type {any} */ (await ctx.api.get(path));
|
|
118
|
+
return ctx.out.result("nb.task.reminders/1", { number: task.taskNumber, reminders }, (d) => (d.reminders.length
|
|
119
|
+
? d.reminders.map((/** @type {any} */ r) => ` ${new Date(r.remindAt).toLocaleString(undefined, { weekday: "short", day: "numeric", month: "short", hour: "numeric", minute: "2-digit" })}${r.note ? ` ${ctx.out.c.muted(safe(r.note))}` : ""}`)
|
|
120
|
+
: `No reminders on #${d.number} · nb task remind ${d.number} "tomorrow 9am"`));
|
|
121
|
+
}
|
|
122
|
+
const { parseWhen } = await import("../dates.mjs");
|
|
123
|
+
const at = parseWhen(words.join(" "));
|
|
124
|
+
if (!at) throw usage(`"${words.join(" ")}" isn't a time I know`, 'Try: "tomorrow 9am", "friday 14:30", "in 2 hours", "today 5pm"');
|
|
125
|
+
const { reminder } = /** @type {any} */ (await ctx.api.post(path, { at: at.toISOString(), ...(ctx.flags.message ? { note: String(ctx.flags.message) } : {}) }));
|
|
126
|
+
ctx.out.result("nb.task.remind/1", { number: task.taskNumber, at: reminder.remindAt, note: reminder.note }, (d) =>
|
|
127
|
+
`${ctx.out.c.success(ctx.out.sym.done)} I'll remind you about #${d.number} ${new Date(d.at).toLocaleString(undefined, { weekday: "short", day: "numeric", month: "short", hour: "numeric", minute: "2-digit" })}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** @param {Context} ctx */
|
|
131
|
+
export const taskWatch = (ctx) => personal(ctx, "watch");
|
|
132
|
+
/** @param {Context} ctx */
|
|
133
|
+
export const taskStar = (ctx) => personal(ctx, "star");
|
|
134
|
+
|
|
73
135
|
/** @param {Context} ctx */
|
|
74
136
|
export async function taskAssign(ctx) {
|
|
75
137
|
// nb task assign 4 @sam, or several: nb task assign 3 4 --to sam (C2). Left out: choose from the members.
|
|
@@ -196,7 +258,7 @@ export async function commentList(ctx) {
|
|
|
196
258
|
const task = await resolveTask(ctx, taskRef(ctx, undefined));
|
|
197
259
|
const comments = task.comments.map((/** @type {any} */ c) => ({ id: c.id, by: c.authorUsername ?? c.authorName ?? null, text: c.content, at: c.createdAt }));
|
|
198
260
|
ctx.out.result("nb.comment.list/1", { number: task.taskNumber, comments, untrusted: true }, (d) =>
|
|
199
|
-
d.comments.length ? d.comments.map((/** @type {any} */ c) => ` ${ctx.out.c.muted(String(c.at)
|
|
261
|
+
d.comments.length ? d.comments.map((/** @type {any} */ c) => ` ${ctx.out.c.muted(formatWhen(String(c.at)))} ${c.by ? `@${safe(c.by)}` : "someone"}: ${commentText(c.text).replace(/\n/g, " ")}${c.id ? ctx.out.c.muted(` ${String(c.id).slice(0, 8)}`) : ""}`) : `#${d.number} has no comments`);
|
|
200
262
|
}
|
|
201
263
|
|
|
202
264
|
/** A comment on lines of a file (report D10): `nb comment add -m "…" --file src/app.ts:12-18`. @param {Context} ctx */
|
package/lib/config.mjs
CHANGED
|
@@ -190,6 +190,8 @@ export function readProjectConfig(root, warn) {
|
|
|
190
190
|
startedTask: raw.startedTask ?? null,
|
|
191
191
|
profile: raw.profile ?? null,
|
|
192
192
|
linkedAt: raw.linkedAt,
|
|
193
|
+
/** Folders this copy keeps in sync (C3 `nb sync --only`); none = everything. */
|
|
194
|
+
only: Array.isArray(raw.only) ? raw.only.filter((/** @type {unknown} */ x) => typeof x === "string") : [],
|
|
193
195
|
};
|
|
194
196
|
}
|
|
195
197
|
|
package/lib/context.mjs
CHANGED
|
@@ -18,7 +18,8 @@ export const VERSION = JSON.parse(fs.readFileSync(PACKAGE_JSON, "utf8")).version
|
|
|
18
18
|
* @param {{ flags: Record<string, any>, positionals: string[], cwd?: string, env?: NodeJS.ProcessEnv, fetchImpl?: typeof fetch, io?: Parameters<typeof createOutput>[1] }} input
|
|
19
19
|
*/
|
|
20
20
|
export function createContext({ flags, positionals, cwd = process.cwd(), env = process.env, fetchImpl, io }) {
|
|
21
|
-
|
|
21
|
+
if (flags.format !== undefined && !["table", "json", "csv", "md"].includes(String(flags.format))) throw new CliError("USAGE", `--format ${flags.format}: use table, json, csv or md`);
|
|
22
|
+
const out = createOutput({ json: Boolean(flags.json || env.NB_JSON === "1"), quiet: Boolean(flags.quiet), plain: Boolean(flags.plain), verbose: Boolean(flags.verbose), fields: flags.fields ? String(flags.fields).split(",").map((f) => f.trim()).filter(Boolean) : null, pager: !flags["no-pager"], format: flags.format ? /** @type {any} */ (String(flags.format)) : null }, io);
|
|
22
23
|
const root = findRoot(cwd);
|
|
23
24
|
const project = root ? readProjectConfig(root, (m) => out.warn(m)) : null;
|
|
24
25
|
const profile = currentProfile({ flags, env, project });
|
|
@@ -30,6 +31,8 @@ export function createContext({ flags, positionals, cwd = process.cwd(), env = p
|
|
|
30
31
|
confirmToken: typeof flags.confirm === "string" ? flags.confirm : null,
|
|
31
32
|
onUndo: (u) => appendUndo(env, { token: u.token, at: Date.now(), method: u.method, path: u.path, origin: profile.origin, session: env.NB_AGENT_SESSION ?? null }),
|
|
32
33
|
onRetry: ({ waitMs, reason }) => out.note(out.c.muted(`${reason}; retrying in ${Math.max(1, Math.round(waitMs / 1000))} s`)),
|
|
34
|
+
// Commands with their own --dry-run (push, pull) plan without writing; every other one stops at its first write.
|
|
35
|
+
dryRun: Boolean(flags["dry-run"]) && !flags.ownDryRun,
|
|
33
36
|
});
|
|
34
37
|
|
|
35
38
|
// The first step comes first (C1): signed out, "link this folder" is the wrong advice.
|
package/lib/dates.mjs
CHANGED
|
@@ -45,3 +45,27 @@ export function dueRange(word, now = new Date()) {
|
|
|
45
45
|
const [y, m, d] = date.split("-").map(Number);
|
|
46
46
|
return { after: new Date(y, m - 1, d).toISOString(), before: new Date(y, m - 1, d + 1).toISOString() };
|
|
47
47
|
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* A moment for reminders (C2): "tomorrow 9am", "friday 14:30", "in 2 hours", "in 30 minutes", "today 5pm", or a
|
|
51
|
+
* date alone (9:00 that day). Read in the person's time zone; null when it isn't one.
|
|
52
|
+
* @param {string} text @param {Date} [now] @returns {Date | null}
|
|
53
|
+
*/
|
|
54
|
+
export function parseWhen(text, now = new Date()) {
|
|
55
|
+
const t = String(text ?? "").trim().toLowerCase().replace(/\s+/g, " ");
|
|
56
|
+
const rel = /^in (\d{1,4}) ?(m|min|mins|minute|minutes|h|hr|hrs|hour|hours)$/.exec(t);
|
|
57
|
+
if (rel) return new Date(now.getTime() + Number(rel[1]) * (rel[2].startsWith("h") ? 3_600_000 : 60_000));
|
|
58
|
+
if (!Number.isNaN(Date.parse(t)) && /\d{4}-\d{2}-\d{2}t/.test(t)) return new Date(t.toUpperCase());
|
|
59
|
+
const time = /(?:^|\s)(?:at\s)?(\d{1,2})(?::(\d{2}))?\s?(am|pm)?$/.exec(t);
|
|
60
|
+
const dayPart = time ? t.slice(0, time.index).trim() : t;
|
|
61
|
+
if (time && !time[3] && !time[2] && !dayPart) return null; // a bare number isn't a time
|
|
62
|
+
const day = parseDate(dayPart || "today", now);
|
|
63
|
+
if (!day) return null;
|
|
64
|
+
let hour = time ? Number(time[1]) : 9;
|
|
65
|
+
const minute = time?.[2] ? Number(time[2]) : 0;
|
|
66
|
+
if (time?.[3] === "pm" && hour < 12) hour += 12;
|
|
67
|
+
if (time?.[3] === "am" && hour === 12) hour = 0;
|
|
68
|
+
if (hour > 23 || minute > 59) return null;
|
|
69
|
+
const [y, m, d] = day.split("-").map(Number);
|
|
70
|
+
return new Date(y, m - 1, d, hour, minute);
|
|
71
|
+
}
|
package/lib/error-fixes.mjs
CHANGED
|
@@ -38,6 +38,7 @@ export const FIXES = /** @type {Record<string, string>} */ ({
|
|
|
38
38
|
"NOT_A_TASK": "nb inbox open <n>",
|
|
39
39
|
"NOTHING_TO_APPROVE": "nb inbox open <n>",
|
|
40
40
|
"NEEDS_INPUT": "Answer with --answer key=value, or --yes for the recommended choice",
|
|
41
|
+
"DRY_RUN": "Run the same command without --dry-run to make the change",
|
|
41
42
|
"CANCELLED": "Run the command again when ready",
|
|
42
43
|
"OFFLINE": "nb doctor checks the connection; nb sync sends the queue",
|
|
43
44
|
"TIMEOUT": "Try again; nb doctor checks the connection",
|
|
@@ -53,6 +54,7 @@ export const FIXES = /** @type {Record<string, string>} */ ({
|
|
|
53
54
|
"CORRUPT_DOWNLOAD": "Run nb pull again",
|
|
54
55
|
"UPLOAD_FAILED": "Run nb push again; it picks up where it stopped",
|
|
55
56
|
"CONFIRMATION_INVALID": "Run the command without --confirm to get a new one",
|
|
57
|
+
"UPGRADE_FAILED": "Run npm i -g @networkbase/cli@latest yourself to see why",
|
|
56
58
|
"GIT_FAILED": "Run the git command yourself to see why",
|
|
57
59
|
"EDITOR_FAILED": "Set your editor: export EDITOR=nano",
|
|
58
60
|
"UNKNOWN_TOOL": "Restart the agent so it reads the current tool list",
|
package/lib/errors.mjs
CHANGED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// `nb help <topic>` (report C5): how a part of nb fits together, with examples that the tests run through the
|
|
2
|
+
// command table, so an example can never name a command or flag that doesn't exist.
|
|
3
|
+
|
|
4
|
+
export const TOPICS = /** @type {Record<string, { title: string, lines: string[], examples: string[] }>} */ ({
|
|
5
|
+
files: {
|
|
6
|
+
title: "Files: one folder, kept in step with the workspace",
|
|
7
|
+
lines: [
|
|
8
|
+
"nb init links this folder to a workspace. nb pull brings files down; nb push sends your changes up.",
|
|
9
|
+
"Every push of the same path is a new version; nothing is overwritten. nb file history shows them, nb file use goes back.",
|
|
10
|
+
"If a file changed on both sides, you get a conflict copy (name.remote-vN.ext) and nb resolve settles it.",
|
|
11
|
+
],
|
|
12
|
+
examples: ["nb pull", "nb push report.md -m \"First draft\"", "nb file history report.md", "nb file use report.md v1", "nb sync --only design"],
|
|
13
|
+
},
|
|
14
|
+
agents: {
|
|
15
|
+
title: "Agents: Claude Code, Codex, Cursor and others working with you",
|
|
16
|
+
lines: [
|
|
17
|
+
"nb agent setup connects an agent; you approve it once in the browser and choose what it may do alone.",
|
|
18
|
+
"Big changes (finishing tasks, final files, deleting) wait for your yes. Everything it changes can be undone.",
|
|
19
|
+
],
|
|
20
|
+
examples: ["nb agent setup claude", "nb agent access claude --small", "nb agent status", "nb undo --session"],
|
|
21
|
+
},
|
|
22
|
+
classes: {
|
|
23
|
+
title: "Classes: assignments, hand-ins and reviews",
|
|
24
|
+
lines: [
|
|
25
|
+
"Students: nb assignment list shows what's due; nb assignment hand-in sends your work with the class's late rules.",
|
|
26
|
+
"Teachers: nb review list shows what's waiting; approve or return several at once.",
|
|
27
|
+
],
|
|
28
|
+
examples: ["nb assignment list", "nb assignment hand-in 3 essay.pdf -m \"Final\"", "nb review list -w cse-3b", "nb review approve 3 5 8"],
|
|
29
|
+
},
|
|
30
|
+
"sign-in": {
|
|
31
|
+
title: "Signing in",
|
|
32
|
+
lines: [
|
|
33
|
+
"nb login opens your browser; over SSH it shows a code and a QR code instead.",
|
|
34
|
+
"Your sign-in lasts a year; nb warns a week before it ends, and nb login renews the same one.",
|
|
35
|
+
"In CI, use a personal token: echo $TOKEN | nb login --with-token, or set NETWORKBASE_TOKEN.",
|
|
36
|
+
],
|
|
37
|
+
examples: ["nb login", "nb login --device", "nb whoami", "nb token list"],
|
|
38
|
+
},
|
|
39
|
+
offline: {
|
|
40
|
+
title: "Working offline",
|
|
41
|
+
lines: [
|
|
42
|
+
"Without a connection, pushes wait in a queue and nb status reads from what was last pulled.",
|
|
43
|
+
"nb queue shows what's waiting; nb queue retry sends it when you're back.",
|
|
44
|
+
],
|
|
45
|
+
examples: ["nb queue", "nb queue retry", "nb queue drop 1", "nb diff"],
|
|
46
|
+
},
|
|
47
|
+
});
|
package/lib/network.mjs
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// A company proxy and its own certificates (report C6). Node's fetch only uses HTTPS_PROXY with NODE_USE_ENV_PROXY=1
|
|
2
|
+
// (Node 22.21+ and 24+), and NODE_EXTRA_CA_CERTS is read at start-up, so when either is needed nb starts itself again
|
|
3
|
+
// once with them set. Nothing changes for anyone who doesn't use a proxy or extra certificates.
|
|
4
|
+
|
|
5
|
+
/** Node versions whose fetch can use HTTPS_PROXY. @param {string} version like "22.22.0" */
|
|
6
|
+
export function proxyCapable(version) {
|
|
7
|
+
const [major = 0, minor = 0] = version.split(".").map(Number);
|
|
8
|
+
return major >= 23 || (major === 22 && minor >= 21);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What to add to the environment for this run, or null when nothing is needed.
|
|
13
|
+
* @param {Record<string, any>} config the user config (`proxy`, `ca-file`) @param {NodeJS.ProcessEnv} env @param {string} nodeVersion
|
|
14
|
+
* @returns {Record<string, string> | null}
|
|
15
|
+
*/
|
|
16
|
+
export function networkEnv(config, env, nodeVersion) {
|
|
17
|
+
if (env.NB_NETWORK_APPLIED) return null;
|
|
18
|
+
/** @type {Record<string, string>} */
|
|
19
|
+
const add = {};
|
|
20
|
+
if (config["ca-file"] && env.NODE_EXTRA_CA_CERTS !== config["ca-file"]) add.NODE_EXTRA_CA_CERTS = String(config["ca-file"]);
|
|
21
|
+
const proxy = config.proxy ?? env.HTTPS_PROXY ?? env.https_proxy ?? null;
|
|
22
|
+
if (proxy && proxyCapable(nodeVersion)) {
|
|
23
|
+
if (config.proxy && env.HTTPS_PROXY !== config.proxy) { add.HTTPS_PROXY = String(config.proxy); add.HTTP_PROXY = String(config.proxy); }
|
|
24
|
+
if (env.NODE_USE_ENV_PROXY !== "1") add.NODE_USE_ENV_PROXY = "1";
|
|
25
|
+
}
|
|
26
|
+
return Object.keys(add).length ? { ...add, NB_NETWORK_APPLIED: "1" } : null;
|
|
27
|
+
}
|
package/lib/print/notices.mjs
CHANGED
|
@@ -38,6 +38,9 @@ export async function afterCommand(ctx) {
|
|
|
38
38
|
const minor = (/** @type {string} */ v) => v.split(".").slice(0, 2).join(".");
|
|
39
39
|
if (seen.lastRun && minor(seen.lastRun) !== minor(ctx.version)) {
|
|
40
40
|
ctx.out.note(`${c.brand(ctx.out.sym.brand)} Updated to nb ${ctx.version}`);
|
|
41
|
+
// What's new in this minor version (F7), in three lines.
|
|
42
|
+
const { WHATS_NEW } = await import("../whats-new.mjs");
|
|
43
|
+
for (const line of WHATS_NEW[minor(ctx.version)] ?? []) ctx.out.note(c.muted(` · ${line}`));
|
|
41
44
|
ctx.out.note(c.muted(" What changed: https://www.npmjs.com/package/@networkbase/cli?activeTab=readme · nb help"));
|
|
42
45
|
}
|
|
43
46
|
if (Date.now() - (seen.checkedAt ?? 0) > DAY) {
|
package/lib/print/out.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { spawnSync } from "node:child_process";
|
|
|
6
6
|
import { colorLevel, palette, pad, safe, symbols, truncateEnd, truncateMiddle, asciiOnly, width, hyperlinks } from "./style.mjs";
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
|
-
* @typedef {{ json: boolean, quiet: boolean, plain: boolean, verbose: boolean, fields: string[] | null, pager: boolean }} OutputMode
|
|
9
|
+
* @typedef {{ json: boolean, quiet: boolean, plain: boolean, verbose: boolean, fields: string[] | null, pager: boolean, format?: "table" | "json" | "csv" | "md" | null }} OutputMode
|
|
10
10
|
* @typedef {ReturnType<typeof createOutput>} Output
|
|
11
11
|
*/
|
|
12
12
|
|
|
@@ -23,7 +23,11 @@ export function createOutput(mode, io = {}) {
|
|
|
23
23
|
const level = plain ? 0 : colorLevel(stderr, env);
|
|
24
24
|
const c = palette(level);
|
|
25
25
|
const sym = symbols(plain || asciiOnly(env));
|
|
26
|
-
|
|
26
|
+
// --format (C11): json is --json; csv and md print lists as a spreadsheet or a Markdown table, and nothing else.
|
|
27
|
+
const json = Boolean(mode.json) || mode.format === "json";
|
|
28
|
+
const format = mode.format === "csv" || mode.format === "md" ? mode.format : null;
|
|
29
|
+
/** Lines a table made in csv/md form, so result() prints only those. @type {Set<string>} */
|
|
30
|
+
const tableLines = new Set();
|
|
27
31
|
const quiet = Boolean(mode.quiet);
|
|
28
32
|
const columns = () => Math.max(40, stderr.columns || stdout.columns || 80);
|
|
29
33
|
/** @type {string[]} */
|
|
@@ -79,8 +83,9 @@ export function createOutput(mode, io = {}) {
|
|
|
79
83
|
stdout.write(`${JSON.stringify(envelope)}\n`);
|
|
80
84
|
return;
|
|
81
85
|
}
|
|
82
|
-
|
|
86
|
+
let lines = human(data);
|
|
83
87
|
if (lines === null || lines === undefined) return;
|
|
88
|
+
if (format) lines = (Array.isArray(lines) ? lines : [lines]).filter((l) => tableLines.has(l));
|
|
84
89
|
const text = Array.isArray(lines) ? lines.join("\n") : lines;
|
|
85
90
|
if (text === "") return;
|
|
86
91
|
const out = text.endsWith("\n") ? text : `${text}\n`;
|
|
@@ -114,6 +119,19 @@ export function createOutput(mode, io = {}) {
|
|
|
114
119
|
* @param {any[]} rows
|
|
115
120
|
*/
|
|
116
121
|
table(allCols, rows) {
|
|
122
|
+
if (format) {
|
|
123
|
+
// Plain text without colour or truncation: a cell is what the column's value says.
|
|
124
|
+
const plainCell = (/** @type {string} */ s) => stripForJson(String(s ?? ""));
|
|
125
|
+
const csv = (/** @type {string} */ s) => (/[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s);
|
|
126
|
+
const md = (/** @type {string} */ s) => s.replace(/\|/g, "\\|").replace(/\n/g, " ");
|
|
127
|
+
const head = allCols.map((col) => col.title || " ");
|
|
128
|
+
const body = rows.map((row) => allCols.map((col) => plainCell(col.value(row))));
|
|
129
|
+
const out = format === "csv"
|
|
130
|
+
? [head, ...body].map((r) => r.map(csv).join(","))
|
|
131
|
+
: [`| ${head.map(md).join(" | ")} |`, `|${head.map(() => " --- ").join("|")}|`, ...body.map((r) => `| ${r.map(md).join(" | ")} |`)];
|
|
132
|
+
for (const l of out) tableLines.add(l);
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
117
135
|
const natural = (/** @type {typeof allCols[number]} */ col) => Math.max(width(col.title), ...rows.map((r) => width(col.value(r))));
|
|
118
136
|
const fixedWidth = (/** @type {typeof allCols} */ cs) => cs.reduce((a, col) => a + (col.flex ? 10 : natural(col)), 0) + 2 * cs.length;
|
|
119
137
|
let cols = allCols;
|
package/lib/sync/transfer.mjs
CHANGED
|
@@ -94,7 +94,7 @@ const BATCH_FILES = 50;
|
|
|
94
94
|
/**
|
|
95
95
|
* Uploads through files/place in batches (≤ 50 files, ≤ 3 MiB inline); bigger files use signed upload slots.
|
|
96
96
|
* @param {Api} api
|
|
97
|
-
* @param {{ workspaceId: string, items: Array<{ path: string, abs: string, size: number, hash: string, baseVersion?: number | null }>, taskId?: string | null, as?: string | null, message?: string | null, keepBoth?: boolean, folder?: string | null, confirmSecrets?: boolean, keyBase?: string }} input
|
|
97
|
+
* @param {{ workspaceId: string, items: Array<{ path: string, abs: string, size: number, hash: string, baseVersion?: number | null }>, taskId?: string | null, as?: string | null, message?: string | null, keepBoth?: boolean, folder?: string | null, confirmSecrets?: boolean, keyBase?: string, onBytes?: (path: string, sent: number, total: number) => void }} input
|
|
98
98
|
* @param {(done: number, total: number) => void} [progress]
|
|
99
99
|
*/
|
|
100
100
|
export async function uploadFiles(api, input, progress) {
|
|
@@ -135,7 +135,7 @@ export async function uploadFiles(api, input, progress) {
|
|
|
135
135
|
progress?.(done, input.items.length);
|
|
136
136
|
}
|
|
137
137
|
if (large.length) {
|
|
138
|
-
results.push(...(await uploadLarge(api, input.workspaceId, large, input.message ?? null)));
|
|
138
|
+
results.push(...(await uploadLarge(api, input.workspaceId, large, input.message ?? null, input.onBytes)));
|
|
139
139
|
progress?.(input.items.length, input.items.length);
|
|
140
140
|
}
|
|
141
141
|
return { files: results, transition: lastTransition };
|
|
@@ -145,8 +145,9 @@ export async function uploadFiles(api, input, progress) {
|
|
|
145
145
|
* Files over 3 MiB: signed upload slots, PUT, then finalize (the 1.x bulk path). The base-version check happened
|
|
146
146
|
* just before through a fresh manifest; the bulk routes don't take one (noted in the phase notes).
|
|
147
147
|
* @param {Api} api @param {string} workspaceId @param {Array<{ path: string, abs: string, size: number, hash: string }>} items @param {string | null} message
|
|
148
|
+
* @param {(path: string, sent: number, total: number) => void} [onBytes] progress of each big file (C3)
|
|
148
149
|
*/
|
|
149
|
-
async function uploadLarge(api, workspaceId, items, message) {
|
|
150
|
+
async function uploadLarge(api, workspaceId, items, message, onBytes) {
|
|
150
151
|
/** @type {any[]} */
|
|
151
152
|
const out = [];
|
|
152
153
|
for (let i = 0; i < items.length; i += BATCH_FILES) {
|
|
@@ -158,7 +159,12 @@ async function uploadLarge(api, workspaceId, items, message) {
|
|
|
158
159
|
for (const slot of intent.files) {
|
|
159
160
|
const item = batch.find((f) => f.path === slot.path);
|
|
160
161
|
if (!item) continue;
|
|
161
|
-
|
|
162
|
+
// ponytail: a file stopped midway (Ctrl+C) goes up whole on the next push, not from where it stopped; files are
|
|
163
|
+
// at most 25 MB. Byte-level resume needs a resumable upload protocol on storage.
|
|
164
|
+
const stream = fs.createReadStream(item.abs);
|
|
165
|
+
let sent = 0;
|
|
166
|
+
stream.on("data", (chunk) => { sent += chunk.length; onBytes?.(item.path, sent, item.size); });
|
|
167
|
+
const put = await fetch(slot.uploadUrl, /** @type {RequestInit} */ ({ method: "PUT", headers: { "content-type": mimeFor(item.path), "content-length": String(item.size) }, body: /** @type {any} */ (stream), duplex: "half", signal: AbortSignal.timeout(10 * 60_000) }));
|
|
162
168
|
if (!put.ok) throw new CliError("UPLOAD_FAILED", `Uploading ${item.path} failed (HTTP ${put.status})`, { hint: "Run the command again" });
|
|
163
169
|
}
|
|
164
170
|
const finalized = /** @type {any} */ (await api.post("/api/v1/extension/bulk-finalize", {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// What a new minor version brings (F7 "what's new"), shown once after updating. Newest first.
|
|
2
|
+
export const WHATS_NEW = /** @type {Record<string, string[]>} */ ({
|
|
3
|
+
"2.1": [
|
|
4
|
+
"nb on its own shows where you are; nb next says what to work on",
|
|
5
|
+
"Labels, blocked by, reminders, starred tasks and files; trash, copy and lock files",
|
|
6
|
+
"--dry-run on every command; nb help files|agents|classes|sign-in|offline",
|
|
7
|
+
],
|
|
8
|
+
});
|