From 6404daf5e6d5e4d0612edf05194226319868f46c Mon Sep 17 00:00:00 2001 From: Sam Gammon Date: Sat, 21 Nov 2026 12:54:35 -0800 Subject: [PATCH 01/36] feat(apidocs): add the apidocs/1 renderer core, samples and dev loop @elide/apidocs turns the apidocs/1 model that Elide's Javadoc doclet and Dokka plugin write into static HTML and Markdown pages that work from file:// and inside a -javadoc.jar. This commit holds the parts that do not depend on the page layout: - schema/apidocs-1.schema.json, with src/model.ts generated from it (scripts/gen-types.ts, no dependencies). It adds an extension receiver and Kotlin default arguments beside the doclet's Java model. - render(model, theme): the site as a file map, and markdown.ts for the Markdown twins, llms.txt, llms-full.txt, api.json, element-list, the search index script and sitemap.xml. It also has the render-time highlighter, signature layout, sanitizer for raw nodes, link resolution, and the documentation-tree and declaration components. - Vite library builds of two classic IIFE scripts: dist/render.js (global ApiDocs) and assets/apidocs.js (client islands). Preact is inlined in both. - dist/runner.mjs, which runs render.js in Bun or Node over files and writes the site. The JVM tools ship it in their jars. - Hand-written Java and Kotlin sample models that cover every feature (samples/FEATURES.md maps each one to a page), including a generated type with hundreds of members. - `bun run dev`: a Vite dev server on 127.0.0.1:5180 that renders the samples, or a real model given with --model, through the same render() and reloads on edits. `bun run sample` builds a model through the runner and serves it or opens it from file://. The repository root exposes both as apidocs:dev and apidocs:sample. - Tests: schema validation of the samples and the doclet's fixture, snapshots, an output checker (absolute URLs, module scripts, fetch, missing files and anchors), and Playwright from file:// with JavaScript on and off plus axe in light and dark. The layout files (page shell and navigation, pages, groupings, client islands, stylesheet, theme and Elide preset) are being redesigned separately and land in a following commit, so this commit does not build or test on its own. Checks run before splitting, with every file in place: `bunx turbo run lint test --filter=@elide/apidocs` (tsc clean, 40 tests pass); `bun run build`; the runner on Bun and on Node gives byte-identical output for the fixture. --- .changeset/apidocs-package.md | 7 + bun.lock | 29 + package.json | 2 + packages/apidocs/README.md | 100 + packages/apidocs/package.json | 53 + packages/apidocs/samples/FEATURES.md | 59 + packages/apidocs/samples/build.ts | 272 + packages/apidocs/samples/index.ts | 8 + packages/apidocs/samples/java.ts | 344 + packages/apidocs/samples/kotlin.ts | 185 + packages/apidocs/schema/apidocs-1.schema.json | 412 ++ packages/apidocs/scripts/assets.ts | 20 + packages/apidocs/scripts/dev.ts | 199 + packages/apidocs/scripts/gen-artwork.ts | 38 + packages/apidocs/scripts/gen-types.ts | 79 + packages/apidocs/scripts/sample.ts | 83 + packages/apidocs/src/client/search.ts | 36 + .../apidocs/src/components/declaration.tsx | 217 + packages/apidocs/src/components/doc.tsx | 125 + packages/apidocs/src/context.ts | 20 + packages/apidocs/src/entry-render.ts | 6 + packages/apidocs/src/highlight.ts | 161 + packages/apidocs/src/index.ts | 6 + packages/apidocs/src/markdown.ts | 257 + packages/apidocs/src/model.ts | 343 + packages/apidocs/src/presets/elide-artwork.ts | 10 + packages/apidocs/src/render.tsx | 113 + packages/apidocs/src/runner.mjs | 68 + packages/apidocs/src/sanitize.ts | 15 + packages/apidocs/src/signature.ts | 62 + packages/apidocs/src/site.ts | 150 + packages/apidocs/test/browser.test.ts | 124 + packages/apidocs/test/check.ts | 82 + .../test/fixtures/fixture-java.api.json | 6551 +++++++++++++++++ packages/apidocs/test/render.test.ts | 154 + packages/apidocs/test/validate.ts | 68 + packages/apidocs/tsconfig.json | 18 + packages/apidocs/vite.client.config.ts | 5 + packages/apidocs/vite.render.config.ts | 6 + packages/apidocs/vite.shared.ts | 19 + turbo.json | 9 + 41 files changed, 10515 insertions(+) create mode 100644 .changeset/apidocs-package.md create mode 100644 packages/apidocs/README.md create mode 100644 packages/apidocs/package.json create mode 100644 packages/apidocs/samples/FEATURES.md create mode 100644 packages/apidocs/samples/build.ts create mode 100644 packages/apidocs/samples/index.ts create mode 100644 packages/apidocs/samples/java.ts create mode 100644 packages/apidocs/samples/kotlin.ts create mode 100644 packages/apidocs/schema/apidocs-1.schema.json create mode 100644 packages/apidocs/scripts/assets.ts create mode 100644 packages/apidocs/scripts/dev.ts create mode 100644 packages/apidocs/scripts/gen-artwork.ts create mode 100644 packages/apidocs/scripts/gen-types.ts create mode 100644 packages/apidocs/scripts/sample.ts create mode 100644 packages/apidocs/src/client/search.ts create mode 100644 packages/apidocs/src/components/declaration.tsx create mode 100644 packages/apidocs/src/components/doc.tsx create mode 100644 packages/apidocs/src/context.ts create mode 100644 packages/apidocs/src/entry-render.ts create mode 100644 packages/apidocs/src/highlight.ts create mode 100644 packages/apidocs/src/index.ts create mode 100644 packages/apidocs/src/markdown.ts create mode 100644 packages/apidocs/src/model.ts create mode 100644 packages/apidocs/src/presets/elide-artwork.ts create mode 100644 packages/apidocs/src/render.tsx create mode 100644 packages/apidocs/src/runner.mjs create mode 100644 packages/apidocs/src/sanitize.ts create mode 100644 packages/apidocs/src/signature.ts create mode 100644 packages/apidocs/src/site.ts create mode 100644 packages/apidocs/test/browser.test.ts create mode 100644 packages/apidocs/test/check.ts create mode 100644 packages/apidocs/test/fixtures/fixture-java.api.json create mode 100644 packages/apidocs/test/render.test.ts create mode 100644 packages/apidocs/test/validate.ts create mode 100644 packages/apidocs/tsconfig.json create mode 100644 packages/apidocs/vite.client.config.ts create mode 100644 packages/apidocs/vite.render.config.ts create mode 100644 packages/apidocs/vite.shared.ts diff --git a/.changeset/apidocs-package.md b/.changeset/apidocs-package.md new file mode 100644 index 0000000..1d0b45f --- /dev/null +++ b/.changeset/apidocs-package.md @@ -0,0 +1,7 @@ +--- +"@elide/apidocs": minor +--- + +Add `@elide/apidocs`: static HTML and Markdown API reference pages from the `apidocs/1` model that Elide's Javadoc +doclet and Dokka plugin write, with a JSON Schema, a classic-script renderer bundle and runner for JVM tools, client +islands, neutral and Elide theme presets, sample models and a hot-reload development loop. diff --git a/bun.lock b/bun.lock index 872db84..4ee5794 100644 --- a/bun.lock +++ b/bun.lock @@ -112,6 +112,29 @@ "vitest": "^5.1.0", }, }, + "packages/apidocs": { + "name": "@elide/apidocs", + "version": "0.0.0", + "bin": { + "apidocs": "./src/cli.ts", + }, + "dependencies": { + "@elide/brand": "workspace:*", + "@elide/tokens": "workspace:*", + "@fontsource-variable/instrument-sans": "^5.3.0", + "@fontsource-variable/inter": "^5.3.0", + "@fontsource-variable/jetbrains-mono": "^5.3.0", + "preact": "^11.2.0", + "preact-render-to-string": "^6.8.2", + }, + "devDependencies": { + "@types/bun": "^1.3.0", + "axe-core": "4.14.0", + "playwright": "^1.65.0", + "typescript": "^7.0.2", + "vite": "^8.3.6", + }, + }, "packages/brand": { "name": "@elide/brand", "version": "0.2.0", @@ -347,6 +370,8 @@ "@dotenvx/primitives": ["@dotenvx/primitives@0.8.0", "", {}, "sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg=="], + "@elide/apidocs": ["@elide/apidocs@workspace:packages/apidocs"], + "@elide/benchmark": ["@elide/benchmark@workspace:apps/benchmark"], "@elide/brand": ["@elide/brand@workspace:packages/brand"], @@ -909,6 +934,8 @@ "@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="], + "@types/bun": ["@types/bun@1.4.5", "", { "dependencies": { "bun-types": "1.4.5" } }, "sha512-DpgwNI9z0L1S0gtb45QLCWgwCUcMLnsHYMJHQvpNj7erGiCGBvpggltAIeARrtobNMKMuy0UP7i56tKKgwFs/Q=="], + "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], @@ -1083,6 +1110,8 @@ "browserslist": ["browserslist@4.29.5", "", { "dependencies": { "baseline-browser-mapping": "^2.11.33", "caniuse-lite": "^1.0.30001819", "electron-to-chromium": "^1.5.464", "node-releases": "^2.0.60", "update-browserslist-db": "^1.3.4" }, "bin": { "browserslist": "cli.js" } }, "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ=="], + "bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + "bundle-name": ["bundle-name@4.1.1", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA=="], "bundle-require": ["bundle-require@5.1.0", "", { "dependencies": { "load-tsconfig": "^0.2.3" }, "peerDependencies": { "esbuild": ">=0.18" } }, "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA=="], diff --git a/package.json b/package.json index 7f10dd7..1e6a231 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,8 @@ "scripts": { "build": "turbo run build", "dev": "turbo run dev", + "apidocs:dev": "bun run --cwd packages/apidocs dev", + "apidocs:sample": "bun run --cwd packages/apidocs sample", "lint": "turbo run lint", "test": "turbo run test", "test:preact": "turbo run test --filter=@elide/preact", diff --git a/packages/apidocs/README.md b/packages/apidocs/README.md new file mode 100644 index 0000000..27ce9a7 --- /dev/null +++ b/packages/apidocs/README.md @@ -0,0 +1,100 @@ +# @elide/apidocs + +Static API reference pages, as HTML and Markdown, from the `apidocs/1` model that Elide's Javadoc doclet and Dokka +plugin write. Pages are prerendered with Preact. They work from `file://`, from any path prefix and inside a +`-javadoc.jar`. Branding is a theme input; the package's own components carry none. + +## What it builds + +`bun run build` writes `dist/`: + +| File | What it is | +| --- | --- | +| `render.js` | One classic script (IIFE) that defines the global `ApiDocs = { schema, render }`. Preact and the highlighter are inlined. `render(model, theme)` is a pure function: no file, network, Node, Bun or DOM API. | +| `runner.mjs` | Runs `render.js` in Bun or Node and writes the site. The JVM tools ship it with `render.js` and `assets/`. | +| `assets/` | `apidocs.css`, `apidocs.js` (the client islands, Preact inlined, loaded with `defer`) and the fonts the Elide preset uses. | +| `apidocs-1.schema.json` | The model's JSON Schema. `src/model.ts` is generated from it. | + +```sh +node dist/runner.mjs --bundle dist/render.js --assets dist/assets --model api.json --theme theme.json --out site/ +``` + +The runner prints `{"files":N,"bytes":N,"renderMs":N}` and exits 0, or prints the error and exits 1. It never reaches +the network. + +## Output + +Every page has an `.html` and an `.md` twin: `index`, `/index` and `/`, with nested +types as `Outer.Inner`. The root also holds `llms.txt`, `llms-full.txt`, `api.json`, `element-list` and `assets/`. +With a theme `baseUrl` it also has `sitemap.xml`, and pages carry canonical links. Every link is relative and names +its file. Scripts are classic. Search reads `assets/search-index.js`, which assigns a global, so nothing uses `fetch`. +With JavaScript off, pages keep all their content; only search, the theme switch, copy buttons and table-of-contents +tracking go away. + +## Themes + +A theme is JSON: + +```json +{ + "extends": "elide", + "productName": "Komodo", + "links": { "header": [{ "label": "GitHub", "url": "https://github.com/elide-dev/komodo" }] }, + "sourceLink": "https://github.com/elide-dev/komodo/blob/{ref}/{path}#L{line}", + "sourceRef": "main", + "baseUrl": "https://example.com/api/", + "tokens": { "light": { "accent": "#6d28d9" }, "dark": { "accent": "#c4b5fd" } }, + "css": ".member { scroll-margin-top: 80px; }" +} +``` + +The stylesheet reads only `--apidocs-*` custom properties; `tokens` sets them without the prefix (see the top of +`src/styles/apidocs.css` for the names). `extends` picks a preset. `neutral` is the default and is unbranded. +`elide` maps the tokens to `@elide/tokens` and takes its logo from `@elide/brand`. A theme can also set `logo` +(SVG markup for light and dark), `favicon`, `fonts` and `footer`. + +## Development + +From this directory (or from the repository root with `bun run apidocs:dev` and `bun run apidocs:sample`): + +```sh +bun run dev # http://127.0.0.1:5180/, opens the browser +bun run dev --port 5190 --no-open +bun run dev --model ../../../../../bazel-bin/tools/release/komodo-api-api.json # a real model +``` + +The dev server renders pages with the production `render()` and the same components, under +`/site///`. Editing a component, the stylesheet, a theme preset, a sample or the `--model` file +reloads the page. In dev, the islands run as a module; the built pages load the `defer` bundle instead. The bar at the +top is for development only and is not part of any output. It switches the model (Java sample, Kotlin sample, the +`--model` file), the theme preset, light or dark, the viewport width, and JavaScript off for the current page. + +To check the portable output in the same loop, build it exactly as the doclet will: + +```sh +bun run sample # the Java sample, neutral theme, into dist/sample/java-neutral/ +bun run sample --sample kotlin --preset elide --open # opens it from file:// +bun run sample --model path/to/api.json --serve # serves it on http://127.0.0.1:5181/ +bun run sample --runtime node # run the runner with Node instead of Bun +``` + +It runs `bun run build` first (`--no-build` skips that), then `dist/runner.mjs`, and prints the `file://` URL. + +### The samples + +`samples/java.ts` and `samples/kotlin.ts` are hand-written models in the doclet's and the Dokka plugin's flavors. +One generated type has hundreds of members. [`samples/FEATURES.md`](samples/FEATURES.md) lists each feature and the +page that shows it, and says how to add one. + +## Tests + +`bun test` (turbo runs `build` first): + +- the samples and the Komodo doclet's fixture model (`test/fixtures/fixture-java.api.json`) validate against the + schema; `src/model.ts` and the Elide artwork module are current; +- HTML and Markdown snapshots of the fixture's pages; +- the output checker (`test/check.ts`) over every model and preset: no absolute URLs other than the model's externals + and theme links, no module scripts, no `fetch`, and no link to a missing file or anchor; +- in Chromium, a site built with `dist/runner.mjs` opened from `file://` with JavaScript on and off, and axe on the + page shell in light and dark. Locally, point `PLAYWRIGHT_BROWSERS_PATH` at a Playwright 1.65 browser directory, or + install one with `bunx playwright install chromium`. diff --git a/packages/apidocs/package.json b/packages/apidocs/package.json new file mode 100644 index 0000000..e8c1857 --- /dev/null +++ b/packages/apidocs/package.json @@ -0,0 +1,53 @@ +{ + "name": "@elide/apidocs", + "version": "0.0.0", + "private": true, + "description": "Static API reference pages (HTML and Markdown) from the apidocs/1 model that Elide's Javadoc doclet and Dokka plugin write. Prerendered with Preact; works from file:// and inside a -javadoc.jar.", + "license": "UNLICENSED", + "type": "module", + "sideEffects": false, + "exports": { + ".": "./src/index.ts", + "./schema": "./schema/apidocs-1.schema.json", + "./render.js": "./dist/render.js", + "./assets/*": "./dist/assets/*" + }, + "bin": { + "apidocs": "./src/cli.ts" + }, + "files": [ + "dist", + "schema", + "src", + "README.md" + ], + "scripts": { + "build": "bun scripts/gen-types.ts --check && bun scripts/gen-artwork.ts --check && vite build --config vite.render.config.ts && vite build --config vite.client.config.ts && bun scripts/assets.ts", + "dev": "bun scripts/dev.ts", + "sample": "bun scripts/sample.ts", + "generate": "bun scripts/gen-types.ts && bun scripts/gen-artwork.ts", + "lint": "tsc -p tsconfig.json --noEmit", + "test": "bun test" + }, + "dependencies": { + "@elide/brand": "workspace:*", + "@elide/tokens": "workspace:*", + "@fontsource-variable/instrument-sans": "^5.3.0", + "@fontsource-variable/inter": "^5.3.0", + "@fontsource-variable/jetbrains-mono": "^5.3.0", + "preact": "^11.2.0", + "preact-render-to-string": "^6.8.2" + }, + "devDependencies": { + "@types/bun": "^1.3.0", + "axe-core": "4.14.0", + "playwright": "^1.65.0", + "typescript": "^7.0.2", + "vite": "^8.3.6" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/elide-dev/components.git", + "directory": "packages/apidocs" + } +} diff --git a/packages/apidocs/samples/FEATURES.md b/packages/apidocs/samples/FEATURES.md new file mode 100644 index 0000000..f5721fd --- /dev/null +++ b/packages/apidocs/samples/FEATURES.md @@ -0,0 +1,59 @@ +# Sample features + +Each feature the renderer supports, and the sample page that shows it. Paths are relative to the site root. Open +them with `bun run dev` (pick the sample in the dev bar) or `bun run sample`. `java` is `samples/java.ts`, the +doclet's flavor. `kotlin` is `samples/kotlin.ts`, the Dokka plugin's flavor. `render.test.ts` validates both against +`schema/apidocs-1.schema.json` and runs the output checker over both. + +| Feature | Sample | Page | +| --- | --- | --- | +| Module overview, packages table, all-types table | java, kotlin | `index.html` | +| Package description with a heading and a see-also link | java | `com/example/geo/index.html` | +| Several packages with descriptions | java, kotlin | `index.html` | +| Empty package | java, kotlin | `com/example/geo/spi/index.html`, `org/example/kgeo/internal/index.html` | +| Class, abstract class, final class | java | `com/example/geo/Polygon.html`, `AbstractShape.html`, `Shapes.html` | +| Interface; sealed interface with permitted subtypes | java | `com/example/geo/Shape.html` | +| Record with documented components (`#param-radius`) | java | `com/example/geo/Circle.html` | +| Enum with a deprecated constant | java, kotlin | `com/example/geo/Units.html`, `org/example/kgeo/LengthUnit.html` | +| Annotation interface with element defaults | java, kotlin | `com/example/geo/Measured.html`, `org/example/kgeo/experimental/ExperimentalGeometry.html` | +| Exception (grouped under Exceptions) | java | `com/example/geo/GeometryException.html` | +| Nested types, two levels deep, in breadcrumbs and navigation | java | `com/example/geo/Shapes.Builder.Option.html` | +| Generics with bounds and wildcards | java | `com/example/geo/Shapes.html#largest(java.util.Collection)` | +| Constructors | java, kotlin | `com/example/geo/Circle.html`, `org/example/kgeo/Point.html` | +| Overloads | java, kotlin | `Shapes.html` `area(Circle)` and `area(Polygon)`; `org/example/kgeo/Geometry.html` `distance` | +| Fields and constants | java, kotlin | `Shapes.html#PRECISION`; `org/example/kgeo/index.html#VERSION` | +| Varargs | java | `Shapes.html#total(com.example.geo.Shape...)`, `Polygon.html` constructor | +| Parameters, returns and throws (declared and unchecked) | java | `Shapes.html#parse(java.lang.String)` | +| API note, implementation requirements and implementation note callouts | java | `Shapes.html#parse(java.lang.String)`, `Shape.html` | +| Deprecated with a replacement link, and deprecated for removal | java, kotlin | `Shapes.html#sum(java.util.List)`, `com/example/geo/LegacyShape.html`, `org/example/kgeo/index.html#totalArea(List)` | +| Since badges | java, kotlin | most pages | +| Nullability badges (JSpecify and Kotlin `?`) | java, kotlin | `Shapes.html#find(java.util.Map,java.lang.String)`, `org/example/kgeo/index.html#parseShape(String)` | +| Null-marked badge | java | `com/example/geo/index.html` | +| Inherited members | java | `com/example/geo/Polygon.html#inherited-members` | +| Inherited description ("copied from") | java | `com/example/geo/Polygon.html#area()` | +| See-also: declaration link, labeled link, plain text, URL | java | `com/example/geo/Shapes.html` (type description) | +| Internal and external links (JDK, Kotlin stdlib) | java, kotlin | signatures on every page | +| Unresolved link rendered as plain code | java, kotlin | `Shapes.html#describe(com.example.geo.Shape)`, `org/example/kgeo/coroutines/index.html` `watchShapes` | +| Code samples in Java and Kotlin | java, kotlin | `Shapes.html` description; `org/example/kgeo/coroutines/index.html` | +| Tables, ordered and unordered lists, block quote | java | `Shapes.html` description | +| Raw HTML node (block and inline) | java | `Shapes.html` description (`
`) and `describe` (``) | +| Very long signature, one parameter per line | java | `Shapes.html` `transform` | +| A type with hundreds of members (generated) | java | `com/example/geo/registry/ShapeCatalog.html` | +| Top-level functions and properties | kotlin | `org/example/kgeo/index.html` | +| Extension function and property with a receiver | kotlin | `org/example/kgeo/index.html` `scaled` and `isDegenerate` | +| Object and companion object | kotlin | `org/example/kgeo/Geometry.html`, `org/example/kgeo/Circle.Companion.html` | +| Data, sealed, value and enum classes | kotlin | `Circle.html`, `Shape.html`, `Meters.html`, `LengthUnit.html` under `org/example/kgeo/` | +| Suspend function | kotlin | `org/example/kgeo/coroutines/index.html` `loadShapes` | +| Inline function with a reified type parameter | kotlin | `org/example/kgeo/Geometry.html` `filterShapes` | +| Operator function | kotlin | `org/example/kgeo/Meters.html` `plus` | +| Type aliases | kotlin | `org/example/kgeo/index.html#type-aliases` | +| Default arguments | kotlin | `org/example/kgeo/Point.html`, `scaled` | +| Markdown twin, `llms.txt`, `llms-full.txt`, `api.json`, `element-list` | java, kotlin | site root; `.md` beside every page | + +## Adding a feature + +1. Add the declaration to `samples/java.ts` or `samples/kotlin.ts` (or both), with the builders in `samples/build.ts`. + Write what the doclet or the Dokka plugin would emit; when the model needs a new field, change + `schema/apidocs-1.schema.json` first and run `bun run generate`. +2. Add a row above naming the page that shows it. +3. Run `bun test`: the samples must validate against the schema and pass the output checker. diff --git a/packages/apidocs/samples/build.ts b/packages/apidocs/samples/build.ts new file mode 100644 index 0000000..b8b6a0b --- /dev/null +++ b/packages/apidocs/samples/build.ts @@ -0,0 +1,272 @@ +/** + * Builders for the hand-written sample models. They produce exactly what the + * doclet (Java) and the Dokka plugin (Kotlin) write: signatures as tokens, + * documentation as trees. `md` turns a short marked-up string into inlines: + * `code`, *emphasis*, **strong**, [[id]] or [[id|label]] for a declaration + * link, [label](url) for a URL link. + */ +import type { Block, Deprecation, Doc, Inline, Member, Note, Param, Ref, Token, Type, TypeParam } from "../src/model"; + +// ---- Tokens. + +export const kw = (text: string): Token => ({ kind: "keyword", text }); +export const nm = (text: string): Token => ({ kind: "name", text }); +export const pu = (text: string): Token => ({ kind: "punct", text }); +export const tp = (text: string): Token => ({ kind: "typeParam", text }); +export const lit = (text: string): Token => ({ kind: "literal", text }); +export const prm = (text: string): Token => ({ kind: "param", text }); +export function ty(text: string, ref?: string, url?: string): Token { + return { kind: "type", text, ...(ref ? { ref } : {}), ...(url ? { url } : {}) }; +} +export function an(text: string, ref?: string, url?: string): Token { + return { kind: "annotation", text, ...(ref ? { ref } : {}), ...(url ? { url } : {}) }; +} + +/** Tokens from parts; strings are punctuation, and adjacent punctuation merges. */ +export function tk(...parts: (Token | Token[] | string)[]): Token[] { + const out: Token[] = []; + for (const part of parts.flat()) { + const token = typeof part === "string" ? pu(part) : part; + const last = out[out.length - 1]; + if (token.kind === "punct" && last?.kind === "punct") out[out.length - 1] = pu(last.text + token.text); + else if (token.text) out.push(token); + } + return out; +} + +export const JDK = "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/"; +export const KOTLIN = "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/"; +export const jdk = (pkg: string, name: string) => ty(name, `${pkg}.${name}`, `${JDK}${pkg.replace(/\./g, "/")}/${name}.html`); +export const kt = (name: string) => ty(name, `kotlin/${name}///PointingToDeclaration/`, `${KOTLIN}-${name.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`).slice(1)}/`); + +// ---- Documentation. + +export function md(text: string): Inline[] { + const out: Inline[] = []; + const re = /`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*|\[\[([^\]|]+)(?:\|([^\]]+))?\]\]|\[([^\]]+)\]\(([^)]+)\)/g; + let at = 0; + for (const m of text.matchAll(re)) { + if (m.index! > at) out.push({ kind: "text", text: text.slice(at, m.index) }); + if (m[1]) out.push({ kind: "code", text: m[1] }); + else if (m[2]) out.push({ kind: "strong", children: md(m[2]) }); + else if (m[3]) out.push({ kind: "emphasis", children: md(m[3]) }); + else if (m[4]) { + const label = m[5] ?? linkLabel(m[4]); + out.push({ kind: "link", target: { id: m[4] }, code: true, children: [{ kind: "text", text: label }] }); + } else out.push({ kind: "link", url: m[7]!, children: md(m[6]!) }); + at = m.index! + m[0].length; + } + if (at < text.length) out.push({ kind: "text", text: text.slice(at) }); + return out; +} + +/** The label {@link} would show: Type, Type.member(Simple, Types), or a Kotlin DRI's last name. */ +function linkLabel(id: string): string { + if (id.includes("/")) return id.split("/").filter(Boolean).filter(p => p !== "PointingToDeclaration" && !p.startsWith("#"))[1] ?? id; + const [owner, member] = id.split("#"); + const type = owner!.slice(owner!.lastIndexOf(".") + 1).replace(/\$/g, "."); + if (!member) return /^[a-z]/.test(type) ? owner! : type; + const simple = member.replace(/\(([^)]*)\)/, (_, ps: string) => `(${ps.split(",").filter(Boolean).map(p => p.slice(p.lastIndexOf(".") + 1)).join(", ")})`); + return `${type}.${simple}`; +} + +export const P = (text: string): Block => ({ kind: "paragraph", children: md(text) }); +export const UL = (...items: (string | Block[])[]): Block => ({ kind: "list", items: items.map(i => (typeof i === "string" ? [P(i)] : i)) }); +export const OL = (...items: string[]): Block => ({ kind: "list", ordered: true, items: items.map(i => [P(i)]) }); +export const CODE = (language: string | undefined, text: string): Block => ({ kind: "code", ...(language ? { language } : {}), text }); +export const H = (level: number, text: string): Block => ({ kind: "heading", level, children: md(text) }); +export const QUOTE = (text: string): Block => ({ kind: "quote", children: [P(text)] }); +export const RAW = (html: string, text: string): Block => ({ kind: "raw", html, text }); +export function TABLE(caption: string, head: string[], rows: string[][]): Block { + return { kind: "table", caption: md(caption), head: [head.map(h => [P(h)])], rows: rows.map(r => r.map(c => [P(c)])) }; +} + +export interface DocSpec { + body?: string | Block[]; + notes?: [Note["kind"], string | Block[]][]; + see?: (string | Inline[])[]; + inheritedFrom?: Ref; +} + +/** A doc tree; the summary is the body's first sentence. */ +export function doc(spec: DocSpec | string): Doc { + const s = typeof spec === "string" ? { body: spec } : spec; + const body = typeof s.body === "string" ? s.body.split("\n\n").map(P) : (s.body ?? []); + const first = body[0]; + let summary: Inline[] = []; + if (first?.kind === "paragraph") { + for (const node of first.children ?? []) { + if (node.kind === "text" && /\.(\s|$)/.test(node.text)) { + summary.push({ kind: "text", text: node.text.slice(0, node.text.search(/\.(\s|$)/) + 1) }); + break; + } + summary.push(node); + } + } + return { + ...(summary.length ? { summary } : {}), + ...(body.length ? { body } : {}), + ...(s.notes?.length ? { notes: s.notes.map(([kind, b]) => ({ kind, body: typeof b === "string" ? [P(b)] : b })) } : {}), + ...(s.see?.length ? { see: s.see.map(e => (typeof e === "string" ? md(e) : e)) } : {}), + ...(s.inheritedFrom ? { inheritedFrom: s.inheritedFrom } : {}), + }; +} + +export const blocks = (text: string): Block[] => text.split("\n\n").map(P); +export const deprecated = (text: string, since?: string, forRemoval?: boolean): Deprecation => ({ + doc: blocks(text), ...(since ? { since } : {}), ...(forRemoval ? { forRemoval } : {}), +}); + +// ---- Members. + +export interface ParamSpec { + name: string; + type: Token[]; + doc?: string; + varargs?: boolean; + nullness?: Param["nullness"]; + defaultValue?: string; + annotations?: Token[][]; +} + +export interface MemberSpec { + name: string; + kind?: Member["kind"]; + mods?: string[]; + annotations?: Token[][]; + typeParams?: { name: string; bounds?: Token[][]; doc?: string }[]; + receiver?: ParamSpec; + params?: ParamSpec[]; + returns?: { type: Token[]; doc?: string; nullness?: Param["nullness"] }; + type?: Token[]; + nullness?: Param["nullness"]; + throws?: { type: Token[]; doc?: string; declared?: boolean }[]; + constant?: string; + defaultValue?: string; + overrides?: Ref; + implicit?: boolean; + doc?: DocSpec | string; + deprecated?: Deprecation; + since?: string; + line?: number; + file?: string; +} + +function params(list: ParamSpec[] | undefined): Param[] { + return (list ?? []).map(p => ({ + name: p.name, type: p.type, + ...(p.varargs ? { varargs: true } : {}), + ...(p.defaultValue ? { defaultValue: p.defaultValue } : {}), + ...(p.nullness ? { nullness: p.nullness } : {}), + ...(p.annotations ? { annotations: p.annotations } : {}), + ...(p.doc ? { doc: blocks(p.doc) } : {}), + })); +} + +function typeParams(list: MemberSpec["typeParams"]): TypeParam[] { + return (list ?? []).map(t => ({ name: t.name, ...(t.bounds ? { bounds: t.bounds } : {}), ...(t.doc ? { doc: blocks(t.doc) } : {}) })); +} + +function typeParamTokens(list: MemberSpec["typeParams"], keyword: string): Token[] { + if (!list?.length) return []; + return tk("<", ...list.flatMap((t, i) => [ + ...(i ? [pu(", ")] : []), tp(t.name), + ...(t.bounds?.length ? [pu(` ${keyword} `), ...t.bounds.flatMap((b, j) => [...(j ? [pu(" & ")] : []), ...b])] : []), + ]), ">"); +} + +/** The JDK doclet's anchor: the name and erased parameter types. */ +function javaAnchor(spec: MemberSpec): string { + if (spec.kind === "field" || spec.kind === "enumConstant") return spec.name; + const name = spec.kind === "constructor" ? "" : spec.name; + const types = (spec.params ?? []).map(p => { + const head = p.type.find(t => t.kind === "type" || t.kind === "typeParam" || t.kind === "keyword")!; + const base = head.kind === "type" && head.ref ? head.ref.replace(/\$/g, ".") : head.text; + const array = p.type.some(t => t.kind === "punct" && t.text.includes("[]")); + return base + (p.varargs ? "..." : array ? "[]" : ""); + }); + return `${name}(${types.join(",")})`; +} + +function base(owner: string, spec: MemberSpec, anchor: string, id: string, signature: Token[], kind: Member["kind"]): Member { + return { + id, anchor, kind, name: spec.name, + ...(spec.mods?.length ? { modifiers: spec.mods } : {}), + ...(spec.annotations?.length ? { annotations: spec.annotations } : {}), + ...(spec.typeParams?.length ? { typeParams: typeParams(spec.typeParams) } : {}), + ...(spec.receiver ? { receiver: params([spec.receiver])[0] } : {}), + signature, + ...(spec.params?.length ? { params: params(spec.params) } : {}), + ...(spec.returns ? { returns: { type: spec.returns.type, ...(spec.returns.nullness ? { nullness: spec.returns.nullness } : {}), ...(spec.returns.doc ? { doc: blocks(spec.returns.doc) } : {}) } } : {}), + ...(spec.type ? { type: spec.type } : {}), + ...(spec.nullness ? { nullness: spec.nullness } : {}), + ...(spec.throws?.length ? { throws: spec.throws.map(t => ({ type: t.type, ...(t.declared ? { declared: true } : {}), ...(t.doc ? { doc: blocks(t.doc) } : {}) })) } : {}), + ...(spec.constant ? { constant: spec.constant } : {}), + ...(spec.defaultValue ? { defaultValue: spec.defaultValue } : {}), + ...(spec.overrides ? { overrides: spec.overrides } : {}), + ...(spec.implicit ? { implicit: true } : {}), + ...(spec.doc ? { doc: doc(spec.doc) } : {}), + ...(spec.deprecated ? { deprecated: spec.deprecated } : {}), + ...(spec.since ? { since: spec.since } : {}), + ...(spec.line ? { source: { path: spec.file ?? owner.replace(/\$.*/, "").replace(/\./g, "/") + ".java", line: spec.line } } : {}), + }; +} + +/** A Java member, as the doclet writes it. */ +export function javaMember(owner: string, ownerName: string, spec: MemberSpec): Member { + const kind = spec.kind ?? "method"; + const sig: (Token | Token[] | string)[] = []; + for (const mod of spec.mods ?? []) sig.push(kw(mod), " "); + if (kind === "enumConstant") sig.push(nm(spec.name)); + else if (kind === "field") sig.push(spec.type!, " ", nm(spec.name)); + else { + const tps = typeParamTokens(spec.typeParams, "extends"); + if (tps.length) sig.push(tps, " "); + if (kind !== "constructor") sig.push(spec.returns?.type ?? [kw("void")], " "); + sig.push(nm(kind === "constructor" ? ownerName.split(".").pop()! : spec.name), "("); + (spec.params ?? []).forEach((p, i) => { + if (i) sig.push(", "); + for (const a of p.annotations ?? []) sig.push(a, " "); + sig.push(p.type, " ", prm(p.name)); + }); + sig.push(")"); + if (spec.defaultValue) sig.push(" ", kw("default"), " ", lit(spec.defaultValue)); + const declared = (spec.throws ?? []).filter(t => t.declared); + if (declared.length) sig.push(" ", kw("throws"), " ", ...declared.flatMap((t, i) => [...(i ? [", "] : []), t.type])); + } + const anchor = javaAnchor({ ...spec, kind }); + return base(owner, { ...spec, file: spec.file }, anchor, `${owner}#${anchor}`, tk(...sig), kind); +} + +/** A Kotlin member, as the Dokka plugin writes it: ids are DRIs, anchors are readable names. */ +export function kotlinMember(owner: string, spec: MemberSpec): Member { + const kind = spec.kind ?? "function"; + const sig: (Token | Token[] | string)[] = []; + for (const mod of spec.mods ?? []) sig.push(kw(mod), " "); + sig.push(kw(kind === "property" ? (spec.mods?.includes("var") ? "" : "val") : kind === "constructor" ? "constructor" : "fun")); + if (kind !== "constructor") sig.push(" "); + const tps = typeParamTokens(spec.typeParams, ":"); + if (tps.length) sig.push(tps, " "); + if (spec.receiver) sig.push(spec.receiver.type, "."); + if (kind !== "constructor") sig.push(nm(spec.name)); + if (kind === "property") sig.push(": ", spec.type!); + else { + sig.push("("); + (spec.params ?? []).forEach((p, i) => { + if (i) sig.push(", "); + if (p.varargs) sig.push(kw("vararg"), " "); + sig.push(prm(p.name), ": ", p.type); + if (p.defaultValue) sig.push(" = ", lit(p.defaultValue)); + }); + sig.push(")"); + if (spec.returns) sig.push(": ", spec.returns.type); + } + const anchor = kind === "property" ? spec.name : `${spec.name}(${(spec.params ?? []).map(p => p.type.map(t => t.text).join("")).join(",")})`; + const id = `${owner}/${spec.name}/${spec.receiver ? spec.receiver.type.map(t => t.text).join("") : ""}#${(spec.params ?? []).map(p => p.type.map(t => t.text).join("")).join("#")}/PointingToDeclaration/`; + return base(owner, { ...spec, file: spec.file ?? `${owner.split("/")[0]!.replace(/\./g, "/")}/${(owner.split("/")[1] || "Top")}.kt` }, anchor, id, tk(...sig.filter(s => s !== "")), kind); +} + +/** A type: fills the defaults every type needs. */ +export function type(t: Partial & Pick, language = "java"): Type { + return { language, ...t } as Type; +} diff --git a/packages/apidocs/samples/index.ts b/packages/apidocs/samples/index.ts new file mode 100644 index 0000000..497539f --- /dev/null +++ b/packages/apidocs/samples/index.ts @@ -0,0 +1,8 @@ +/** The sample models, as plain JSON values (exactly what a doclet or plugin would write). */ +import type { Model } from "../src/model"; +import { javaSample } from "./java"; +import { kotlinSample } from "./kotlin"; + +const plain = (model: Model): Model => JSON.parse(JSON.stringify(model)); + +export const samples: Record<"java" | "kotlin", Model> = { java: plain(javaSample), kotlin: plain(kotlinSample) }; diff --git a/packages/apidocs/samples/java.ts b/packages/apidocs/samples/java.ts new file mode 100644 index 0000000..f4004a0 --- /dev/null +++ b/packages/apidocs/samples/java.ts @@ -0,0 +1,344 @@ +/** + * The Java-flavored sample: what the Javadoc doclet writes for a small + * geometry library. Hand-written, except the generated Registry type with + * hundreds of members. samples/FEATURES.md lists what each page shows. + */ +import type { Member, Model, Package, Type } from "../src/model"; +import { + an, blocks, CODE, deprecated, doc, H, jdk, javaMember, kw, lit, nm, OL, P, QUOTE, RAW, TABLE, tk, tp, ty, type, UL, +} from "./build"; + +const G = "com.example.geo"; +const IO = "com.example.geo.io"; +const BIG = "com.example.geo.registry"; +const EMPTY = "com.example.geo.spi"; + +const t = (name: string, pkg = G) => ty(name.replace(/\$/g, "."), `${pkg}.${name}`); +const STRING = jdk("java.lang", "String"); +const OBJECT = jdk("java.lang", "Object"); +const DOUBLE = kw("double"); +const INT = kw("int"); +const NULLABLE = an("@Nullable", "org.jspecify.annotations.Nullable", "https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"); +const objectRef = { id: "java.lang.Object", url: `https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html` }; +const objectMembers = ["equals(java.lang.Object)", "getClass()", "hashCode()", "notify()", "notifyAll()", "toString()", "wait()", "wait(long)", "wait(long,int)"] + .map(a => ({ id: `java.lang.Object#${a}`, text: a.replace(/\(.*/, ""), url: `${objectRef.url}#${a}` })); +const fromObject = { from: { ...objectRef, text: "Object" }, kind: "class", members: objectMembers }; + +const m = (owner: string, spec: Parameters[2]) => javaMember(owner, owner.slice(owner.lastIndexOf(".") + 1).replace(/\$/g, "."), spec); + +// ---- com.example.geo + +const shape: Type = type({ + id: `${G}.Shape`, name: "Shape", kind: "interface", modifiers: ["public", "sealed"], + signature: tk(kw("public"), " ", kw("sealed"), " ", kw("interface"), " ", nm("Shape"), " ", kw("extends"), " ", jdk("java.lang", "Comparable"), "<", t("Shape"), "> ", kw("permits"), " ", t("Circle"), ", ", t("Polygon")), + interfaces: [tk(jdk("java.lang", "Comparable"), "<", t("Shape"), ">")], + permits: [{ id: `${G}.Circle` }, { id: `${G}.Polygon` }], + members: [ + m(`${G}.Shape`, { name: "area", returns: { type: [DOUBLE], doc: "the area in square meters, never negative" }, doc: "The shape's area.", line: 24 }), + m(`${G}.Shape`, { + name: "compareTo", mods: ["default"], params: [{ name: "other", type: [t("Shape")], nullness: "nonNull", doc: "the shape to compare with" }], + returns: { type: [INT], doc: "a negative number, zero or a positive number as this shape is smaller, equal or larger" }, + doc: { body: "Compares shapes by area.", notes: [["implSpec", "The default compares `area()` with `Double.compare`."]] }, line: 31, + }), + m(`${G}.Shape`, { name: "name", mods: ["default"], returns: { type: tk(NULLABLE, " ", STRING), nullness: "nullable", doc: "the name, or `null` for an anonymous shape" }, doc: "Returns the shape's name, or `null` for an anonymous shape.", since: "1.1", line: 40 }), + ], + doc: doc({ + body: [P("A closed plane figure."), P("Every shape reports its area in square [[com.example.geo.Units#METERS|meters]]. Shapes order by area, so a `List` sorts from smallest to largest.")], + notes: [["apiNote", "The hierarchy is **sealed**: only [[com.example.geo.Circle]] and [[com.example.geo.Polygon]] implement it, so a `switch` over a shape is exhaustive."]], + }), + since: "1.0", nullMarked: true, source: { path: "com/example/geo/Shape.java", line: 18 }, +}); + +const circle: Type = type({ + id: `${G}.Circle`, name: "Circle", kind: "record", modifiers: ["public"], + signature: tk(kw("public"), " ", kw("record"), " ", nm("Circle"), "(", DOUBLE, " ", { kind: "param", text: "radius" }, ", ", NULLABLE, " ", STRING, " ", { kind: "param", text: "label" }, ") ", kw("implements"), " ", t("Shape")), + superclass: [jdk("java.lang", "Record")], ancestors: [{ id: "java.lang.Record", url: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html" }, objectRef], + interfaces: [[t("Shape")]], + components: [ + { name: "radius", type: [DOUBLE], doc: blocks("the radius in meters; not negative") }, + { name: "label", type: tk(NULLABLE, " ", STRING), nullness: "nullable", doc: blocks("an optional label shown by [[com.example.geo.Shape#name()]]") }, + ], + members: [ + m(`${G}.Circle`, { name: "Circle", kind: "constructor", mods: ["public"], params: [{ name: "radius", type: [DOUBLE], doc: "the radius in meters; not negative" }, { name: "label", type: tk(NULLABLE, " ", STRING), nullness: "nullable", doc: "an optional label" }], throws: [{ type: [jdk("java.lang", "IllegalArgumentException")], doc: "if `radius` is negative" }], doc: "Checks the radius.", line: 22 }), + m(`${G}.Circle`, { name: "of", mods: ["public", "static"], params: [{ name: "radius", type: [DOUBLE], doc: "the radius in meters" }], returns: { type: [t("Circle")], nullness: "nonNull", doc: "an unlabeled circle" }, doc: "Creates an unlabeled circle.", line: 34 }), + m(`${G}.Circle`, { name: "area", mods: ["public"], returns: { type: [DOUBLE], doc: "the area in square meters, never negative" }, overrides: { id: `${G}.Shape#area()` }, doc: { body: "The shape's area. For a circle this is `π r²`.", inheritedFrom: undefined }, line: 40 }), + m(`${G}.Circle`, { name: "radius", mods: ["public"], returns: { type: [DOUBLE], doc: "the radius in meters; not negative" }, implicit: true }), + m(`${G}.Circle`, { name: "label", mods: ["public"], returns: { type: tk(NULLABLE, " ", STRING), nullness: "nullable", doc: "an optional label" }, implicit: true }), + m(`${G}.Circle`, { name: "toString", mods: ["public", "final"], returns: { type: [STRING], nullness: "nonNull" }, implicit: true }), + ], + inherited: [{ from: { id: `${G}.Shape`, text: "Shape" }, kind: "interface", members: [{ id: `${G}.Shape#compareTo(com.example.geo.Shape)`, text: "compareTo" }, { id: `${G}.Shape#name()`, text: "name" }] }], + doc: doc("A circle, the simplest shape.\n\nCircles compare by radius as well as by area: their order is the same."), + since: "1.0", nullMarked: true, source: { path: "com/example/geo/Circle.java", line: 16 }, +}); + +const abstractShape: Type = type({ + id: `${G}.AbstractShape`, name: "AbstractShape", kind: "class", modifiers: ["public", "abstract"], + signature: tk(kw("public"), " ", kw("abstract"), " ", kw("class"), " ", nm("AbstractShape")), + superclass: [OBJECT], ancestors: [objectRef], + members: [ + m(`${G}.AbstractShape`, { name: "perimeter", mods: ["public", "abstract"], returns: { type: [DOUBLE], doc: "the perimeter in meters" }, doc: "The length of the shape's boundary.", line: 20 }), + m(`${G}.AbstractShape`, { name: "describe", mods: ["public"], returns: { type: [STRING], nullness: "nonNull", doc: "a description such as `polygon, 4 sides`" }, doc: "Describes the shape for logs.", line: 28 }), + ], + inherited: [fromObject], + doc: doc("Shared behavior for shapes with a boundary."), since: "1.0", nullMarked: true, +}); + +const polygon: Type = type({ + id: `${G}.Polygon`, name: "Polygon", kind: "class", modifiers: ["public", "non-sealed"], + signature: tk(kw("public"), " ", kw("non-sealed"), " ", kw("class"), " ", nm("Polygon"), " ", kw("extends"), " ", t("AbstractShape"), " ", kw("implements"), " ", t("Shape")), + superclass: [t("AbstractShape")], ancestors: [{ id: `${G}.AbstractShape` }, objectRef], interfaces: [[t("Shape")]], + members: [ + m(`${G}.Polygon`, { name: "Polygon", kind: "constructor", mods: ["public"], params: [{ name: "sides", type: tk(DOUBLE, "..."), varargs: true, doc: "each side's length in meters; at least three" }], throws: [{ type: [jdk("java.lang", "IllegalArgumentException")], doc: "if there are fewer than three sides" }], doc: "Creates a regular polygon from its sides.", line: 25 }), + m(`${G}.Polygon`, { name: "area", mods: ["public"], returns: { type: [DOUBLE], doc: "the area in square meters, never negative" }, overrides: { id: `${G}.Shape#area()` }, doc: { body: "The shape's area.", inheritedFrom: { id: `${G}.Shape#area()` } }, line: 36 }), + m(`${G}.Polygon`, { name: "perimeter", mods: ["public"], returns: { type: [DOUBLE], doc: "the perimeter in meters" }, overrides: { id: `${G}.AbstractShape#perimeter()` }, doc: "The sum of the sides.", line: 44 }), + ], + inherited: [ + { from: { id: `${G}.AbstractShape`, text: "AbstractShape" }, kind: "class", members: [{ id: `${G}.AbstractShape#describe()`, text: "describe" }] }, + fromObject, + { from: { id: `${G}.Shape`, text: "Shape" }, kind: "interface", members: [{ id: `${G}.Shape#compareTo(com.example.geo.Shape)`, text: "compareTo" }, { id: `${G}.Shape#name()`, text: "name" }] }, + ], + doc: doc("A regular polygon. Not sealed: applications may extend it."), since: "1.0", nullMarked: true, +}); + +const units: Type = type({ + id: `${G}.Units`, name: "Units", kind: "enum", modifiers: ["public"], + signature: tk(kw("public"), " ", kw("enum"), " ", nm("Units")), + superclass: tk(jdk("java.lang", "Enum"), "<", t("Units"), ">"), ancestors: [{ id: "java.lang.Enum", url: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html" }, objectRef], + members: [ + m(`${G}.Units`, { name: "values", mods: ["public", "static"], returns: { type: tk(t("Units"), "[]"), nullness: "nonNull" }, implicit: true }), + m(`${G}.Units`, { name: "valueOf", mods: ["public", "static"], params: [{ name: "name", type: [STRING], nullness: "nonNull" }], returns: { type: [t("Units")], nullness: "nonNull" }, implicit: true }), + m(`${G}.Units`, { name: "METERS", kind: "enumConstant", type: [t("Units")], doc: "Meters: the base unit." }), + m(`${G}.Units`, { name: "FEET", kind: "enumConstant", type: [t("Units")], doc: "International feet.", deprecated: deprecated("Use [[com.example.geo.Units#METERS]]; mixing units causes rounding errors.", "1.2"), annotations: [tk(an("@Deprecated", "java.lang.Deprecated", "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Deprecated.html"), "(", { kind: "param", text: "since" }, " = ", lit('"1.2"'), ")")] }), + m(`${G}.Units`, { name: "toMeters", mods: ["public"], params: [{ name: "value", type: [DOUBLE], doc: "a length in this unit" }], returns: { type: [DOUBLE], doc: "the length in meters" }, doc: "Converts a length in this unit to meters." }), + ], + doc: doc("Units of length."), since: "1.0", nullMarked: true, +}); + +const measured: Type = type({ + id: `${G}.Measured`, name: "Measured", kind: "annotation", modifiers: ["public"], + annotations: [[an("@Documented", "java.lang.annotation.Documented", "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/annotation/Documented.html")]], + signature: tk(kw("public"), " ", kw("@interface"), " ", nm("Measured")), + members: [ + m(`${G}.Measured`, { name: "unit", kind: "annotationElement", returns: { type: [t("Units")], doc: "the unit" }, defaultValue: "METERS", doc: "The unit of the values." }), + m(`${G}.Measured`, { name: "precision", kind: "annotationElement", returns: { type: [INT], doc: "the number of digits" }, defaultValue: "3", doc: "Significant digits." }), + ], + doc: doc("Marks a declaration whose values are lengths, and in which unit."), since: "1.1", nullMarked: true, +}); + +const geoException: Type = type({ + id: `${G}.GeometryException`, name: "GeometryException", kind: "class", modifiers: ["public"], + signature: tk(kw("public"), " ", kw("class"), " ", nm("GeometryException"), " ", kw("extends"), " ", jdk("java.lang", "Exception")), + superclass: [jdk("java.lang", "Exception")], + ancestors: ["Exception", "Throwable"].map(n => ({ id: `java.lang.${n}`, url: `https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/${n}.html` })).concat([objectRef]), + members: [m(`${G}.GeometryException`, { name: "GeometryException", kind: "constructor", mods: ["public"], params: [{ name: "message", type: [STRING], doc: "what was wrong" }], doc: "Creates an exception." })], + doc: doc("A shape that cannot exist, such as a triangle whose sides violate the triangle inequality."), since: "1.0", nullMarked: true, +}); + +const legacyShape: Type = type({ + id: `${G}.LegacyShape`, name: "LegacyShape", kind: "class", modifiers: ["public", "final"], + signature: tk(kw("public"), " ", kw("final"), " ", kw("class"), " ", nm("LegacyShape")), + superclass: [OBJECT], ancestors: [objectRef], + deprecated: deprecated("Use [[com.example.geo.Polygon]]; this class predates sealed shapes and will be removed in 3.0.", "2.0", true), + doc: doc("A shape from the 1.x API."), since: "1.0", +}); + +const shapesId = `${G}.Shapes`; +const shapes: Type = type({ + id: shapesId, name: "Shapes", kind: "class", modifiers: ["public", "final"], + signature: tk(kw("public"), " ", kw("final"), " ", kw("class"), " ", nm("Shapes")), + superclass: [OBJECT], ancestors: [objectRef], + members: [ + m(shapesId, { name: "PRECISION", kind: "field", mods: ["public", "static", "final"], type: [INT], constant: "6", doc: "The default number of significant digits: `6`.", line: 60 }), + m(shapesId, { name: "NAME", kind: "field", mods: ["public", "static", "final"], type: [STRING], nullness: "nonNull", constant: '"geo"', doc: "The library's name as tools report it." }), + m(shapesId, { name: "area", mods: ["public", "static"], params: [{ name: "circle", type: [t("Circle")], nullness: "nonNull", doc: "the circle" }], returns: { type: [DOUBLE], doc: "its area" }, doc: "The area of a circle. One of two overloads." }), + m(shapesId, { name: "area", mods: ["public", "static"], params: [{ name: "polygon", type: [t("Polygon")], nullness: "nonNull", doc: "the polygon" }], returns: { type: [DOUBLE], doc: "its area" }, doc: "The area of a polygon. One of two overloads." }), + m(shapesId, { + name: "largest", mods: ["public", "static"], + typeParams: [{ name: "T", bounds: [[t("Shape")], tk(jdk("java.lang", "Comparable"), "")], doc: "the shape type" }], + params: [{ name: "shapes", type: tk(jdk("java.util", "Collection"), ""), nullness: "nonNull", doc: "the shapes; not empty" }], + returns: { type: [tp("T")], doc: "the largest of `shapes`" }, + throws: [{ type: [jdk("java.util", "NoSuchElementException")], doc: "if `shapes` is empty" }], + doc: { body: "Returns the largest shape.", notes: [["implSpec", "Compares with [[java.lang.Comparable#compareTo(T)|Comparable.compareTo]], keeping the first of equal shapes."]] }, + }), + m(shapesId, { + name: "total", mods: ["public", "static"], annotations: [tk(an("@Measured", `${G}.Measured`), "(", { kind: "param", text: "precision" }, " = ", lit("6"), ")")], + params: [{ name: "shapes", type: tk(t("Shape"), "..."), varargs: true, nullness: "nonNull", doc: "the shapes" }], + returns: { type: [DOUBLE], doc: "the total area in square meters; `0` for no shapes" }, doc: "Sums the shapes' areas.", + }), + m(shapesId, { + name: "parse", mods: ["public", "static"], params: [{ name: "text", type: [STRING], nullness: "nonNull", doc: "the text form, such as `circle 2.5`" }], + returns: { type: [t("Shape")], nullness: "nonNull", doc: "the shape" }, + throws: [ + { type: [jdk("java.io", "IOException")], declared: true, doc: "if the text names a file that cannot be read" }, + { type: [t("GeometryException")], declared: true, doc: "if the text describes an impossible shape" }, + { type: [jdk("java.lang", "IllegalStateException")], doc: "if the parser was closed" }, + ], + doc: { + body: [P("Parses a shape from its text form."), CODE("java", 'Shape s = Shapes.parse("circle 2.5");\nassert s instanceof Circle c && c.radius() == 2.5;')], + notes: [ + ["apiNote", "The text form is **not stable** across releases: store shapes some other way. Parsing `circle -1` throws rather than returning an empty shape."], + ["implNote", "Parses with a hand-written scanner; no regular expressions."], + ], + see: ["[[com.example.geo.io.ShapeReader]]", "[Shape text format](https://example.com/geo/format)"], + }, + }), + m(shapesId, { + name: "sum", mods: ["public", "static"], params: [{ name: "shapes", type: tk(jdk("java.util", "List"), "<", t("Shape"), ">"), nullness: "nonNull", doc: "the shapes" }], + returns: { type: [DOUBLE], doc: "the total area" }, + deprecated: deprecated("Use [[com.example.geo.Shapes#total(com.example.geo.Shape...)|total(Shape...)]], which takes any number of shapes.", "1.1", true), + annotations: [tk(an("@Deprecated", "java.lang.Deprecated", "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Deprecated.html"), "(", { kind: "param", text: "since" }, " = ", lit('"1.1"'), ", ", { kind: "param", text: "forRemoval" }, " = ", lit("true"), ")")], + doc: "Sums the areas of a list of shapes.", + }), + m(shapesId, { + name: "find", mods: ["public", "static"], since: "1.1", + params: [ + { name: "shapes", type: tk(jdk("java.util", "Map"), "<", STRING, ", ? ", kw("extends"), " ", t("Shape"), ">"), nullness: "nonNull", doc: "shapes by name" }, + { name: "name", type: [STRING], nullness: "nonNull", doc: "the name to look up" }, + ], + returns: { type: tk(NULLABLE, " ", t("Shape")), nullness: "nullable", doc: "the shape, or `null` when there is none" }, + doc: { body: [P("Finds a shape by name. Unlike [[com.example.geo.Shapes$Registry|the registry]], this never throws for a missing name.")] }, + }), + m(shapesId, { + name: "transform", mods: ["public", "static"], + typeParams: [{ name: "S", bounds: [[t("Shape")]] }, { name: "R", bounds: [tk(jdk("java.lang", "Comparable"), "")] }], + params: [ + { name: "shapes", type: tk(jdk("java.util", "Collection"), ""), doc: "the input shapes" }, + { name: "mapper", type: tk(jdk("java.util.function", "Function"), ""), doc: "maps each shape" }, + { name: "filter", type: tk(jdk("java.util.function", "Predicate"), ""), doc: "keeps a result when it returns `true`" }, + { name: "comparator", type: tk(jdk("java.util", "Comparator"), ""), doc: "orders the results" }, + { name: "limit", type: [INT], doc: "the most results to return" }, + { name: "units", type: [t("Units")], doc: "the unit for measured results" }, + { name: "label", type: tk(NULLABLE, " ", STRING), nullness: "nullable", doc: "a label for diagnostics, or `null`" }, + ], + returns: { type: tk(jdk("java.util", "List"), "<", tp("R"), ">"), nullness: "nonNull", doc: "the sorted, filtered results" }, + throws: [{ type: [t("GeometryException")], declared: true, doc: "if a shape cannot be measured in `units`" }], + doc: "Maps, filters and sorts shapes in one pass. A long signature, laid out one parameter per line.", + }), + m(shapesId, { + name: "describe", mods: ["public", "static"], params: [{ name: "shape", type: [t("Shape")], doc: "the shape" }], + returns: { type: [STRING], doc: "the description" }, + doc: { body: [P("Describes a shape. This links to [[com.example.geo.Ellipse|an ellipse type]] that this model does not contain, so the link renders as plain code."), { kind: "paragraph", children: [{ kind: "text", text: "Also an inline raw node: E = mc" }, { kind: "raw", html: "2", text: "2" }, { kind: "text", text: "." }] }] }, + }), + ], + inherited: [fromObject], + doc: doc({ + body: [ + P("Operations on [[com.example.geo.Shape|shapes]]."), + P("Every method is *pure*: it never modifies its arguments. **Thread safety:** every method is safe to call concurrently."), + UL("[[com.example.geo.Shapes#largest(java.util.Collection)]] picks the largest shape.", "[[com.example.geo.Shapes#total(com.example.geo.Shape...)]] sums areas."), + OL("Measure each shape.", "Compare the results with `compareTo`."), + TABLE("Unit factors", ["Unit", "Factor"], [["[[com.example.geo.Units#METERS]]", "1.0"], ["[[com.example.geo.Units#FEET]]", "0.3048"]]), + H(2, "Java and Kotlin"), + CODE("java", "Shape big = Shapes.largest(List.of(Circle.of(1), new Polygon(1, 1, 1)));\ndouble total = Shapes.total(big, Circle.of(3)); // 0x1F, 3.5e2"), + CODE("kotlin", "val big = Shapes.largest(listOf(Circle.of(1.0), Polygon(1.0, 1.0, 1.0)))\nval total: Double = Shapes.total(big, Circle.of(3.0))"), + QUOTE("Measure twice, cut once."), + RAW('
Precision
Six digits
', "Precision: Six digits"), + ], + notes: [["implNote", "Areas are computed in double precision."]], + see: ["[[com.example.geo.Shape]]", "[[com.example.geo.Shape#area()|the area of a shape]]", '"Euclid, Elements, Book I"', "[Area on Wikipedia](https://en.wikipedia.org/wiki/Area)"], + }), + since: "1.0", nullMarked: true, source: { path: "com/example/geo/Shapes.java", line: 50 }, +}); + +const builder: Type = type({ + id: `${G}.Shapes$Builder`, name: "Shapes.Builder", kind: "class", modifiers: ["public", "static", "final"], enclosing: shapesId, + signature: tk(kw("public"), " ", kw("static"), " ", kw("final"), " ", kw("class"), " ", nm("Shapes.Builder")), + superclass: [OBJECT], ancestors: [objectRef], + members: [ + m(`${G}.Shapes$Builder`, { name: "Builder", kind: "constructor", mods: ["public"], doc: "Creates an empty builder." }), + m(`${G}.Shapes$Builder`, { name: "with", mods: ["public"], params: [{ name: "option", type: [t("Shapes$Builder$Option")], doc: "the option to set" }], returns: { type: [t("Shapes$Builder")], doc: "this builder" }, doc: "Sets an option." }), + ], + inherited: [fromObject], doc: doc("Builds a list of shapes one at a time."), since: "1.2", nullMarked: true, +}); + +const option: Type = type({ + id: `${G}.Shapes$Builder$Option`, name: "Shapes.Builder.Option", kind: "enum", modifiers: ["public"], enclosing: `${G}.Shapes$Builder`, + signature: tk(kw("public"), " ", kw("enum"), " ", nm("Shapes.Builder.Option")), + members: [ + m(`${G}.Shapes$Builder$Option`, { name: "SORTED", kind: "enumConstant", type: [t("Shapes$Builder$Option")], doc: "Keep shapes sorted by area." }), + m(`${G}.Shapes$Builder$Option`, { name: "DISTINCT", kind: "enumConstant", type: [t("Shapes$Builder$Option")], doc: "Drop shapes equal to one already added." }), + ], + doc: doc("Options for a builder: a type nested two levels deep."), nullMarked: true, +}); + +const registry: Type = type({ + id: `${G}.Shapes$Registry`, name: "Shapes.Registry", kind: "interface", modifiers: ["public", "static"], enclosing: shapesId, + signature: tk(kw("public"), " ", kw("interface"), " ", nm("Shapes.Registry")), + members: [m(`${G}.Shapes$Registry`, { name: "lookup", params: [{ name: "name", type: [STRING], doc: "the shape's name" }], returns: { type: [t("Shape")], doc: "the shape" }, throws: [{ type: [jdk("java.util", "NoSuchElementException")], doc: "if no shape has that name" }], doc: "Looks up a shape by name." })], + doc: doc("Shapes by name."), nullMarked: true, +}); + +// ---- com.example.geo.io + +const reader: Type = type({ + id: `${IO}.ShapeReader`, name: "ShapeReader", kind: "class", modifiers: ["public", "final"], + signature: tk(kw("public"), " ", kw("final"), " ", kw("class"), " ", nm("ShapeReader"), " ", kw("implements"), " ", jdk("java.lang", "AutoCloseable")), + superclass: [OBJECT], ancestors: [objectRef], interfaces: [[jdk("java.lang", "AutoCloseable")]], + members: [ + m(`${IO}.ShapeReader`, { name: "read", mods: ["public", "static"], params: [{ name: "in", type: [jdk("java.io", "InputStream")], doc: "the stream; not closed" }], returns: { type: tk(jdk("java.util", "List"), "<", t("Shape"), ">"), doc: "the shapes, in order" }, throws: [{ type: [jdk("java.io", "IOException")], declared: true, doc: "if reading fails" }], doc: "Reads every shape from a stream of UTF-8 text." }), + m(`${IO}.ShapeReader`, { name: "read", mods: ["public", "static"], params: [{ name: "reader", type: [jdk("java.io", "Reader")], doc: "the reader; not closed" }, { name: "charset", type: [jdk("java.nio.charset", "Charset")], doc: "the charset the text was decoded from" }], returns: { type: tk(jdk("java.util", "List"), "<", t("Shape"), ">"), doc: "the shapes, in order" }, throws: [{ type: [jdk("java.io", "IOException")], declared: true, doc: "if reading fails" }], doc: "Reads every shape from a reader." }), + m(`${IO}.ShapeReader`, { name: "close", mods: ["public"], throws: [{ type: [jdk("java.io", "IOException")], declared: true, doc: "if closing the reader fails" }], doc: "Closes the underlying reader.", overrides: { id: "java.lang.AutoCloseable#close()", url: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html#close()" } }), + ], + inherited: [fromObject], + doc: doc({ body: "Reads shapes in their text form, one per line.", see: ["[[com.example.geo.Shapes#parse(java.lang.String)]]"] }), since: "1.0", +}); + +// ---- com.example.geo.registry: one type with hundreds of members. + +function generated(): Type { + const id = `${BIG}.ShapeCatalog`; + const members: Member[] = []; + const families = ["circle", "square", "triangle", "hexagon", "octagon", "ellipse", "star", "arc", "ring", "sector"]; + const verbs = ["area", "perimeter", "scale", "rotate", "translate", "mirror", "contains", "intersects", "union", "bounds"]; + for (let i = 0; i < 40; i++) { + members.push(m(id, { name: `${families[i % 10]!.toUpperCase()}_${Math.floor(i / 10) + 1}`, kind: "field", mods: ["public", "static", "final"], type: [STRING], constant: `"${families[i % 10]}-${i}"`, doc: `The catalog key of ${families[i % 10]} variant ${Math.floor(i / 10) + 1}.` })); + } + for (const family of families) { + for (const verb of verbs) { + for (const arity of [1, 2, 3]) { + const cap = family[0]!.toUpperCase() + family.slice(1); + members.push(m(id, { + name: `${verb}${cap}`, mods: ["public"], + params: Array.from({ length: arity }, (_, k) => ({ name: ["shape", "factor", "origin"][k]!, type: [k === 0 ? t("Shape", G) : DOUBLE], doc: ["the shape", "the factor", "the origin offset"][k] })), + returns: { type: [verb === "contains" || verb === "intersects" ? kw("boolean") : DOUBLE], doc: `the ${verb} result` }, + doc: `Computes ${verb} for a ${family}${arity > 1 ? ` with ${arity} arguments` : ""}.`, + })); + } + } + } + return type({ + id, name: "ShapeCatalog", kind: "class", modifiers: ["public", "final"], + signature: tk(kw("public"), " ", kw("final"), " ", kw("class"), " ", nm("ShapeCatalog")), + superclass: [OBJECT], ancestors: [objectRef], members, inherited: [fromObject], + doc: doc("A catalog with hundreds of members, generated to exercise long pages, the member summary and the table of contents."), + since: "2.0", + }); +} + +const packages: Package[] = [ + { + id: G, name: G, nullMarked: true, since: "1.0", + doc: doc({ + body: [P("Shapes, units and measurements."), H(2, "Where to start"), P("Start with [[com.example.geo.Shape]] and the operations in [[com.example.geo.Shapes]]. Readers live in [[com.example.geo.io]].")], + see: ["[[com.example.geo.io]]"], + }), + types: [abstractShape, circle, geoException, legacyShape, measured, polygon, shape, shapes, builder, option, registry, units].sort((a, b) => a.name.localeCompare(b.name)), + }, + { id: IO, name: IO, since: "1.0", doc: doc("Reading shapes from streams. Not null-marked: nullness here is unspecified unless annotated."), types: [reader] }, + { id: BIG, name: BIG, since: "2.0", doc: doc("A generated catalog, for performance."), types: [generated()] }, + { id: EMPTY, name: EMPTY, since: "2.1", doc: doc("Service-provider interfaces. Reserved: this package declares nothing public yet.") }, +]; + +export const javaSample: Model = { + schema: "apidocs/1", + module: { + name: "geo", version: "2.1.0", languages: ["java"], + doc: doc({ body: [P("A small geometry library: the Java-flavored sample for `@elide/apidocs`."), P("It shows every construct the doclet writes. See `samples/FEATURES.md` for the list.")] }), + }, + externals: [ + { prefix: "java.", url: "https://docs.oracle.com/en/java/javase/25/docs/api/{module}/" }, + { prefix: "org.jspecify.", url: "https://jspecify.dev/docs/api/" }, + ], + packages, +}; + diff --git a/packages/apidocs/samples/kotlin.ts b/packages/apidocs/samples/kotlin.ts new file mode 100644 index 0000000..70c67ff --- /dev/null +++ b/packages/apidocs/samples/kotlin.ts @@ -0,0 +1,185 @@ +/** + * The Kotlin-flavored sample: what the Dokka plugin will write. Ids are Dokka + * DRIs; anchors are readable names. It covers top-level functions and + * properties, extensions with receivers, objects and companions, data, sealed, + * value and enum classes, suspend and inline functions, type aliases, nullable + * types and default arguments. + */ +import type { Model, Package, Token, Type } from "../src/model"; +import { an, blocks, CODE, deprecated, doc, kotlinMember, kw, lit, nm, P, prm, tk, tp, ty, type, UL } from "./build"; + +const K = "org.example.kgeo"; +const KC = "org.example.kgeo.coroutines"; +const KE = "org.example.kgeo.experimental"; + +const dri = (pkg: string, cls: string) => `${pkg}/${cls}///PointingToDeclaration/`; +const t = (name: string, pkg = K) => ty(name, dri(pkg, name)); +const std = (name: string, pkg = "kotlin") => + ty(name, dri(pkg, name), `https://kotlinlang.org/api/core/kotlin-stdlib/${pkg}/-${name.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()}/`); +const DOUBLE = std("Double"); +const STRING = std("String"); +const BOOLEAN = std("Boolean"); +const list = (...item: Token[]) => tk(std("List", "kotlin.collections"), "<", ...item, ">"); +const nullable = (...type: Token[]) => tk(...type, "?"); +const f = (owner: string, spec: Parameters[1]) => kotlinMember(owner, spec); + +const shape: Type = type({ + id: dri(K, "Shape"), name: "Shape", kind: "class", modifiers: ["public", "sealed"], + signature: tk(kw("sealed"), " ", kw("class"), " ", nm("Shape")), + members: [ + f(`${K}/Shape`, { name: "area", kind: "property", mods: ["abstract"], type: [DOUBLE], nullness: "nonNull", doc: "The area in square meters; never negative." }), + f(`${K}/Shape`, { name: "describe", mods: ["open"], returns: { type: [STRING], doc: "a description such as `circle r=2.0`" }, doc: "Describes the shape for logs." }), + ], + doc: doc({ body: "A closed plane figure.\n\nThe hierarchy is sealed, so a `when` over a shape needs no `else` branch.", notes: [["apiNote", "Subclasses live in this module only; a `when` over [[org.example.kgeo/Shape///PointingToDeclaration/|Shape]] is exhaustive."]] }), + since: "1.0", source: { path: "org/example/kgeo/Shape.kt", line: 12 }, +}, "kotlin"); + +const circle: Type = type({ + id: dri(K, "Circle"), name: "Circle", kind: "class", modifiers: ["public", "data"], + signature: tk(kw("data"), " ", kw("class"), " ", nm("Circle"), "(", kw("val"), " ", prm("radius"), ": ", DOUBLE, ", ", kw("val"), " ", prm("label"), ": ", STRING, "? = ", lit("null"), ") : ", t("Shape"), "()"), + superclass: [t("Shape")], ancestors: [{ id: dri(K, "Shape") }, { id: dri("kotlin", "Any"), url: "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-any/" }], + members: [ + f(`${K}/Circle`, { name: "Circle", kind: "constructor", params: [{ name: "radius", type: [DOUBLE], doc: "the radius in meters" }, { name: "label", type: nullable(STRING), nullness: "nullable", defaultValue: "null", doc: "an optional label" }], doc: "Creates a circle." }), + f(`${K}/Circle`, { name: "radius", kind: "property", type: [DOUBLE], doc: "The radius in meters." }), + f(`${K}/Circle`, { name: "label", kind: "property", type: nullable(STRING), nullness: "nullable", doc: "An optional label, or `null`." }), + f(`${K}/Circle`, { name: "area", kind: "property", mods: ["override"], type: [DOUBLE], overrides: { id: `${K}/Shape/area/#/PointingToDeclaration/` }, doc: "The area: `π r²`." }), + f(`${K}/Circle`, { name: "copy", params: [{ name: "radius", type: [DOUBLE], defaultValue: "this.radius" }, { name: "label", type: nullable(STRING), nullness: "nullable", defaultValue: "this.label" }], returns: { type: [t("Circle")] }, implicit: true }), + ], + doc: doc("A circle: a data class with a default argument and a companion object."), since: "1.0", +}, "kotlin"); + +const companion: Type = type({ + id: `${K}/Circle.Companion///PointingToDeclaration/`, name: "Circle.Companion", kind: "object", modifiers: ["public", "companion"], enclosing: dri(K, "Circle"), + signature: tk(kw("companion"), " ", kw("object"), " ", nm("Companion")), + members: [ + f(`${K}/Circle.Companion`, { name: "UNIT", kind: "property", mods: ["const"], type: [DOUBLE], constant: "1.0", doc: "The unit radius." }), + f(`${K}/Circle.Companion`, { name: "unit", returns: { type: [t("Circle")], doc: "a circle of radius [[org.example.kgeo/Circle.Companion/UNIT/#/PointingToDeclaration/|UNIT]]" }, doc: "The unit circle." }), + ], + doc: doc("Factories for circles."), since: "1.0", +}, "kotlin"); + +const rect: Type = type({ + id: dri(K, "Rectangle"), name: "Rectangle", kind: "class", modifiers: ["public", "data"], + signature: tk(kw("data"), " ", kw("class"), " ", nm("Rectangle"), "(", kw("val"), " ", prm("width"), ": ", t("Meters"), ", ", kw("val"), " ", prm("height"), ": ", t("Meters"), " = ", prm("width"), ") : ", t("Shape"), "()"), + superclass: [t("Shape")], ancestors: [{ id: dri(K, "Shape") }], + members: [ + f(`${K}/Rectangle`, { name: "Rectangle", kind: "constructor", params: [{ name: "width", type: [t("Meters")], doc: "the width" }, { name: "height", type: [t("Meters")], defaultValue: "width", doc: "the height; a square when left out" }], doc: "Creates a rectangle, or a square when `height` is left out." }), + f(`${K}/Rectangle`, { name: "area", kind: "property", mods: ["override"], type: [DOUBLE], doc: "Width times height." }), + ], + doc: doc("An axis-aligned rectangle."), since: "1.0", +}, "kotlin"); + +const meters: Type = type({ + id: dri(K, "Meters"), name: "Meters", kind: "class", modifiers: ["public", "value"], + annotations: [[an("@JvmInline", dri("kotlin.jvm", "JvmInline"), "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.jvm/-jvm-inline/")]], + signature: tk(kw("value"), " ", kw("class"), " ", nm("Meters"), "(", kw("val"), " ", prm("value"), ": ", DOUBLE, ") : ", std("Comparable"), "<", t("Meters"), ">"), + interfaces: [tk(std("Comparable"), "<", t("Meters"), ">")], + members: [ + f(`${K}/Meters`, { name: "value", kind: "property", type: [DOUBLE], doc: "The length in meters." }), + f(`${K}/Meters`, { name: "plus", mods: ["operator"], params: [{ name: "other", type: [t("Meters")], doc: "the length to add" }], returns: { type: [t("Meters")], doc: "the sum" }, doc: "Adds two lengths: `a + b`." }), + f(`${K}/Meters`, { name: "compareTo", mods: ["override"], params: [{ name: "other", type: [t("Meters")] }], returns: { type: [std("Int")] }, doc: "Compares lengths." }), + ], + doc: doc({ body: "A length in meters, as a value class: no allocation on the JVM.", notes: [["implNote", "Compiles to a `double` wherever the type is not boxed."]] }), since: "1.1", +}, "kotlin"); + +const lengthUnit: Type = type({ + id: dri(K, "LengthUnit"), name: "LengthUnit", kind: "enum", modifiers: ["public"], + signature: tk(kw("enum"), " ", kw("class"), " ", nm("LengthUnit"), "(", kw("val"), " ", prm("factor"), ": ", DOUBLE, ")"), + members: [ + f(`${K}/LengthUnit`, { name: "METER", kind: "enumConstant", type: [t("LengthUnit")], doc: "The base unit." }), + f(`${K}/LengthUnit`, { name: "FOOT", kind: "enumConstant", type: [t("LengthUnit")], doc: "International feet.", deprecated: deprecated("Use [[org.example.kgeo/LengthUnit/METER/#/PointingToDeclaration/|METER]].", "1.2") }), + f(`${K}/LengthUnit`, { name: "factor", kind: "property", type: [DOUBLE], doc: "Meters per unit." }), + ], + doc: doc("Units of length."), since: "1.0", +}, "kotlin"); + +const geometry: Type = type({ + id: dri(K, "Geometry"), name: "Geometry", kind: "object", modifiers: ["public"], + signature: tk(kw("object"), " ", nm("Geometry")), + members: [ + f(`${K}/Geometry`, { name: "distance", params: [{ name: "a", type: [t("Point")] }, { name: "b", type: [t("Point")] }], returns: { type: [DOUBLE], doc: "the Euclidean distance" }, doc: "The distance between two points. One of two overloads." }), + f(`${K}/Geometry`, { name: "distance", params: [{ name: "a", type: [t("Point")], doc: "the first point" }, { name: "b", type: [t("Point")], doc: "the second point" }, { name: "metric", type: [t("Metric")], defaultValue: "Metric.EUCLID", doc: "how to measure" }], returns: { type: [DOUBLE], doc: "the distance under `metric`" }, doc: "The distance between two points under a metric." }), + f(`${K}/Geometry`, { + name: "filterShapes", mods: ["inline"], typeParams: [{ name: "reified T", bounds: [[t("Shape")]], doc: "the shape type to keep" }], + params: [{ name: "shapes", type: list(t("Shape")), doc: "the shapes" }], returns: { type: list(tp("T")), doc: "the shapes of type `T`" }, + doc: { body: [P("Keeps the shapes of one type."), CODE("kotlin", "val circles: List = Geometry.filterShapes(shapes)")] }, + }), + ], + doc: doc("Geometry functions, as a singleton object."), since: "1.0", +}, "kotlin"); + +const point: Type = type({ + id: dri(K, "Point"), name: "Point", kind: "class", modifiers: ["public", "data"], + signature: tk(kw("data"), " ", kw("class"), " ", nm("Point"), "(", kw("val"), " ", prm("x"), ": ", DOUBLE, " = ", lit("0.0"), ", ", kw("val"), " ", prm("y"), ": ", DOUBLE, " = ", lit("0.0"), ")"), + members: [ + f(`${K}/Point`, { name: "Point", kind: "constructor", params: [{ name: "x", type: [DOUBLE], defaultValue: "0.0", doc: "the x coordinate" }, { name: "y", type: [DOUBLE], defaultValue: "0.0", doc: "the y coordinate" }], doc: "Creates a point; both coordinates default to zero." }), + f(`${K}/Point`, { name: "x", kind: "property", type: [DOUBLE], doc: "The x coordinate." }), + f(`${K}/Point`, { name: "y", kind: "property", type: [DOUBLE], doc: "The y coordinate." }), + ], + doc: doc("A point in the plane."), since: "1.0", +}, "kotlin"); + +const metric: Type = type({ + id: dri(K, "Metric"), name: "Metric", kind: "interface", modifiers: ["public", "fun"], + signature: tk(kw("fun"), " ", kw("interface"), " ", nm("Metric")), + members: [f(`${K}/Metric`, { name: "measure", mods: ["abstract"], params: [{ name: "a", type: [t("Point")] }, { name: "b", type: [t("Point")] }], returns: { type: [DOUBLE] }, doc: "Measures the distance from `a` to `b`." })], + doc: doc("How to measure distance: a functional interface."), since: "1.1", +}, "kotlin"); + +const experimental: Type = type({ + id: dri(KE, "ExperimentalGeometry"), name: "ExperimentalGeometry", kind: "annotation", modifiers: ["public"], + annotations: [tk(an("@RequiresOptIn", dri("kotlin", "RequiresOptIn"), "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-requires-opt-in/"))], + signature: tk(kw("annotation"), " ", kw("class"), " ", nm("ExperimentalGeometry")), + doc: doc("Marks API that may change without notice. Opt in with `@OptIn(ExperimentalGeometry::class)`."), since: "2.0", +}, "kotlin"); + +const top = `${K}/`; +const packages: Package[] = [ + { + id: K, name: K, since: "1.0", + doc: doc({ body: [P("Shapes and measurements in Kotlin."), UL("Shapes: [[org.example.kgeo/Shape///PointingToDeclaration/|Shape]] and its subclasses.", "Extensions on shapes, such as `scaled`.")] }), + types: [circle, companion, geometry, lengthUnit, meters, metric, point, rect, shape], + typeAliases: [ + { id: `${K}/ShapeList///PointingToDeclaration/`, name: "ShapeList", signature: tk(kw("typealias"), " ", nm("ShapeList"), " = ", list(t("Shape"))), target: list(t("Shape")), doc: doc("A list of shapes."), since: "1.0" }, + { id: `${K}/Transform///PointingToDeclaration/`, name: "Transform", typeParams: [{ name: "T", doc: blocks("the value type") }], signature: tk(kw("typealias"), " ", nm("Transform"), "<", tp("T"), "> = (", tp("T"), ") -> ", tp("T")), target: tk("(", tp("T"), ") -> ", tp("T")), doc: doc("A function from a value to a value of the same type."), since: "1.1" }, + ], + functions: [ + f(top, { name: "area", params: [{ name: "shape", type: [t("Shape")], doc: "the shape" }], returns: { type: [DOUBLE], doc: "its area" }, doc: "The area of a shape: a top-level function.", since: "1.0" }), + f(top, { name: "scaled", receiver: { name: "this", type: [t("Shape")], doc: "the shape to scale" }, params: [{ name: "by", type: [DOUBLE], defaultValue: "1.0", doc: "the scale factor" }], returns: { type: [t("Shape")], doc: "a scaled copy" }, doc: "Scales a shape: an extension function with a default argument." }), + f(top, { + name: "parseShape", annotations: [tk(an("@Throws", dri("kotlin", "Throws"), "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-throws/"), "(", ty("IOException", "java.io.IOException", "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html"), "::", kw("class"), ")")], + params: [{ name: "text", type: [STRING], doc: "the text form" }], returns: { type: nullable(t("Shape")), nullness: "nullable", doc: "the shape, or `null` when `text` is blank" }, + throws: [{ type: [ty("IOException", "java.io.IOException", "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html")], declared: true, doc: "if the text names a file that cannot be read" }], + doc: { body: "Parses a shape; blank text gives `null`.", notes: [["apiNote", "Returns `null` for blank input instead of throwing, unlike the Java API."]] }, + }), + f(top, { name: "totalArea", params: [{ name: "shapes", type: list(t("Shape")) }], returns: { type: [DOUBLE] }, deprecated: deprecated("Use `shapes.sumOf { it.area }`.", "1.2"), doc: "Sums areas." }), + ], + properties: [ + f(top, { name: "VERSION", kind: "property", mods: ["const"], type: [STRING], constant: '"2.1.0"', doc: "The library version." }), + f(top, { name: "defaultUnit", kind: "property", mods: ["var"], type: [t("LengthUnit")], doc: "The unit lengths use when none is given. Mutable." }), + f(top, { name: "isDegenerate", kind: "property", receiver: { name: "this", type: [t("Shape")] }, type: [BOOLEAN], doc: "Whether the shape has zero area: an extension property." }), + ], + }, + { + id: KC, name: KC, since: "1.2", doc: doc("Suspending APIs for loading shapes."), + functions: [ + f(`${KC}/`, { name: "loadShapes", mods: ["suspend"], params: [{ name: "path", type: [STRING], doc: "a file path" }], returns: { type: list(t("Shape")), doc: "the shapes in the file" }, doc: { body: [P("Loads shapes without blocking."), CODE("kotlin", 'runBlocking {\n val shapes = loadShapes("shapes.txt")\n println(shapes.size)\n}')] } }), + f(`${KC}/`, { name: "watchShapes", params: [{ name: "path", type: [STRING] }], returns: { type: tk(ty("Flow", dri("kotlinx.coroutines.flow", "Flow")), "<", t("Shape"), ">") }, doc: "Emits shapes as the file changes. Links to a kotlinx type outside this model, so `Flow` renders as plain code." }), + ], + }, + { id: KE, name: KE, since: "2.0", doc: doc("Experimental API."), types: [experimental] }, + { id: `${K}.internal`, name: `${K}.internal`, doc: doc("Internal helpers. This package declares nothing public.") }, +]; + +export const kotlinSample: Model = { + schema: "apidocs/1", + module: { + name: "kgeo", version: "2.1.0", languages: ["kotlin"], + doc: doc({ body: [P("A small Kotlin geometry library: the Kotlin-flavored sample for `@elide/apidocs`."), P("It shows what the Dokka plugin writes. See `samples/FEATURES.md` for the list.")] }), + }, + externals: [ + { prefix: "kotlin", url: "https://kotlinlang.org/api/core/kotlin-stdlib/" }, + { prefix: "java.", url: "https://docs.oracle.com/en/java/javase/25/docs/api/{module}/" }, + ], + packages, +}; diff --git a/packages/apidocs/schema/apidocs-1.schema.json b/packages/apidocs/schema/apidocs-1.schema.json new file mode 100644 index 0000000..fc61a4f --- /dev/null +++ b/packages/apidocs/schema/apidocs-1.schema.json @@ -0,0 +1,412 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://elide.dev/schemas/apidocs-1.schema.json", + "title": "Model", + "description": "The apidocs/1 model of one module's public API, as the Javadoc doclet and the Dokka plugin write it. A null value, false and an empty list are left out, so each is the default when a property is absent. Lists keep the extractor's order.", + "$ref": "#/$defs/Model", + "$defs": { + "Model": { + "description": "One module's model.", + "type": "object", + "additionalProperties": false, + "required": ["schema", "module"], + "properties": { + "schema": { "const": "apidocs/1", "description": "The schema name." }, + "module": { "$ref": "#/$defs/Module" }, + "externals": { "type": "array", "items": { "$ref": "#/$defs/External" }, "description": "Where references outside this model point, by name prefix; the first match wins." }, + "packages": { "type": "array", "items": { "$ref": "#/$defs/Package" }, "description": "The documented packages, sorted by name." } + } + }, + "Module": { + "description": "The documented module.", + "type": "object", + "additionalProperties": false, + "required": ["name"], + "properties": { + "name": { "type": "string", "description": "The module's name, as pages show it." }, + "version": { "type": "string", "description": "The module's version." }, + "languages": { "type": "array", "items": { "type": "string" }, "description": "The source languages, sorted: java, kotlin." }, + "doc": { "$ref": "#/$defs/Doc" } + } + }, + "External": { + "description": "Documentation outside this model: a reference whose id starts with prefix links below url.", + "type": "object", + "additionalProperties": false, + "required": ["prefix", "url"], + "properties": { + "prefix": { "type": "string", "description": "A package or name prefix, such as java." }, + "url": { "type": "string", "description": "The base URL (absolute) or path (relative to the model's root); {module} stands for a target's module." } + } + }, + "Package": { + "description": "A package (Java) or a package's top-level declarations (Kotlin).", + "type": "object", + "additionalProperties": false, + "required": ["id", "name"], + "properties": { + "id": { "type": "string", "description": "The package's id: its qualified name." }, + "name": { "type": "string", "description": "The qualified name; empty for the unnamed package." }, + "doc": { "$ref": "#/$defs/Doc" }, + "since": { "type": "string" }, + "deprecated": { "$ref": "#/$defs/Deprecation" }, + "nullMarked": { "type": "boolean", "description": "Whether the package is JSpecify @NullMarked." }, + "types": { "type": "array", "items": { "$ref": "#/$defs/Type" }, "description": "The package's types, nested types included, sorted by name." }, + "functions": { "type": "array", "items": { "$ref": "#/$defs/Member" }, "description": "Top-level functions (Kotlin)." }, + "properties": { "type": "array", "items": { "$ref": "#/$defs/Member" }, "description": "Top-level properties (Kotlin)." }, + "typeAliases": { "type": "array", "items": { "$ref": "#/$defs/TypeAlias" }, "description": "Type aliases (Kotlin)." } + } + }, + "TypeKind": { + "description": "What a type declaration is.", + "enum": ["class", "interface", "record", "enum", "annotation", "object"] + }, + "Type": { + "description": "A type declaration. Its page is /.html.", + "type": "object", + "additionalProperties": false, + "required": ["id", "name", "kind", "language", "signature"], + "properties": { + "id": { "type": "string", "description": "The stable id: the binary name (p.Outer$Inner) for Java, Dokka's DRI for Kotlin." }, + "name": { "type": "string", "description": "The name inside its package, nesting joined with dots (Outer.Inner)." }, + "kind": { "$ref": "#/$defs/TypeKind" }, + "language": { "type": "string", "description": "java or kotlin." }, + "modifiers": { "type": "array", "items": { "type": "string" }, "description": "Modifiers in canonical order, without implied ones." }, + "annotations": { "type": "array", "items": { "$ref": "#/$defs/Tokens" }, "description": "Documented annotations, each as tokens." }, + "typeParams": { "type": "array", "items": { "$ref": "#/$defs/TypeParam" } }, + "signature": { "$ref": "#/$defs/Tokens", "description": "The declaration line as tokens." }, + "superclass": { "$ref": "#/$defs/Tokens", "description": "The direct superclass as tokens; absent for interfaces." }, + "interfaces": { "type": "array", "items": { "$ref": "#/$defs/Tokens" }, "description": "Implemented or extended interfaces." }, + "ancestors": { "type": "array", "items": { "$ref": "#/$defs/Ref" }, "description": "The superclass chain, nearest first." }, + "permits": { "type": "array", "items": { "$ref": "#/$defs/Ref" }, "description": "Permitted subtypes of a sealed type." }, + "enclosing": { "type": "string", "description": "The enclosing type's id." }, + "components": { "type": "array", "items": { "$ref": "#/$defs/Param" }, "description": "Record components with their @param documentation." }, + "members": { "type": "array", "items": { "$ref": "#/$defs/Member" }, "description": "Declared members, in declaration order." }, + "inherited": { "type": "array", "items": { "$ref": "#/$defs/Inherited" }, "description": "Members inherited from supertypes, grouped by declaring type." }, + "doc": { "$ref": "#/$defs/Doc" }, + "deprecated": { "$ref": "#/$defs/Deprecation" }, + "since": { "type": "string" }, + "nullMarked": { "type": "boolean", "description": "Whether the declaration is in a JSpecify @NullMarked scope." }, + "source": { "$ref": "#/$defs/Source" } + } + }, + "MemberKind": { + "description": "What a member is.", + "enum": ["constructor", "method", "field", "enumConstant", "annotationElement", "function", "property"] + }, + "Member": { + "description": "A member of a type, or a Kotlin top-level function or property.", + "type": "object", + "additionalProperties": false, + "required": ["id", "anchor", "kind", "name", "signature"], + "properties": { + "id": { "type": "string", "description": "# for Java, Dokka's DRI for Kotlin." }, + "anchor": { "type": "string", "description": "The fragment on its page; for Java the JDK doclet's, such as read(java.io.InputStream)." }, + "kind": { "$ref": "#/$defs/MemberKind" }, + "name": { "type": "string", "description": "The simple name; a constructor is named after its type." }, + "modifiers": { "type": "array", "items": { "type": "string" } }, + "annotations": { "type": "array", "items": { "$ref": "#/$defs/Tokens" } }, + "typeParams": { "type": "array", "items": { "$ref": "#/$defs/TypeParam" } }, + "receiver": { "$ref": "#/$defs/Param", "description": "The receiver of a Kotlin extension function or property." }, + "signature": { "$ref": "#/$defs/Tokens", "description": "The declaration as tokens, on one line." }, + "params": { "type": "array", "items": { "$ref": "#/$defs/Param" } }, + "returns": { "$ref": "#/$defs/Returns" }, + "type": { "$ref": "#/$defs/Tokens", "description": "The type of a field, property or enum constant." }, + "nullness": { "$ref": "#/$defs/Nullness" }, + "throws": { "type": "array", "items": { "$ref": "#/$defs/Thrown" }, "description": "Declared and documented exceptions, merged." }, + "constant": { "type": "string", "description": "A compile-time constant's value as a source literal." }, + "defaultValue": { "type": "string", "description": "An annotation element's default as source text." }, + "overrides": { "$ref": "#/$defs/Ref", "description": "The member this one overrides or implements." }, + "implicit": { "type": "boolean", "description": "Whether the compiler declares it (a record's accessors, an enum's values())." }, + "doc": { "$ref": "#/$defs/Doc" }, + "deprecated": { "$ref": "#/$defs/Deprecation" }, + "since": { "type": "string" }, + "source": { "$ref": "#/$defs/Source" } + } + }, + "TypeAlias": { + "description": "A Kotlin type alias.", + "type": "object", + "additionalProperties": false, + "required": ["id", "name", "signature", "target"], + "properties": { + "id": { "type": "string" }, + "name": { "type": "string" }, + "typeParams": { "type": "array", "items": { "$ref": "#/$defs/TypeParam" } }, + "signature": { "$ref": "#/$defs/Tokens" }, + "target": { "$ref": "#/$defs/Tokens" }, + "doc": { "$ref": "#/$defs/Doc" }, + "deprecated": { "$ref": "#/$defs/Deprecation" }, + "since": { "type": "string" }, + "source": { "$ref": "#/$defs/Source" } + } + }, + "Nullness": { + "description": "Whether a reference type admits null; absent when unknown or not applicable.", + "enum": ["nullable", "nonNull"] + }, + "Param": { + "description": "A value parameter or record component.", + "type": "object", + "additionalProperties": false, + "required": ["name", "type"], + "properties": { + "name": { "type": "string" }, + "type": { "$ref": "#/$defs/Tokens" }, + "varargs": { "type": "boolean" }, + "defaultValue": { "type": "string", "description": "A Kotlin default argument as source text." }, + "nullness": { "$ref": "#/$defs/Nullness" }, + "annotations": { "type": "array", "items": { "$ref": "#/$defs/Tokens" } }, + "doc": { "$ref": "#/$defs/Blocks" } + } + }, + "TypeParam": { + "description": "A type parameter.", + "type": "object", + "additionalProperties": false, + "required": ["name"], + "properties": { + "name": { "type": "string" }, + "bounds": { "type": "array", "items": { "$ref": "#/$defs/Tokens" } }, + "doc": { "$ref": "#/$defs/Blocks" } + } + }, + "Returns": { + "description": "A return value.", + "type": "object", + "additionalProperties": false, + "required": ["type"], + "properties": { + "type": { "$ref": "#/$defs/Tokens" }, + "nullness": { "$ref": "#/$defs/Nullness" }, + "doc": { "$ref": "#/$defs/Blocks" } + } + }, + "Thrown": { + "description": "An exception a member throws.", + "type": "object", + "additionalProperties": false, + "required": ["type"], + "properties": { + "type": { "$ref": "#/$defs/Tokens" }, + "declared": { "type": "boolean", "description": "Whether the throws clause names it." }, + "doc": { "$ref": "#/$defs/Blocks" } + } + }, + "Deprecation": { + "description": "A deprecation.", + "type": "object", + "additionalProperties": false, + "properties": { + "doc": { "$ref": "#/$defs/Blocks" }, + "since": { "type": "string" }, + "forRemoval": { "type": "boolean" } + } + }, + "Inherited": { + "description": "Members a type inherits from one supertype.", + "type": "object", + "additionalProperties": false, + "required": ["from", "kind"], + "properties": { + "from": { "$ref": "#/$defs/Ref" }, + "kind": { "type": "string", "description": "class or interface." }, + "members": { "type": "array", "items": { "$ref": "#/$defs/Ref" } } + } + }, + "Source": { + "description": "A declaration's place in its source.", + "type": "object", + "additionalProperties": false, + "required": ["path", "line"], + "properties": { + "path": { "type": "string", "description": "The file's path below its source root." }, + "line": { "type": "integer", "minimum": 1 } + } + }, + "Ref": { + "description": "A reference to a declaration. It links locally when the model has the id, else through url, else not at all.", + "type": "object", + "additionalProperties": false, + "required": ["id"], + "properties": { + "id": { "type": "string" }, + "text": { "type": "string", "description": "The text to show, when not the target's own name." }, + "url": { "type": "string", "description": "The target's URL, when outside this model and an external covers it." } + } + }, + "TokenKind": { + "description": "What a signature token is.", + "enum": ["keyword", "name", "type", "typeParam", "annotation", "literal", "punct", "param"] + }, + "Token": { + "description": "One token of a signature.", + "type": "object", + "additionalProperties": false, + "required": ["kind", "text"], + "properties": { + "kind": { "$ref": "#/$defs/TokenKind" }, + "text": { "type": "string" }, + "ref": { "type": "string", "description": "The target's model id, for a type or annotation." }, + "url": { "type": "string", "description": "The target's URL when outside the model." } + } + }, + "Tokens": { "type": "array", "items": { "$ref": "#/$defs/Token" } }, + "Doc": { + "description": "Documentation as a tree. Parameter, return and exception documentation live on those parts.", + "type": "object", + "additionalProperties": false, + "properties": { + "summary": { "$ref": "#/$defs/Inlines", "description": "The first sentence." }, + "body": { "$ref": "#/$defs/Blocks", "description": "The full description, first sentence included." }, + "notes": { "type": "array", "items": { "$ref": "#/$defs/Note" } }, + "see": { "type": "array", "items": { "$ref": "#/$defs/Inlines" } }, + "inheritedFrom": { "$ref": "#/$defs/Ref", "description": "The member whose documentation this is, when inherited." } + } + }, + "NoteKind": { "enum": ["apiNote", "implSpec", "implNote"] }, + "Note": { + "description": "An @apiNote, @implSpec or @implNote section.", + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { + "kind": { "$ref": "#/$defs/NoteKind" }, + "body": { "$ref": "#/$defs/Blocks" } + } + }, + "Blocks": { "type": "array", "items": { "$ref": "#/$defs/Block" } }, + "Inlines": { "type": "array", "items": { "$ref": "#/$defs/Inline" } }, + "Block": { + "oneOf": [ + { "$ref": "#/$defs/Paragraph" }, + { "$ref": "#/$defs/ListBlock" }, + { "$ref": "#/$defs/CodeBlock" }, + { "$ref": "#/$defs/Table" }, + { "$ref": "#/$defs/Heading" }, + { "$ref": "#/$defs/Quote" }, + { "$ref": "#/$defs/RawBlock" } + ] + }, + "Paragraph": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "paragraph" }, "children": { "$ref": "#/$defs/Inlines" } } + }, + "ListBlock": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { + "kind": { "const": "list" }, + "ordered": { "type": "boolean" }, + "items": { "type": "array", "items": { "$ref": "#/$defs/Blocks" } } + } + }, + "CodeBlock": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "text"], + "properties": { + "kind": { "const": "code" }, + "language": { "type": "string", "description": "Absent for the declaration's own language." }, + "text": { "type": "string" } + } + }, + "Table": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { + "kind": { "const": "table" }, + "caption": { "$ref": "#/$defs/Inlines" }, + "head": { "type": "array", "items": { "$ref": "#/$defs/Row" } }, + "rows": { "type": "array", "items": { "$ref": "#/$defs/Row" } } + } + }, + "Row": { "type": "array", "items": { "$ref": "#/$defs/Blocks" } }, + "Heading": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "level"], + "properties": { + "kind": { "const": "heading" }, + "level": { "type": "integer", "minimum": 1 }, + "children": { "$ref": "#/$defs/Inlines" } + } + }, + "Quote": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "quote" }, "children": { "$ref": "#/$defs/Blocks" } } + }, + "RawBlock": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "html", "text"], + "properties": { "kind": { "const": "raw" }, "html": { "type": "string" }, "text": { "type": "string" } } + }, + "Inline": { + "oneOf": [ + { "$ref": "#/$defs/Text" }, + { "$ref": "#/$defs/Code" }, + { "$ref": "#/$defs/Emphasis" }, + { "$ref": "#/$defs/Strong" }, + { "$ref": "#/$defs/Link" }, + { "$ref": "#/$defs/Break" }, + { "$ref": "#/$defs/RawInline" } + ] + }, + "Text": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "text"], + "properties": { "kind": { "const": "text" }, "text": { "type": "string" } } + }, + "Code": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "text"], + "properties": { "kind": { "const": "code" }, "text": { "type": "string" } } + }, + "Emphasis": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "emphasis" }, "children": { "$ref": "#/$defs/Inlines" } } + }, + "Strong": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "strong" }, "children": { "$ref": "#/$defs/Inlines" } } + }, + "Link": { + "description": "A link to a declaration (target) or a URL. An unresolved declaration link renders as its label.", + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { + "kind": { "const": "link" }, + "target": { "$ref": "#/$defs/Ref" }, + "url": { "type": "string" }, + "code": { "type": "boolean", "description": "Whether the label is code ({@link}) rather than prose ({@linkplain})." }, + "children": { "$ref": "#/$defs/Inlines" } + } + }, + "Break": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "break" } } + }, + "RawInline": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "html", "text"], + "properties": { "kind": { "const": "raw" }, "html": { "type": "string" }, "text": { "type": "string" } } + } + } +} diff --git a/packages/apidocs/scripts/assets.ts b/packages/apidocs/scripts/assets.ts new file mode 100644 index 0000000..ced65ea --- /dev/null +++ b/packages/apidocs/scripts/assets.ts @@ -0,0 +1,20 @@ +/** + * Completes dist/: the stylesheet, the fonts the Elide preset names, the + * runner, and the JSON Schema, beside the two bundles Vite wrote. + */ +import { copyFileSync, mkdirSync } from "node:fs"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +import { elide } from "../src/presets/elide"; + +const require = createRequire(import.meta.url); +const pkg = (path: string) => fileURLToPath(new URL(`../${path}`, import.meta.url)); +mkdirSync(pkg("dist/assets/fonts"), { recursive: true }); +copyFileSync(pkg("src/styles/apidocs.css"), pkg("dist/assets/apidocs.css")); +copyFileSync(pkg("src/runner.mjs"), pkg("dist/runner.mjs")); +copyFileSync(pkg("schema/apidocs-1.schema.json"), pkg("dist/apidocs-1.schema.json")); +for (const font of elide.fonts ?? []) { + const file = font.asset.slice("fonts/".length); + const family = file.replace(/-latin-.*$/, ""); + copyFileSync(require.resolve(`@fontsource-variable/${family}/files/${file}`), pkg(`dist/assets/${font.asset}`)); +} diff --git a/packages/apidocs/scripts/dev.ts b/packages/apidocs/scripts/dev.ts new file mode 100644 index 0000000..49a038e --- /dev/null +++ b/packages/apidocs/scripts/dev.ts @@ -0,0 +1,199 @@ +/** + * The development loop: a Vite server that renders the sample models (or a + * real api.json) with the production render() and reloads the page when a + * component, the stylesheet, a theme, a sample or the model file changes. + * + * bun run dev [--port 5180] [--model path/to/api.json] [--no-open] + * + * Pages are served under /site///; / is a dev-only shell with + * controls for the theme preset, light or dark, the model and the viewport + * width. The shell and the module script that runs the islands in dev are not + * part of any output: `bun run sample` builds what the doclet writes. + */ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createServer, type ViteDevServer } from "vite"; + +const args = process.argv.slice(2); +const flag = (name: string) => { + const at = args.indexOf(`--${name}`); + return at < 0 ? undefined : args[at + 1]; +}; +const port = Number(flag("port") ?? 5180); +const host = flag("host") ?? "127.0.0.1"; +const modelPath = flag("model") ? resolve(process.env.INIT_CWD ?? process.cwd(), flag("model")!) : undefined; +const open = !args.includes("--no-open"); + +const root = fileURLToPath(new URL("..", import.meta.url)); +const require = createRequire(import.meta.url); +type Output = Record; +const cache = new Map(); + +async function site(server: ViteDevServer, model: string, preset: string): Promise { + const key = `${model}/${preset}`; + const cached = cache.get(key); + if (cached) return cached; + const { render } = await server.ssrLoadModule("/src/render.tsx"); + let input: unknown; + if (model === "model") { + if (!modelPath) throw new Error("Start the server with --model to browse a real model"); + input = readFileSync(modelPath, "utf8"); + } else { + const { samples } = await server.ssrLoadModule("/samples/index.ts"); + input = samples[model]; + if (!input) throw new Error(`No sample named ${model}`); + } + const started = performance.now(); + const out = render(input, { extends: preset === "elide" ? "elide" : "neutral" }) as Output; + console.log(` rendered ${model} with ${preset}: ${Object.keys(out).length} files in ${Math.round(performance.now() - started)} ms`); + cache.set(key, out); + return out; +} + +/** The dev-only replacement for the deferred client bundle: the islands as a module, plus Vite's reload client. */ +const DEV_SCRIPTS = ''; + +function asset(name: string): { body: Buffer | string; type: string } { + if (name === "apidocs.css") return { body: readFileSync(resolve(root, "src/styles/apidocs.css"), "utf8"), type: "text/css" }; + if (name.startsWith("fonts/")) { + const file = name.slice("fonts/".length); + return { body: readFileSync(require.resolve(`@fontsource-variable/${file.replace(/-latin-.*$/, "")}/files/${file}`)), type: "font/woff2" }; + } + throw new Error(`No asset ${name}`); +} + +const TYPES: Record = { + html: "text/html; charset=utf-8", md: "text/markdown; charset=utf-8", txt: "text/plain; charset=utf-8", + js: "text/javascript; charset=utf-8", css: "text/css; charset=utf-8", json: "application/json", + svg: "image/svg+xml", xml: "application/xml", +}; + +function shell(): string { + const models = ["java", "kotlin", ...(modelPath ? ["model"] : [])]; + return ` +apidocs dev + +
+ @elide/apidocs dev + + + + + + open page +
+
+ +`; +} + +const server = await createServer({ + root, + configFile: false, + appType: "custom", + oxc: { jsx: { runtime: "automatic", importSource: "preact" } }, + resolve: { dedupe: ["preact"] }, + server: { port, host, strictPort: true, open: open ? "/" : false }, + plugins: [{ + name: "apidocs-dev", + configureServer(dev) { + if (modelPath) dev.watcher.add(modelPath); + dev.watcher.on("change", file => { + if (file === modelPath || /\/(src|samples)\//.test(file)) { + cache.clear(); + dev.moduleGraph.invalidateAll(); + dev.ws.send({ type: "full-reload" }); + } + }); + dev.middlewares.use(async (req, res, next) => { + const url = new URL(req.url ?? "/", "http://localhost"); + if (url.pathname === "/") { + res.setHeader("content-type", TYPES.html!); + res.end(shell()); + return; + } + const match = /^\/site\/([^/]+)\/([^/]+)\/(.*)$/.exec(url.pathname); + if (!match) return next(); + const [, model, preset, rawPath] = match; + const path = decodeURIComponent(rawPath || "index.html"); + try { + const out = await site(dev, model!, preset!); + const file = out[path]; + if (file === undefined) { + res.statusCode = 404; + res.end(`Not in the rendered site: ${path}`); + return; + } + const ext = path.slice(path.lastIndexOf(".") + 1); + if (typeof file === "string") { + let body = file; + if (ext === "html") { + body = url.searchParams.has("nojs") + ? body.replace(/]*>[\s\S]*?<\/script>/g, m => (m.includes("ld+json") ? m : "")) + : body.replace(/', + "b.html": '

', + "c.js": "fetch('x')", + }, { allowed: [] }); + expect(errors).toEqual([ + "a.html: module script", + "a.html: absolute URL https://evil.example/x", + "a.html: link to a missing anchor b.html#nope", + "a.html: link to a missing file missing.html", + 'a.html: link does not name its file: "#top"', + "a.html: link names a directory: dir/", + "c.js: uses fetch", + ]); + }); +}); + +describe("parts", () => { + test("highlights Java and Kotlin", () => { + expect(highlight('String s = "a"; // c', "java")).toEqual([ + { cls: "t", text: "String" }, { text: " s = " }, { cls: "s", text: '"a"' }, { text: "; " }, { cls: "c", text: "// c" }, + ]); + expect(highlight("suspend fun f() = 1", "kotlin").filter(r => r.cls === "k").map(r => r.text)).toEqual(["suspend", "fun"]); + expect(highlight("x", "cobol")).toEqual([{ text: "x" }]); + }); + test("lays out long signatures one parameter per line", () => { + const tokens: Token[] = [ + { kind: "keyword", text: "public" }, { kind: "punct", text: " " }, { kind: "name", text: "transform" }, + { kind: "punct", text: "(" }, { kind: "type", text: "Map" }, { kind: "punct", text: "<" }, { kind: "type", text: "String" }, + { kind: "punct", text: ", " }, { kind: "type", text: "Object" }, { kind: "punct", text: "> " }, { kind: "param", text: "aVeryLongParameterName" }, + { kind: "punct", text: ", " }, { kind: "keyword", text: "int" }, { kind: "punct", text: " " }, { kind: "param", text: "anotherQuiteLongParameterName" }, + { kind: "punct", text: ")" }, + ]; + expect(layoutSignature(tokens).map(t => t.text).join("")).toBe( + "public transform(\n Map aVeryLongParameterName,\n int anotherQuiteLongParameterName\n)"); + expect(layoutSignature(tokens.slice(0, 4))).toEqual(tokens.slice(0, 4)); + }); + test("ranks search results", () => { + const entries: [string, string, string, string, string][] = [ + ["readAll()", "method", "a", "Reader", ""], ["Reader", "class", "b", "p", ""], ["ShapeReader", "class", "c", "p", ""], ["thread()", "method", "d", "X", ""], + ]; + expect(search(entries, "reader").map(e => e[0])).toEqual(["Reader", "ShapeReader", "readAll()"]); + expect(search(entries, "read").map(e => e[0])).toEqual(["Reader", "readAll()", "ShapeReader", "thread()"]); + expect(search(entries, "")).toEqual([]); + }); + test("drops executable markup from raw nodes", () => { + expect(sanitize('2y')).toBe("2y"); + }); +}); diff --git a/packages/apidocs/test/validate.ts b/packages/apidocs/test/validate.ts new file mode 100644 index 0000000..12eb16b --- /dev/null +++ b/packages/apidocs/test/validate.ts @@ -0,0 +1,68 @@ +/** + * A strict validator for the JSON Schema subset apidocs-1.schema.json uses: + * type, properties, required, additionalProperties: false, items, $ref, + * const, enum, oneOf and minimum. Returns every error with its JSON path. + */ +import schema from "../schema/apidocs-1.schema.json"; + +interface S { + $ref?: string; + type?: string; + const?: unknown; + enum?: unknown[]; + oneOf?: S[]; + items?: S; + properties?: Record; + required?: string[]; + additionalProperties?: boolean; + minimum?: number; +} + +const defs = (schema as { $defs: Record }).$defs; + +export function validate(value: unknown): string[] { + const errors: string[] = []; + check(value, schema as S, "$", errors); + return errors; +} + +function check(value: unknown, s: S, path: string, errors: string[]) { + if (s.$ref) return check(value, defs[s.$ref.replace("#/$defs/", "")]!, path, errors); + if (s.const !== undefined && value !== s.const) errors.push(`${path}: expected ${JSON.stringify(s.const)}`); + if (s.enum && !s.enum.includes(value)) errors.push(`${path}: ${JSON.stringify(value)} is not one of ${s.enum.join(", ")}`); + if (s.oneOf) { + const matches = s.oneOf.filter(option => { + const sub: string[] = []; + check(value, option, path, sub); + return sub.length === 0; + }); + if (matches.length !== 1) errors.push(`${path}: matches ${matches.length} of the oneOf options (kind ${JSON.stringify((value as { kind?: unknown })?.kind)})`); + return; + } + switch (s.type) { + case "string": if (typeof value !== "string") errors.push(`${path}: expected a string`); break; + case "boolean": if (typeof value !== "boolean") errors.push(`${path}: expected a boolean`); break; + case "integer": + if (!Number.isInteger(value)) errors.push(`${path}: expected an integer`); + else if (s.minimum !== undefined && (value as number) < s.minimum) errors.push(`${path}: below ${s.minimum}`); + break; + case "array": + if (!Array.isArray(value)) errors.push(`${path}: expected an array`); + else value.forEach((item, i) => check(item, s.items!, `${path}[${i}]`, errors)); + break; + case "object": { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + errors.push(`${path}: expected an object`); + break; + } + const record = value as Record; + for (const key of s.required ?? []) if (!(key in record)) errors.push(`${path}: missing ${key}`); + for (const [key, item] of Object.entries(record)) { + const prop = s.properties?.[key]; + if (!prop) { + if (s.additionalProperties === false) errors.push(`${path}: unexpected property ${key}`); + } else check(item, prop, `${path}.${key}`, errors); + } + } + } +} diff --git a/packages/apidocs/tsconfig.json b/packages/apidocs/tsconfig.json new file mode 100644 index 0000000..5216944 --- /dev/null +++ b/packages/apidocs/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react-jsx", + "jsxImportSource": "preact", + "strict": true, + "noUncheckedIndexedAccess": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "types": ["bun"] + }, + "include": ["src", "scripts", "test", "samples", "*.ts"] +} diff --git a/packages/apidocs/vite.client.config.ts b/packages/apidocs/vite.client.config.ts new file mode 100644 index 0000000..698ae6a --- /dev/null +++ b/packages/apidocs/vite.client.config.ts @@ -0,0 +1,5 @@ +import { defineConfig } from "vite"; +import { bundle } from "./vite.shared.ts"; + +// assets/apidocs.js: the client islands, Preact inlined, loaded with defer. +export default defineConfig(bundle("src/client/islands.tsx", "ApiDocsClient", "apidocs.js", "dist/assets")); diff --git a/packages/apidocs/vite.render.config.ts b/packages/apidocs/vite.render.config.ts new file mode 100644 index 0000000..3587f1d --- /dev/null +++ b/packages/apidocs/vite.render.config.ts @@ -0,0 +1,6 @@ +import { defineConfig } from "vite"; +import { bundle } from "./vite.shared.ts"; + +// render.js: the pure render(model, theme) function, Preact and the highlighter inlined, one classic script that +// defines the global ApiDocs. +export default defineConfig(bundle("src/entry-render.ts", "ApiDocs", "render.js", "dist")); diff --git a/packages/apidocs/vite.shared.ts b/packages/apidocs/vite.shared.ts new file mode 100644 index 0000000..06d4401 --- /dev/null +++ b/packages/apidocs/vite.shared.ts @@ -0,0 +1,19 @@ +import type { UserConfig } from "vite"; + +/** Settings both bundles share: Preact JSX, ES2020 output (GraalJS, Bun, Node and browsers), no CDN, no splitting. */ +export function bundle(entry: string, name: string, fileName: string, outDir: string): UserConfig { + return { + oxc: { jsx: { runtime: "automatic", importSource: "preact" } }, + resolve: { dedupe: ["preact"] }, + build: { + target: "es2020", + outDir, + emptyOutDir: false, + minify: true, + sourcemap: false, + copyPublicDir: false, + lib: { entry, name, formats: ["iife"], fileName: () => fileName }, + }, + logLevel: "warn", + }; +} diff --git a/turbo.json b/turbo.json index 35e33b8..a794cf5 100644 --- a/turbo.json +++ b/turbo.json @@ -40,6 +40,15 @@ "^build" ] }, + "@elide/apidocs#build": { + "dependsOn": ["^build"], + "outputs": ["dist/**"] + }, + "@elide/apidocs#test": { + "dependsOn": ["build"], + "cache": false, + "passThroughEnv": ["PLAYWRIGHT_BROWSERS_PATH"] + }, "@elide/elements#test": { "dependsOn": ["build"], "cache": false From 62930485e62b8d5614cc9b2f3e3ada12f540094d Mon Sep 17 00:00:00 2001 From: Sam Gammon Date: Sat, 21 Nov 2026 12:57:52 -0800 Subject: [PATCH 02/36] fix(apidocs): allowlist raw HTML and reject unsafe link URLs Documentation comments are untrusted input once the renderer documents third-party code, and its pages are served from the publisher's origin. Two paths let comment content execute. Raw HTML nodes went through a regex blocklist that entity-encoded schemes, unquoted or malformed attributes, srcdoc, data: URLs and svg/iframe content could bypass. sanitize() now parses the markup with a small tokenizer (the render bundle has no DOM) and rebuilds it from an allowlist: the inline and block tags Javadoc uses, title on any of them, href on a, colspan and rowspan as numbers, and scope from its four values. Values are entity-decoded, then escaped. Script-like elements (script, style, iframe, svg, math, object, template, ...) are dropped with their content. Other unknown tags keep their text. Unterminated tags and attributes end the input. Open tags are closed. Link URLs from the model or the theme went into href unchecked. safeUrl() decodes character references, strips the control characters and whitespace that browsers ignore, and allows only http:, https:, mailto: and relative URLs. It applies in resolve() (refs, signature tokens, externals), in documentation links, in source links and in the Markdown output. An unsafe link renders its label as plain text. The theme's header and footer links, base URL and source-link template pass the same check before rendering. The output checker also fails on any on*= attribute and on any href or src that safeUrl rejects. Checks run: `bun test test/security.test.ts` (62 pass). It covers javascript: in mixed case, with entity, tab, newline and control-character obfuscation, data:text/html, vbscript:, file:, event handlers in every quoting style, ", "DATA:text/html;base64,PHNjcmlwdD4=", "vbscript:msgbox(1)", + "file:///etc/passwd", "blob:https://x/y", "\\\\evil/share", "java\u0000script:alert(1)", + ]; + for (const url of hostile) test(`rejects ${JSON.stringify(url)}`, () => expect(safeUrl(url)).toBeUndefined()); + const fine = ["https://example.com/a?b#c", "HTTP://example.com", "mailto:a@example.com", "../x.html#y", "x.html", "a/b.html#read(java.io.InputStream)"]; + for (const url of fine) test(`keeps ${url}`, () => expect(safeUrl(url)).toBe(url)); +}); + +describe("sanitize", () => { + const cases: [string, string][] = [ + ['x', "x"], + ["x", "x"], + ["x", "x"], + ['x', "x"], + ["x", "x"], + ['x', 'x'], + ["after", "after"], + ["after", "after"], + ["", ""], + ["after", "after"], + ['after', "after"], + ['x', "x"], + ['x', "x"], + ['x', "x"], + ['x', "x"], + ['x', "x"], + ['ok', 'ok'], + ['2', "2"], + ["shown", "shown"], + ["xshown", "shown"], + ["", ""], + ["unclosed", "unclosed"], + [' 2", "1 < 2 && 3 > 2"], + ["kept", "kept"], + ["

ok

", "

ok

"], + ["text", "text"], + ['c', 'c'], + ['h', 'h'], + ['t', 't'], + ["
stray", "stray"], + ]; + for (const [input, output] of cases) test(`sanitizes ${JSON.stringify(input)}`, () => expect(sanitize(input)).toBe(output)); +}); + +describe("hostile models and themes", () => { + const hostile: Model = { + schema: "apidocs/1", + module: { name: "evil", doc: { body: [{ kind: "paragraph", children: [ + { kind: "link", url: "javascript:alert(1)", children: [{ kind: "text", text: "click me" }] }, + { kind: "link", url: "javascript:alert(2)", children: [{ kind: "text", text: "encoded" }] }, + { kind: "raw", html: '2', text: "2" }, + ] }, { kind: "raw", html: "", text: "" }] } }, + externals: [{ prefix: "x.", url: "javascript:alert(7)//" }], + packages: [{ id: "p", name: "p", types: [{ + id: "p.T", name: "T", kind: "class", language: "java", + signature: [{ kind: "type", text: "Evil", ref: "x.Evil", url: "javascript:alert(8)" }], + source: { path: "p/T.java", line: 1 }, + doc: { see: [[{ kind: "link", url: "data:text/html,", children: [{ kind: "text", text: "see" }] }]] }, + }] }], + }; + const theme = { + links: { header: [{ label: "bad", url: "javascript:alert(10)" }, { label: "good", url: "https://example.com/" }], footer: [{ label: "bad", url: " vbscript:x" }] }, + sourceLink: "javascript:alert('{path}')", + baseUrl: "javascript:alert(11)//", + }; + const site = render(hostile, theme); + + test("the output has no event handlers and no unsafe URLs", () => { + expect(checkSite(site, { allowed: ["https://example.com/"] })).toEqual([]); + for (const [file, content] of Object.entries(site)) { + if (typeof content !== "string" || !file.endsWith(".html")) continue; + expect(content).not.toMatch(/javascript:|vbscript:|data:text|onerror|onload|onclick/i); + expect(content).not.toMatch(/", "DATA:text/html;base64,PHNjcmlwdD4=", "vbscript:msgbox(1)", "file:///etc/passwd", "blob:https://x/y", "\\\\evil/share", "java\u0000script:alert(1)", + "jav&#x61;script:alert(1)", "jav&amp;#x61;script:alert(1)", "&#106;avascript:alert(1)", + "javascript&colon;alert(1)", "javascript&amp;colon;alert(1)", "java script:alert(1)", + "java script:alert(1)", "&amp;amp;amp;amp;amp;#106;avascript:alert(1)", ]; for (const url of hostile) test(`rejects ${JSON.stringify(url)}`, () => expect(safeUrl(url)).toBeUndefined()); const fine = ["https://example.com/a?b#c", "HTTP://example.com", "mailto:a@example.com", "../x.html#y", "x.html", "a/b.html#read(java.io.InputStream)"]; @@ -61,6 +64,26 @@ describe("sanitize", () => { for (const [input, output] of cases) test(`sanitizes ${JSON.stringify(input)}`, () => expect(sanitize(input)).toBe(output)); }); +describe("Markdown link destinations", () => { + const model: Model = { + schema: "apidocs/1", + module: { name: "m", doc: { body: [{ kind: "paragraph", children: [ + { kind: "link", url: "https://example.com/a?b=1&c=(x) y\"z'`v\\", children: [{ kind: "text", text: "odd" }] }, + { kind: "link", url: "jav&#x61;script:alert(1)", children: [{ kind: "text", text: "double" }] }, + ] }] } }, + }; + const md = render(model)["index.md"] as string; + test("are percent-encoded so a Markdown renderer cannot reinterpret them", () => { + const destination = /\[odd\]\(([^\s]*)\)/.exec(md)?.[1]; + expect(destination).toBe("https://example.com/a?b=1%26c=%28x%29%20y%22z%27%3Cw%3E%60v%5C"); + expect(destination).not.toMatch(/[&()<>"'`\\ ]/); + }); + test("drop a doubly encoded script URL, keeping the label", () => { + expect(md).toContain("double"); + expect(md).not.toMatch(/script:/i); + }); +}); + describe("hostile models and themes", () => { const hostile: Model = { schema: "apidocs/1", From 6c18339d4aafd47e3718ffa2817e1541973ccb29 Mon Sep 17 00:00:00 2001 From: Sam Gammon Date: Sat, 21 Nov 2026 13:12:05 -0800 Subject: [PATCH 04/36] feat(apidocs): add the redesigned page layout, and test it The layout was redesigned at the owner's direction, over three review rounds of the dev pages. This commit adds the layout files as they stand (page shell and navigator, pages, groupings, client islands, stylesheet, theme and Elide preset), and adapts and extends the tests to them. Layout changes: - Navigator: two flat lists with no disclosure widgets. Packages are listed by the part of the name that differs, under a shared-prefix row (sharedPrefix). Then the current package's types are listed by kind, with one-letter kind tiles (kindGlyph). Rows are one line, truncate, and carry a title. - "On this page" rail: sections with counts. A section with more than 12 entries is folded into
. Members can be filtered. - One Callout component for API notes, implementation requirements, implementation notes and deprecations, each with an icon tile and a label. There are no left bars; the large signature has a hairline border. - Controls that need the script carry data-js-only. A head script marks before first paint, so those controls show at once with script and never without it. - A checkbox toggles the navigator without script: it hides it on wide screens and shows it on narrow ones. localStorage remembers "closed", and [ toggles it. The checkbox sits inside the header landmark. - Fonts use font-display: optional and metric-adjusted local fallbacks. Font preloads are added at run time only off file://, where crossorigin font preloads fail. - @view-transition, content-visibility on member cards, and scrollbar-gutter: stable. Tests: - render.test.ts: callout classes; sharedPrefix (one package, several, one equal to the prefix, the default package); no
in the navigator; a rail section over 12 entries folded and a short one not; data-js-only controls and the head script; the navigator checkbox; preloads absent from static HTML and listed for upright faces only. The checker allows inline classic scripts and JSON-LD, and still rejects module scripts, fetch, on* attributes and unsafe URLs. HTML snapshots refreshed. - browser.test.ts: from file:// with JavaScript off, script-only controls stay hidden. With it on, they show before the deferred bundle runs. Also covered: search, the theme switch, copy, table-of-contents tracking, and the navigator toggle on wide and narrow screens. On wide screens the choice survives a reload and [ toggles it. Font preloads appear over HTTP (3) and not on file:// (0), with no console errors. Cumulative layout shift is 0 on load for a type page, both with fonts and with font requests blocked. axe reports nothing in light or dark. Checks run: `bunx turbo run lint test --filter=@elide/apidocs --force` (tsc clean, 127 tests pass); the layout files' checksums did not change between the test run and this commit. --- packages/apidocs/src/client/islands.tsx | 343 ++++++++++ packages/apidocs/src/components/chrome.tsx | 344 ++++++++++ .../apidocs/src/components/declaration.tsx | 42 +- packages/apidocs/src/pages.tsx | 406 ++++++++++++ packages/apidocs/src/presets/elide.ts | 101 +++ packages/apidocs/src/structure.ts | 136 ++++ packages/apidocs/src/styles/apidocs.css | 626 ++++++++++++++++++ packages/apidocs/src/theme.ts | 111 ++++ .../test/__snapshots__/render.test.ts.snap | 33 + packages/apidocs/test/browser.test.ts | 138 +++- packages/apidocs/test/render.test.ts | 58 +- 11 files changed, 2304 insertions(+), 34 deletions(-) create mode 100644 packages/apidocs/src/client/islands.tsx create mode 100644 packages/apidocs/src/components/chrome.tsx create mode 100644 packages/apidocs/src/pages.tsx create mode 100644 packages/apidocs/src/presets/elide.ts create mode 100644 packages/apidocs/src/structure.ts create mode 100644 packages/apidocs/src/styles/apidocs.css create mode 100644 packages/apidocs/src/theme.ts create mode 100644 packages/apidocs/test/__snapshots__/render.test.ts.snap diff --git a/packages/apidocs/src/client/islands.tsx b/packages/apidocs/src/client/islands.tsx new file mode 100644 index 0000000..0a445f9 --- /dev/null +++ b/packages/apidocs/src/client/islands.tsx @@ -0,0 +1,343 @@ +/** + * The client bundle: four small islands over prerendered pages. Each one finds + * its static markup and adds behavior; with JavaScript off the pages lose these + * and nothing else. Classic script, no modules, no fetch: the search index is a + * script that assigns window.apidocsSearch, loaded on first use. + */ +import { render } from "preact"; + +import { type Entry, search } from "./search"; + +declare global { + interface Window { + apidocsSearch?: Entry[]; + } +} + +const doc = document; +const root = doc.documentElement.getAttribute("data-root") ?? "./"; + +function storage(): Storage | undefined { + try { + return window.localStorage; + } catch { + return undefined; + } +} + +// ---- Theme switch: system, light, dark; the choice persists where storage works. + +function themeSwitch() { + const button = doc.querySelector("[data-theme-switch]"); + if (!button) return; + const modes = ["system", "light", "dark"] as const; + type Mode = (typeof modes)[number]; + let mode: Mode = "system"; + try { + const stored = storage()?.getItem("apidocs-theme"); + if (stored === "light" || stored === "dark") mode = stored; + } catch { + /* storage blocked: follow the system */ + } + const apply = () => { + if (mode === "system") doc.documentElement.removeAttribute("data-theme"); + else doc.documentElement.setAttribute("data-theme", mode); + button.dataset.mode = mode; + button.setAttribute("aria-label", `Color theme: ${mode}. Change`); + button.title = `Theme: ${mode}`; + }; + button.hidden = false; + apply(); + button.addEventListener("click", () => { + mode = modes[(modes.indexOf(mode) + 1) % modes.length]!; + try { + if (mode === "system") storage()?.removeItem("apidocs-theme"); + else storage()?.setItem("apidocs-theme", mode); + } catch { + /* not persisted */ + } + apply(); + }); +} + +// ---- Copy buttons on signatures and code blocks. + +function copyButtons() { + for (const button of doc.querySelectorAll("[data-copy]")) { + button.hidden = false; + button.addEventListener("click", async () => { + const text = button.parentElement?.querySelector("pre")?.textContent ?? ""; + let ok = false; + try { + await navigator.clipboard.writeText(text); + ok = true; + } catch { + const area = doc.createElement("textarea"); + area.value = text; + area.setAttribute("readonly", ""); + area.style.position = "fixed"; + area.style.opacity = "0"; + doc.body.appendChild(area); + area.select(); + try { + ok = doc.execCommand("copy"); + } catch { + ok = false; + } + area.remove(); + } + button.textContent = ok ? "Copied" : "Copy failed"; + button.dataset.copied = ""; + setTimeout(() => { + button.textContent = "Copy"; + delete button.dataset.copied; + }, 1500); + }); + } +} + +// ---- Search over the lazily loaded index. + +function loadIndex(): Promise { + if (window.apidocsSearch) return Promise.resolve(window.apidocsSearch); + return new Promise((resolve, reject) => { + const script = doc.createElement("script"); + script.src = `${root}assets/search-index.js`; + script.onload = () => (window.apidocsSearch ? resolve(window.apidocsSearch) : reject(new Error("empty index"))); + script.onerror = () => reject(new Error("search index did not load")); + doc.head.appendChild(script); + }); +} + +function Results({ items, active, query }: { items: Entry[]; active: number; query: string }) { + if (!items.length) return ; + return ( + <> + {items.map((item, i) => ( +
  • + + + {item[1]} + {(item[3] || item[4]) && {[item[3], item[4]].filter(Boolean).join(": ")}} + +
  • + ))} + + ); +} + +function Highlight({ text, query }: { text: string; query: string }) { + const at = text.toLowerCase().indexOf(query.trim().toLowerCase()); + if (at < 0 || !query.trim()) return <>{text}; + const end = at + query.trim().length; + return <>{text.slice(0, at)}{text.slice(at, end)}{text.slice(end)}; +} + +function searchBox() { + const box = doc.querySelector("[data-search]"); + const input = box?.querySelector("input"); + const list = box?.querySelector("ul"); + if (!box || !input || !list) return; + box.hidden = false; + doc.querySelector(".search-fallback")?.setAttribute("hidden", ""); + let items: Entry[] = []; + let active = 0; + let entries: Entry[] | undefined; + + const show = () => { + const open = input.value.trim().length > 0; + list.hidden = !open; + input.setAttribute("aria-expanded", String(open)); + if (open) { + render(, list); + input.setAttribute("aria-activedescendant", items.length ? `apidocs-result-${active}` : ""); + doc.getElementById(`apidocs-result-${active}`)?.scrollIntoView({ block: "nearest" }); + } + }; + const update = async () => { + try { + entries ??= await loadIndex(); + } catch { + entries = []; + } + items = search(entries, input.value); + active = 0; + show(); + }; + input.addEventListener("focus", () => void loadIndex().then(e => (entries = e)).catch(() => undefined)); + input.addEventListener("input", () => void update()); + input.addEventListener("keydown", event => { + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + if (!items.length) return; + event.preventDefault(); + active = (active + (event.key === "ArrowDown" ? 1 : items.length - 1)) % items.length; + show(); + } else if (event.key === "Enter") { + const item = items[active]; + if (item) { + event.preventDefault(); + window.location.href = root + item[2]; + } + } else if (event.key === "Escape") { + input.value = ""; + items = []; + show(); + input.blur(); + } + }); + doc.addEventListener("click", event => { + if (!box.contains(event.target as Node)) { + list.hidden = true; + input.setAttribute("aria-expanded", "false"); + } + }); + doc.addEventListener("keydown", event => { + const target = event.target as HTMLElement; + if (event.key === "/" && !event.metaKey && !event.ctrlKey && !/^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName) && !target.isContentEditable) { + event.preventDefault(); + input.focus(); + } + }); +} + +// ---- Table of contents: mark the section in view; keep the navigation's scroll position. + +function tableOfContents() { + const toc = doc.querySelector(".toc"); + const links = new Map(); + for (const link of doc.querySelectorAll("[data-toc-target]")) links.set(link.dataset.tocTarget!, link); + if (toc && links.size && "IntersectionObserver" in window) { + const visible = new Set(); + let current: HTMLAnchorElement | undefined; + const observer = new IntersectionObserver(entries => { + for (const entry of entries) { + if (entry.isIntersecting) visible.add(entry.target.id); + else visible.delete(entry.target.id); + } + // The most specific entry in view: a member over the section that contains it. + let first: HTMLAnchorElement | undefined; + for (const [id, link] of links) { + if (!visible.has(id)) continue; + if (!first || (link.closest(".toc-entries") && !first.closest(".toc-entries"))) first = link; + if (first.closest(".toc-entries")) break; + } + if (first && first !== current) { + current?.removeAttribute("aria-current"); + first.setAttribute("aria-current", "true"); + current = first; + const fold = first.closest("details"); + if (fold) fold.open = true; + const top = first.offsetTop - toc.clientHeight / 3; + if (first.offsetTop < toc.scrollTop || first.offsetTop > toc.scrollTop + toc.clientHeight - 40) toc.scrollTop = Math.max(0, top); + } + }, { rootMargin: "-56px 0px -55% 0px" }); + for (const id of links.keys()) { + const target = doc.getElementById(id); + if (target) observer.observe(target); + } + } + + const nav = doc.querySelector(".sidebar"); + if (nav) { + const key = `apidocs-nav:${new URL(root, window.location.href).pathname}`; + let restored = false; + try { + const saved = window.sessionStorage.getItem(key); + if (saved) { + nav.scrollTop = Number(saved); + restored = true; + } + } catch { + /* storage blocked */ + } + const currentLink = nav.querySelector('[aria-current="page"]'); + if (currentLink && (!restored || currentLink.offsetTop < nav.scrollTop || currentLink.offsetTop > nav.scrollTop + nav.clientHeight)) { + nav.scrollTop = Math.max(0, currentLink.offsetTop - nav.clientHeight / 3); + } + window.addEventListener("pagehide", () => { + try { + window.sessionStorage.setItem(key, String(nav.scrollTop)); + } catch { + /* storage blocked */ + } + }); + } +} + +// ---- List filters: narrow the navigator, or the page rail and the member summary, to rows that match. + +function listFilter(boxSelector: string, rowSelector: string, also?: string) { + const box = doc.querySelector(boxSelector); + const input = box?.querySelector("input"); + if (!box || !input) return; + box.hidden = false; + input.addEventListener("input", () => { + const query = input.value.trim().toLowerCase(); + const scope = box.parentElement!; + for (const fold of scope.querySelectorAll("details")) if (query) fold.open = true; + for (const row of scope.querySelectorAll(rowSelector)) { + const hit = !query || (row.textContent ?? "").toLowerCase().includes(query); + row.toggleAttribute("data-filtered-out", !hit); + } + if (also) { + for (const row of doc.querySelectorAll(also)) { + const hit = !query || (row.querySelector("th")?.textContent ?? "").toLowerCase().includes(query); + row.toggleAttribute("data-filtered-out", !hit); + } + } + }); + input.addEventListener("keydown", event => { + if (event.key === "Escape") { + input.value = ""; + input.dispatchEvent(new Event("input")); + } + }); +} + +// ---- The navigator toggle: remember "hidden" on wide screens; "[" toggles it. + +function navigatorToggle() { + const toggle = doc.querySelector("#apidocs-nav-toggle"); + if (!toggle) return; + const wide = window.matchMedia("(min-width: 861px)"); + toggle.addEventListener("change", () => { + if (!wide.matches) return; + try { + window.localStorage.setItem("apidocs-nav", toggle.checked ? "closed" : "open"); + } catch { + /* storage blocked */ + } + }); + // A narrow screen's open panel must not become a hidden navigator when the window grows, or the reverse. + wide.addEventListener("change", () => { + let closed = false; + try { + closed = window.localStorage.getItem("apidocs-nav") === "closed"; + } catch { + /* storage blocked */ + } + toggle.checked = wide.matches && closed; + }); + doc.addEventListener("keydown", event => { + const target = event.target as HTMLElement; + if (event.key === "[" && !event.metaKey && !event.ctrlKey && !event.altKey && !/^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName) && !target.isContentEditable) { + toggle.checked = !toggle.checked; + toggle.dispatchEvent(new Event("change")); + } + }); +} + +function start() { + doc.documentElement.dataset.js = ""; + themeSwitch(); + copyButtons(); + searchBox(); + tableOfContents(); + navigatorToggle(); + // Types only: packages stay, so the way to another package is never filtered away. + listFilter("[data-nav-filter]", ".nav-section:not(:first-of-type) .nav-list > li"); + listFilter("[data-toc-filter]", ".toc-entries > li", "#member-summary table.summary tbody tr"); +} + +if (doc.readyState === "loading") doc.addEventListener("DOMContentLoaded", start); +else start(); diff --git a/packages/apidocs/src/components/chrome.tsx b/packages/apidocs/src/components/chrome.tsx new file mode 100644 index 0000000..b653fab --- /dev/null +++ b/packages/apidocs/src/components/chrome.tsx @@ -0,0 +1,344 @@ +/** The page shell: head, header, navigation, breadcrumbs, table of contents and footer. */ +import type { ComponentChildren } from "preact"; +import { usePage } from "../context"; +import type { Package, Type } from "../model"; +import { INDEX, isAbsolute, isThrowable, packagePage, relative, rootOf, typePage } from "../site"; +import { typeGroups } from "../structure"; +import type { Theme } from "../theme"; + +export interface Crumb { + label: string; + page?: string; +} + +export interface TocItem { + id: string; + label: string; + depth: number; + code?: boolean; +} + +/** + * Runs before first paint: applies a stored theme choice, and marks the page as scripted so the controls that + * need the script take their space at once instead of appearing (and moving the page) when the bundle loads. + */ +const THEME_BOOT = + 'document.documentElement.setAttribute("data-js","");try{var t=localStorage.getItem("apidocs-theme");if(t==="light"||t==="dark")document.documentElement.setAttribute("data-theme",t)}catch(e){}'; + +/** The width that keeps an SVG's aspect ratio at a height, from its viewBox, so the image reserves its box before it loads. */ +function logoWidth(svg: string, height: number): number | undefined { + const box = /viewBox="\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)/.exec(svg); + if (!box) return undefined; + const w = Number(box[1]); + const h = Number(box[2]); + return w > 0 && h > 0 ? Math.round((height * w) / h) : undefined; +} + +/** Restores the navigator's scroll position as soon as it is parsed, so it never jumps after paint. */ +const NAV_BOOT = + '(function(){var n=document.getElementById("apidocs-nav");if(!n)return;try{var k="apidocs-nav:"+new URL(document.documentElement.getAttribute("data-root")||"./",location.href).pathname;var s=sessionStorage.getItem(k);if(s)n.scrollTop=+s}catch(e){}var c=n.querySelector(\'[aria-current="page"]\');if(c&&(c.offsetTopn.scrollTop+n.clientHeight-40))n.scrollTop=Math.max(0,c.offsetTop-n.clientHeight/3)})()'; + +/** + * Preloads the upright font files, so they are ready at first paint. Done from the head script, not with link + * elements in the markup, because a font preload is a cross-origin request and a page opened from file:// has + * no origin to make one with: there the links would fail and log errors, and the faces load from CSS as usual. + */ +function fontPreload(fonts: Theme["fonts"], root: string): string { + const urls = (fonts ?? []) + .filter(face => face.preload ?? (face.style ?? "normal") === "normal") + .map(face => `${root}assets/${face.asset}`); + if (urls.length === 0) return ""; + const list = JSON.stringify(urls).replace(/ + + + + {title} + + + {canonical && } + + + + {theme.favicon && } +
    fixture1.0
    All types

    Geometry

    classin fixture.javasince 1.0null-marked

    public final class Geometry
    Inheritance
    1. Object
    2. Geometry

    Operations on shapes.

    Every method is pure: it never modifies its arguments. Thread safety: every method is safe to call concurrently.

    1. First, measure.

    2. Then compare, with compareTo.

    Unit factors
    UnitFactor
    Units.METERS1.0
    Units.FEET0.3048
    Shape big = Geometry.largest(List.of(Circle.of(1), Rect.square(2)));
    +double total = Geometry.totalArea(big, Circle.of(3));

    Measure twice, cut once.

    Edge cases

    Text with an entity — a superscript kept as raw markup, a line
    break, a hyperlink, and <angle brackets> as literal text.

    Implementation note

    Areas are computed in double precision.

    See also

    Nested types

    NameKindDescription
    LegacyclassMethods from before null markings; their nullness is unspecified.

    Member summary

    Fields

    NameDescription
    static int PRECISIONThe default number of significant digits: 6.
    static String NAMEThe library's name, "fixture", as tools report it.

    Methods

    NameDescription
    static T largest(Collection)Returns the largest shape.
    static double totalArea(Shape...)Sums the shapes' areas.
    static Shape parse(String)Parses a shape from its text form, such as circle 2.5.
    static double sum(List)deprecatedSums the areas of a list of shapes.
    static Shape find(Map, String)Finds a shape by name.

    Fields

    PRECISION

    static
    public static final int PRECISION

    The default number of significant digits: 6.

    Value

    int
    Constant: 6

    NAME

    static
    public static final String NAME

    The library's name, "fixture", as tools report it.

    Value

    Stringnon-null
    Constant: "fixture"

    Methods

    largest

    static
    public static <T extends Shape & Comparable<? super T>> T largest(
    +    Collection<? extends T> shapes
    +)

    Returns the largest shape.

    Type parameters

    <T>
    the shape type

    Parameters

    shapesCollection<? extends T>non-null
    the shapes; not empty

    Returns

    T
    the largest of shapes

    Throws

    NoSuchElementExceptionunchecked
    if shapes is empty

    Implementation requirements

    Compares with Comparable.compareTo(Object), keeping the first of equal shapes.

    totalArea

    static
    @Measured(precision = 6)
    +public static double totalArea(Shape... shapes)

    Sums the shapes' areas.

    Parameters

    shapesShape...non-null
    the shapes

    Returns

    double
    the total area in square meters; 0 for no shapes

    parse

    static
    public static Shape parse(String text) throws IOException, ParseException

    Parses a shape from its text form, such as circle 2.5.

    Parameters

    textStringnon-null
    the text form

    Returns

    Shapenon-null
    the shape

    Throws

    IOException
    if the text names a file that cannot be read
    IllegalStateExceptionunchecked
    if the parser was closed
    ParseException
    No description.

    API note

    The text form is not stable across releases; store shapes some other way.

    sum

    staticdeprecated for removal
    @Deprecated(since = "1.1", forRemoval = true)
    +public static double sum(List<Shape> shapes)

    Deprecated for removal since 1.1

    Use totalArea(Shape...), which takes any number of shapes.

    Sums the areas of a list of shapes.

    Parameters

    shapesList<Shape>non-null
    the shapes

    Returns

    double
    the total area

    find

    staticsince 1.1
    public static @Nullable Shape find(
    +    Map<String, ? extends Shape> shapes,
    +    String name
    +)

    Finds a shape by name.

    Parameters

    shapesMap<String, ? extends Shape>non-null
    shapes by name
    nameStringnon-null
    the name to look up

    Returns

    @Nullable Shapenullable
    the shape, or null when there is none

    Inherited members

    +" +`; + +exports[`render HTML snapshots: fixture/java/Circle.html 1`] = ` +" +Circle (fixture 1.0)
    fixture1.0
    All types

    Circle

    recordin fixture.javasince 1.0null-marked

    public record Circle(double radius, @Nullable String label) implements Shape
    Inheritance
    1. Object
    2. Record
    3. Circle
    Implements

    A circle.

    Record components

    radiusdouble
    the radius in meters; not negative
    label@Nullable Stringnullable
    an optional label

    Member summary

    Constructors

    NameDescription
    Circle(double, String)Checks the radius.

    Methods

    NameDescription
    static Circle of(double)Creates an unlabeled circle.
    double area()The shape's area.
    String name()Returns the shape's name, or null for an anonymous shape.
    R accept(Shape.Visitor)Calls the visitor's method for this shape's kind.
    String toString()No description.
    int hashCode()No description.
    boolean equals(Object)No description.
    double radius()No description.
    String label()No description.

    Constructors

    Circle

    public Circle(double radius, @Nullable String label)

    Checks the radius.

    Parameters

    radiusdouble
    the radius in meters; not negative
    label@Nullable Stringnullable
    an optional label

    Throws

    IllegalArgumentExceptionunchecked
    if radius is negative

    Methods

    of

    static
    public static Circle of(double radius)

    Creates an unlabeled circle.

    Parameters

    radiusdouble
    the radius in meters

    Returns

    Circlenon-null
    the circle

    area

    public double area()

    The shape's area. For a circle this is π r².

    Returns

    double
    the area in square meters, never negative

    Overrides area().

    name

    public @Nullable String name()

    Returns the shape's name, or null for an anonymous shape.

    Description copied from name().

    Returns

    @Nullable Stringnullable
    the shape's name, or null for an anonymous shape

    Overrides name().

    accept

    public <R> R accept(Shape.Visitor<R> visitor)

    Calls the visitor's method for this shape's kind.

    Description copied from accept().

    Type parameters

    <R>
    the visitor's result type

    Parameters

    visitorShape.Visitor<R>non-null
    the visitor

    Returns

    R
    what the visitor returned

    Overrides accept().

    toString

    public final String toString()

    No description.

    Returns

    Stringnon-null
    No description.

    Overrides toString().

    hashCode

    public final int hashCode()

    No description.

    Returns

    int
    No description.

    Overrides hashCode().

    equals

    public final boolean equals(Object o)

    No description.

    Parameters

    oObjectnon-null
    No description.

    Returns

    boolean
    No description.

    Overrides equals(java.lang.Object).

    radius

    public double radius()

    No description.

    Returns

    double
    No description.

    label

    public @Nullable String label()

    No description.

    Returns

    @Nullable Stringnullable
    No description.

    Inherited members

    From interface Shape

    compareTo

    +" +`; + +exports[`render HTML snapshots: fixture/java/index.html 1`] = ` +" +fixture.java (fixture 1.0)
    fixture1.0
    All types

    fixture.java

    packagesince 1.0null-marked

    Shapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents.

    Where to start

    Start with fixture.java.Shape and the operations in fixture.java.Geometry. Readers live in fixture.java.io.

    Interfaces

    NameDescription
    CanvasSomewhere to draw shapes.
    ShapeA closed plane figure.

    Classes

    NameDescription
    AbstractCanvasA canvas that counts what it draws.
    BoxA mutable holder for one comparable value.
    GeometryOperations on shapes.
    PolygonA regular polygon.
    RectAn axis-aligned rectangle.

    Records

    NameDescription
    CircleA circle.

    Enums

    NameDescription
    UnitsUnits of length.

    Exceptions

    NameDescription
    GeometryExceptionA shape that cannot exist, such as a triangle whose sides violate the triangle inequality.

    Annotations

    NameDescription
    MeasuredMarks a declaration whose values are lengths, and in which unit.
    +" +`; + +exports[`render HTML snapshots: index.html 1`] = ` +" +fixture 1.0 API
    fixture1.0
    All types

    fixture

    version 1.0java

    API reference for fixture.

    Packages

    NameDescription
    fixture.javaShapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents.
    fixture.java.ioReading shapes from streams.

    All types

    fixture.java

    NameKindDescription
    AbstractCanvasabstract classA canvas that counts what it draws.
    BoxclassA mutable holder for one comparable value.
    CanvasinterfaceSomewhere to draw shapes.
    Canvas.LayerinterfaceOne layer of a canvas.
    Canvas.Layer.Kindenum classWhat a layer holds.
    CirclerecordA circle.
    GeometryclassOperations on shapes.
    Geometry.LegacyclassMethods from before null markings; their nullness is unspecified.
    GeometryExceptionexceptionA shape that cannot exist, such as a triangle whose sides violate the triangle inequality.
    Measuredannotation interfaceMarks a declaration whose values are lengths, and in which unit.
    PolygonclassA regular polygon.
    Polygon.BuilderclassBuilds a polygon one side at a time.
    Polygon.EdgeclassOne edge of this polygon: an inner class, bound to its polygon.
    RectclassAn axis-aligned rectangle.
    Shapesealed interfaceA closed plane figure.
    Shape.VisitorinterfaceOperations over each kind of shape.
    Unitsenum classUnits of length.

    fixture.java.io

    NameKindDescription
    ShapeReaderclassReads shapes in their text form, one per line.
    +" +`; diff --git a/packages/apidocs/test/browser.test.ts b/packages/apidocs/test/browser.test.ts index 281ff92..f031861 100644 --- a/packages/apidocs/test/browser.test.ts +++ b/packages/apidocs/test/browser.test.ts @@ -1,75 +1,107 @@ /** * Opens a site built exactly as the doclet builds it (dist/runner.mjs running - * dist/render.js) from file://, with JavaScript on and off, and runs axe on the - * page shell in light and dark. Needs `bun run build` first (turbo runs it) and - * a Playwright Chromium. + * dist/render.js) in Chromium: from file:// with JavaScript on and off, and + * over HTTP where a test needs it. Runs axe on the page shell in light and + * dark. Needs `bun run build` first (turbo runs it) and a Playwright Chromium. */ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { spawnSync } from "node:child_process"; -import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; -import { type Browser, chromium, type Page } from "playwright"; +import { type Browser, type BrowserContextOptions, chromium, type Page } from "playwright"; import { samples } from "../samples"; const root = fileURLToPath(new URL("..", import.meta.url)); const require = createRequire(import.meta.url); let browser: Browser; let site: string; +let out: string; +let server: ReturnType; beforeAll(async () => { if (!existsSync(join(root, "dist/render.js"))) throw new Error("dist/ is missing: run `bun run build` first"); site = mkdtempSync(join(tmpdir(), "apidocs-browser-")); + out = join(site, "out"); const model = join(site, "model.json"); const theme = join(site, "theme.json"); writeFileSync(model, JSON.stringify(samples.java)); writeFileSync(theme, JSON.stringify({ extends: "elide" })); - const run = spawnSync(process.execPath, [join(root, "dist/runner.mjs"), "--bundle", join(root, "dist/render.js"), "--assets", join(root, "dist/assets"), "--model", model, "--theme", theme, "--out", join(site, "out")], { encoding: "utf8" }); + const run = spawnSync(process.execPath, [join(root, "dist/runner.mjs"), "--bundle", join(root, "dist/render.js"), "--assets", join(root, "dist/assets"), "--model", model, "--theme", theme, "--out", out], { encoding: "utf8" }); if (run.status !== 0) throw new Error(run.stderr); + server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + fetch(request) { + const path = decodeURIComponent(new URL(request.url).pathname).replace(/^\/+/, ""); + const file = resolve(out, path); + if (!file.startsWith(out) || !existsSync(file)) return new Response("Not found", { status: 404 }); + const type = file.endsWith(".html") ? "text/html" : file.endsWith(".css") ? "text/css" : file.endsWith(".js") ? "text/javascript" : file.endsWith(".woff2") ? "font/woff2" : "application/octet-stream"; + return new Response(readFileSync(file), { headers: { "content-type": type } }); + }, + }); browser = await chromium.launch(); }); afterAll(async () => { await browser?.close(); + server?.stop(true); if (site) rmSync(site, { recursive: true, force: true }); }); -const url = (path: string) => { +const fileUrl = (path: string) => { const [file, fragment] = path.split("#"); - return pathToFileURL(join(site, "out", file!)).href + (fragment === undefined ? "" : `#${fragment}`); + return pathToFileURL(join(out, file!)).href + (fragment === undefined ? "" : `#${fragment}`); }; +const httpUrl = (path: string) => `http://127.0.0.1:${server.port}/${path}`; -async function open(path: string, options: { javaScriptEnabled?: boolean; colorScheme?: "light" | "dark" } = {}): Promise<{ page: Page; requests: string[]; errors: string[] }> { - const context = await browser.newContext({ javaScriptEnabled: options.javaScriptEnabled ?? true, colorScheme: options.colorScheme ?? "light" }); +async function open(path: string, options: BrowserContextOptions & { http?: boolean } = {}): Promise<{ page: Page; requests: string[]; errors: string[] }> { + const { http, ...contextOptions } = options; + const context = await browser.newContext({ colorScheme: "light", ...contextOptions }); const page = await context.newPage(); const requests: string[] = []; const errors: string[] = []; page.on("request", request => requests.push(request.url())); page.on("pageerror", error => errors.push(error.message)); page.on("console", message => message.type() === "error" && errors.push(message.text())); - await page.goto(url(path)); + await page.goto(http ? httpUrl(path) : fileUrl(path)); return { page, requests, errors }; } describe("from file:// with JavaScript off", () => { - test("pages are complete, and the islands stay hidden", async () => { + test("pages are complete, and script-only controls stay out", async () => { const { page, requests } = await open("com/example/geo/Shapes.html", { javaScriptEnabled: false }); - expect(await page.locator("h1").textContent()).toBe("Shapes"); + expect(await page.getByRole("heading", { level: 1 }).textContent()).toContain("Shapes"); + expect(await page.getByRole("heading", { level: 1, name: "Shapes" }).count()).toBe(1); expect(await page.locator("section.member").count()).toBeGreaterThan(8); - expect(await page.locator("#parse\\(java\\.lang\\.String\\) .note-apiNote").count()).toBe(1); - expect(await page.locator("[data-search]").isHidden()).toBe(true); + expect(await page.locator("#parse\\(java\\.lang\\.String\\) .callout-apiNote").count()).toBe(1); + for (const control of await page.locator("[data-js-only]").all()) expect(await control.isVisible()).toBe(false); expect(await page.locator(".search-fallback").isVisible()).toBe(true); - expect(await page.locator("[data-copy]").first().isHidden()).toBe(true); - expect(await page.locator("[data-theme-switch]").isHidden()).toBe(true); + expect(await page.locator("[data-copy]").first().isVisible()).toBe(false); expect(requests.every(r => r.startsWith("file://"))).toBe(true); await page.context().close(); }); }); describe("from file:// with JavaScript on", () => { - test("search finds a member and opens it", async () => { + test("script-only controls show at first paint, before the deferred bundle runs", async () => { + const bundle = join(out, "assets/apidocs.js"); + renameSync(bundle, `${bundle}.held`); + try { + const { page } = await open("com/example/geo/Shapes.html"); + expect(await page.evaluate(() => document.documentElement.hasAttribute("data-js"))).toBe(true); + expect(await page.locator("[data-search]").isVisible()).toBe(true); + expect(await page.locator("[data-theme-switch]").isVisible()).toBe(true); + expect(await page.locator(".search-fallback").isVisible()).toBe(false); + await page.context().close(); + } finally { + renameSync(`${bundle}.held`, bundle); + } + }); + + test("search finds a member and opens it, with no errors and no network", async () => { const { page, requests, errors } = await open("index.html"); const input = page.getByRole("combobox", { name: "Search the API" }); await input.fill("parse"); @@ -97,12 +129,72 @@ describe("from file:// with JavaScript on", () => { test("copy buttons show, and the table of contents follows the page", async () => { const { page } = await open("com/example/geo/registry/ShapeCatalog.html#scaleStar(com.example.geo.Shape,double)"); - expect(await page.locator("[data-copy]").first().isHidden()).toBe(false); - await page.waitForSelector('.toc a[aria-current="true"]'); - const current = await page.locator('.toc a[aria-current="true"]').textContent(); - expect(current).toContain("scaleStar"); + expect(await page.locator("[data-copy]").first().isVisible()).toBe(true); + await page.waitForSelector('.toc a[aria-current="true"]', { state: "attached" }); + expect(await page.locator('.toc a[aria-current="true"]').first().textContent()).toContain("scaleStar"); + await page.context().close(); + }); + + test("the navigator toggle hides it on a wide screen, remembers that, and [ toggles it", async () => { + const { page } = await open("com/example/geo/Shapes.html", { viewport: { width: 1440, height: 900 } }); + const nav = page.locator("#apidocs-nav"); + expect(await nav.isVisible()).toBe(true); + await page.locator(".nav-button").click(); + expect(await nav.isVisible()).toBe(false); + await page.reload(); + expect(await nav.isVisible()).toBe(false); + await page.locator("main").click({ position: { x: 5, y: 5 } }); + await page.keyboard.press("["); + expect(await nav.isVisible()).toBe(true); + await page.reload(); + expect(await nav.isVisible()).toBe(true); await page.context().close(); }); + + test("the navigator toggle shows it on a narrow screen", async () => { + const { page } = await open("com/example/geo/Shapes.html", { viewport: { width: 390, height: 844 } }); + const nav = page.locator("#apidocs-nav"); + expect(await nav.isVisible()).toBe(false); + await page.locator(".nav-button").click(); + expect(await nav.isVisible()).toBe(true); + await page.context().close(); + }); + + test("font preloads appear over HTTP and not on file://", async () => { + const preloads = (page: Page) => page.locator('head link[rel="preload"][as="font"]').count(); + const local = await open("com/example/geo/Shapes.html"); + expect(await preloads(local.page)).toBe(0); + expect(local.errors).toEqual([]); + await local.page.context().close(); + const served = await open("com/example/geo/Shapes.html", { http: true }); + expect(await preloads(served.page)).toBe(3); + expect(served.errors).toEqual([]); + await served.page.context().close(); + }); +}); + +describe("layout stability", () => { + async function shift(blockFonts: boolean): Promise { + const context = await browser.newContext({ viewport: { width: 1440, height: 900 } }); + const page = await context.newPage(); + if (blockFonts) await page.route("**/*.woff2", route => route.abort()); + await page.addInitScript(() => { + (window as unknown as { cls: number }).cls = 0; + new PerformanceObserver(list => { + for (const entry of list.getEntries() as unknown as { value: number; hadRecentInput: boolean }[]) { + if (!entry.hadRecentInput) (window as unknown as { cls: number }).cls += entry.value; + } + }).observe({ type: "layout-shift", buffered: true }); + }); + await page.goto(httpUrl("com/example/geo/Shapes.html"), { waitUntil: "load" }); + await page.evaluate(() => document.fonts.ready); + await page.waitForTimeout(800); + const cls = await page.evaluate(() => (window as unknown as { cls: number }).cls); + await context.close(); + return cls; + } + test("a type page does not shift as it loads, with fonts", async () => expect(await shift(false)).toBe(0)); + test("a type page does not shift as it loads, with font requests blocked", async () => expect(await shift(true)).toBe(0)); }); describe("accessibility", () => { diff --git a/packages/apidocs/test/render.test.ts b/packages/apidocs/test/render.test.ts index c3d993b..25ad863 100644 --- a/packages/apidocs/test/render.test.ts +++ b/packages/apidocs/test/render.test.ts @@ -9,6 +9,7 @@ import type { Model, Token } from "../src/model"; import { render } from "../src/render"; import { sanitize } from "../src/sanitize"; import { layoutSignature } from "../src/signature"; +import { sharedPrefix } from "../src/components/chrome"; import { checkSite } from "./check"; import { validate } from "./validate"; @@ -85,20 +86,73 @@ describe("render", () => { }); test("notes render as distinct callouts, the API note first", () => { const html = out["fixture/java/Geometry.html"] as string; - expect(html).toContain('class="note note-implSpec"'); + expect(html).toContain('class="callout callout-implSpec"'); const shapes = render(samples.java)["com/example/geo/Shapes.html"] as string; const parse = shapes.slice(shapes.indexOf('id="parse(java.lang.String)"')); - expect(parse.indexOf("note-apiNote")).toBeLessThan(parse.indexOf("note-implNote")); + expect(parse.indexOf("callout-apiNote")).toBeGreaterThan(0); + expect(parse.indexOf("callout-apiNote")).toBeLessThan(parse.indexOf("callout-implNote")); expect(render(samples.java)["com/example/geo/Shapes.md"]).toContain("> **API note**"); }); }); +describe("layout", () => { + const java = render(samples.java, { extends: "elide" }); + const between = (html: string, start: string, end: string) => html.slice(html.indexOf(start), html.indexOf(end, html.indexOf(start))); + + test("sharedPrefix: one package, several, one equal to the prefix, the default package", () => { + expect(sharedPrefix(["com.example.geo"])).toBe("com.example"); + expect(sharedPrefix(["com.example.geo.io", "com.example.geo.spi"])).toBe("com.example.geo"); + expect(sharedPrefix(["com.example.geo", "com.example.geo.io"])).toBe("com.example"); + expect(sharedPrefix(["", "org.example.kgeo"])).toBe("org.example"); + expect(sharedPrefix([""])).toBe(""); + expect(sharedPrefix(["alpha", "beta"])).toBe(""); + }); + test("the navigator has no disclosure widgets", () => { + for (const page of ["index.html", "com/example/geo/index.html", "com/example/geo/Shapes.Builder.Option.html"]) { + const nav = between(java[page] as string, '