Public: anyone can read this; the crew can change it.

A `package.json` opens as its manifest: name and version, scripts, dependencies with their ranges, engines #11217

Parked opened this
Closed without merging

scout/forge:scout/11208-a-package-json-opens-as-its-manifest-nam → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +208 −2
docs/design/areas/render.md +4
@@ -44,6 +44,10 @@ A .zip, .tar or .tar.gz is drawn by `src/web/render/archive-view.ts` as the exis
4444
4545 `src/web/render/env.ts` draws one existing `.table` (`data-dense`): name, example, comment, with group headings as full-width `th` rows. `.env-view` is only a hook on the wrapper and has no rule. How it works: `docs/features/file-env.md`.
4646
47 ## Package manifest (package.json)
48
49 `src/web/render/package-json.ts` draws an `h2`, a `muted small` facts line, then per section an `h3` and one existing `.table` (`data-dense`); script commands are `code`. `.package-view` is only a hook and has no rule. How it works: `docs/features/file-package-json.md`.
50
4751 ## OpenAPI operations (openapi.json, *.openapi.yaml)
4852
4953 `src/web/render/openapi.ts` draws one `h3` per tag and under it one existing `.table` (`data-dense`) of method, path, summary and a `deprecated` mark; the cap line is a `muted small` paragraph. `.openapi-view` is only a hook on the wrapper and has no rule. How it works: `docs/features/file-openapi.md`.
docs/features/file-package-json.md added +11
@@ -0,0 +1,11 @@
1 # A `package.json` opens as its manifest
2
3 A file named exactly `package.json` opens as rows instead of raw text: name and version, one line of facts (`type`, `engines`, license, package manager), then **Scripts** (name, command in mono), **Dependencies**, **Dev dependencies**, and peer/optional dependencies, each with its range. Source is one tap away (`?view=source`). `package-lock.json` and other `.json` keep the config form.
4
5 - Malformed JSON, or JSON that is not an object, keeps the source view with no banner.
6 - At most 500 rows per section, then `N more not shown`. Files over 1 MB keep Source.
7 - Every cell is escaped; drawn on the server; no script, no new CSS (`.package-view` is a hook with no rule).
8
9 **Terminal:** the workspace opens the same rows (`packageTable` in `src/tui/screens/workspace.ts`, over the same `parsePackage`); `s` flips to the source.
10
11 Code: `src/web/render/package-json.ts`, `src/web/render/kinds.ts`. Tests: `test/render-package-json.test.ts`, `test/tui-workspace.test.ts`.
src/tui/screens/workspace.ts +20
@@ -68,6 +68,7 @@ import { RECORD_CAP, parseLcov, worstFirst, type Ratio } from "../../web/render/
6868 import { EVENT_CAP, parseIcs } from "../../web/render/ics.ts";
6969 import { fileSize } from "../../web/ui.ts";
7070 import { parseEml } from "../../web/render/eml-parse.ts";
71 import { parsePackage, ROW_CAP as PKG_ROW_CAP } from "../../web/render/package-json.ts";
7172 import { parseEnv, ROW_CAP as ENV_ROW_CAP } from "../../web/render/env.ts";
7273 import { CARD_CAP, parseVcf } from "../../web/render/vcf-parse.ts";
7374 import { CUE_CAP, parseSubtitles } from "../../web/render/subtitles.ts";
@@ -389,6 +390,22 @@ function envTable(source: string): Table | null {
389390 return { header: ["Name", "Example", "Comment"], rows, more: doc.total - doc.rows.length, delimiter: ",", columns: 3 };
390391 }
391392
393 /** A `package.json` as Section/Name/Value rows; null when it is not a JSON object. Shares the web's parser. */
394 function packageTable(source: string): Table | null {
395 const doc = parsePackage(source);
396 if (doc === undefined) return null;
397 const rows: string[][] = [];
398 if (doc.name !== "") rows.push(["package", doc.name, doc.version]);
399 if (doc.facts.length > 0) rows.push(["facts", doc.facts.join(" · "), ""]);
400 let more = 0;
401 for (const s of doc.sections) {
402 for (const [k, v] of s.rows.slice(0, PKG_ROW_CAP)) rows.push([s.title, k, v]);
403 more += s.total - s.rows.length;
404 }
405 if (rows.length === 0) return null;
406 return { header: ["Section", "Name", "Value"], rows, more, delimiter: ",", columns: 3 };
407 }
408
392409 /** `.eml`: a message, drawn as rows of its headers, body and attachments. */
393410 function isEmlPath(path: string): boolean {
394411 return /\.eml$/i.test(path);
@@ -745,6 +762,9 @@ class Tab {
745762 } else if (isEnvExample(this.path)) {
746763 this.table = envTable(new TextDecoder().decode(source));
747764 if (this.table !== null) this.grid = layoutTable(this.table);
765 } else if (kindByName(this.path) === "package") {
766 this.table = packageTable(new TextDecoder().decode(source));
767 if (this.table !== null) this.grid = layoutTable(this.table);
748768 } else if (isEmlPath(this.path)) {
749769 this.table = emlTable(source);
750770 if (this.table !== null) this.grid = layoutTable(this.table);
src/web/render/kinds.ts +6
@@ -42,6 +42,7 @@ export type FileKind =
4242 | "junit"
4343 | "env"
4444 | "openapi"
45 | "package"
4546 | "dockerfile"
4647 | "sql"
4748 | "text"
@@ -84,6 +85,7 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
8485 junit: 5 * MB,
8586 env: 1 * MB,
8687 openapi: 1 * MB,
88 package: 1 * MB,
8789 dockerfile: 1 * MB,
8890 sql: 1 * MB,
8991 text: 1 * MB,
@@ -219,6 +221,8 @@ export const isEnvExample = (path: string): boolean =>
219221 /** `openapi.json|yaml|yml` and `*.openapi.*`: the name of an OpenAPI document; its content decides whether it is drawn as one. */
220222 const isOpenApiName = (path: string): boolean => /(^|\/|\.)openapi\.(json|ya?ml)$/i.test(path);
221223
224 /** A manifest is named exactly `package.json`; `package-lock.json` and the rest stay config. */
225 const isPackageName = (path: string): boolean => /(^|\/)package\.json$/.test(path);
222226 /** `Dockerfile`, `Containerfile` and `*.Dockerfile`, in any case. */
223227 const isDockerfileName = (path: string): boolean => /(^|\/)(Dockerfile|Containerfile|[^/]+\.Dockerfile)$/i.test(path);
224228
@@ -294,6 +298,7 @@ export function fileKind(path: string, head: Uint8Array): FileKind {
294298 if (isEnvExample(path)) return "env";
295299 if (isJunit(path, head)) return "junit";
296300 if (isOpenApiName(path)) return "openapi";
301 if (isPackageName(path)) return "package";
297302 if (isDockerfileName(path)) return "dockerfile";
298303 return TEXTUAL[extension(path)] ?? "text";
299304 }
@@ -311,6 +316,7 @@ export function kindByName(path: string): FileKind {
311316 if (isLcovName(path)) return "lcov";
312317 if (isEnvExample(path)) return "env";
313318 if (isOpenApiName(path)) return "openapi";
319 if (isPackageName(path)) return "package";
314320 if (isDockerfileName(path)) return "dockerfile";
315321 return MEDIA[ext]?.kind ?? TEXTUAL[ext] ?? "text";
316322 }
src/web/render/package-json.ts added +87
@@ -0,0 +1,87 @@
1 /**
2 * A `package.json` as its manifest: name and version, the facts in one line
3 * (`type`, `engines`, `license`), then scripts, dependencies, devDependencies
4 * and peer/optional dependencies as rows. Source is one tap away.
5 * Pure over the text; a file that is not a JSON object is not drawn at all
6 * (`parsePackage` returns undefined and the blob page keeps its source).
7 * Every cell is escaped by the template; at most `ROW_CAP` rows per section.
8 */
9
10 import { html, type Html } from "../html.ts";
11 import { fileSize } from "../ui.ts";
12 import type { Rendered, RenderInput } from "./renderers.ts";
13
14 export const ROW_CAP = 500;
15
16 export interface PackageSection {
17 readonly title: string;
18 /** Name and value (a command, or a version range), in the file's order. */
19 readonly rows: readonly (readonly [string, string])[];
20 /** Entries in the file, drawn or not. */
21 readonly total: number;
22 }
23
24 export interface PackageDoc {
25 readonly name: string;
26 readonly version: string;
27 readonly description: string;
28 /** `type: module`, `node >=20`, `MIT`: the one-line facts. */
29 readonly facts: readonly string[];
30 readonly sections: readonly PackageSection[];
31 }
32
33 const isObject = (v: unknown): v is Record<string, unknown> =>
34 typeof v === "object" && v !== null && !Array.isArray(v);
35 const str = (v: unknown): string => (typeof v === "string" ? v : "");
36
37 /** The string-valued entries of an object field; anything else is skipped. */
38 function section(title: string, v: unknown): PackageSection | undefined {
39 if (!isObject(v)) return undefined;
40 const all = Object.entries(v).filter((e): e is [string, string] => typeof e[1] === "string");
41 if (all.length === 0) return undefined;
42 return { title, rows: all.slice(0, ROW_CAP), total: all.length };
43 }
44
45 /** Read a manifest. Pure; never throws; undefined when the text is not a JSON object. */
46 export function parsePackage(source: string): PackageDoc | undefined {
47 let raw: unknown;
48 try {
49 raw = JSON.parse(source.replace(/^/, ""));
50 } catch {
51 return undefined;
52 }
53 if (!isObject(raw)) return undefined;
54 const facts: string[] = [];
55 if (typeof raw["type"] === "string") facts.push(`type ${raw["type"]}`);
56 if (isObject(raw["engines"]))
57 for (const [k, v] of Object.entries(raw["engines"])) if (typeof v === "string") facts.push(`${k} ${v}`);
58 if (typeof raw["license"] === "string") facts.push(raw["license"]);
59 if (typeof raw["packageManager"] === "string") facts.push(raw["packageManager"]);
60 const sections = [
61 section("Scripts", raw["scripts"]),
62 section("Dependencies", raw["dependencies"]),
63 section("Dev dependencies", raw["devDependencies"]),
64 section("Peer dependencies", raw["peerDependencies"]),
65 section("Optional dependencies", raw["optionalDependencies"]),
66 ].filter((s): s is PackageSection => s !== undefined);
67 return { name: str(raw["name"]), version: str(raw["version"]), description: str(raw["description"]), facts, sections };
68 }
69
70 export function packageJson(input: RenderInput): Rendered {
71 const doc = parsePackage(new TextDecoder().decode(input.body));
72 if (doc === undefined) return { content: html``, lines: 0, fallback: "This file is not a JSON object to draw." };
73 const scripts = (s: PackageSection): boolean => s.title === "Scripts";
74 const blocks: Html[] = doc.sections.map((s) => {
75 const rows = s.rows.map(([k, v]) =>
76 scripts(s)
77 ? html`<tr><th scope="row"><code>${k}</code></th><td><code>${v}</code></td></tr>`
78 : html`<tr><th scope="row">${k}</th><td class="num">${v}</td></tr>`,
79 );
80 const more = s.total - s.rows.length;
81 return html`<h3>${s.title}</h3><table class="table" data-dense aria-label="${s.title}"><thead><tr><th scope="col">Name</th><th scope="col">${scripts(s) ? "Command" : "Range"}</th></tr></thead><tbody>${rows}</tbody></table>${more > 0 ? html`<p class="muted small">${more.toLocaleString()} more not shown</p>` : html``}`;
82 });
83 const title = doc.name === "" ? "package.json" : doc.version === "" ? doc.name : `${doc.name} ${doc.version}`;
84 const content = html`<div class="package-view"><h2>${title}</h2>${doc.description !== "" ? html`<p>${doc.description}</p>` : html``}${doc.facts.length > 0 ? html`<p class="muted small">${doc.facts.join(" · ")}</p>` : html``}${blocks}</div>`;
85 const n = doc.sections.reduce((a, s) => a + s.total, 0);
86 return { content, lines: 0, summary: `${n.toLocaleString()} ${n === 1 ? "entry" : "entries"} · ${fileSize(input.size)}` };
87 }
src/web/render/renderers.ts +4 −1
@@ -28,6 +28,7 @@ import { log, hasEscape } from "./log.ts";
2828 import { markdown } from "./markdown.ts";
2929 import { model3d } from "./model3d.ts";
3030 import { notebook } from "./notebook.ts";
31 import { packageJson, parsePackage } from "./package-json.ts";
3132 import { patch } from "./patch.ts";
3233 import { pdf } from "./pdf.ts";
3334 import { dockerfile } from "./dockerfile.ts";
@@ -104,6 +105,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
104105 env: envView,
105106 sql: sqlView,
106107 openapi,
108 package: packageJson,
107109 dockerfile,
108110 mail: eml,
109111 archive,
@@ -154,7 +156,8 @@ export function rendererFor(
154156 // TOML as a form, and leaves the rest (INI, .env …) their source.
155157 // A log with no escape in it keeps the source view, exactly as plain text.
156158 const render =
157 (kind === "config" && !isFormConfig(path)) || (kind === "log" && blob.kind !== "too_large" && !hasEscape(blob.body))
159 (kind === "config" && !isFormConfig(path)) || (kind === "package" && blob.kind !== "too_large" && parsePackage(new TextDecoder().decode(blob.body)) === undefined) ||
160 (kind === "log" && blob.kind !== "too_large" && !hasEscape(blob.body))
158161 ? undefined
159162 : renderers[kind];
160163 if (render === undefined) return undefined;
test/render-openapi.test.ts +1 −1
@@ -27,7 +27,7 @@ describe("openapi", () => {
2727 expect(fileKind(p, enc("{}"))).toBe("openapi");
2828 expect(kindByName(p)).toBe("openapi");
2929 }
30 expect(fileKind("package.json", enc("{}"))).toBe("config");
30 expect(fileKind("tsconfig.json", enc("{}"))).toBe("config");
3131 expect(fileKind("myopenapi.json", enc("{}"))).toBe("config");
3232 expect(RENDERERS.openapi).toBe(openapi);
3333 });
test/render-package-json.test.ts added +57
@@ -0,0 +1,57 @@
1 import { describe, expect, test } from "bun:test";
2 import { packageJson, parsePackage, ROW_CAP } from "../src/web/render/package-json.ts";
3 import { fileKind, kindByName } from "../src/web/render/kinds.ts";
4 import { RENDERERS, rendererFor } from "../src/web/render/renderers.ts";
5
6 const enc = (s: string) => new TextEncoder().encode(s);
7 const draw = (text: string) => {
8 const body = enc(text);
9 const r = packageJson({ path: "package.json", size: body.length, body, media: "", download: "" });
10 return { html: String(r.content), summary: r.summary, fallback: r.fallback };
11 };
12 const MANIFEST = JSON.stringify({
13 name: "demo", version: "1.2.3", type: "module", engines: { node: ">=20" },
14 scripts: { test: "bun test", build: "<script>alert(1)</script>" },
15 dependencies: { hono: "^4.0.0" }, devDependencies: { typescript: "~5.4" },
16 });
17
18 describe("package.json", () => {
19 test("the registry names exactly package.json", () => {
20 expect(fileKind("package.json", enc("{}"))).toBe("package");
21 expect(fileKind("apps/web/package.json", enc("{}"))).toBe("package");
22 expect(kindByName("package.json")).toBe("package");
23 expect(fileKind("package-lock.json", enc("{}"))).toBe("config");
24 expect(fileKind("mypackage.json", enc("{}"))).toBe("config");
25 expect(RENDERERS.package).toBe(packageJson);
26 });
27 test("rows for scripts, dependencies with ranges, and the facts line", () => {
28 const h = draw(MANIFEST).html;
29 expect(h).toContain("demo 1.2.3");
30 expect(h).toContain("type module · node &gt;=20");
31 expect(h).toContain("<code>test</code></th><td><code>bun test</code>");
32 expect(h).toContain("hono");
33 expect(h).toContain("^4.0.0");
34 expect(h).toContain("Dev dependencies");
35 expect(h).toContain("~5.4");
36 });
37 test("every value is escaped", () => {
38 const h = draw(MANIFEST).html;
39 expect(h).not.toContain("<script>");
40 expect(h).toContain("&lt;script&gt;");
41 expect(draw('{"name":"<img src=x>"}').html).not.toContain("<img");
42 });
43 test("malformed JSON or a non-object keeps the source view, with no reason", () => {
44 expect(parsePackage("{ nope")).toBeUndefined();
45 expect(parsePackage("[1]")).toBeUndefined();
46 for (const bad of ["{ nope", "[]"]) {
47 const body = enc(bad);
48 expect(rendererFor("package.json", { kind: "text", body, size: body.length } as never)).toBeUndefined();
49 }
50 const body = enc(MANIFEST);
51 expect(rendererFor("package.json", { kind: "text", body, size: body.length } as never)?.render).toBe(packageJson);
52 });
53 test("cap per section", () => {
54 const deps = Object.fromEntries(Array.from({ length: ROW_CAP + 3 }, (_, i) => [`p${i}`, "1"]));
55 expect(draw(JSON.stringify({ dependencies: deps })).html).toContain("3 more not shown");
56 });
57 });
test/tui-workspace.test.ts +18
@@ -698,6 +698,24 @@ describe("the terminal workspace", () => {
698698 }
699699 });
700700
701 test("a package.json opens as rows of scripts and dependencies, and s flips to the source", async () => {
702 const made = await createRepo(forge, alice, { name: "pkgrepo", visibility: "public", description: "tests" });
703 if (!made.ok) throw new Error("repo failed");
704 await commitToBranch(forge, alice, made.value, { message: "seed", files: [{ path: "package.json", content: '{"name":"demo","scripts":{"test":"bun test"},"dependencies":{"hono":"^4.0.0"}}' }] });
705 const h = boot();
706 try {
707 await h.settle();
708 await open(h, "pkgrepo");
709 await openFile(h, "package.json");
710 expect(h.text()).toContain("Dependencies");
711 expect(h.text()).toContain("^4.0.0");
712 await h.press("s");
713 expect(h.text()).toContain('"name":"demo"');
714 } finally {
715 h.stop();
716 }
717 });
718
701719 test("a JUnit-named file that is not a report opens as source and says why", async () => {
702720 const made = await createRepo(forge, alice, { name: "badjunit", visibility: "public", description: "tests" });
703721 if (!made.ok) throw new Error("repo failed");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs