pi-better-show 0.3.1 → 0.5.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 CHANGED
@@ -33,19 +33,67 @@ 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
 
39
72
  ## Core API
40
73
 
41
74
  ```ts
42
- import { parse, toText, inline, encodeAnswer } from "pi-better-show";
75
+ import { parse, toText, inline, encodeAnswer, checkBlocks } from "pi-better-show";
43
76
 
44
77
  parse(markdown: string): Segment[]
45
78
  ```
46
79
 
47
80
  Splits a document into `{type: "markdown", text}`, `{type: "block", kind, data, index}`, and `{type: "invalid", kind, source, error}` segments, in order. `data` is typed per kind (`BlockDataMap`). `index` counts the document's blocks of every kind from 0; invalid blocks take no number. `index` is the block's address for answers.
48
81
 
82
+ ```ts
83
+ checkBlocks(markdown: string, options?: { mermaid?: (source: string) => string | undefined }): BlockProblem[]
84
+ formatProblems(name: string, problems: BlockProblem[]): string
85
+
86
+ interface BlockProblem {
87
+ kind: BlockKind;
88
+ line: number; // 1-based, in the Markdown file
89
+ path: string; // e.g. form question "o5" choice 1 label
90
+ message: string;
91
+ severity: "error" | "warning";
92
+ }
93
+ ```
94
+
95
+ Tells the author what is wrong with the blocks of a file, where `parse` only keeps going. `error`: the block is invalid and the page shows its source (a YAML error is reported at the line that caused it; a flow collection broken by an unquoted ` #` points at the line that opened it). `warning`: the block draws, but part of what was written is lost: a plain value that a ` #` cut short (YAML reads the rest as a comment; the message names the key path and says to quote the value), a key the block does not read at that level (with the known keys, and a "did you mean" for a near miss), or a fence that never closes. Core has no Mermaid parser: pass `options.mermaid`, which returns what is wrong with a diagram source, to check diagrams too. Pure; it loads no more than `parse` does.
96
+
49
97
  ```ts
50
98
  toText(segments: Segment[], profile: TextProfile): string
51
99
 
@@ -60,7 +108,7 @@ interface TextProfile {
60
108
 
61
109
  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
110
 
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.
111
+ 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
112
 
65
113
  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
114
 
@@ -79,7 +127,7 @@ interface Answer {
79
127
  encodeAnswer(answer: Answer): string
80
128
  ```
81
129
 
82
- `encodeAnswer` produces the text the agent reads. For `form`, `review`, and `feedback` it is byte-compatible with pi-herdr-doc-review's `formMessage`, `reviewMessage`, and `pageFeedbackMessage` given the same fields (the legacy `pi-kind` field is ignored). `ref` addresses the block for hosts and does not appear in the text.
130
+ `encodeAnswer` produces the text the agent reads. For `form`, `review`, and `feedback` it is byte-compatible with pi-herdr-doc-review's `formMessage`, `reviewMessage`, and `pageFeedbackMessage` given the same fields (the legacy `pi-kind` field is ignored). `ref` addresses the block for hosts and does not appear in the text. A `pi-note` field (see below) is appended as `Other comments: …`.
83
131
 
84
132
  | Kind | `fields` | Text |
85
133
  |---|---|---|
@@ -96,6 +144,8 @@ validateAnswer(block: BlockSegment, answer: Answer): { ok: true } | { ok: false;
96
144
 
97
145
  `validateAnswer` is for a host that receives an `Answer` from an untrusted client. It accepts the answer when its `kind` fits the block (`options` takes `pick`, the others their own kind), every field names a question, choice, or item of that block, and there are at most 64 fields of at most 1,024 characters each. Several values for one name are accepted only for a `multi` form question (as repeated fields, or the joined value the form element sends); a `single` or `text` question, a pick, and a suggestion take one. A required question must be answered (an empty value or `(no answer)` is not an answer). On a `form` question without an `other` box, a value must be one of its choices. A `checklist` field is an item name once with `checked` or `unchecked`; a `review` may carry `picked` only when the block has `pick`. On refusal `reason` says why, for the host's error reply. Blocks that take no answer (display kinds) are refused.
98
146
 
147
+ **Other comments.** Every submittable element (`pbs-form`, `pbs-review`, `pbs-checklist`, `pbs-options`) shows a fixed "Other comments" box above its submit button (above the options in `pbs-options`; the box is read when the option is picked). Its trimmed text travels in the same answer as the reserved field `pi-note` (`NOTE_FIELD`), once, and a blank box sends nothing. `validateAnswer` accepts it for every interactive kind; a form question or checklist item may not be named `pi-note`. A host that shows the elements needs to do nothing new: the field is in `answer.fields`, so `validateAnswer` and `encodeAnswer` already pass it through. A host that rebuilds the answer from selected fields must forward `pi-note`; set `answered` to the submitted fields so the locked element shows it. The words are `otherComments` in `configure({strings})`.
148
+
99
149
  **Several values.** A block that gathers several values (a `form` with a `multi` question, a `checklist`, a `review`) sends nothing on a tick, a pick, or typing: choices stay changeable until the reader presses Send, and a required `multi` question with none chosen is refused at that question. Only `options` and `suggest` send on the click.
100
150
 
101
151
  ## Server API
@@ -141,6 +191,7 @@ A host gives an element the block's parsed `data` and listens for `pbs-answer` (
141
191
  | `pbs-stats` | `stats` | `StatsData` | | `grid` `stat` `label` `value` `delta` `note` |
142
192
  | `pbs-diff` | `diff` | `DiffData` | | `diff` `scroll` `line` |
143
193
  | `pbs-diagram` | `mermaid` | `MermaidData` | | `diagram` `image` `source` `note` |
194
+ | `pbs-tree` | `tree` | `TreeData` | | `treeview` `bar` `expand-all` `collapse-all` `tree` `item` `node` `toggle` `name` `count` `tags` `tag` `note` `more` `group` |
144
195
 
145
196
  `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
197
 
@@ -186,7 +237,7 @@ Serve diagram images from `pi-better-show/server` (`mermaidSvg(source, { scheme,
186
237
 
187
238
  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
239
 
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.
240
+ **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
241
 
191
242
  ## React
192
243
 
@@ -197,7 +248,7 @@ import { PbsBlock, PbsForm } from "pi-better-show/react";
197
248
  <PbsForm data={formData} answered={fields} density="compact" onAnswer={...} />
198
249
  ```
199
250
 
200
- One component per element (`PbsCallout` ... `PbsDiagram`) 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.
251
+ 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
252
 
202
253
  ## The pi extension: `show_doc`
203
254
 
@@ -217,6 +268,8 @@ Then `/reload` in a running session.
217
268
  | `page` | The default browser (`open`, `xdg-open`), one tab per page, on a loopback page server behind a random token. `.md` renders with its blocks; `.html`, `.tsx`, `.jsx` run in a sandboxed frame; images show as they are. |
218
269
  | `edit` (default) | A text file in your editor: `PI_BETTER_SHOW_EDITOR` (a command line, for example `code -r` or `subl`), else `code`, else `open -t` / `xdg-open`. It must return at once; terminal editors do not work. |
219
270
 
271
+ **Block problems.** `show_doc` appends the problems of each Markdown document it opens (`checkBlocks`, see Core API) after its usual reply, and the `write` and `edit` tools of the agent get them in their own result for a `.md` file that holds a block fence: `Block problems in questions.md:` then `- line 40 form question "o5" choice 1 label (warning): ...`. Files without block fences are not read by the checker; the YAML parser and Mermaid load on the first file that needs them. Mermaid is checked in the extension with `beautiful-mermaid`, which validates the diagram type and parses what it draws; it does not catch every syntax slip in a flowchart.
272
+
220
273
  **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
274
 
222
275
  **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.
@@ -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.1",
3
+ "version": "0.5.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"
@@ -1,3 +1,4 @@
1
+ import { NOTE_FIELD } from "./blocks.ts";
1
2
  import type { Answer } from "./types.ts";
2
3
 
3
4
  type Fields = readonly (readonly [string, string])[];
@@ -64,6 +65,16 @@ function checklistText(fields: Fields, title: string | undefined): string {
64
65
  */
65
66
  export function encodeAnswer(answer: Answer): string {
66
67
  const fields = answer.fields.filter(([name]) => name !== "pi-kind");
68
+ if (answer.kind === "feedback") return encodeKind(answer, fields);
69
+ const note = first(fields, NOTE_FIELD)?.trim();
70
+ const body = encodeKind(
71
+ answer,
72
+ fields.filter(([name]) => name !== NOTE_FIELD),
73
+ );
74
+ return note ? `${body}\n\nOther comments: ${note}` : body;
75
+ }
76
+
77
+ function encodeKind(answer: Answer, fields: Fields): string {
67
78
  switch (answer.kind) {
68
79
  case "form":
69
80
  return formText(fields);
@@ -1,3 +1,4 @@
1
+ import { NOTE_FIELD } from "./blocks.ts";
1
2
  import { entryOf, flag, itemsOf, mappingOf, oneOf, record, requiredText, text } from "./normalize.ts";
2
3
  import type {
3
4
  Cell,
@@ -59,8 +60,10 @@ export function checklist(data: unknown): ChecklistData {
59
60
  const item = entryOf(entry, "label", "item");
60
61
  const label = text(item.label ?? item.name, "label");
61
62
  if (label === undefined) throw new Error("each checklist item needs a label or a name");
63
+ const name = text(item.name, "name") ?? label;
64
+ if (name === NOTE_FIELD) throw new Error('the item name "pi-note" is reserved for the other-comments box');
62
65
  return {
63
- name: text(item.name, "name") ?? label,
66
+ name,
64
67
  label,
65
68
  checked: flag(item.checked, "checked") ?? false,
66
69
  note: text(item.note, "note"),
@@ -37,6 +37,12 @@ export function options(data: unknown): OptionsData {
37
37
  };
38
38
  }
39
39
 
40
+ /**
41
+ * The reserved field every submittable block may add to its answer: the free text from the "Other comments" box.
42
+ * It is omitted when the box is empty, appears at most once, and no form question or checklist item may use the name.
43
+ */
44
+ export const NOTE_FIELD = "pi-note";
45
+
40
46
  const QUESTION_TYPES = ["single", "multi", "text"] as const;
41
47
 
42
48
  function choice(entry: unknown): ChoiceData {
@@ -56,6 +62,7 @@ function question(item: unknown): QuestionData {
56
62
  const label = text(raw.label, "label");
57
63
  const name = text(raw.name, "name") ?? label;
58
64
  if (name === undefined) throw new Error("each question needs a name or a label");
65
+ if (name === NOTE_FIELD) throw new Error('the question name "pi-note" is reserved for the other-comments box');
59
66
  const entries: unknown[] = Array.isArray(raw.choices) ? raw.choices : list(raw.choices, "choices");
60
67
  const choices = entries.map(choice);
61
68
  const type: QuestionType = oneOf(raw.type, QUESTION_TYPES, "type") ?? (choices.length > 0 ? "single" : "text");