@networkbase/cli 1.0.3 → 2.0.0-next.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/README.md +60 -37
- package/bin/nb.mjs +69 -5350
- package/lib/api.mjs +163 -0
- package/lib/args.mjs +140 -0
- package/lib/commands/account.mjs +293 -0
- package/lib/commands/agent.mjs +169 -0
- package/lib/commands/ask.mjs +84 -0
- package/lib/commands/assignments.mjs +199 -0
- package/lib/commands/browse.mjs +140 -0
- package/lib/commands/docs.mjs +178 -0
- package/lib/commands/extras.mjs +114 -0
- package/lib/commands/files.mjs +425 -0
- package/lib/commands/inbox.mjs +98 -0
- package/lib/commands/link.mjs +85 -0
- package/lib/commands/mcp.mjs +149 -0
- package/lib/commands/misc.mjs +263 -0
- package/lib/commands/resolve.mjs +95 -0
- package/lib/commands/table.mjs +225 -0
- package/lib/commands/tasks.mjs +362 -0
- package/lib/commands/undo.mjs +52 -0
- package/lib/commands/watch.mjs +113 -0
- package/lib/commands/work.mjs +190 -0
- package/lib/config.mjs +203 -0
- package/lib/context.mjs +72 -0
- package/lib/errors.mjs +72 -0
- package/lib/keychain.mjs +59 -0
- package/lib/mcp/tools.mjs +336 -0
- package/lib/print/notices.mjs +48 -0
- package/lib/print/out.mjs +151 -0
- package/lib/print/remind.mjs +25 -0
- package/lib/print/style.mjs +110 -0
- package/lib/sync/diff.mjs +41 -0
- package/lib/sync/ignore.mjs +86 -0
- package/lib/sync/local.mjs +68 -0
- package/lib/sync/plan.mjs +94 -0
- package/lib/sync/queue.mjs +31 -0
- package/lib/sync/state.mjs +136 -0
- package/lib/sync/transfer.mjs +172 -0
- package/lib/tui/ask.mjs +124 -0
- package/lib/undo-log.mjs +34 -0
- package/package.json +13 -11
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// The only place the CLI writes to the terminal (report A4.5, A4.7, A4.8, A13.1). stdout carries results
|
|
2
|
+
// (text or one JSON envelope); stderr carries progress, hints, warnings and prompts.
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
import { colorLevel, palette, pad, safe, symbols, truncateEnd, truncateMiddle, asciiOnly, width, hyperlinks } from "./style.mjs";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @typedef {{ json: boolean, quiet: boolean, plain: boolean, verbose: boolean, fields: string[] | null, pager: boolean }} OutputMode
|
|
9
|
+
* @typedef {ReturnType<typeof createOutput>} Output
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {Partial<OutputMode>} mode
|
|
14
|
+
* @param {{ stdout?: NodeJS.WriteStream, stderr?: NodeJS.WriteStream, env?: NodeJS.ProcessEnv, onResult?: (r: { schema: string, data: any, text: string, warnings: string[] }) => void }} [io]
|
|
15
|
+
* onResult: the MCP server takes each result as data plus its plain-text summary instead of printing it.
|
|
16
|
+
*/
|
|
17
|
+
export function createOutput(mode, io = {}) {
|
|
18
|
+
const stdout = io.stdout ?? process.stdout;
|
|
19
|
+
const stderr = io.stderr ?? process.stderr;
|
|
20
|
+
const env = io.env ?? process.env;
|
|
21
|
+
const plain = Boolean(mode.plain) || env.NB_PLAIN === "1" || env.TERM === "dumb";
|
|
22
|
+
const level = plain ? 0 : colorLevel(stderr, env);
|
|
23
|
+
const c = palette(level);
|
|
24
|
+
const sym = symbols(plain || asciiOnly(env));
|
|
25
|
+
const json = Boolean(mode.json);
|
|
26
|
+
const quiet = Boolean(mode.quiet);
|
|
27
|
+
const columns = () => Math.max(40, stderr.columns || stdout.columns || 80);
|
|
28
|
+
/** @type {string[]} */
|
|
29
|
+
const warnings = [];
|
|
30
|
+
const links = !plain && level > 0 && hyperlinks(stdout, env);
|
|
31
|
+
|
|
32
|
+
/** @param {string} text */
|
|
33
|
+
const err = (text) => {
|
|
34
|
+
if (!quiet) stderr.write(text.endsWith("\n") ? text : `${text}\n`);
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
c,
|
|
39
|
+
sym,
|
|
40
|
+
json,
|
|
41
|
+
plain,
|
|
42
|
+
columns,
|
|
43
|
+
interactive: Boolean(process.stdin.isTTY && stderr.isTTY && !json && !env.CI),
|
|
44
|
+
stderr,
|
|
45
|
+
/** Progress or context on stderr. @param {string} text */
|
|
46
|
+
note: (text) => err(text),
|
|
47
|
+
/** @param {string} text */
|
|
48
|
+
done: (text) => err(`${c.success(sym.done)} ${text}`),
|
|
49
|
+
/** Warnings go to stderr, and into the JSON envelope's meta. @param {string} text */
|
|
50
|
+
warn(text) {
|
|
51
|
+
warnings.push(stripForJson(text));
|
|
52
|
+
if (!json) err(`${c.warning(sym.warn)} ${text}`);
|
|
53
|
+
},
|
|
54
|
+
/** Raw text to stdout (file contents, piped output). @param {string | Uint8Array} chunk */
|
|
55
|
+
raw: (chunk) => stdout.write(chunk),
|
|
56
|
+
/**
|
|
57
|
+
* Clickable text in terminals that support OSC 8 links (A5.9); only for the NetworkBase server's own pages, and
|
|
58
|
+
* the text alone everywhere else.
|
|
59
|
+
* @param {string} text @param {string} url @param {string} origin
|
|
60
|
+
*/
|
|
61
|
+
link: (text, url, origin) => (links && url.startsWith(`${origin}/`) && !/[\x00-\x1f\x7f]/.test(url) ? `\x1b]8;;${url}\x1b\\${text}\x1b]8;;\x1b\\` : text),
|
|
62
|
+
/**
|
|
63
|
+
* Print a command's result: one JSON envelope in --json, else the human lines on stdout.
|
|
64
|
+
* @template T
|
|
65
|
+
* @param {string} schema e.g. "nb.task.list/1"
|
|
66
|
+
* @param {T} data
|
|
67
|
+
* @param {(data: T) => string | string[] | null} human
|
|
68
|
+
* @param {{ page?: boolean }} [options] page: long views (help, task view, file view) go through $PAGER in a terminal
|
|
69
|
+
*/
|
|
70
|
+
result(schema, data, human, options = {}) {
|
|
71
|
+
if (io.onResult) {
|
|
72
|
+
const lines = human(data);
|
|
73
|
+
io.onResult({ schema, data, text: lines == null ? "" : Array.isArray(lines) ? lines.join("\n") : lines, warnings });
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (json) {
|
|
77
|
+
const envelope = { ok: true, schema, data: mode.fields?.length ? pickFields(data, mode.fields) : data, ...(warnings.length ? { meta: { warnings } } : {}) };
|
|
78
|
+
stdout.write(`${JSON.stringify(envelope)}\n`);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const lines = human(data);
|
|
82
|
+
if (lines === null || lines === undefined) return;
|
|
83
|
+
const text = Array.isArray(lines) ? lines.join("\n") : lines;
|
|
84
|
+
if (text === "") return;
|
|
85
|
+
const out = text.endsWith("\n") ? text : `${text}\n`;
|
|
86
|
+
if (options.page && mode.pager !== false && stdout.isTTY && process.stdin.isTTY && out.split("\n").length > (stdout.rows || 24)) {
|
|
87
|
+
// less -F quits when it fits, -R keeps colors, -X leaves the text on screen (A4.10).
|
|
88
|
+
const [cmd, ...args] = (env.NB_PAGER ?? env.PAGER ?? "less -FRX").split(" ").filter(Boolean);
|
|
89
|
+
if (cmd && cmd !== "cat" && spawnSync(cmd, args, { input: out, stdio: ["pipe", "inherit", "inherit"] }).status === 0) return;
|
|
90
|
+
}
|
|
91
|
+
stdout.write(out);
|
|
92
|
+
},
|
|
93
|
+
/** @param {import("../errors.mjs").CliError} error */
|
|
94
|
+
error(error) {
|
|
95
|
+
// Server errors link to their entry on /docs/cli (report A2.6).
|
|
96
|
+
const docs = error.status && /^[A-Z_]+$/.test(error.code) ? `https://networkbase.in/docs/cli#error-${error.code}` : null;
|
|
97
|
+
if (json) {
|
|
98
|
+
const body = { ok: false, error: { code: error.code, message: error.message, ...(error.hint ? { hint: error.hint } : {}), ...(error.details !== undefined ? { details: error.details } : {}), ...(docs ? { docs } : {}) } };
|
|
99
|
+
stdout.write(`${JSON.stringify(body)}\n`);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
stderr.write(`${c.danger(sym.error)} ${safe(error.message)}\n`);
|
|
103
|
+
if (error.hint) stderr.write(` ${c.muted(safe(error.hint))}\n`);
|
|
104
|
+
if (docs && env.NB_DOCS_LINKS !== "0") stderr.write(` ${c.muted(docs)}\n`);
|
|
105
|
+
// GitHub Actions shows this line as an error on the run's summary (A5.10).
|
|
106
|
+
if (env.GITHUB_ACTIONS === "true") stderr.write(`::error title=nb::${safe(error.message).replace(/%/g, "%25").replace(/\r?\n/g, "%0A")}\n`);
|
|
107
|
+
},
|
|
108
|
+
/**
|
|
109
|
+
* A table with a header, sized to content; one flexible column is cut to fit, and on a narrow terminal the
|
|
110
|
+
* optional columns go first, from the right (A5.5).
|
|
111
|
+
* @param {Array<{ title: string, value: (row: any) => string, flex?: boolean, path?: boolean, align?: "right", optional?: boolean }>} allCols
|
|
112
|
+
* @param {any[]} rows
|
|
113
|
+
*/
|
|
114
|
+
table(allCols, rows) {
|
|
115
|
+
const natural = (/** @type {typeof allCols[number]} */ col) => Math.max(width(col.title), ...rows.map((r) => width(col.value(r))));
|
|
116
|
+
const fixedWidth = (/** @type {typeof allCols} */ cs) => cs.reduce((a, col) => a + (col.flex ? 10 : natural(col)), 0) + 2 * cs.length;
|
|
117
|
+
let cols = allCols;
|
|
118
|
+
while (fixedWidth(cols) > columns() && cols.some((col) => col.optional)) {
|
|
119
|
+
const drop = cols.map((col) => Boolean(col.optional)).lastIndexOf(true);
|
|
120
|
+
cols = cols.filter((_, i) => i !== drop);
|
|
121
|
+
}
|
|
122
|
+
const cells = rows.map((row) => cols.map((col) => col.value(row)));
|
|
123
|
+
const widths = cols.map((col, i) => Math.max(width(col.title), ...cells.map((r) => width(r[i] ?? ""))));
|
|
124
|
+
const total = widths.reduce((a, b) => a + b, 0) + 2 * (cols.length - 1) + 2;
|
|
125
|
+
const flex = cols.findIndex((col) => col.flex);
|
|
126
|
+
if (flex >= 0 && total > columns()) widths[flex] = Math.max(10, (widths[flex] ?? 10) - (total - columns()));
|
|
127
|
+
const fit = (/** @type {string} */ s, /** @type {number} */ i) => {
|
|
128
|
+
const w = widths[i] ?? 0;
|
|
129
|
+
const cut = cols[i]?.path ? truncateMiddle(s, w, sym.ellipsis) : truncateEnd(s, w, sym.ellipsis);
|
|
130
|
+
return cols[i]?.align === "right" ? " ".repeat(Math.max(0, w - width(cut))) + cut : pad(cut, w);
|
|
131
|
+
};
|
|
132
|
+
const head = ` ${cols.map((col, i) => c.muted(fit(col.title, i))).join(" ")}`.trimEnd();
|
|
133
|
+
return [head, ...cells.map((r) => ` ${r.map((cell, i) => fit(cell, i)).join(" ")}`.trimEnd())];
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* `--fields id,title`: keeps those keys on each object in the result's lists (or on the result itself).
|
|
140
|
+
* @param {any} data @param {string[]} fields
|
|
141
|
+
*/
|
|
142
|
+
export function pickFields(data, fields) {
|
|
143
|
+
const pick = (/** @type {any} */ o) => (o && typeof o === "object" && !Array.isArray(o) ? Object.fromEntries(fields.filter((f) => f in o).map((f) => [f, o[f]])) : o);
|
|
144
|
+
if (Array.isArray(data)) return data.map(pick);
|
|
145
|
+
if (!data || typeof data !== "object") return data;
|
|
146
|
+
const lists = Object.entries(data).filter(([, v]) => Array.isArray(v) && v.some((x) => x && typeof x === "object"));
|
|
147
|
+
return lists.length ? { ...data, ...Object.fromEntries(lists.map(([k, v]) => [k, /** @type {any[]} */ (v).map(pick)])) } : pick(data);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** @param {string} s */
|
|
151
|
+
const stripForJson = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Notes shown at most once a day per key (old command names, update notices), on stderr only (report §26.7).
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
import { globalDir, readJson, writeAtomic } from "../config.mjs";
|
|
5
|
+
|
|
6
|
+
const DAY = 24 * 60 * 60 * 1000;
|
|
7
|
+
|
|
8
|
+
/** @param {import("../context.mjs").Context} ctx @param {string} key @param {string} text */
|
|
9
|
+
export function remindOnce(ctx, key, text) {
|
|
10
|
+
if (ctx.out.json || ctx.flags.quiet) return;
|
|
11
|
+
const file = path.join(globalDir(ctx.env), "reminders.json");
|
|
12
|
+
let seen = /** @type {Record<string, number>} */ ({});
|
|
13
|
+
try {
|
|
14
|
+
seen = readJson(file) ?? {};
|
|
15
|
+
} catch {
|
|
16
|
+
seen = {};
|
|
17
|
+
}
|
|
18
|
+
if (Date.now() - (seen[key] ?? 0) < DAY) return;
|
|
19
|
+
ctx.out.note(ctx.out.c.muted(text));
|
|
20
|
+
try {
|
|
21
|
+
writeAtomic(file, JSON.stringify({ ...seen, [key]: Date.now() }));
|
|
22
|
+
} catch {
|
|
23
|
+
// A read-only home folder only means the note shows again tomorrow.
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// Terminal design system (report §31, A5): semantic colors that follow the user's theme, symbols with an
|
|
2
|
+
// ASCII fallback, display width that counts wide characters, and safe() for every server-provided string.
|
|
3
|
+
|
|
4
|
+
/** @typedef {0 | 1 | 2 | 3} ColorLevel none, 16, 256, truecolor */
|
|
5
|
+
|
|
6
|
+
/** @param {NodeJS.WriteStream} stream @param {NodeJS.ProcessEnv} env @returns {ColorLevel} */
|
|
7
|
+
export function colorLevel(stream, env = process.env) {
|
|
8
|
+
if (env.NB_PLAIN === "1" || env.NO_COLOR) return 0; // no-color.org: set and not empty
|
|
9
|
+
if (env.FORCE_COLOR !== undefined) {
|
|
10
|
+
const forced = Number(env.FORCE_COLOR);
|
|
11
|
+
return /** @type {ColorLevel} */ (Number.isInteger(forced) ? Math.max(0, Math.min(3, forced)) : 1);
|
|
12
|
+
}
|
|
13
|
+
if (!stream.isTTY || env.TERM === "dumb") return 0;
|
|
14
|
+
if (/^(truecolor|24bit)$/i.test(env.COLORTERM ?? "")) return 3;
|
|
15
|
+
if (/256/.test(env.TERM ?? "")) return 2;
|
|
16
|
+
return 1;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Terminals known to show OSC 8 links; others would print the escape as text. NB_LINKS=0/1 overrides.
|
|
21
|
+
* @param {NodeJS.WriteStream} stream @param {NodeJS.ProcessEnv} env
|
|
22
|
+
*/
|
|
23
|
+
export function hyperlinks(stream, env = process.env) {
|
|
24
|
+
if (env.NB_LINKS) return env.NB_LINKS === "1";
|
|
25
|
+
if (!stream.isTTY || env.CI) return false;
|
|
26
|
+
return Boolean(env.WT_SESSION || /^(iTerm\.app|WezTerm|vscode|ghostty|Hyper|Tabby)$/.test(env.TERM_PROGRAM ?? "") || /kitty|alacritty|foot/.test(env.TERM ?? "") || Number(env.VTE_VERSION ?? 0) >= 5000);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Body text uses the terminal's own foreground; color marks meaning only (A5.2). @param {ColorLevel} level */
|
|
30
|
+
export function palette(level) {
|
|
31
|
+
const sgr = (/** @type {string} */ open, /** @type {string} */ close) => (/** @type {string} */ s) => (level ? `\x1b[${open}m${s}\x1b[${close}m` : s);
|
|
32
|
+
return {
|
|
33
|
+
bold: sgr("1", "22"),
|
|
34
|
+
dim: sgr("2", "22"),
|
|
35
|
+
muted: level >= 2 ? sgr("38;5;245", "39") : sgr("90", "39"),
|
|
36
|
+
brand: level === 3 ? sgr("38;2;192;86;56", "39") : level === 2 ? sgr("38;5;173", "39") : sgr("31", "39"),
|
|
37
|
+
accent: sgr("36", "39"),
|
|
38
|
+
success: sgr("32", "39"),
|
|
39
|
+
warning: sgr("33", "39"),
|
|
40
|
+
danger: sgr("31", "39"),
|
|
41
|
+
info: sgr("34", "39"),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param {NodeJS.ProcessEnv} env */
|
|
46
|
+
export function asciiOnly(env = process.env) {
|
|
47
|
+
if (env.NB_ASCII === "1") return true;
|
|
48
|
+
if (process.platform === "win32") return !env.WT_SESSION && !env.TERM_PROGRAM;
|
|
49
|
+
const lang = `${env.LC_ALL ?? ""}${env.LC_CTYPE ?? ""}${env.LANG ?? ""}`;
|
|
50
|
+
return lang !== "" && !/utf-?8/i.test(lang);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** @param {boolean} ascii */
|
|
54
|
+
export function symbols(ascii) {
|
|
55
|
+
return ascii
|
|
56
|
+
? { active: "*", done: "+", warn: "!", error: "x", brand: "@", other: "o", rail: "|", end: "`", cursor: ">", check: "v", arrow: "->", ellipsis: "..." }
|
|
57
|
+
: { active: "◆", done: "◇", warn: "▲", error: "■", brand: "●", other: "○", rail: "│", end: "└", cursor: "❯", check: "✓", arrow: "→", ellipsis: "…" };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Strips C0/C1 control characters (keeps newline and tab) so text from other people can't move the cursor,
|
|
61
|
+
// write the clipboard (OSC 52) or hide content (report A3.11, finding 32).
|
|
62
|
+
|
|
63
|
+
const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
|
|
64
|
+
/** @param {unknown} value */
|
|
65
|
+
export const safe = (value) => String(value ?? "").replace(CONTROL, "");
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
const ANSI = /\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
|
|
69
|
+
/** @param {string} s */
|
|
70
|
+
export const stripAnsi = (s) => s.replace(ANSI, "");
|
|
71
|
+
|
|
72
|
+
const segmenter = typeof Intl.Segmenter === "function" ? new Intl.Segmenter() : null;
|
|
73
|
+
/** East Asian Wide/Fullwidth and emoji take two cells. @param {number} cp */
|
|
74
|
+
const isWide = (cp) =>
|
|
75
|
+
(cp >= 0x1100 && cp <= 0x115f) || (cp >= 0x2e80 && cp <= 0xa4cf) || (cp >= 0xac00 && cp <= 0xd7a3) ||
|
|
76
|
+
(cp >= 0xf900 && cp <= 0xfaff) || (cp >= 0xfe30 && cp <= 0xfe4f) || (cp >= 0xff00 && cp <= 0xff60) ||
|
|
77
|
+
(cp >= 0xffe0 && cp <= 0xffe6) || (cp >= 0x1f300 && cp <= 0x1faff) || (cp >= 0x20000 && cp <= 0x3fffd);
|
|
78
|
+
|
|
79
|
+
/** Cells the text takes in a terminal (report A5.4, finding 100). @param {string} s */
|
|
80
|
+
export function width(s) {
|
|
81
|
+
const plain = stripAnsi(s);
|
|
82
|
+
let total = 0;
|
|
83
|
+
const parts = segmenter ? Array.from(segmenter.segment(plain), (x) => x.segment) : Array.from(plain);
|
|
84
|
+
for (const g of parts) total += isWide(g.codePointAt(0) ?? 0) ? 2 : 1;
|
|
85
|
+
return total;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Cut to `max` cells with an ellipsis at the end (titles). @param {string} s @param {number} max @param {string} [ell] */
|
|
89
|
+
export function truncateEnd(s, max, ell = "…") {
|
|
90
|
+
if (width(s) <= max) return s;
|
|
91
|
+
let out = "";
|
|
92
|
+
for (const ch of Array.from(stripAnsi(s))) {
|
|
93
|
+
if (width(out + ch) > max - width(ell)) break;
|
|
94
|
+
out += ch;
|
|
95
|
+
}
|
|
96
|
+
return out + ell;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Cut in the middle (paths keep their start and file name). @param {string} s @param {number} max @param {string} [ell] */
|
|
100
|
+
export function truncateMiddle(s, max, ell = "…") {
|
|
101
|
+
const plain = stripAnsi(s);
|
|
102
|
+
if (width(plain) <= max) return plain;
|
|
103
|
+
const chars = Array.from(plain);
|
|
104
|
+
const keep = max - width(ell);
|
|
105
|
+
const head = Math.ceil(keep / 3);
|
|
106
|
+
return chars.slice(0, head).join("") + ell + chars.slice(chars.length - (keep - head)).join("");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Pad to `n` cells. @param {string} s @param {number} n */
|
|
110
|
+
export const pad = (s, n) => s + " ".repeat(Math.max(0, n - width(s)));
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Unified diff of two texts (report A1.12, A5.5). Line LCS; files over 4,000 lines get a summary instead.
|
|
2
|
+
|
|
3
|
+
const MAX_LINES = 4000;
|
|
4
|
+
const CONTEXT = 3;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @param {string} a old text @param {string} b new text
|
|
8
|
+
* @returns {{ lines: Array<{ kind: " " | "-" | "+" | "@", text: string }>, added: number, removed: number } | null} null when too big
|
|
9
|
+
*/
|
|
10
|
+
export function unifiedDiff(a, b) {
|
|
11
|
+
const x = a.split("\n");
|
|
12
|
+
const y = b.split("\n");
|
|
13
|
+
if (x.length > MAX_LINES || y.length > MAX_LINES) return null;
|
|
14
|
+
const n = x.length;
|
|
15
|
+
const m = y.length;
|
|
16
|
+
const lcs = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
|
|
17
|
+
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) lcs[i][j] = x[i] === y[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
|
|
18
|
+
/** @type {Array<{ kind: " " | "-" | "+", text: string, oi: number, ni: number }>} */
|
|
19
|
+
const ops = [];
|
|
20
|
+
let i = 0;
|
|
21
|
+
let j = 0;
|
|
22
|
+
while (i < n || j < m) {
|
|
23
|
+
if (i < n && j < m && x[i] === y[j]) { ops.push({ kind: " ", text: x[i] ?? "", oi: i, ni: j }); i++; j++; }
|
|
24
|
+
else if (j < m && (i >= n || lcs[i][j + 1] >= lcs[i + 1][j])) { ops.push({ kind: "+", text: y[j] ?? "", oi: i, ni: j }); j++; }
|
|
25
|
+
else { ops.push({ kind: "-", text: x[i] ?? "", oi: i, ni: j }); i++; }
|
|
26
|
+
}
|
|
27
|
+
const changed = ops.map((op, k) => (op.kind !== " " ? k : -1)).filter((k) => k >= 0);
|
|
28
|
+
/** @type {Array<{ kind: " " | "-" | "+" | "@", text: string }>} */
|
|
29
|
+
const lines = [];
|
|
30
|
+
let k = 0;
|
|
31
|
+
while (k < changed.length) {
|
|
32
|
+
const start = Math.max(0, (changed[k] ?? 0) - CONTEXT);
|
|
33
|
+
let end = Math.min(ops.length, (changed[k] ?? 0) + CONTEXT + 1);
|
|
34
|
+
while (k + 1 < changed.length && (changed[k + 1] ?? 0) - CONTEXT <= end) { k++; end = Math.min(ops.length, (changed[k] ?? 0) + CONTEXT + 1); }
|
|
35
|
+
const first = ops[start];
|
|
36
|
+
lines.push({ kind: "@", text: `@@ -${(first?.oi ?? 0) + 1} +${(first?.ni ?? 0) + 1} @@` });
|
|
37
|
+
for (const op of ops.slice(start, end)) lines.push({ kind: op.kind, text: op.text });
|
|
38
|
+
k++;
|
|
39
|
+
}
|
|
40
|
+
return { lines, added: ops.filter((o) => o.kind === "+").length, removed: ops.filter((o) => o.kind === "-").length };
|
|
41
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// What never syncs (report A1.3): built-ins, then .gitignore files (root and nested, with negation), then
|
|
2
|
+
// .nbignore (same syntax, wins). Fixes finding 21's whole-folder uploads and the "add it to .gitignore"
|
|
3
|
+
// hint the 1.x CLI gave but never honoured.
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
/** Always skipped: VCS, our metadata, dependencies, OS junk, editor swap files. */
|
|
8
|
+
const BUILT_IN = [".git/", ".networkbase/", ".tasks/", "node_modules/", ".DS_Store", "Thumbs.db", "desktop.ini", "*.swp", "*.swo", "*~", ".#*", "4913", "*.nbtmp-*"];
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* gitignore glob → RegExp over a path relative to the ignore file's folder.
|
|
12
|
+
* @param {string} pattern
|
|
13
|
+
*/
|
|
14
|
+
function compile(pattern) {
|
|
15
|
+
let p = pattern;
|
|
16
|
+
const negated = p.startsWith("!");
|
|
17
|
+
if (negated) p = p.slice(1);
|
|
18
|
+
const dirOnly = p.endsWith("/");
|
|
19
|
+
if (dirOnly) p = p.slice(0, -1);
|
|
20
|
+
const anchored = p.includes("/") && !p.startsWith("**/") ? true : false;
|
|
21
|
+
if (p.startsWith("/")) p = p.slice(1);
|
|
22
|
+
let re = "";
|
|
23
|
+
for (let i = 0; i < p.length; i++) {
|
|
24
|
+
const ch = p[i] ?? "";
|
|
25
|
+
if (ch === "*") {
|
|
26
|
+
if (p[i + 1] === "*") {
|
|
27
|
+
const slashAfter = p[i + 2] === "/";
|
|
28
|
+
re += slashAfter ? "(?:.*/)?" : ".*";
|
|
29
|
+
i += slashAfter ? 2 : 1;
|
|
30
|
+
} else re += "[^/]*";
|
|
31
|
+
} else if (ch === "?") re += "[^/]";
|
|
32
|
+
else if (ch === "[") {
|
|
33
|
+
const end = p.indexOf("]", i);
|
|
34
|
+
if (end > i) { re += p.slice(i, end + 1); i = end; } else re += "\\[";
|
|
35
|
+
} else re += ch.replace(/[.+^${}()|\\]/g, "\\$&");
|
|
36
|
+
}
|
|
37
|
+
const regex = new RegExp(`${anchored ? "^" : "(?:^|/)"}${re}(?:/.*)?$`);
|
|
38
|
+
return { regex, negated, dirOnly };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param {string} text */
|
|
42
|
+
const parse = (text) =>
|
|
43
|
+
text
|
|
44
|
+
.split(/\r?\n/)
|
|
45
|
+
.map((line) => line.replace(/(?<!\\)\s+$/, ""))
|
|
46
|
+
.filter((line) => line && !line.startsWith("#"))
|
|
47
|
+
.map(compile);
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {string} root linked folder
|
|
51
|
+
* @returns {(relPosix: string, isDir: boolean) => boolean} true = skip
|
|
52
|
+
*/
|
|
53
|
+
export function createIgnore(root) {
|
|
54
|
+
/** @type {Map<string, ReturnType<typeof compile>[]>} folder (posix, "" = root) → rules */
|
|
55
|
+
const byDir = new Map();
|
|
56
|
+
const builtIn = BUILT_IN.map(compile);
|
|
57
|
+
|
|
58
|
+
/** @param {string} dirRel */
|
|
59
|
+
const rulesFor = (dirRel) => {
|
|
60
|
+
if (byDir.has(dirRel)) return /** @type {ReturnType<typeof compile>[]} */ (byDir.get(dirRel));
|
|
61
|
+
const abs = path.join(root, ...dirRel.split("/").filter(Boolean));
|
|
62
|
+
const read = (/** @type {string} */ name) => {
|
|
63
|
+
try { return parse(fs.readFileSync(path.join(abs, name), "utf8")); } catch { return []; }
|
|
64
|
+
};
|
|
65
|
+
const rules = [...read(".gitignore"), ...read(".nbignore")];
|
|
66
|
+
byDir.set(dirRel, rules);
|
|
67
|
+
return rules;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
return (rel, isDir) => {
|
|
71
|
+
// A folder rule also covers paths inside it ("node_modules/x.js"), not only the folder itself.
|
|
72
|
+
for (const r of builtIn) if (r.regex.test(rel) && (!r.dirOnly || isDir || rel.includes("/"))) return true;
|
|
73
|
+
let ignored = false;
|
|
74
|
+
const parts = rel.split("/");
|
|
75
|
+
// Rules from each ancestor folder apply to the path relative to that folder; later (deeper) rules win.
|
|
76
|
+
for (let depth = 0; depth < parts.length; depth++) {
|
|
77
|
+
const dir = parts.slice(0, depth).join("/");
|
|
78
|
+
const sub = parts.slice(depth).join("/");
|
|
79
|
+
for (const r of rulesFor(dir)) {
|
|
80
|
+
if (r.dirOnly && !isDir && !sub.includes("/")) continue;
|
|
81
|
+
if (r.regex.test(sub)) ignored = !r.negated;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return ignored;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// What's in the linked folder (report A1.2, A1.3, A1.16). Files are hashed only when size or mtime changed
|
|
2
|
+
// since the last sync, like git's index; symlinks and ignored paths are reported, not uploaded.
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
import { createIgnore } from "./ignore.mjs";
|
|
7
|
+
import { hashFile } from "./state.mjs";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @typedef {{ remote: string, abs: string, size: number, mtimeMs: number, hash: string }} LocalFile
|
|
11
|
+
* @typedef {{ path: string, reason: string }} Skipped
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Workspace path for a folder-relative path: NFC, forward slashes, under the linked remote folder. @param {string} remoteRoot @param {string} rel */
|
|
15
|
+
export function toRemote(remoteRoot, rel) {
|
|
16
|
+
const clean = rel.split(path.sep).join("/").normalize("NFC").replace(/^\/+/, "");
|
|
17
|
+
return remoteRoot === "/" ? `/${clean}` : `${remoteRoot.replace(/\/+$/, "")}/${clean}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Folder-relative path for a workspace path, or null when it's outside the linked remote folder. @param {string} remoteRoot @param {string} remote */
|
|
21
|
+
export function toRelative(remoteRoot, remote) {
|
|
22
|
+
const prefix = remoteRoot === "/" ? "/" : `${remoteRoot.replace(/\/+$/, "")}/`;
|
|
23
|
+
return remote.startsWith(prefix) ? remote.slice(prefix.length) : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {{ root: string, remoteRoot: string, base: Record<string, import("./state.mjs").BaseEntry>, maxFileBytes?: number, only?: string[] }} input
|
|
28
|
+
* `only`: folder-relative paths (files or folders) to limit the scan to
|
|
29
|
+
* @returns {Promise<{ files: Map<string, LocalFile>, skipped: Skipped[] }>}
|
|
30
|
+
*/
|
|
31
|
+
export async function scanLocal({ root, remoteRoot, base, maxFileBytes, only }) {
|
|
32
|
+
const ignored = createIgnore(root);
|
|
33
|
+
/** @type {Map<string, LocalFile>} */
|
|
34
|
+
const files = new Map();
|
|
35
|
+
/** @type {Skipped[]} */
|
|
36
|
+
const skipped = [];
|
|
37
|
+
|
|
38
|
+
/** @param {string} rel */
|
|
39
|
+
async function visit(rel) {
|
|
40
|
+
const abs = path.join(root, rel);
|
|
41
|
+
let st;
|
|
42
|
+
try {
|
|
43
|
+
st = fs.lstatSync(abs);
|
|
44
|
+
} catch {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const relPosix = rel.split(path.sep).join("/");
|
|
48
|
+
if (st.isSymbolicLink()) { skipped.push({ path: relPosix, reason: "symlink (not followed)" }); return; }
|
|
49
|
+
if (relPosix && ignored(relPosix, st.isDirectory())) return;
|
|
50
|
+
if (st.isDirectory()) {
|
|
51
|
+
for (const name of fs.readdirSync(abs).sort()) await visit(rel ? path.join(rel, name) : name);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
if (!st.isFile()) return;
|
|
55
|
+
if (maxFileBytes && st.size > maxFileBytes) {
|
|
56
|
+
skipped.push({ path: relPosix, reason: `over the ${Math.round(maxFileBytes / 1024 / 1024)} MB file limit` });
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const remote = toRemote(remoteRoot, rel);
|
|
60
|
+
const known = base[remote];
|
|
61
|
+
const hash = known && known.size === st.size && known.mtimeMs === st.mtimeMs ? known.baseHash : /** @type {string} */ (await hashFile(abs));
|
|
62
|
+
files.set(remote, { remote, abs, size: st.size, mtimeMs: st.mtimeMs, hash });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (only?.length) for (const rel of only) await visit(path.normalize(rel));
|
|
66
|
+
else await visit("");
|
|
67
|
+
return { files, skipped };
|
|
68
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Three-way decisions (report A1.5, A1.6): for each path, compare your file, the server's file and what was
|
|
2
|
+
// last synced (the base). Pure — no I/O — so every row of the table is tested directly.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @typedef {{ nodeId: string, version: number, hash: string | null, size: number, updatedAt?: string | null }} RemoteFile
|
|
6
|
+
* @typedef {"unchanged" | "modified" | "added" | "deleted" | "remote-modified" | "remote-added" | "remote-deleted" | "conflict" | "same-change" | "moved"} FileState
|
|
7
|
+
* @typedef {"none" | "push" | "pull" | "adopt" | "remove-local" | "restore" | "conflict" | "keep-local" | "delete-remote" | "move"} FileAction
|
|
8
|
+
* @typedef {{ path: string, state: FileState, action: FileAction, local?: import("./local.mjs").LocalFile, remote?: RemoteFile, base?: import("./state.mjs").BaseEntry, note?: string, from?: string }} PlanItem
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {{ base: Record<string, import("./state.mjs").BaseEntry>, local: Map<string, import("./local.mjs").LocalFile>, remote: Map<string, RemoteFile> }} input
|
|
13
|
+
* @returns {PlanItem[]}
|
|
14
|
+
*/
|
|
15
|
+
export function planSync({ base, local, remote }) {
|
|
16
|
+
const paths = new Set([...Object.keys(base), ...local.keys(), ...remote.keys()]);
|
|
17
|
+
/** @type {PlanItem[]} */
|
|
18
|
+
const items = [];
|
|
19
|
+
for (const p of [...paths].sort()) {
|
|
20
|
+
const b = base[p];
|
|
21
|
+
const l = local.get(p);
|
|
22
|
+
const r = remote.get(p);
|
|
23
|
+
const localChanged = Boolean(l && b && l.hash !== b.baseHash);
|
|
24
|
+
const remoteChanged = Boolean(r && b && (r.version !== b.baseVersion && r.hash !== b.baseHash));
|
|
25
|
+
/** @param {FileState} state @param {FileAction} action @param {string} [note] */
|
|
26
|
+
const add = (state, action, note) => items.push({ path: p, state, action, ...(l ? { local: l } : {}), ...(r ? { remote: r } : {}), ...(b ? { base: b } : {}), ...(note ? { note } : {}) });
|
|
27
|
+
|
|
28
|
+
if (b) {
|
|
29
|
+
if (l && r) {
|
|
30
|
+
if (!localChanged && !remoteChanged) add("unchanged", r.version !== b.baseVersion ? "adopt" : "none");
|
|
31
|
+
else if (localChanged && !remoteChanged) add("modified", "push");
|
|
32
|
+
else if (!localChanged && remoteChanged) add("remote-modified", "pull");
|
|
33
|
+
else if (l.hash === r.hash) add("same-change", "adopt");
|
|
34
|
+
else add("conflict", "conflict", "changed here and on the server");
|
|
35
|
+
} else if (!l && r) {
|
|
36
|
+
if (remoteChanged) add("remote-modified", "restore", "deleted here but changed on the server: restoring the server's version");
|
|
37
|
+
else add("deleted", "delete-remote");
|
|
38
|
+
} else if (l && !r) {
|
|
39
|
+
if (localChanged) add("added", "keep-local", "deleted on the server after you changed it: kept here as a new file");
|
|
40
|
+
else add("remote-deleted", "remove-local");
|
|
41
|
+
} else {
|
|
42
|
+
add("unchanged", "none", "gone everywhere");
|
|
43
|
+
}
|
|
44
|
+
} else if (l && r) {
|
|
45
|
+
if (l.hash === r.hash) add("unchanged", "adopt");
|
|
46
|
+
else add("conflict", "conflict", "a file with this name exists on the server with different content");
|
|
47
|
+
} else if (l) add("added", "push");
|
|
48
|
+
else if (r) add("remote-added", "pull");
|
|
49
|
+
}
|
|
50
|
+
return detectMoves(items);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* A file deleted here and a new file with the same content is a move or rename (A1.17): one "move" item keeps the
|
|
55
|
+
* file's history on the server instead of a delete and a new upload. Only unambiguous pairs (one each per hash).
|
|
56
|
+
* @param {PlanItem[]} items
|
|
57
|
+
*/
|
|
58
|
+
export function detectMoves(items) {
|
|
59
|
+
/** @param {PlanItem[]} list */
|
|
60
|
+
const byHash = (list, hashOf = (/** @type {PlanItem} */ i) => i.local?.hash) => {
|
|
61
|
+
/** @type {Map<string, PlanItem[]>} */
|
|
62
|
+
const m = new Map();
|
|
63
|
+
for (const i of list) { const h = hashOf(i); if (h) m.set(h, [...(m.get(h) ?? []), i]); }
|
|
64
|
+
return m;
|
|
65
|
+
};
|
|
66
|
+
const gone = byHash(items.filter((i) => i.action === "delete-remote"), (i) => i.base?.baseHash);
|
|
67
|
+
const added = byHash(items.filter((i) => i.action === "push" && !i.base && !i.remote));
|
|
68
|
+
/** @type {Set<PlanItem>} */
|
|
69
|
+
const drop = new Set();
|
|
70
|
+
for (const [hash, [to, ...moreTo]] of added) {
|
|
71
|
+
const from = gone.get(hash);
|
|
72
|
+
if (!to || moreTo.length || from?.length !== 1) continue;
|
|
73
|
+
const old = /** @type {PlanItem} */ (from[0]);
|
|
74
|
+
drop.add(old);
|
|
75
|
+
Object.assign(to, { state: "moved", action: "move", from: old.path, base: old.base, remote: old.remote });
|
|
76
|
+
}
|
|
77
|
+
return drop.size ? items.filter((i) => !drop.has(i)) : items;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The status words `nb status` prints (A1.5). @param {PlanItem} item */
|
|
81
|
+
export function stateLabel(item) {
|
|
82
|
+
switch (item.state) {
|
|
83
|
+
case "modified": return "modified";
|
|
84
|
+
case "added": return "added";
|
|
85
|
+
case "deleted": return "deleted";
|
|
86
|
+
case "remote-modified": return item.action === "restore" ? "restore" : "remote changed";
|
|
87
|
+
case "remote-added": return "remote new";
|
|
88
|
+
case "remote-deleted": return "remote deleted";
|
|
89
|
+
case "conflict": return "conflict";
|
|
90
|
+
case "same-change": return "same change";
|
|
91
|
+
case "moved": return `moved from ${item.from}`;
|
|
92
|
+
default: return "unchanged";
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Pushes made while offline (report A12.4): saved in .networkbase/queue.json and sent in order by the next
|
|
2
|
+
// `nb sync`. Each entry keeps its id, which seeds the idempotency keys, and the base versions stay in state.json,
|
|
3
|
+
// so a change someone made meanwhile comes back as a conflict, never an overwrite.
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
import { DIR_NAME, readJson, writeAtomic } from "../config.mjs";
|
|
7
|
+
|
|
8
|
+
export const QUEUE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
9
|
+
|
|
10
|
+
/** @typedef {{ id: string, op: "push", paths: string[], flags: Record<string, any>, queuedAt: string }} QueueEntry */
|
|
11
|
+
|
|
12
|
+
/** @param {string} root */
|
|
13
|
+
const file = (root) => path.join(root, DIR_NAME, "queue.json");
|
|
14
|
+
|
|
15
|
+
/** @param {string} root @returns {QueueEntry[]} */
|
|
16
|
+
export function readQueue(root) {
|
|
17
|
+
const data = readJson(file(root));
|
|
18
|
+
return Array.isArray(data?.entries) ? data.entries : [];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @param {string} root @param {QueueEntry[]} entries */
|
|
22
|
+
export function writeQueue(root, entries) {
|
|
23
|
+
writeAtomic(file(root), `${JSON.stringify({ version: 1, entries })}\n`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {string} root @param {QueueEntry} entry */
|
|
27
|
+
export function enqueue(root, entry) {
|
|
28
|
+
const entries = readQueue(root).filter((e) => e.id !== entry.id);
|
|
29
|
+
writeQueue(root, [...entries, entry]);
|
|
30
|
+
return entries.length + 1;
|
|
31
|
+
}
|