pi-better-show 0.3.0 → 0.4.0
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 +39 -5
- package/bin/pbs-tree.js +424 -0
- package/package.json +5 -1
- package/src/core/parse.ts +2 -0
- package/src/core/text.ts +24 -0
- package/src/core/tree.ts +84 -0
- package/src/core/types.ts +34 -1
- package/src/core/validate.ts +10 -0
- package/src/elements/index.ts +4 -0
- package/src/elements/strings.ts +13 -0
- package/src/elements/tree.ts +261 -0
- package/src/extension/client/bridge.ts +29 -0
- package/src/extension/client/feedback.ts +38 -16
- package/src/extension/client/frame.ts +27 -1
- package/src/extension/client/host-config.ts +20 -0
- package/src/extension/client/host-page.ts +73 -0
- package/src/extension/client/host.ts +12 -24
- package/src/extension/client/page.ts +3 -12
- package/src/extension/controller.ts +34 -16
- package/src/extension/index.ts +1 -2
- package/src/extension/server.ts +20 -2
- package/src/extension/tool.ts +7 -3
- package/src/react/index.ts +3 -0
package/README.md
CHANGED
|
@@ -33,6 +33,39 @@ A block is a fenced code block whose first word is the kind, or a GitHub alert.
|
|
|
33
33
|
| `table` | YAML `{columns, rows, sort, filter}` | |
|
|
34
34
|
| `steps` | YAML `{items: [{title, status: done\|doing\|todo\|blocked, when, body}]}` | |
|
|
35
35
|
| `stats` | YAML list of `{label, value, delta, tone, note}` | |
|
|
36
|
+
| `tree` | indented lines (two spaces per level, first line the root): `name/` for a folder, then `{tags}` and ` # note` | |
|
|
37
|
+
|
|
38
|
+
**The `tree` block** shows a directory tree for structure reviews:
|
|
39
|
+
|
|
40
|
+
```tree
|
|
41
|
+
pi-better-show/
|
|
42
|
+
src/ # one package, four entries
|
|
43
|
+
core/ {focus} # parser and text, no DOM
|
|
44
|
+
parse.ts
|
|
45
|
+
validate.ts {new} # checks answers
|
|
46
|
+
elements/ # web components
|
|
47
|
+
tests/
|
|
48
|
+
README.md {changed}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
A folder's name ends with `/`; tags are `new`, `changed`, `removed`, `focus`, `risk` (an unknown tag makes the block invalid); the note after ` # ` takes inline Markdown; a `… N more` line stands for entries a limit cut. A tree has at most 2,000 nodes and 32 levels (the root is level 1). The block carries a snapshot, so every host draws it; `toText` writes it in `tree` style (`├──`, `└──`, tags as `[new]`, notes after ` — `), in a fence on Discord.
|
|
52
|
+
|
|
53
|
+
**`pbs-tree`** prints the fence for a folder: `npx pbs-tree [dir]` or `bunx pbs-tree [dir]` (plain JavaScript on node built-ins; runs under node and bun). Output is sorted by name in byte order, so a snapshot is reproducible; symlinks are not followed. Flags follow Linux `tree` where they exist:
|
|
54
|
+
|
|
55
|
+
| Flag | Meaning |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `-L n` | depth |
|
|
58
|
+
| `-d` | folders only |
|
|
59
|
+
| `-a` | include dot files (default skips them; `.git` is always skipped) |
|
|
60
|
+
| `-I pattern` | leave out names matching the glob (`*` `?` `[..]`); `\|` separates several; repeatable |
|
|
61
|
+
| `-P pattern` | list only files matching; a folder is kept when it holds a match (even below the `-L` cut); ignored with `-d` |
|
|
62
|
+
| `--gitignore` | honour `.gitignore` files, those of the folder and of the folders above it up to the repository's top |
|
|
63
|
+
| `--dirsfirst` | folders before files |
|
|
64
|
+
| `--filelimit n` | do not open a folder holding more than n entries; writes `… N more` in its place |
|
|
65
|
+
| `--prune` | drop folders that hold nothing (what `-L` hides still counts); ignored with `-d` |
|
|
66
|
+
| `--changed-since <rev>` | tag `new`, `changed`, `removed` from `git diff --name-status <rev>` against the working tree; removed files are listed though absent, untracked files are `new`, a rename is a removed and a new file |
|
|
67
|
+
|
|
68
|
+
A tree over the block's limits is refused (exit 1) with the node count; narrow it with `-L`, `-I`, `--gitignore`. Names that would read as a note or tags get a no-break space, and a newline in a name becomes `?`. Exit codes: 0, 1 for a failure (not a folder, git failed, too large), 2 for a bad flag.
|
|
36
69
|
|
|
37
70
|
A block whose body is not valid YAML, or does not fit its schema, becomes an `invalid` segment that keeps its source and the reason; nothing throws.
|
|
38
71
|
|
|
@@ -60,7 +93,7 @@ interface TextProfile {
|
|
|
60
93
|
|
|
61
94
|
The interactive kinds end with a reply instruction (`options`, `form`, `review`, `suggest`, and `checklist`): "Reply with a number.", "Reply in text, one line per question, like `1: b`.", and so on. `lang: "zh-TW"` writes them in Traditional Chinese; pass the conversation's language when you know it. Block content is never translated.
|
|
62
95
|
|
|
63
|
-
Every `BlockSegment` and `InvalidSegment` carries `raw`: the block's exact original text, fences (or an alert's whole `>` quote) included, byte for byte. Kinds listed in `keep` are emitted as `raw` verbatim, valid or invalid, for a surface that draws them itself; other kinds convert as usual. `DISPLAY_KINDS` (`alert`, `cards`, `mermaid`, `mindmap`, `diff`, `table`, `steps`, `stats`) is the usual `keep` list for such a surface; `INTERACTIVE_KINDS` (`options`, `suggest`, `form`, `checklist`, `review`) are the kinds a reader answers, the ones a surface that cannot draw them gets as reply instructions. Without `keep`, output is unchanged.
|
|
96
|
+
Every `BlockSegment` and `InvalidSegment` carries `raw`: the block's exact original text, fences (or an alert's whole `>` quote) included, byte for byte. Kinds listed in `keep` are emitted as `raw` verbatim, valid or invalid, for a surface that draws them itself; other kinds convert as usual. `DISPLAY_KINDS` (`alert`, `cards`, `mermaid`, `mindmap`, `diff`, `table`, `steps`, `stats`, `tree`) is the usual `keep` list for such a surface; `INTERACTIVE_KINDS` (`options`, `suggest`, `form`, `checklist`, `review`) are the kinds a reader answers, the ones a surface that cannot draw them gets as reply instructions. Without `keep`, output is unchanged.
|
|
64
97
|
|
|
65
98
|
Renders a document for a surface that cannot draw blocks. A diagram goes through the `mermaid` hook; when there is no hook, or it returns `undefined` or a drawing wider than `width`, the output is the Mermaid source in a code block plus a pointer to the web view. No block-kind fence is left in the output, except Discord's native `diff`.
|
|
66
99
|
|
|
@@ -141,6 +174,7 @@ A host gives an element the block's parsed `data` and listens for `pbs-answer` (
|
|
|
141
174
|
| `pbs-stats` | `stats` | `StatsData` | | `grid` `stat` `label` `value` `delta` `note` |
|
|
142
175
|
| `pbs-diff` | `diff` | `DiffData` | | `diff` `scroll` `line` |
|
|
143
176
|
| `pbs-diagram` | `mermaid` | `MermaidData` | | `diagram` `image` `source` `note` |
|
|
177
|
+
| `pbs-tree` | `tree` | `TreeData` | | `treeview` `bar` `expand-all` `collapse-all` `tree` `item` `node` `toggle` `name` `count` `tags` `tag` `note` `more` `group` |
|
|
144
178
|
|
|
145
179
|
`TAGS` maps a block kind to its tag. There is no whole-document element: the extension renders Markdown on its page server, and other hosts use their own renderer.
|
|
146
180
|
|
|
@@ -186,7 +220,7 @@ Serve diagram images from `pi-better-show/server` (`mermaidSvg(source, { scheme,
|
|
|
186
220
|
|
|
187
221
|
Structure carries `part` names for `::part()` restyling. A panel has the same border on all four sides, or none; a tone shows as a tint, a badge, an icon, and the heading colour, never a coloured or thicker one-sided border. `examples/demo.css` maps the Roundtable and Straw boss tokens as examples.
|
|
188
222
|
|
|
189
|
-
**Keyboard.** Every control is a native control, labelled. `pbs-mindmap` follows the ARIA tree pattern (arrows move, Right and Left open and close, Enter and Space toggle, Home and End jump); `pbs-table` sorts from header buttons (`aria-sort`) and filters from a labelled search box.
|
|
223
|
+
**Keyboard.** Every control is a native control, labelled. `pbs-mindmap` follows the ARIA tree pattern (arrows move, Right and Left open and close, Enter and Space toggle, Home and End jump); `pbs-tree` follows it too, and opens folders to depth 2 (deeper folders that hold a tagged node open their path) with "expand all" and "collapse all" buttons; `pbs-table` sorts from header buttons (`aria-sort`) and filters from a labelled search box.
|
|
190
224
|
|
|
191
225
|
## React
|
|
192
226
|
|
|
@@ -197,7 +231,7 @@ import { PbsBlock, PbsForm } from "pi-better-show/react";
|
|
|
197
231
|
<PbsForm data={formData} answered={fields} density="compact" onAnswer={...} />
|
|
198
232
|
```
|
|
199
233
|
|
|
200
|
-
One component per element (`PbsCallout` ... `
|
|
234
|
+
One component per element (`PbsCallout` ... `PbsTree`) plus `PbsBlock`, which draws a `parse` segment with the element for its kind and addresses it by its `index`. Props: `data`, `answered`, `onAnswer(answer, event)` (return `false` to refuse), `blockRef`, `density`, `scheme`, `lang`, `className`, `id`, `ref`. A parent render with equal `data` does not redraw the element or clear what the user typed. React 19 or later, as an optional peer dependency.
|
|
201
235
|
|
|
202
236
|
## The pi extension: `show_doc`
|
|
203
237
|
|
|
@@ -219,7 +253,7 @@ Then `/reload` in a running session.
|
|
|
219
253
|
|
|
220
254
|
**Markdown pages.** Prose is Markdown with raw HTML left as text; every block above becomes its element. Select a passage to comment on it; the panel collects comments and an overall note and sends them in one message. A form, pick, chip, checklist, or review reaches the agent as a message: steered into a running turn, or starting a turn when the agent is idle (`encodeAnswer`). Diagrams are drawn on the server, in the page's colour scheme. Images and links resolve against the page's directory: nothing loads from above it, from a dot file or directory, or from another site. Every response carries a CSP, and the server answers only the loopback host.
|
|
221
255
|
|
|
222
|
-
**Agent pages.** `.html` and `.tsx`/`.jsx` run in `<iframe sandbox="allow-scripts allow-forms">` without `allow-same-origin`: no storage, no cookies, and no way to answer on its own: the server refuses a POST whose Origin is not its own (a frame's is `null`) or that is not JSON, and an event stream not opened from its own page. A `<form action="cgi-bin:pi-answer">` or `piBetterShow.send(fields)` answers through the page around the frame. A TSX page's default export is a React component, built by esbuild on each load with the React this package ships; `import {PbsBlock, PbsForm, ..., parse, encodeAnswer, send} from "pi-kit"` gives it the wrappers.
|
|
256
|
+
**Agent pages.** `.html` and `.tsx`/`.jsx` run in `<iframe sandbox="allow-scripts allow-forms">` without `allow-same-origin`: no storage, no cookies, and no way to answer on its own: the server refuses a POST whose Origin is not its own (a frame's is `null`) or that is not JSON, and an event stream not opened from its own page. A `<form action="cgi-bin:pi-answer">` or `piBetterShow.send(fields)` answers through the page around the frame. The page around the frame carries the same feedback panel as a Markdown page: the frame reports the text the user selects to its parent by `postMessage({source: "pbs-frame", type: "selection", text})` (cut to 2000 characters, accepted only from the page's own frame with origin `null`), the user comments on passages and adds an overall note, and one Send delivers a `feedback` answer named by the HTML `<title>`, else the file name. A TSX page works the same way. A TSX page's default export is a React component, built by esbuild on each load with the React this package ships; `import {PbsBlock, PbsForm, ..., parse, encodeAnswer, send} from "pi-kit"` gives it the wrappers.
|
|
223
257
|
|
|
224
258
|
**Edit mode.** Your editor opens the file and the extension watches it. When you save, the change since the version the agent last saw goes to it as a zero-context diff (`@@` headers carry line numbers): steered into a running turn, or attached to your next message when idle, so a save never starts a turn. A save in the same instant as the agent's own write is not reported.
|
|
225
259
|
|
|
@@ -236,7 +270,7 @@ Then `/reload` in a running session.
|
|
|
236
270
|
| `better-show:answer` | `{version, id, answerId, answer}` with `answer` an `Answer`. It reaches the agent as the same message a page answer produces. |
|
|
237
271
|
| `better-show:answer-result` | `{version, id, answerId, accepted, reason?}`; `reason` is `closed`, `invalid` (wrong version or shape, or a `text` document), `empty`, or a delivery error. A repeated `answerId` gets its first result back and delivers nothing again. A payload without a string `id` and `answerId` gets no reply. |
|
|
238
272
|
|
|
239
|
-
A viewer that shows an `html` document in a frame receives its answers as `postMessage({source: "pbs-frame", type: "answer", answerId, answer})` from the frame (origin `"null"`) and replies `{source: "pbs-host", type: "answer-result", answerId, accepted, reason?}`.
|
|
273
|
+
A viewer that shows an `html` document in a frame receives its answers as `postMessage({source: "pbs-frame", type: "answer", answerId, answer})` from the frame (origin `"null"`) and replies `{source: "pbs-host", type: "answer-result", answerId, accepted, reason?}`. It also receives `{source: "pbs-frame", type: "selection", text, top?, left?}` whenever the user's selection in the frame changes (`text` is empty when it was cleared) and may offer its own feedback panel with it.
|
|
240
274
|
|
|
241
275
|
**Moving from pi-herdr-doc-review.** Uninstall it and install this package; `show_doc` keeps its name and parameters. Gone: Herdr panes, nvim and vim, Chawan and terminal-browser, and the `<pi-*>` page-kit tags (write `form`, `review`, ... blocks instead, or use the `pbs-*` elements). The event names changed from `doc-review:*` (version 1) to `better-show:*` (version 2).
|
|
242
276
|
|
package/bin/pbs-tree.js
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// pbs-tree: prints a folder as a ```tree block for pi-better-show. Flags follow Linux `tree` where they exist.
|
|
3
|
+
// Plain JavaScript on node built-ins only: it runs from node_modules, where node does not strip types, under node and bun.
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
6
|
+
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
|
|
9
|
+
// The limits of the tree block (TREE_LIMITS in src/core/types.ts; a test keeps the two in step).
|
|
10
|
+
const MAX_NODES = 2000;
|
|
11
|
+
const MAX_DEPTH = 32;
|
|
12
|
+
|
|
13
|
+
const USAGE = `Usage: pbs-tree [options] [dir]
|
|
14
|
+
|
|
15
|
+
Prints dir (default .) as a \`\`\`tree block, sorted by name in byte order.
|
|
16
|
+
|
|
17
|
+
-L n list n levels
|
|
18
|
+
-d folders only
|
|
19
|
+
-a include dot files (.git is always skipped)
|
|
20
|
+
-I pattern leave out names matching the glob (* ? [..]); | separates several; repeatable
|
|
21
|
+
-P pattern list only files matching the glob; folders are kept when they hold a match
|
|
22
|
+
--gitignore honour .gitignore files
|
|
23
|
+
--dirsfirst folders before files
|
|
24
|
+
--filelimit n do not open a folder holding more than n entries; write "… N more" instead
|
|
25
|
+
--prune leave out folders that hold nothing
|
|
26
|
+
--changed-since rev tag files new, changed or removed since rev (git diff --name-status rev; removed files are listed)
|
|
27
|
+
-h, --help this text
|
|
28
|
+
`;
|
|
29
|
+
|
|
30
|
+
class Usage extends Error {}
|
|
31
|
+
class Failure extends Error {}
|
|
32
|
+
|
|
33
|
+
/** @param {string} message */
|
|
34
|
+
const usage = (message) => new Usage(message);
|
|
35
|
+
|
|
36
|
+
function options(argv) {
|
|
37
|
+
let parsed;
|
|
38
|
+
try {
|
|
39
|
+
parsed = parseArgs({
|
|
40
|
+
args: argv,
|
|
41
|
+
allowPositionals: true,
|
|
42
|
+
options: {
|
|
43
|
+
L: { type: "string", short: "L" },
|
|
44
|
+
d: { type: "boolean", short: "d" },
|
|
45
|
+
a: { type: "boolean", short: "a" },
|
|
46
|
+
I: { type: "string", short: "I", multiple: true },
|
|
47
|
+
P: { type: "string", short: "P", multiple: true },
|
|
48
|
+
gitignore: { type: "boolean" },
|
|
49
|
+
dirsfirst: { type: "boolean" },
|
|
50
|
+
filelimit: { type: "string" },
|
|
51
|
+
prune: { type: "boolean" },
|
|
52
|
+
"changed-since": { type: "string" },
|
|
53
|
+
help: { type: "boolean", short: "h" },
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
} catch (error) {
|
|
57
|
+
throw usage(error instanceof Error ? error.message : String(error));
|
|
58
|
+
}
|
|
59
|
+
const { values, positionals } = parsed;
|
|
60
|
+
if (values.help) return { help: true };
|
|
61
|
+
if (positionals.length > 1) throw usage(`one folder at most, got ${positionals.length}`);
|
|
62
|
+
const count = (name, text, least) => {
|
|
63
|
+
if (text === undefined) return undefined;
|
|
64
|
+
if (!/^\d+$/.test(text) || Number(text) < least)
|
|
65
|
+
throw usage(`${name} needs a whole number of at least ${least}, got "${text}"`);
|
|
66
|
+
return Number(text);
|
|
67
|
+
};
|
|
68
|
+
const since = values["changed-since"];
|
|
69
|
+
if (since !== undefined && (since === "" || since.startsWith("-")))
|
|
70
|
+
throw usage(`--changed-since needs a revision, got "${since}"`);
|
|
71
|
+
return {
|
|
72
|
+
help: false,
|
|
73
|
+
dir: positionals[0] ?? ".",
|
|
74
|
+
depth: count("-L", values.L, 1),
|
|
75
|
+
dirsOnly: values.d === true,
|
|
76
|
+
dotFiles: values.a === true,
|
|
77
|
+
exclude: (values.I ?? []).flatMap(globs),
|
|
78
|
+
include: (values.P ?? []).flatMap(globs),
|
|
79
|
+
gitignore: values.gitignore === true,
|
|
80
|
+
dirsFirst: values.dirsfirst === true,
|
|
81
|
+
fileLimit: count("--filelimit", values.filelimit, 1),
|
|
82
|
+
prune: values.prune === true,
|
|
83
|
+
since,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ---- globs ---------------------------------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
/** A bracket expression at `glob[at]` (`[abc]`, `[a-z]`, `[!abc]`) as a regex class and the index after it; undefined when it is not closed. */
|
|
90
|
+
function bracket(glob, at) {
|
|
91
|
+
const end = glob.indexOf("]", at + 2);
|
|
92
|
+
if (end < 0) return undefined;
|
|
93
|
+
let set = glob.slice(at + 1, end);
|
|
94
|
+
const negate = set.startsWith("!") || set.startsWith("^");
|
|
95
|
+
if (negate) set = set.slice(1);
|
|
96
|
+
return { source: `[${negate ? "^" : ""}${set.replace(/[\\\]^]/g, "\\$&")}]`, end };
|
|
97
|
+
}
|
|
98
|
+
const literal = (char) => char.replace(/[\\^$.|+(){}[\]*?/]/g, "\\$&");
|
|
99
|
+
|
|
100
|
+
/** A shell glob (`*`, `?`, `[..]`, `[!..]`) as a regex over a whole name. */
|
|
101
|
+
function globRegex(glob) {
|
|
102
|
+
let source = "";
|
|
103
|
+
for (let i = 0; i < glob.length; i++) {
|
|
104
|
+
const char = glob[i];
|
|
105
|
+
if (char === "*") source += ".*";
|
|
106
|
+
else if (char === "?") source += ".";
|
|
107
|
+
else if (char === "[") {
|
|
108
|
+
const set = bracket(glob, i);
|
|
109
|
+
if (set) {
|
|
110
|
+
source += set.source;
|
|
111
|
+
i = set.end;
|
|
112
|
+
} else source += "\\[";
|
|
113
|
+
} else source += literal(char);
|
|
114
|
+
}
|
|
115
|
+
return new RegExp(`^${source}$`, "s");
|
|
116
|
+
}
|
|
117
|
+
/** `a|b` as two regexes. */
|
|
118
|
+
const globs = (list) => list.split("|").filter(Boolean).map(globRegex);
|
|
119
|
+
const matches = (list, name) => list.some((regex) => regex.test(name));
|
|
120
|
+
|
|
121
|
+
// ---- .gitignore ------------------------------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
/** A gitignore pattern's glob as a regex over a `/`-separated path (`*` and `?` stop at `/`, `**` does not). */
|
|
124
|
+
function ignoreRegex(glob) {
|
|
125
|
+
let source = "";
|
|
126
|
+
for (let i = 0; i < glob.length; i++) {
|
|
127
|
+
const char = glob[i];
|
|
128
|
+
if (char === "*" && glob[i + 1] === "*") {
|
|
129
|
+
const whole = (i === 0 || glob[i - 1] === "/") && (glob[i + 2] === "/" || glob[i + 2] === undefined);
|
|
130
|
+
if (whole && glob[i + 2] === "/") {
|
|
131
|
+
source += "(?:.*/)?";
|
|
132
|
+
i += 2;
|
|
133
|
+
} else {
|
|
134
|
+
source += whole ? ".*" : "[^/]*";
|
|
135
|
+
i += 1;
|
|
136
|
+
}
|
|
137
|
+
} else if (char === "*") source += "[^/]*";
|
|
138
|
+
else if (char === "?") source += "[^/]";
|
|
139
|
+
else if (char === "[") {
|
|
140
|
+
const set = bracket(glob, i);
|
|
141
|
+
if (set) {
|
|
142
|
+
source += set.source;
|
|
143
|
+
i = set.end;
|
|
144
|
+
} else source += "\\[";
|
|
145
|
+
} else if (char === "\\" && i + 1 < glob.length) {
|
|
146
|
+
i++;
|
|
147
|
+
source += literal(glob[i] ?? "");
|
|
148
|
+
} else source += literal(char);
|
|
149
|
+
}
|
|
150
|
+
return new RegExp(`^${source}$`, "s");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The rules of one .gitignore file. */
|
|
154
|
+
function ignoreRules(text) {
|
|
155
|
+
const rules = [];
|
|
156
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
157
|
+
let line = raw.replace(/(?<!\\)[ \t]+$/, "");
|
|
158
|
+
if (line === "" || line.startsWith("#")) continue;
|
|
159
|
+
const negate = line.startsWith("!");
|
|
160
|
+
if (negate) line = line.slice(1);
|
|
161
|
+
const dirOnly = line.endsWith("/");
|
|
162
|
+
if (dirOnly) line = line.slice(0, -1);
|
|
163
|
+
if (line === "") continue;
|
|
164
|
+
// A pattern with a slash inside it (or in front) is relative to the .gitignore's folder; the others match a name at any depth.
|
|
165
|
+
const anchored = line.includes("/");
|
|
166
|
+
if (line.startsWith("/")) line = line.slice(1);
|
|
167
|
+
rules.push({ negate, dirOnly, anchored, regex: ignoreRegex(line) });
|
|
168
|
+
}
|
|
169
|
+
return rules;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Whether the .gitignore files in `files` (outermost first) ignore `path`; the last rule that matches decides. */
|
|
173
|
+
function ignored(files, path, isDir) {
|
|
174
|
+
let verdict = false;
|
|
175
|
+
for (const file of files) {
|
|
176
|
+
if (!path.startsWith(file.base + sep)) continue;
|
|
177
|
+
const relative = path
|
|
178
|
+
.slice(file.base.length + 1)
|
|
179
|
+
.split(sep)
|
|
180
|
+
.join("/");
|
|
181
|
+
const name = relative.slice(relative.lastIndexOf("/") + 1);
|
|
182
|
+
for (const rule of file.rules) {
|
|
183
|
+
if (rule.dirOnly && !isDir) continue;
|
|
184
|
+
if (rule.regex.test(rule.anchored ? relative : name)) verdict = !rule.negate;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return verdict;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The .gitignore files from the repository's top (the first folder above with a .git) down to `dir`. */
|
|
191
|
+
function ancestorIgnores(dir) {
|
|
192
|
+
const chain = [];
|
|
193
|
+
for (let at = dir; ; at = dirname(at)) {
|
|
194
|
+
chain.unshift(at);
|
|
195
|
+
if (existsSync(join(at, ".git")) || dirname(at) === at) break;
|
|
196
|
+
}
|
|
197
|
+
// Without a repository above, only the folder itself counts.
|
|
198
|
+
if (!existsSync(join(chain[0], ".git"))) return ignoreFiles([dir]);
|
|
199
|
+
return ignoreFiles(chain);
|
|
200
|
+
}
|
|
201
|
+
function ignoreFiles(folders) {
|
|
202
|
+
const files = [];
|
|
203
|
+
for (const base of folders) files.push(...ignoreFile(base));
|
|
204
|
+
return files;
|
|
205
|
+
}
|
|
206
|
+
function ignoreFile(base) {
|
|
207
|
+
try {
|
|
208
|
+
return [{ base, rules: ignoreRules(readFileSync(join(base, ".gitignore"), "utf8")) }];
|
|
209
|
+
} catch {
|
|
210
|
+
return [];
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ---- git ---------------------------------------------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
function git(dir, args) {
|
|
217
|
+
try {
|
|
218
|
+
return execFileSync("git", ["-C", dir, ...args], {
|
|
219
|
+
encoding: "utf8",
|
|
220
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
221
|
+
maxBuffer: 1 << 28,
|
|
222
|
+
});
|
|
223
|
+
} catch (error) {
|
|
224
|
+
const detail =
|
|
225
|
+
error && typeof error === "object" && "stderr" in error ? String(error.stderr).trim() : String(error);
|
|
226
|
+
throw new Failure(`git ${args[0]} failed: ${detail}`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** `path -> "new" | "changed" | "removed"` for the working tree against `rev`; untracked files count as new. */
|
|
231
|
+
function changes(dir, rev) {
|
|
232
|
+
const status = new Map();
|
|
233
|
+
const diff = git(dir, ["diff", "--name-status", "--no-renames", "-z", "--relative", rev, "--"]).split("\0");
|
|
234
|
+
for (let i = 0; i + 1 < diff.length; i += 2) {
|
|
235
|
+
const letter = (diff[i] ?? "")[0];
|
|
236
|
+
const path = diff[i + 1];
|
|
237
|
+
if (!path) continue;
|
|
238
|
+
status.set(path, letter === "A" || letter === "C" ? "new" : letter === "D" ? "removed" : "changed");
|
|
239
|
+
}
|
|
240
|
+
for (const path of git(dir, ["ls-files", "--others", "--exclude-standard", "-z"]).split("\0")) {
|
|
241
|
+
if (path && !status.has(path)) status.set(path, "new");
|
|
242
|
+
}
|
|
243
|
+
return status;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The removed files as a trie, so a folder listing can add the names the disk no longer has. */
|
|
247
|
+
function removedTrie(status) {
|
|
248
|
+
const root = { children: new Map(), file: false };
|
|
249
|
+
for (const [path, tag] of status) {
|
|
250
|
+
if (tag !== "removed") continue;
|
|
251
|
+
let at = root;
|
|
252
|
+
for (const part of path.split("/")) {
|
|
253
|
+
const next = at.children.get(part) ?? { children: new Map(), file: false };
|
|
254
|
+
at.children.set(part, next);
|
|
255
|
+
at = next;
|
|
256
|
+
}
|
|
257
|
+
at.file = true;
|
|
258
|
+
}
|
|
259
|
+
return root;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ---- the walk -------------------------------------------------------------------------------------------------------
|
|
263
|
+
|
|
264
|
+
const compare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
265
|
+
|
|
266
|
+
function snapshot(settings) {
|
|
267
|
+
const root = resolve(settings.dir);
|
|
268
|
+
let stat;
|
|
269
|
+
try {
|
|
270
|
+
stat = statSync(root);
|
|
271
|
+
} catch {
|
|
272
|
+
throw new Failure(`${settings.dir}: no such folder`);
|
|
273
|
+
}
|
|
274
|
+
if (!stat.isDirectory()) throw new Failure(`${settings.dir}: not a folder`);
|
|
275
|
+
|
|
276
|
+
const status = settings.since === undefined ? new Map() : changes(root, settings.since);
|
|
277
|
+
const removed = settings.since === undefined || settings.dirsOnly ? undefined : removedTrie(status);
|
|
278
|
+
const outer = settings.gitignore ? ancestorIgnores(root) : [];
|
|
279
|
+
// What -L hides still decides whether a folder is empty or holds a match.
|
|
280
|
+
const needsAll = settings.prune || settings.include.length > 0;
|
|
281
|
+
const filtering = !settings.dirsOnly;
|
|
282
|
+
const pruning = filtering && (settings.prune || settings.include.length > 0);
|
|
283
|
+
|
|
284
|
+
/** The entries of a folder that survive -a, -I, .gitignore, and -d, in listing order. */
|
|
285
|
+
function entries(abs, parts, trie, files) {
|
|
286
|
+
const found = new Map();
|
|
287
|
+
if (abs !== undefined) {
|
|
288
|
+
let listing = [];
|
|
289
|
+
try {
|
|
290
|
+
listing = readdirSync(abs, { withFileTypes: true });
|
|
291
|
+
} catch (error) {
|
|
292
|
+
process.stderr.write(`pbs-tree: cannot read ${abs}: ${error instanceof Error ? error.message : error}\n`);
|
|
293
|
+
}
|
|
294
|
+
for (const entry of listing)
|
|
295
|
+
found.set(entry.name, { name: entry.name, dir: entry.isDirectory(), virtual: false });
|
|
296
|
+
}
|
|
297
|
+
if (trie) {
|
|
298
|
+
for (const [name, child] of trie.children) {
|
|
299
|
+
if (!found.has(name)) found.set(name, { name, dir: !child.file, virtual: true });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const kept = [...found.values()].filter((entry) => {
|
|
303
|
+
if (entry.name === ".git") return false;
|
|
304
|
+
if (!settings.dotFiles && entry.name.startsWith(".")) return false;
|
|
305
|
+
if (matches(settings.exclude, entry.name)) return false;
|
|
306
|
+
if (settings.dirsOnly && !entry.dir) return false;
|
|
307
|
+
// A removed path has no file to look at, but its name still meets the same rules.
|
|
308
|
+
const where = join(abs ?? join(root, ...parts), entry.name);
|
|
309
|
+
if (files.length > 0 && ignored(files, where, entry.dir)) return false;
|
|
310
|
+
return true;
|
|
311
|
+
});
|
|
312
|
+
kept.sort((a, b) => (settings.dirsFirst && a.dir !== b.dir ? (a.dir ? -1 : 1) : compare(a.name, b.name)));
|
|
313
|
+
return kept;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The nodes of a folder and whether it holds anything that survives -P and --prune.
|
|
318
|
+
* `emit` is false below the -L cut: nothing is returned, but `holds` is still worked out.
|
|
319
|
+
*/
|
|
320
|
+
function walk(abs, parts, trie, level, emit, files) {
|
|
321
|
+
const list = entries(abs, parts, trie, files);
|
|
322
|
+
if (settings.fileLimit !== undefined && list.length > settings.fileLimit) {
|
|
323
|
+
return {
|
|
324
|
+
nodes: emit ? [{ name: `… ${list.length} more`, dir: false, tags: [], children: [], more: list.length }] : [],
|
|
325
|
+
holds: true,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
const nodes = [];
|
|
329
|
+
let holds = false;
|
|
330
|
+
for (const entry of list) {
|
|
331
|
+
const path = [...parts, entry.name];
|
|
332
|
+
if (!entry.dir) {
|
|
333
|
+
if (filtering && settings.include.length > 0 && !matches(settings.include, entry.name)) continue;
|
|
334
|
+
holds = true;
|
|
335
|
+
if (emit) {
|
|
336
|
+
const tag = status.get(path.join("/"));
|
|
337
|
+
nodes.push({
|
|
338
|
+
name: entry.name,
|
|
339
|
+
dir: false,
|
|
340
|
+
tags: entry.virtual ? ["removed"] : tag ? [tag] : [],
|
|
341
|
+
children: [],
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
const below = trie?.children.get(entry.name);
|
|
347
|
+
const deeper = level < (settings.depth ?? Number.POSITIVE_INFINITY);
|
|
348
|
+
const inside = entry.virtual ? undefined : join(abs ?? "", entry.name);
|
|
349
|
+
let result = { nodes: [], holds: false };
|
|
350
|
+
if (deeper || needsAll || entry.virtual) {
|
|
351
|
+
const nested = inside !== undefined && settings.gitignore ? [...files, ...ignoreFile(inside)] : files;
|
|
352
|
+
result = walk(inside, path, below, level + 1, emit && deeper, nested);
|
|
353
|
+
}
|
|
354
|
+
// A folder that only exists as the home of removed files is shown only while one of them is.
|
|
355
|
+
if (entry.virtual && !result.holds) continue;
|
|
356
|
+
if (pruning && !result.holds) continue;
|
|
357
|
+
holds = true;
|
|
358
|
+
if (emit) nodes.push({ name: entry.name, dir: true, tags: [], children: result.nodes });
|
|
359
|
+
}
|
|
360
|
+
return { nodes, holds };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const name = basename(root) || root;
|
|
364
|
+
return { name, dir: true, tags: [], children: walk(root, [], removed, 1, true, outer).nodes };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ---- output ------------------------------------------------------------------------------------------------------------
|
|
368
|
+
|
|
369
|
+
const NBSP = "\u00a0";
|
|
370
|
+
/** A name as one line of the block: control characters become `?`, and what would read as markup is kept apart by a no-break space. */
|
|
371
|
+
function safe(name) {
|
|
372
|
+
return (
|
|
373
|
+
[...name]
|
|
374
|
+
.map((char) => (char < " " || char === "\u007f" ? "?" : char))
|
|
375
|
+
.join("")
|
|
376
|
+
.replace(/^ +| +$/g, (spaces) => NBSP.repeat(spaces.length))
|
|
377
|
+
.replace(/ # /g, ` #${NBSP}`)
|
|
378
|
+
// A trailing " #" would meet the " {tags}" suffix and read as a note.
|
|
379
|
+
.replace(/ #$/, `${NBSP}#`)
|
|
380
|
+
.replace(/(^| )(\{[^{}]*\})$/, `${NBSP}$2`)
|
|
381
|
+
.replace(/^… (\d+) more$/, `…${NBSP}$1 more`)
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function render(tree) {
|
|
386
|
+
let count = 0;
|
|
387
|
+
let deepest = 0;
|
|
388
|
+
const out = [];
|
|
389
|
+
const longest = { backticks: 0 };
|
|
390
|
+
const walk = (node, level) => {
|
|
391
|
+
count++;
|
|
392
|
+
deepest = Math.max(deepest, level + 1);
|
|
393
|
+
const name = node.more === undefined ? safe(node.name) : node.name;
|
|
394
|
+
for (const run of name.match(/`+/g) ?? []) longest.backticks = Math.max(longest.backticks, run.length);
|
|
395
|
+
const tags = node.tags.length > 0 ? ` {${node.tags.join(", ")}}` : "";
|
|
396
|
+
out.push(`${" ".repeat(level)}${name}${node.dir ? "/" : ""}${tags}`);
|
|
397
|
+
for (const child of node.children) walk(child, level + 1);
|
|
398
|
+
};
|
|
399
|
+
walk(tree, 0);
|
|
400
|
+
if (count > MAX_NODES) {
|
|
401
|
+
throw new Failure(
|
|
402
|
+
`${count} nodes; a tree block holds at most ${MAX_NODES}. Narrow it with -L, -I, -P, --gitignore, --prune or --filelimit.`,
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
if (deepest > MAX_DEPTH) {
|
|
406
|
+
throw new Failure(`${deepest} levels; a tree block holds at most ${MAX_DEPTH}. Narrow it with -L.`);
|
|
407
|
+
}
|
|
408
|
+
const fence = "`".repeat(Math.max(3, longest.backticks + 1));
|
|
409
|
+
return `${fence}tree\n${out.join("\n")}\n${fence}\n`;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
try {
|
|
413
|
+
const settings = options(process.argv.slice(2));
|
|
414
|
+
if (settings.help) process.stdout.write(USAGE);
|
|
415
|
+
else process.stdout.write(render(snapshot(settings)));
|
|
416
|
+
} catch (error) {
|
|
417
|
+
if (error instanceof Usage) {
|
|
418
|
+
process.stderr.write(`pbs-tree: ${error.message}\n\n${USAGE}`);
|
|
419
|
+
process.exitCode = 2;
|
|
420
|
+
} else if (error instanceof Failure) {
|
|
421
|
+
process.stderr.write(`pbs-tree: ${error.message}\n`);
|
|
422
|
+
process.exitCode = 1;
|
|
423
|
+
} else throw error;
|
|
424
|
+
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-show",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Interactive blocks for agent-written Markdown: one vocabulary, text fallback, and answer encoding shared by every host, plus the show_doc extension for pi",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "wayne930242",
|
|
8
|
+
"bin": {
|
|
9
|
+
"pbs-tree": "./bin/pbs-tree.js"
|
|
10
|
+
},
|
|
8
11
|
"files": [
|
|
12
|
+
"bin",
|
|
9
13
|
"src",
|
|
10
14
|
"README.md",
|
|
11
15
|
"LICENSE"
|
package/src/core/parse.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { parse as parseYaml } from "yaml";
|
|
2
2
|
import * as legacy from "./blocks.ts";
|
|
3
3
|
import * as added from "./blocks-new.ts";
|
|
4
|
+
import { tree } from "./tree.ts";
|
|
4
5
|
import {
|
|
5
6
|
type AlertData,
|
|
6
7
|
type AlertTone,
|
|
@@ -49,6 +50,7 @@ const CONVERTERS: { [K in Exclude<BlockKind, "alert">]: Convert<K> } = {
|
|
|
49
50
|
table: yaml(added.table),
|
|
50
51
|
steps: yaml(added.steps),
|
|
51
52
|
stats: yaml(added.stats),
|
|
53
|
+
tree,
|
|
52
54
|
};
|
|
53
55
|
|
|
54
56
|
/** The first line of the error: YAML's own messages end it with a colon and append a source excerpt. */
|
package/src/core/text.ts
CHANGED
|
@@ -21,6 +21,8 @@ import type {
|
|
|
21
21
|
TableData,
|
|
22
22
|
TextLang,
|
|
23
23
|
TextProfile,
|
|
24
|
+
TreeData,
|
|
25
|
+
TreeNode,
|
|
24
26
|
} from "./types.ts";
|
|
25
27
|
import { displayWidth } from "./width.ts";
|
|
26
28
|
|
|
@@ -230,6 +232,26 @@ function stats(dialect: Dialect, data: StatsData): string {
|
|
|
230
232
|
.join("\n");
|
|
231
233
|
}
|
|
232
234
|
|
|
235
|
+
/** A tree in `tree` style, one line per node: tags as `[new]`, the note after ` — `. Notes lose their Markdown: the lines sit in a fence. */
|
|
236
|
+
function tree(dialect: Dialect, data: TreeData): string {
|
|
237
|
+
const lines: string[] = [];
|
|
238
|
+
const label = (node: TreeNode): string => {
|
|
239
|
+
const tags = node.tags.map((tag) => `[${tag}]`);
|
|
240
|
+
const note = node.note === undefined ? "" : ` — ${oneLine(inlinePlain(node.note))}`;
|
|
241
|
+
return `${[`${node.name}${node.dir ? "/" : ""}`, ...tags].join(" ")}${note}`;
|
|
242
|
+
};
|
|
243
|
+
const walk = (node: TreeNode, prefix: string) => {
|
|
244
|
+
node.children.forEach((child, index) => {
|
|
245
|
+
const last = index === node.children.length - 1;
|
|
246
|
+
lines.push(`${prefix}${last ? "└── " : "├── "}${label(child)}`);
|
|
247
|
+
walk(child, `${prefix}${last ? " " : "│ "}`);
|
|
248
|
+
});
|
|
249
|
+
};
|
|
250
|
+
lines.push(label(data.root));
|
|
251
|
+
walk(data.root, "");
|
|
252
|
+
return code(dialect, lines.join("\n"));
|
|
253
|
+
}
|
|
254
|
+
|
|
233
255
|
const widest = (text: string): number => Math.max(0, ...text.split("\n").map(displayWidth));
|
|
234
256
|
|
|
235
257
|
/** A diagram as a text drawing when the hook can and it fits; else its source and a pointer to the web view. */
|
|
@@ -272,6 +294,8 @@ function block(dialect: Dialect, segment: BlockSegment): string {
|
|
|
272
294
|
return steps(dialect, segment.data);
|
|
273
295
|
case "stats":
|
|
274
296
|
return stats(dialect, segment.data);
|
|
297
|
+
case "tree":
|
|
298
|
+
return tree(dialect, segment.data);
|
|
275
299
|
}
|
|
276
300
|
}
|
|
277
301
|
|