diff --git a/CHANGELOG.md b/CHANGELOG.md index 189e0d41c7..c91805ffa6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1486,6 +1486,22 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru reference, never because its text matches a name, and a map-valued attribute such as `@filter` prints its keys sorted. A theme ejected from an rc needs no change. Generated-output change — regenerate to pick it up; three-way merge preserves hand edits. +- **codegen-ts: the `template` generator renders the docs view.** Documentation pages are + ordinary configured Mustache templates. Two new scopes walk the docs view: `perNode` (one file + per top-level node of any type, filtered with `match`: `"."`, `".*"`, `"*"` + or a list; `"*"` skips requirement nodes, which `perRequirement` owns) and `perRequirement` (one per requirement at any depth). `perModel` and `perPackage` + read the view with `data: "docsView"`; without it they keep the per-entity dictionary, so an + existing spec renders the same bytes. `{path}` in `outputPattern` is the page the view gives a + node or requirement, and every docs-view page gets `root`, the way back to the site root, so + `{{root}}{{path}}` links from any page. `subDir` sets the directory the paths are relative to, + `assets: { from }` copies a directory of text files into `subDir`, and `linkCheck: true` + fails the run, writing nothing, when a relative link in an entry's HTML pages lands on no file or + anchor. The same keys work in a JSON template spec (`template-spec.schema.json`). + `Generator.checkRunOutput` is the hook that runs the check once every generator has rendered; + `@metaobjectsdev/docs-site` exports the link check as `findDanglingLinks`. Gated by the new + `docs-view/` case of `fixtures/template-codegen-conformance/`, which TypeScript runs today and + the other ports take on with their own docs view. The explorer site is unchanged. See + `docs/features/codegen-concepts.md`, "Templates over the docs view". - **`@flattenedColumnPrefix`: name a flattened value object's columns.** On a `field.object` with `@storage: "flattened"`, it replaces the default prefix (the field's column and `_`) verbatim; `""` keeps the members' own column names. It sits on the embedding field because one value diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 06e2d063ed..695f20f473 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -43,7 +43,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/registry-conformance/`](../fixtures/registry-conformance/) | 1 canonical manifest | ✓ (reference emitter) | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/object-model-conformance/`](../fixtures/object-model-conformance/) | 1 shared metadata fixture (per-port scenarios) | ✓ | ✓ | ✓ | ✓ | ✓ | — | | [`fixtures/codegen-conformance/`](../fixtures/codegen-conformance/) | 7 shared inputs; `shared-provided-enum` carries the enum-type decision table and `cross-package-binding` the reference-binding decision table (ADR-0059) every port answers; `xpkg-value-object-refs` (ruling R52) is run by C# and TypeScript only so far — Java, Kotlin and Python in [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549 | ✓ | ✓ | ✓ | ✓ | ✓ | — | -| [`fixtures/template-codegen-conformance/`](../fixtures/template-codegen-conformance/) | 3 | ✓ | ✓ | ✓ | ✓ | ✓ | — | +| [`fixtures/template-codegen-conformance/`](../fixtures/template-codegen-conformance/) | 3 + the `docs-view/` case (16 files: the docs-view scopes, `{path}`, `subDir`, assets and the link check) | ✓ (both) | ✓ (root case; `docs-view/` planned) | ✓ (root case; `docs-view/` planned) | ✓ (root case; `docs-view/` planned) | ✓ (root case; `docs-view/` planned) | — | | [`fixtures/template-output-render-conformance/`](../fixtures/template-output-render-conformance/) | 5 | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ (generated `render-helper` crates) | | [`fixtures/generator-registry-conformance/`](../fixtures/generator-registry-conformance/) | 1 canonical manifest | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/provider-composition-conformance/`](../fixtures/provider-composition-conformance/) | 18 (11 error-shape + 4 compose-load + 3 attr-ownership) | ✓ | ✓ | — (JVM registry via Java) | ✓ | ✓ | — | diff --git a/docs/README.md b/docs/README.md index 546f1a58e4..0182dbc440 100644 --- a/docs/README.md +++ b/docs/README.md @@ -38,7 +38,7 @@ docs/ │ ├── yaml-authoring.md │ ├── cli.md # CLI command matrix across all five ports │ ├── language-differences.md # what differs by language: Node for the schema, list defaults, error bodies, names, data access -│ ├── codegen-concepts.md # declarative template-codegen scopes (perEntity/perPackage/perModel) +│ ├── codegen-concepts.md # declarative template-codegen scopes (perEntity/perPackage/perModel; TypeScript adds the docs-view scopes) │ ├── codegen-data-shapes.md # the neutral template data dict shared cross-port │ ├── downstream-metadata-decisions.md # guidance for adopters extending the metamodel │ ├── semantic-modelling.md # how to shape vocabulary of your own: type, subtype, generator and configuration diff --git a/docs/features/codegen-concepts.md b/docs/features/codegen-concepts.md index ecbaf197f7..67e5a07b1d 100644 --- a/docs/features/codegen-concepts.md +++ b/docs/features/codegen-concepts.md @@ -245,8 +245,8 @@ pattern instead of hand-rolled grouping. ### Declarative template scopes A `templateGenerator` can take the scope walk declaratively instead of a hand-written -`walk` — pass `scope` (`"perEntity" | "perPackage" | "perModel"`) plus an -`outputPattern`, and the generator derives the neutral template data dict per unit and +`walk` — pass `scope` (`"perEntity" | "perPackage" | "perModel"`; TypeScript also +takes the docs-view scopes, below) plus an `outputPattern`, and the generator derives the neutral template data dict per unit and names each file via the pattern. `walk` and `scope` are mutually exclusive — provide exactly one. The `outputPattern` placeholders are `{name}`, `{Name}`, and `{package}` (an unknown placeholder throws); `{package}` resolves through `effectivePackage` and @@ -267,6 +267,60 @@ templateGenerator({ }); ``` +#### Templates over the docs view (TypeScript) + +A template can also read the **docs view** ([docs-view.md](docs-view.md)): every top-level +node of every type, its effective attributes, members, references both ways, the +requirements that claim it, and the requirement tree. Documentation is then ordinary +template codegen, configured like any other entry. Two scopes walk it: + +- **`perNode`**: one file per top-level node of any type, filtered with `match`: a + pattern `"."`, `".*"` or `"*"` (the default), or a list of them. + `"*"` skips requirement nodes, because `perRequirement` owns their pages; a pattern that + names the requirement type (`"requirement.*"`) still selects them. +- **`perRequirement`**: one file per requirement at any depth, filtered the same way + (`"requirement.functional"`). + +`perModel` and `perPackage` read the view when the entry says `data: "docsView"`; +without it they keep the per-entity dictionary above, so an existing spec is unchanged. +A docs-view page's data is the whole view, plus the unit (`node`, `requirement` or +`package`) and `root`, the way from the page back to the site root. `{path}` in the +`outputPattern` is the page the view gives a node or requirement, so a link is +`` and lands whichever page it is written from. + +Three more keys build a site: + +- **`subDir`**: the directory under the target the output paths, and `root`, are + relative to. +- **`assets`**: `{ "from": "" }` copies every file under a project directory into + `subDir`, at its path relative to `from`. Text files only; a file that is not UTF-8 is + refused. +- **`linkCheck: true`** (with `format: "html"`): once the whole run has rendered, every + relative link in the entry's pages must name a file the run wrote (or one already on + disk, unless it is a generated file a full run no longer produces and so deletes) and, + with `#anchor`, an element with that `id`. A link that lands on nothing fails + the run, naming the page and the link, and nothing is written. + +```json +{ "generators": [ + { "name": "site-index", "template": "index", "scope": "perModel", "data": "docsView", "subDir": "site", + "outputPattern": "index.html", "format": "html", "assets": { "from": "site-assets" } }, + { "name": "site-objects", "template": "object", "scope": "perNode", "match": "object.*", "subDir": "site", + "outputPattern": "{path}", "format": "html", "linkCheck": true }, + { "name": "site-requirements", "template": "requirement", "scope": "perRequirement", "subDir": "site", + "outputPattern": "{path}", "format": "html", "linkCheck": true } +] } +``` + +The view is built from the model the run loaded, the requirement ledger `meta gen` +computed and the files and routes the rest of the run produced, so an entry that reads it +runs after the other generators. Templates should stay inside the subset every port's +engine renders alike: the view supplies counts and booleans, so a template never needs +`.length`, a number's truth or a dotted name shadowed inside a loop. TypeScript runs these +scopes today, gated by `fixtures/template-codegen-conformance/docs-view/`; the other ports +take them on with their own docs view. The model explorer (`docsSiteFile()`) is not built +this way yet. + The same declarative surface is available on the **JVM (Java + Kotlin)** via `TemplateScopeGenerator` (`com.metaobjects.generator.template`), a Maven-wirable generator over the byte-equivalent render engine. Wire it as a standard diff --git a/docs/features/codegen-data-shapes.md b/docs/features/codegen-data-shapes.md index c97ab322ec..4bea7d7612 100644 --- a/docs/features/codegen-data-shapes.md +++ b/docs/features/codegen-data-shapes.md @@ -97,6 +97,11 @@ it. The field names are a byte-gated **cross-port contract** (the `fixtures/template-codegen-conformance/` corpus locks them) — change them only via the spec. +The `perNode` and `perRequirement` scopes, and `data: "docsView"` on `perModel` and +`perPackage`, feed the **docs view** instead ([docs-view.md](docs-view.md)), the same facts +the documentation pages read, pinned by `fixtures/template-codegen-conformance/docs-view/` +([codegen-concepts.md](codegen-concepts.md#templates-over-the-docs-view-typescript)). + ```ts interface FieldTemplateData { name: string; @@ -244,5 +249,5 @@ Mermaid diagram): 5. Document the new shape on this page under a new section. The `templateGenerator()` factory does the rest — no new generator scaffolding is -needed. Take the built-in `scope` + `outputPattern` walk when one of the three scopes +needed. Take the built-in `scope` + `outputPattern` walk when one of the scopes fits; supply your own `walk` only when it does not. diff --git a/docs/features/docs-view.md b/docs/features/docs-view.md index eb6ac7bcee..32f6202a74 100644 --- a/docs/features/docs-view.md +++ b/docs/features/docs-view.md @@ -15,8 +15,14 @@ writes the same bytes for the same model, and the shared corpus TypeScript builds it today. `buildDocsView` and `serializeDocsView` are exported from `@metaobjectsdev/metadata`, and `docsSiteFile()` writes the result as the site's `explorer.json` (see [explorer-site.md](explorer-site.md)). The other ports build it as their -own step of the same plan. The explorer pages still render their HTML in TypeScript; moving that -into templates is a later step. +own step of the same plan. The explorer pages still render their HTML in TypeScript. + +A page of your own is a template over the view: the TypeScript `template` generator renders it +with the `perNode` and `perRequirement` scopes (and `data: "docsView"` on `perModel` and +`perPackage`), writes each page at its `path` with `{path}` in the output pattern, and hands +every page a `root` so `{{root}}{{path}}` links from anywhere. It can copy a directory of +assets beside the pages and check that every link lands. See +[codegen-concepts.md](codegen-concepts.md#templates-over-the-docs-view-typescript). ## What it is built from diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 296fc59fb9..1ddec092a8 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -206,7 +206,7 @@ export default defineConfig({ templateGenerator({ name: "entity-service", // kebab-case; surfaces in diagnostics template: "service/entity-service", // → templates/service/entity-service.mustache - scope: "perEntity", // "perEntity" | "perPackage" | "perModel" + scope: "perEntity", // "perEntity" | "perPackage" | "perModel" | "perNode" | "perRequirement" outputPattern: "{package}/{Name}Service.ts", // format: "text", // optional escaper; defaults to "text" // target: "api", // optional named output target @@ -219,8 +219,10 @@ Templates resolve through the project's `templates/` directory first, then the f defaults — so `template: "service/entity-service"` reads `/templates/service/entity-service.mustache`. The `outputPattern` placeholders are `{name}`, `{Name}` and `{package}` (whose `::` segments become nested -directories); an unknown placeholder throws. Abstract objects are excluded from every -scope. +directories), and `{path}` for the docs-view scopes `perNode` and `perRequirement` +([templates over the docs view](../features/codegen-concepts.md#templates-over-the-docs-view-typescript)); +an unknown placeholder throws. Abstract objects are excluded from every +scope that reads the per-entity dictionary; the docs-view scopes include them. `scope` and `walk` are mutually exclusive — supply exactly one. Take a `scope` when one of the three walks fits; supply your own `walk` when it does not. diff --git a/fixtures/template-codegen-conformance/README.md b/fixtures/template-codegen-conformance/README.md index 9b00eaf960..54d312a76b 100644 --- a/fixtures/template-codegen-conformance/README.md +++ b/fixtures/template-codegen-conformance/README.md @@ -6,7 +6,7 @@ Every port runs `spec.json` (a list of `{ name, template, scope, outputPattern } generators) over `metadata/meta.shop.json`, resolving templates from `templates/`, and must produce output **byte-identical** to `expected/`. -The corpus exercises all three built-in scopes: +The root case exercises the three per-entity-dictionary scopes: - **`perEntity`** (`entity.mustache` → `.txt`) — the neutral per-entity data dict: fields (name/type/required/isArray/maxLength), and Order's `product` @@ -20,6 +20,28 @@ this corpus gates the *new* surface: the structural data dict, the scope names (`perEntity`/`perPackage`/`perModel`), and the output-pattern grammar (`{name}`/`{Name}`/`{package}`). +## The `docs-view/` case + +`docs-view/` is a second case with its own `spec.json`, `metadata/` (every file, loaded +together), `templates/`, `site-assets/` and `expected/`. Its entries read the **docs view** +(`docs/features/docs-view.md`) of the model alone: no verify payload, manifest or routes, +so `sources` is all `false`. It gates: + +- the `perNode` scope with `match` (`"object.*"`, and a list `["object.entity"]`) and the + `perRequirement` scope, each at `{path}`; +- `data: "docsView"` on `perModel` and `perPackage`; +- `subDir` (the site under `site/`) and `root`, the way back to it, used by every link + (`{{root}}{{path}}`) and by a Markdown entry outside the site (`briefs/`); +- `assets` (`site-assets/assets/` copied to `site/assets/`); +- `linkCheck`: every relative link in the checked entries lands on a file and an anchor, + including links to pages a later entry renders. + +The templates stay inside the subset every port's engine renders alike: no `.length`, no +number's truth, no dotted name inside a loop. TypeScript runs this case today; another port +runs it once it builds the docs view. A port that has no link check still matches the bytes. + Regenerate `expected/` after an intentional change to the data dict or scope walks by pointing the generator at the `expected/` directory and committing the result -(see each port's conformance test). +(see each port's conformance test). In TypeScript: +`UPDATE_TEMPLATE_CONFORMANCE=1 bun test packages/codegen-ts/test/template-codegen/conformance.test.ts` +from `server/typescript/` rewrites both cases. diff --git a/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/billing/Invoice.md b/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/billing/Invoice.md new file mode 100644 index 0000000000..9c9d147336 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/billing/Invoice.md @@ -0,0 +1,3 @@ +# Invoice + +Site root: `../../../` diff --git a/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/shop/BaseEntity.md b/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/shop/BaseEntity.md new file mode 100644 index 0000000000..750fb2d1be --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/shop/BaseEntity.md @@ -0,0 +1,3 @@ +# BaseEntity + +Site root: `../../../` diff --git a/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/shop/Customer.md b/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/shop/Customer.md new file mode 100644 index 0000000000..6fe6ed6dfe --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/shop/Customer.md @@ -0,0 +1,3 @@ +# Customer + +Site root: `../../../` diff --git a/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/shop/Order.md b/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/shop/Order.md new file mode 100644 index 0000000000..99da07c192 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/briefs/acme/shop/Order.md @@ -0,0 +1,3 @@ +# Order + +Site root: `../../../` diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/assets/css/site.css b/fixtures/template-codegen-conformance/docs-view/expected/site/assets/css/site.css new file mode 100644 index 0000000000..0251c043f1 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/assets/css/site.css @@ -0,0 +1,2 @@ +body { font-family: sans-serif; } +.missing { color: #b00; } diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/index.html b/fixtures/template-codegen-conformance/docs-view/expected/site/index.html new file mode 100644 index 0000000000..1b3ec64563 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/index.html @@ -0,0 +1,10 @@ + + +

Home

+ +

Model

+

6 nodes, 4 requirements.

+
    +
  • acme::billing (1)
  • +
  • acme::shop (5)
  • +
diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/billing/Invoice.html b/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/billing/Invoice.html new file mode 100644 index 0000000000..b1eafd1790 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/billing/Invoice.html @@ -0,0 +1,35 @@ + + +

Home

+ +

Invoice

+

object.entity

+ + +

source (1)

+ + +
rdb
+

field (2)

+ + + +
idlong
orderIdlong
+

identity (1)

+ + +
pkprimary
+

relationship (1)

+ + +
orderassociation
+

References

+ +

Referenced by

+
    +
+

Claimed by

+
    +
diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/shop/BaseEntity.html b/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/shop/BaseEntity.html new file mode 100644 index 0000000000..dade59ab55 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/shop/BaseEntity.html @@ -0,0 +1,28 @@ + + +

Home

+ +

BaseEntity

+

object.entity (abstract)

+ + +

field (1)

+ + +
idlong
+

identity (1)

+ + +
pkprimary
+

References

+
    +
+

Referenced by

+ +

Claimed by

+ diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/shop/Customer.html b/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/shop/Customer.html new file mode 100644 index 0000000000..9d15fc558f --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/shop/Customer.html @@ -0,0 +1,33 @@ + + +

Home

+ +

Customer

+

object.entity

+

Someone who buys from the shop.

+

Extends BaseEntity

+

field (2)

+ + + +
idlongfrom BaseEntity
emailstring
+

identity (1)

+ + +
pkprimaryfrom BaseEntity
+

source (1)

+ + +
rdb
+

References

+ +

Referenced by

+ +

Claimed by

+
    +
diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/shop/Order.html b/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/shop/Order.html new file mode 100644 index 0000000000..98d4f0f4e2 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/model/acme/shop/Order.html @@ -0,0 +1,42 @@ + + +

Home

+ +

Order

+

object.entity

+

A placed order & its <total>.

+

Extends BaseEntity

+

field (3)

+ + + + +
idlongfrom BaseEntity
customerIdlong
referencestring
+

identity (2)

+ + + +
pkprimaryfrom BaseEntity
customerRefreference
+

source (1)

+ + +
rdb
+

relationship (1)

+ + +
customerassociation
+

References

+ +

Referenced by

+ +

Claimed by

+ diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/packages/acme/billing.html b/fixtures/template-codegen-conformance/docs-view/expected/site/packages/acme/billing.html new file mode 100644 index 0000000000..b7e66dea83 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/packages/acme/billing.html @@ -0,0 +1,9 @@ + + +

Home

+ +

acme::billing

+

object.entity (1)

+ diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/packages/acme/shop.html b/fixtures/template-codegen-conformance/docs-view/expected/site/packages/acme/shop.html new file mode 100644 index 0000000000..acbd658460 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/packages/acme/shop.html @@ -0,0 +1,19 @@ + + +

Home

+ +

acme::shop

+

object.entity (3)

+ +

requirement.architectural (1)

+ +

requirement.functional (1)

+ diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Addressable.html b/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Addressable.html new file mode 100644 index 0000000000..7c61b042be --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Addressable.html @@ -0,0 +1,15 @@ + + +

Home

+ +

+

Addressable

+

architectural, live, depth 0

+
Every stored row has a stable id.
+

Implemented by

+ +

Below

+
    +
diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Shop.Recorded.html b/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Shop.Recorded.html new file mode 100644 index 0000000000..2b791a21fa --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Shop.Recorded.html @@ -0,0 +1,16 @@ + + +

Home

+ +

Shop /

+

Recorded

+

functional, live, depth 1

+
An order is recorded when it is placed.
+

Implemented by

+ +

Below

+
    +
diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Shop.Refunded.html b/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Shop.Refunded.html new file mode 100644 index 0000000000..cb801eb48c --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Shop.Refunded.html @@ -0,0 +1,15 @@ + + +

Home

+ +

Shop /

+

Refunded

+

functional, planned, depth 1

+
A customer can be refunded.
+

Implemented by

+
    +
  • Refund: Refund
  • +
+

Below

+
    +
diff --git a/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Shop.html b/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Shop.html new file mode 100644 index 0000000000..e5abcfb9c7 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/expected/site/requirements/acme/shop/Shop.html @@ -0,0 +1,16 @@ + + +

Home

+ +

+

Shop

+

functional, live, depth 0

+
A customer can buy from the shop.
+

Implemented by

+
    +
+

Below

+ diff --git a/fixtures/template-codegen-conformance/docs-view/metadata/meta.billing.json b/fixtures/template-codegen-conformance/docs-view/metadata/meta.billing.json new file mode 100644 index 0000000000..3fcf3b3f4e --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/metadata/meta.billing.json @@ -0,0 +1,19 @@ +{ + "metadata.root": { + "package": "acme::billing", + "children": [ + { + "object.entity": { + "name": "Invoice", + "children": [ + { "source.rdb": { "@table": "invoices" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "orderId" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } }, + { "relationship.association": { "name": "order", "@cardinality": "one", "@objectRef": "acme::shop::Order" } } + ] + } + } + ] + } +} diff --git a/fixtures/template-codegen-conformance/docs-view/metadata/meta.shop.json b/fixtures/template-codegen-conformance/docs-view/metadata/meta.shop.json new file mode 100644 index 0000000000..022d8c9dd2 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/metadata/meta.shop.json @@ -0,0 +1,82 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "BaseEntity", + "abstract": true, + "children": [ + { "field.long": { "name": "id", "@description": "The row's stable id." } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] + } + }, + { + "object.entity": { + "name": "Customer", + "extends": "BaseEntity", + "@description": "Someone who buys from the shop.", + "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.string": { "name": "email", "@required": true, "@maxLength": 200 } } + ] + } + }, + { + "object.entity": { + "name": "Order", + "extends": "BaseEntity", + "@description": "A placed order & its .", + "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "customerId" } }, + { "field.string": { "name": "reference", "@maxLength": 20 } }, + { "identity.reference": { "name": "customerRef", "@fields": ["customerId"], "@references": "Customer" } }, + { "relationship.association": { "name": "customer", "@cardinality": "one", "@objectRef": "Customer" } } + ] + } + }, + { + "requirement.functional": { + "name": "Shop", + "@level": 1, + "@status": "live", + "@statement": "A customer can buy from the shop.", + "@counterexample": "A customer who cannot buy.", + "children": [ + { + "requirement.functional": { + "name": "Recorded", + "@level": 4, + "@status": "live", + "@statement": "An order is recorded when it is placed.", + "@counterexample": "A placed order has no row.", + "@implementedBy": ["Order", "Order.reference"] + } + }, + { + "requirement.functional": { + "name": "Refunded", + "@level": 4, + "@status": "planned", + "@statement": "A customer can be refunded.", + "@counterexample": "A refund nobody can make.", + "@implementedBy": ["Refund"] + } + } + ] + } + }, + { + "requirement.architectural": { + "name": "Addressable", + "@status": "live", + "@statement": "Every stored row has a stable id.", + "@counterexample": "A row nobody can point at.", + "@implementedBy": ["BaseEntity"] + } + } + ] + } +} diff --git a/fixtures/template-codegen-conformance/docs-view/site-assets/assets/css/site.css b/fixtures/template-codegen-conformance/docs-view/site-assets/assets/css/site.css new file mode 100644 index 0000000000..0251c043f1 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/site-assets/assets/css/site.css @@ -0,0 +1,2 @@ +body { font-family: sans-serif; } +.missing { color: #b00; } diff --git a/fixtures/template-codegen-conformance/docs-view/spec.json b/fixtures/template-codegen-conformance/docs-view/spec.json new file mode 100644 index 0000000000..762bca0e7d --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/spec.json @@ -0,0 +1,9 @@ +{ + "generators": [ + { "name": "site-index", "template": "index", "scope": "perModel", "data": "docsView", "subDir": "site", "outputPattern": "index.html", "format": "html", "linkCheck": true, "assets": { "from": "site-assets" } }, + { "name": "site-packages", "template": "package", "scope": "perPackage", "data": "docsView", "subDir": "site", "outputPattern": "packages/{package}.html", "format": "html" }, + { "name": "site-objects", "template": "object", "scope": "perNode", "match": "object.*", "subDir": "site", "outputPattern": "{path}", "format": "html", "linkCheck": true }, + { "name": "site-requirements", "template": "requirement", "scope": "perRequirement", "subDir": "site", "outputPattern": "{path}", "format": "html", "linkCheck": true }, + { "name": "site-briefs", "template": "brief", "scope": "perNode", "match": ["object.entity"], "outputPattern": "briefs/{package}/{name}.md", "format": "markdown" } + ] +} diff --git a/fixtures/template-codegen-conformance/docs-view/templates/brief.mustache b/fixtures/template-codegen-conformance/docs-view/templates/brief.mustache new file mode 100644 index 0000000000..2e7df07bbe --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/templates/brief.mustache @@ -0,0 +1,3 @@ +# {{#node}}{{name}}{{/node}} + +Site root: `{{root}}` diff --git a/fixtures/template-codegen-conformance/docs-view/templates/head.mustache b/fixtures/template-codegen-conformance/docs-view/templates/head.mustache new file mode 100644 index 0000000000..1d1df7e6ac --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/templates/head.mustache @@ -0,0 +1,3 @@ + + +

Home

diff --git a/fixtures/template-codegen-conformance/docs-view/templates/index.mustache b/fixtures/template-codegen-conformance/docs-view/templates/index.mustache new file mode 100644 index 0000000000..722d6580f0 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/templates/index.mustache @@ -0,0 +1,8 @@ +{{> head}} +

Model

+

{{counts.nodes}} nodes, {{counts.requirements}} requirements.

+
    +{{#packages}} +
  • {{name}} ({{count}})
  • +{{/packages}} +
diff --git a/fixtures/template-codegen-conformance/docs-view/templates/link.mustache b/fixtures/template-codegen-conformance/docs-view/templates/link.mustache new file mode 100644 index 0000000000..bd4f86f016 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/templates/link.mustache @@ -0,0 +1 @@ +{{^unresolved}}{{label}}{{/unresolved}}{{#unresolved}}{{label}}{{/unresolved}} \ No newline at end of file diff --git a/fixtures/template-codegen-conformance/docs-view/templates/object.mustache b/fixtures/template-codegen-conformance/docs-view/templates/object.mustache new file mode 100644 index 0000000000..b86e5dc147 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/templates/object.mustache @@ -0,0 +1,33 @@ +{{> head}} +{{#node}} +

{{name}}

+

{{type}}.{{subType}}{{#abstract}} (abstract){{/abstract}}

+{{#description}}

{{description}}

{{/description}} +{{#extends}}

Extends {{> link}}

{{/extends}} +{{#memberGroups}} +

{{type}} ({{count}})

+ +{{#members}} + +{{/members}} +
{{name}}{{subType}}{{#declaredOn}}from {{> link}}{{/declaredOn}}
+{{/memberGroups}} +

References

+
    +{{#refs}} +
  • {{attr}}{{#via}} on {{> link}}{{/via}}: {{#target}}{{> link}}{{/target}}
  • +{{/refs}} +
+

Referenced by

+
    +{{#referencedBy}} +
  • {{#from}}{{> link}}{{/from}} ({{attr}})
  • +{{/referencedBy}} +
+

Claimed by

+
    +{{#claims}} +
  • {{#requirement}}{{> link}}{{/requirement}} {{status}}{{#member}}, on {{member}}{{/member}}
  • +{{/claims}} +
+{{/node}} diff --git a/fixtures/template-codegen-conformance/docs-view/templates/package.mustache b/fixtures/template-codegen-conformance/docs-view/templates/package.mustache new file mode 100644 index 0000000000..a8515fcd6b --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/templates/package.mustache @@ -0,0 +1,12 @@ +{{> head}} +{{#package}} +

{{name}}

+{{#groups}} +

{{type}}.{{subType}} ({{count}})

+
    +{{#nodes}} +
  • {{> link}}
  • +{{/nodes}} +
+{{/groups}} +{{/package}} diff --git a/fixtures/template-codegen-conformance/docs-view/templates/requirement.mustache b/fixtures/template-codegen-conformance/docs-view/templates/requirement.mustache new file mode 100644 index 0000000000..36f867af32 --- /dev/null +++ b/fixtures/template-codegen-conformance/docs-view/templates/requirement.mustache @@ -0,0 +1,19 @@ +{{> head}} +{{#requirement}} +

{{#breadcrumbs}}{{> link}} / {{/breadcrumbs}}

+

{{label}}

+

{{subType}}, {{status}}, depth {{depth}}

+
{{statement}}
+

Implemented by

+
    +{{#implementedBy}} +
  • {{ref}}: {{#target}}{{> link}}{{/target}}
  • +{{/implementedBy}} +
+

Below

+
    +{{#children}} +
  • {{> link}}
  • +{{/children}} +
+{{/requirement}} diff --git a/server/typescript/packages/codegen-ts/src/docs-view-run.ts b/server/typescript/packages/codegen-ts/src/docs-view-run.ts new file mode 100644 index 0000000000..9c82b32384 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/docs-view-run.ts @@ -0,0 +1,59 @@ +// The docs view of a run (`docs/features/docs-view.md`): built from the model the run already +// loaded, the requirement ledger the caller computed (`ctx.requirementLedger`), the files the +// run generated (`ctx.runOutput`) and the routes it mounts. The explorer site and the template +// generator's `docsView` data both read it, so a page sees the same facts whichever renders it. + +import { buildDocsView, type DocsView } from "@metaobjectsdev/metadata"; +import type { GenContext } from "./generator.js"; +import { buildApiModelForRun } from "./generators/api-model.js"; + +/** A route the run mounts, keyed by its node's resolution key: the docs view's `routes` input. */ +interface RunRoute { + node: string; + method: string; + path: string; +} + +/** The routes the run mounts, as the api reference states them (`METHOD /path` per symbol). */ +function runRoutes(ctx: GenContext): RunRoute[] { + const routes: RunRoute[] = []; + for (const unit of buildApiModelForRun(ctx).units) { + const node = unit.package !== undefined && unit.package !== "" ? `${unit.package}::${unit.node}` : unit.node; + for (const sym of unit.symbols) { + if (sym.kind !== "rest") continue; + const space = sym.name.indexOf(" "); + if (space < 0) continue; + routes.push({ node, method: sym.name.slice(0, space), path: sym.name.slice(space + 1) }); + } + } + return routes; +} + +/** The docs view of this run. `who` prefixes the warning when the ledger cannot be built. */ +export function runDocsView(ctx: GenContext, who: string): DocsView { + // The manifest's shape (path → generatedBy, sourceNode), from the files this run wrote: a + // fresh clone builds the same view as the machine that last generated. Only a generator + // marked `readsRunOutput` is handed the run's files; without them no node lists files. + const runFiles = ctx.runOutput?.(); + const manifest: Record = {}; + for (const f of runFiles ?? []) { + manifest[f.path] = { generatedBy: f.generatedBy, ...(f.sourceNode !== undefined && { sourceNode: f.sourceNode }) }; + } + // The ledger is the requirement gate's; a gate that throws leaves the section out (as a + // missing verify input does) rather than failing the whole run in the docs step. + let ledger: unknown; + try { + ledger = ctx.requirementLedger?.(); + } catch (err) { + ctx.warn(`${who}: the requirement ledger could not be built, so the docs show none: ${err instanceof Error ? err.message : String(err)}`); + } + // No route at all means this run recorded none (no routes generator, or REST off), which the + // view says as such; an empty list would claim the run mounted nothing. + const routes = runRoutes(ctx); + return buildDocsView({ + root: ctx.loadedRoot, + ...(ledger !== undefined && { verify: ledger }), + ...(runFiles !== undefined && { manifest }), + ...(routes.length > 0 && { routes }), + }); +} diff --git a/server/typescript/packages/codegen-ts/src/generator.ts b/server/typescript/packages/codegen-ts/src/generator.ts index 7284c390b2..37dee7f2bc 100644 --- a/server/typescript/packages/codegen-ts/src/generator.ts +++ b/server/typescript/packages/codegen-ts/src/generator.ts @@ -181,6 +181,15 @@ export interface GenContext { warn: (msg: string) => void; } +/** What `Generator.checkRunOutput` is given. Paths are absolute, as the runner writes them. */ +export interface RunOutputCheck { + /** The files this generator emitted, in its order. */ + own: readonly { fullPath: string; content: string }[]; + /** A file's text: this run's output when it emitted the path, else the file on disk, else + * `undefined`. A run narrowed with `--generators` reads the rest of the site from disk. */ + read: (fullPath: string) => string | undefined; +} + /** One file of the run, as `GenContext.runOutput` lists it. */ export interface RunOutputFile { /** Project-relative path, `/`-separated. */ @@ -293,6 +302,14 @@ export interface Generator { * (`ctx.runOutput`). The runner runs every marked generator after every unmarked one, * in declared order, so the list it reads is complete. */ readsRunOutput?: boolean; + /** + * A check over the run's output, called once after EVERY selected generator has run and + * before anything is written, so it sees the files the generators after this one emit too. + * It returns one message per problem; any message fails the run, naming this generator, and + * nothing is written. The template generator's `linkCheck` is one: every relative link in its + * pages must land on a file and an anchor this run (or the disk) holds. + */ + checkRunOutput?: (run: RunOutputCheck) => readonly string[]; /** §A6 — marks the generator that emits the Names artifact. The runner * aggregates this across the suite into ResolvedGenConfig.includeNames, which the * entity generator reads to decide whether it may reference those constants. diff --git a/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts b/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts index a3824cdaf8..da8713729e 100644 --- a/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts @@ -23,11 +23,10 @@ import { readFileSync } from "node:fs"; import { basename, join, resolve } from "node:path"; import { existsSync } from "node:fs"; -import { buildDocsView } from "@metaobjectsdev/metadata"; import { generateExplorerSite, generateSite, readPromptTexts } from "@metaobjectsdev/docs-site"; import type { EmittedFile, GenContext, Generator, GeneratorFactory } from "../generator.js"; import { DOCS_TARGET_NAME } from "../docs-run.js"; -import { buildApiModelForRun } from "./api-model.js"; +import { runDocsView } from "../docs-view-run.js"; import { makeScratchDir, removeTree } from "../scratch-dir.js"; /** The site lands here, under the target. */ @@ -155,54 +154,10 @@ async function buildInScratch(prefix: string, build: (outDir: string) => string[ } } -/** A route the run mounts, keyed by its node's resolution key: the docs view's `routes` input. */ -interface RunRoute { - node: string; - method: string; - path: string; -} - -/** The routes the run mounts, as the api reference states them (`METHOD /path` per symbol). */ -function runRoutes(ctx: GenContext): RunRoute[] { - const routes: RunRoute[] = []; - for (const unit of buildApiModelForRun(ctx).units) { - const node = unit.package !== undefined && unit.package !== "" ? `${unit.package}::${unit.node}` : unit.node; - for (const sym of unit.symbols) { - if (sym.kind !== "rest") continue; - const space = sym.name.indexOf(" "); - if (space < 0) continue; - routes.push({ node, method: sym.name.slice(0, space), path: sym.name.slice(space + 1) }); - } - } - return routes; -} - async function explorerSite(ctx: GenContext, project: string, prefix: string, opts: DocsSiteFileOpts | undefined): Promise { - // The manifest's shape (path → generatedBy, sourceNode), from the files this run wrote: a - // fresh clone builds the same site as the machine that last generated. - const manifest: Record = {}; - for (const f of ctx.runOutput?.() ?? []) { - manifest[f.path] = { generatedBy: f.generatedBy, ...(f.sourceNode !== undefined && { sourceNode: f.sourceNode }) }; - } - // The ledger is the requirement gate's; a gate that throws leaves the section out (as a - // missing verify input does) rather than failing the whole run in the docs step. - let ledger: unknown; - try { - ledger = ctx.requirementLedger?.(); - } catch (err) { - ctx.warn(`docs-site: the requirement ledger could not be built, so the site shows none: ${err instanceof Error ? err.message : String(err)}`); - } - // No route at all means this run recorded none (no routes generator, or REST off), which the - // site says as such; an empty list would claim the run mounted nothing. - const routes = runRoutes(ctx); // The docs view is built from the model this run already loaded: ids, pages, inheritance and // references are the loader's, never re-derived from a serialized copy. - const view = buildDocsView({ - root: ctx.loadedRoot, - ...(ledger !== undefined && { verify: ledger }), - manifest, - ...(routes.length > 0 && { routes }), - }); + const view = runDocsView(ctx, "docs-site"); const texts = readPromptTexts(view, promptSourceDirs(ctx, project, opts, ctx.sourceRoots ?? [])); const owned = ownedSiteDirs(project); if (owned.templatesDir !== undefined && !existsSync(join(owned.templatesDir, EXPLORER_MARKER_TEMPLATE))) { diff --git a/server/typescript/packages/codegen-ts/src/generators/template-generator.ts b/server/typescript/packages/codegen-ts/src/generators/template-generator.ts index 043fa74dd1..4defc33d0b 100644 --- a/server/typescript/packages/codegen-ts/src/generators/template-generator.ts +++ b/server/typescript/packages/codegen-ts/src/generators/template-generator.ts @@ -27,9 +27,12 @@ // docsFile() is the first templateGenerator instance (rc.12), which is why the // documents framing stuck; it is the first instance, not the boundary. -import type { MetaRoot, MetaObject } from "@metaobjectsdev/metadata"; +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join, relative, resolve, sep } from "node:path"; +import { REQUIREMENT, type MetaRoot, type MetaObject, type DocsView } from "@metaobjectsdev/metadata"; import { render, type Provider, type RenderFormat } from "@metaobjectsdev/render"; -import type { Generator, GenContext, EmittedFile, GeneratorFactory } from "../generator.js"; +import { findDanglingLinks } from "@metaobjectsdev/docs-site"; +import type { Generator, GenContext, EmittedFile, GeneratorFactory, RunOutputCheck } from "../generator.js"; import { projectProvider } from "../render-engine/framework-provider.js"; import { expandOutputPattern } from "../template-codegen/output-pattern.js"; import { @@ -38,13 +41,28 @@ import { buildModelTemplateData, packageOf, } from "../template-codegen/template-data.js"; +import { runDocsView } from "../docs-view-run.js"; -/** The three built-in walk scopes (SP-1 §3.1). Same vocabulary as the engine - * helpers perEntity/perPackage/perModel. */ -export type TemplateScope = "perEntity" | "perPackage" | "perModel"; +/** The built-in walk scopes (SP-1 §3.1). `perEntity`, `perPackage` and `perModel` are the same + * vocabulary as the engine helpers; `perNode` and `perRequirement` walk the docs view + * (`docs/features/docs-view.md`): one file per top-level node of any type, and one per + * requirement at any depth. */ +export type TemplateScope = "perEntity" | "perPackage" | "perModel" | "perNode" | "perRequirement"; + +/** What a template reads. `entities`, the default for the first three scopes, is the neutral + * per-entity dictionary (`template-data.ts`). `docsView` is the docs view, the data of + * `perNode` and `perRequirement` and an opt-in for `perPackage` and `perModel`. */ +export type TemplateData = "entities" | "docsView"; export type TemplateFormat = RenderFormat; +/** A directory of static files copied beside the pages, unchanged. */ +export interface TemplateAssets { + /** The directory, relative to the project root. Every file under it is copied under the + * generator's `subDir`, at its path relative to this directory. */ + from: string; +} + export interface TemplateWalkResult { /** The data dict to render against. Templates reference its keys; the * shape is the public-API contract template authors consume. */ @@ -64,12 +82,32 @@ export interface TemplateGeneratorOpts { * escape hatch; most consumers declare a `scope` + `outputPattern` instead. */ walk?: (root: MetaRoot) => TemplateWalkResult[] | Promise; /** Built-in walk scope (SP-1 §3.1) — declarative alternative to `walk`. The - * generator derives the neutral data dict (template-data.ts) per unit and - * names each file via `outputPattern`. Mutually exclusive with `walk`. */ + * generator derives the data per unit and names each file via `outputPattern`. + * Mutually exclusive with `walk`. */ scope?: TemplateScope; - /** Output path pattern for the built-in `scope` walk: `{name}` `{Name}` - * `{package}` (SP-1 §3.3). Required with `scope`; ignored with `walk`. */ + /** Output path pattern for the built-in `scope` walk: `{name}` `{Name}` `{package}` + * (SP-1 §3.3), and `{path}` (the node's or requirement's page in the docs view) for + * `perNode` and `perRequirement`. Required with `scope`; ignored with `walk`. */ outputPattern?: string; + /** What the template reads (see {@link TemplateData}). Default `entities`, except for + * `perNode` and `perRequirement`, which read only `docsView`. */ + data?: TemplateData; + /** `perNode` and `perRequirement` only: which kinds get a page. A pattern is + * `.`, `.*` or `*`; a list matches any of its patterns. Default `*`. + * In `perNode`, `*` does not select requirement nodes, because `perRequirement` owns their + * pages; a pattern naming the requirement type (`requirement.*`) still selects them. */ + match?: string | readonly string[]; + /** A directory under the target the output paths are relative to, and the site root a + * docs-view page's `root` leads back to. Default: the target's own directory. */ + subDir?: string; + /** A directory of static files (stylesheets, scripts) copied under `subDir` with the pages. + * Text files only: a file that is not UTF-8 is refused. */ + assets?: TemplateAssets; + /** Check every relative link in this generator's pages once the whole run has rendered: + * each must name a file the run emitted (or one already on disk that a full run does not + * delete as no longer generated) and, with `#anchor`, an element carrying `id="anchor"` in it. A link that does not land fails the run, naming the + * page and the link. Requires `format: "html"`. */ + linkCheck?: boolean; /** Template reference. Resolved by the configured Provider chain — by * default the project's `templates/.mustache` first, then the * framework defaults at `codegen-ts/templates/.mustache`. */ @@ -91,9 +129,22 @@ export interface TemplateGeneratorOpts { target?: string; } -/** Derive a `walk` from a built-in scope + output pattern. Each scope yields the - * neutral data dict for its unit and names the file via the pattern. */ -function scopeWalk( +/** The scopes that walk the docs view, and so read only it. */ +const VIEW_ONLY_SCOPES: readonly TemplateScope[] = ["perNode", "perRequirement"]; +const MATCH_PATTERN = /^(\*|[A-Za-z][A-Za-z0-9_-]*\.(\*|[A-Za-z][A-Za-z0-9_-]*))$/; + +/** Whether a node of `type`/`subType` is one `match` names. */ +function matchesKind(patterns: readonly string[], type: string, subType: string): boolean { + return patterns.some((p) => p === "*" || p === `${type}.*` || p === `${type}.${subType}`); +} + +/** `../` once per directory in `path`: the way from a page back to its site root. */ +function rootOf(path: string): string { + return "../".repeat(path.split("/").length - 1); +} + +/** Derive a `walk` over the neutral per-entity dictionary from a built-in scope + pattern. */ +function entityScopeWalk( scope: TemplateScope, pattern: string, ): (root: MetaRoot) => TemplateWalkResult[] { @@ -123,21 +174,106 @@ function scopeWalk( }; } +/** The pages of a scope over the docs view. Every page's data is the whole view, plus `root` + * (the way back to the site root, so a link is `{{root}}{{path}}`) and, for one unit, the + * unit itself: `node`, `requirement` or `package`. */ +function viewScopeWalk(view: DocsView, scope: TemplateScope, pattern: string, match: readonly string[]): TemplateWalkResult[] { + const page = (outputPath: string, unit: Record): TemplateWalkResult => ({ + data: { ...view, ...unit, root: rootOf(outputPath) }, + outputPath, + }); + if (scope === "perNode") { + const nonRequirement = match.filter((p) => p !== "*"); + return view.nodes + .filter((n) => matchesKind(n.type === REQUIREMENT ? nonRequirement : match, n.type, n.subType)) + .map((n) => page(expandOutputPattern(pattern, { name: n.name, package: n.package, path: n.path }), { node: n })); + } + if (scope === "perRequirement") { + return view.requirements + .filter((r) => matchesKind(match, REQUIREMENT, r.subType)) + .map((r) => page(expandOutputPattern(pattern, { name: r.name, package: r.package, path: r.path }), { requirement: r })); + } + if (scope === "perPackage") { + return view.packages.map((p) => page(expandOutputPattern(pattern, { package: p.name }), { package: p })); + } + if (scope === "perModel") return [page(expandOutputPattern(pattern, {}), {})]; + throw new Error(`the ${scope} scope does not read the docs view; use perNode with match "object.entity"`); +} + +/** Every file under `dir`, relative to it with `/` separators, sorted by code unit. */ +function filesUnder(dir: string): string[] { + const out: string[] = []; + const visit = (d: string): void => { + for (const name of readdirSync(d)) { + const p = join(d, name); + if (statSync(p).isDirectory()) visit(p); + else out.push(relative(dir, p).split(sep).join("/")); + } + }; + visit(dir); + return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); +} + +/** The asset files, as output paths under `prefix`. */ +function assetFiles(name: string, assets: TemplateAssets, project: string, prefix: string): EmittedFile[] { + const from = resolve(project, assets.from); + let isDir = false; + try { + isDir = statSync(from).isDirectory(); + } catch { + // Reported below. + } + if (!isDir) throw new Error(`templateGenerator(${name}): the assets directory does not exist: ${assets.from}`); + const decoder = new TextDecoder("utf-8", { fatal: true }); + return filesUnder(from).map((rel) => { + let content: string; + try { + content = decoder.decode(readFileSync(join(from, rel))); + } catch { + throw new Error(`templateGenerator(${name}): asset ${assets.from}/${rel} is not a UTF-8 text file; assets are copied as text`); + } + return { path: prefix + rel, content }; + }); +} + export const templateGenerator = function templateGenerator( opts: TemplateGeneratorOpts, ): Generator { const fmt: TemplateFormat = opts.format ?? "text"; const hasWalk = typeof opts.walk === "function"; const hasScope = opts.scope !== undefined; + const label = `templateGenerator(${opts.name})`; if (hasWalk === hasScope) { - throw new Error( - `templateGenerator(${opts.name}): provide exactly one of \`walk\` or (\`scope\` + \`outputPattern\`)`, - ); + throw new Error(`${label}: provide exactly one of \`walk\` or (\`scope\` + \`outputPattern\`)`); } if (hasScope && (opts.outputPattern === undefined || opts.outputPattern === "")) { - throw new Error(`templateGenerator(${opts.name}): \`scope\` requires a non-empty \`outputPattern\``); + throw new Error(`${label}: \`scope\` requires a non-empty \`outputPattern\``); } - const walk = hasWalk ? opts.walk! : scopeWalk(opts.scope!, opts.outputPattern!); + const viewOnly = hasScope && VIEW_ONLY_SCOPES.includes(opts.scope!); + const data: TemplateData = opts.data ?? (viewOnly ? "docsView" : "entities"); + if (hasWalk && opts.data !== undefined) throw new Error(`${label}: \`data\` applies to a \`scope\`, not a \`walk\``); + if (viewOnly && data !== "docsView") { + throw new Error(`${label}: the ${opts.scope} scope reads the docs view; \`data\` must be "docsView"`); + } + if (data === "docsView" && opts.scope === "perEntity") { + throw new Error(`${label}: the perEntity scope reads the entity dictionary; for a page per object over the docs view use perNode with match "object.*"`); + } + const match = opts.match === undefined ? ["*"] : typeof opts.match === "string" ? [opts.match] : [...opts.match]; + if (opts.match !== undefined) { + if (!viewOnly) throw new Error(`${label}: \`match\` applies to the perNode and perRequirement scopes`); + const bad = match.find((m) => !MATCH_PATTERN.test(m)); + if (match.length === 0 || bad !== undefined) { + throw new Error(`${label}: \`match\` takes ".", ".*" or "*", got '${bad ?? "[]"}'`); + } + } + if (opts.linkCheck === true && fmt !== "html") { + throw new Error(`${label}: \`linkCheck\` reads HTML links, so it needs format "html"`); + } + const subDir = (opts.subDir ?? "").replace(/^\/+|\/+$/g, ""); + const prefix = subDir === "" ? "" : `${subDir}/`; + // The pages the last generate() rendered, for the link check (the assets follow them). + let pageCount = 0; + let pagePaths: string[] = []; const generator: Generator = { name: opts.name, async generate(ctx: GenContext): Promise { @@ -154,30 +290,56 @@ export const templateGenerator = function templateGenerator( ); provider = projectProvider(process.cwd()); } - const walkRes = await walk(ctx.loadedRoot); + const walkRes = hasWalk + ? await opts.walk!(ctx.loadedRoot) + : data === "docsView" + ? viewScopeWalk(runDocsView(ctx, label), opts.scope!, opts.outputPattern!, match) + : entityScopeWalk(opts.scope!, opts.outputPattern!)(ctx.loadedRoot); const files: EmittedFile[] = []; - for (const { data, outputPath } of walkRes) { + for (const { data: payload, outputPath } of walkRes) { let content: string; try { content = render({ ref: opts.template, - payload: data, + payload, provider, format: fmt, }); } catch (err) { const msg = err instanceof Error ? err.message : String(err); throw new Error( - `templateGenerator(${opts.name}) failed rendering '${opts.template}' for '${outputPath}': ${msg}`, + `${label} failed rendering '${opts.template}' for '${outputPath}': ${msg}`, { cause: err instanceof Error ? err : undefined }, ); } - files.push({ path: outputPath, content }); + files.push({ path: prefix + outputPath, content }); + } + pageCount = files.length; + pagePaths = files.map((f) => f.path); + if (opts.assets !== undefined) { + files.push(...assetFiles(opts.name, opts.assets, ctx.inputRoot ?? ctx.projectRoot ?? process.cwd(), prefix)); } return files; }, }; if (opts.filter) generator.filter = opts.filter; if (opts.target) generator.target = opts.target; + // The view lists the files each node produced, so it is built once the rest of the run has. + if (data === "docsView") generator.readsRunOutput = true; + // ADR-0064: the assets are read beside the model, so editing one regenerates. + if (opts.assets !== undefined) generator.inputs = [opts.assets.from]; + if (opts.linkCheck === true) { + generator.checkRunOutput = (run: RunOutputCheck): readonly string[] => { + // The pages are the rendered files (the assets come after them), in the target's own + // directory: the check works in paths relative to it, so its report reads as the output. + const pages = run.own.slice(0, pageCount); + const first = pages[0]; + if (first === undefined) return []; + const outDir = first.fullPath.slice(0, first.fullPath.length - pagePaths[0]!.length); + const dangling = findDanglingLinks(pagePaths.slice(0, pages.length), (p) => run.read(join(outDir, ...p.split("/")))); + if (dangling.length === 0) return []; + return [`link check failed, ${dangling.length} link(s) land on nothing: ${dangling.join("; ")}`]; + }; + } return generator; } as GeneratorFactory; diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index e9f5c77253..12d10972d2 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -6,7 +6,7 @@ export { runGen, declaredGeneratorNames, stableGeneratorName, undeclaredGeneratorsMessage } from "./runner.js"; export type { RunGenOpts, RunGenResult } from "./runner.js"; -export type { Generator, GenContext, EmittedFile, GeneratorFactory, RunOutputFile } from "./generator.js"; +export type { Generator, GenContext, EmittedFile, GeneratorFactory, RunOutputFile, RunOutputCheck } from "./generator.js"; export { perEntity, perPackage, perModel, oncePerRun, selectedEntities } from "./generator.js"; // The one aggregation of the UI-tier markers, Hono routes and the routes' `expose` option: // the run's own answers to "does this run emit a UI tier?" and "which verbs are mounted?". diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index 105edb2239..1b1f3a27d3 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -907,6 +907,8 @@ export async function runGen(opts: RunGenOpts): Promise { }; const wholeKeys = new Set(safeEntities.map((e) => e.resolutionKey())); + // The generators with a `checkRunOutput`, and the files each emitted: checked after the loop. + const checked: { generator: Generator; own: { fullPath: string; content: string }[] }[] = []; for (const generator of selected) { const selfTarget = targetOf(generator); // Resolve the WRITE-time location against projectRoot when outDir is @@ -1048,6 +1050,9 @@ export async function runGen(opts: RunGenOpts): Promise { throw new Error(`[${generator.name}] ${msg}`, { cause: err }); } + if (generator.checkRunOutput !== undefined) { + checked.push({ generator, own: files.map((f) => ({ fullPath: join(writeOutDir, f.path), content: f.content })) }); + } for (const file of files) { // A file rendered from one object the entity filter did not name is not this run's // to write: `perEntity` already skips those, and this holds a generator that renders @@ -1096,6 +1101,29 @@ export async function runGen(opts: RunGenOpts): Promise { ); } + // 4b. Output checks (`Generator.checkRunOutput`): after every generator, so a check sees what + // the generators after its own emitted; before the write, so a failed check writes nothing. + if (checked.length > 0) { + const byPath = new Map(emitted.map((f) => [f.fullPath, f.content])); + const swept = projectRoot !== undefined && opts.generatorNames === undefined && baseline !== "adopt" && !entityNarrowed + ? new Set(listGeneratedPaths(genStateDir).map((p) => resolve(projectRoot, p))) + : new Set(); + const read = (fullPath: string): string | undefined => { + const mine = byPath.get(fullPath); + if (mine !== undefined) return mine; + if (swept.has(resolve(fullPath))) return undefined; + try { + return readFileSync(fullPath, "utf8"); + } catch { + return undefined; + } + }; + for (const { generator, own } of checked) { + const problems = generator.checkRunOutput!({ own, read }); + if (problems.length > 0) throw new Error(`[${generator.name}] ${problems.join("; ")}`); + } + } + // 5. Write phase. const writes: WriteResult[] = []; const conflicts: WriteResult[] = []; diff --git a/server/typescript/packages/codegen-ts/src/template-codegen/output-pattern.ts b/server/typescript/packages/codegen-ts/src/template-codegen/output-pattern.ts index 17e008f4e9..8ad9e7b8ac 100644 --- a/server/typescript/packages/codegen-ts/src/template-codegen/output-pattern.ts +++ b/server/typescript/packages/codegen-ts/src/template-codegen/output-pattern.ts @@ -1,9 +1,11 @@ // Expands the tiny, fixed output-pattern grammar shared cross-port (SP-1 §3.3). -// Placeholders: {name}, {Name} (PascalCase of name), {package} (:: → /). +// Placeholders: {name}, {Name} (PascalCase of name), {package} (:: → /), and {path}: the +// page a docs-view node or requirement lives at (`docs/features/docs-view.md`, "Pages and +// anchors"), which only the perNode and perRequirement scopes have. // An empty {package} collapses its trailing slash so `{package}/{name}` with no // package yields just `{name}`. Unknown placeholders are a hard error. -const KNOWN = new Set(["name", "Name", "package"]); +const KNOWN = new Set(["name", "Name", "package", "path"]); function pascalCase(s: string): string { return s @@ -15,7 +17,7 @@ function pascalCase(s: string): string { export function expandOutputPattern( pattern: string, - vars: { name?: string; package?: string }, + vars: { name?: string; package?: string; path?: string }, ): string { let pkgWasEmpty = false; const out = pattern.replace(/\{(\w+)\}/g, (_m, token: string) => { @@ -27,6 +29,12 @@ export function expandOutputPattern( if (p === "") pkgWasEmpty = true; return p; } + if (token === "path") { + if (vars.path === undefined) { + throw new Error(`output pattern '${pattern}' uses {path} but no page path is in scope (the perNode and perRequirement scopes give one)`); + } + return vars.path; + } if (vars.name === undefined) { throw new Error(`output pattern '${pattern}' uses {${token}} but no entity name is in scope`); } diff --git a/server/typescript/packages/codegen-ts/src/template-codegen/template-spec.schema.json b/server/typescript/packages/codegen-ts/src/template-codegen/template-spec.schema.json index 9d762d24ce..6d9f54294f 100644 --- a/server/typescript/packages/codegen-ts/src/template-codegen/template-spec.schema.json +++ b/server/typescript/packages/codegen-ts/src/template-codegen/template-spec.schema.json @@ -6,6 +6,9 @@ "type": "object", "required": ["generators"], "additionalProperties": false, + "$defs": { + "match": { "type": "string", "pattern": "^(\\*|[A-Za-z][A-Za-z0-9_-]*\\.(\\*|[A-Za-z][A-Za-z0-9_-]*))$" } + }, "properties": { "generators": { "type": "array", @@ -16,10 +19,27 @@ "properties": { "name": { "type": "string", "minLength": 1 }, "template": { "type": "string", "minLength": 1 }, - "scope": { "enum": ["perEntity", "perPackage", "perModel"] }, + "scope": { "enum": ["perEntity", "perPackage", "perModel", "perNode", "perRequirement"] }, "outputPattern": { "type": "string", "minLength": 1 }, "format": { "enum": ["text", "html", "xml", "csv", "json", "markdown", "spreadsheet"] }, - "target": { "type": "string", "minLength": 1 } + "target": { "type": "string", "minLength": 1 }, + "data": { + "description": "What the template reads: the per-entity dictionary (default) or the docs view (docs/features/docs-view.md). perNode and perRequirement read only the docs view.", + "enum": ["entities", "docsView"] + }, + "match": { + "description": "perNode and perRequirement: which kinds get a page, as ., .* or *.", + "oneOf": [{ "$ref": "#/$defs/match" }, { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/match" } }] + }, + "subDir": { "type": "string", "description": "The directory under the target the output paths, and a docs-view page's root, are relative to." }, + "assets": { + "description": "A directory of static text files, relative to the project, copied under subDir.", + "type": "object", + "required": ["from"], + "additionalProperties": false, + "properties": { "from": { "type": "string", "minLength": 1 } } + }, + "linkCheck": { "type": "boolean", "description": "Fail the run when a relative link in this entry's HTML pages lands on no file or anchor." } } } } diff --git a/server/typescript/packages/codegen-ts/src/template-codegen/template-spec.ts b/server/typescript/packages/codegen-ts/src/template-codegen/template-spec.ts index 18b79e2033..56b75bd829 100644 --- a/server/typescript/packages/codegen-ts/src/template-codegen/template-spec.ts +++ b/server/typescript/packages/codegen-ts/src/template-codegen/template-spec.ts @@ -3,9 +3,10 @@ // (SP-1 §4); a JSON Schema (template-spec.schema.json) sits beside it. import { ESCAPERS, type RenderFormat } from "@metaobjectsdev/render"; import type { Generator } from "../generator.js"; -import { templateGenerator, type TemplateScope } from "../generators/template-generator.js"; +import { templateGenerator, type TemplateAssets, type TemplateData, type TemplateScope } from "../generators/template-generator.js"; -const SCOPES = ["perEntity", "perPackage", "perModel"] as const satisfies readonly TemplateScope[]; +const SCOPES = ["perEntity", "perPackage", "perModel", "perNode", "perRequirement"] as const satisfies readonly TemplateScope[]; +const DATA = ["entities", "docsView"] as const satisfies readonly TemplateData[]; const FORMATS = Object.keys(ESCAPERS) as readonly RenderFormat[]; export interface TemplateSpecEntry { @@ -15,6 +16,16 @@ export interface TemplateSpecEntry { outputPattern: string; format?: RenderFormat; target?: string; + /** What the template reads: `entities` (the per-entity dictionary) or `docsView`. */ + data?: TemplateData; + /** perNode / perRequirement: `.`, `.*` or `*`, or a list of them. */ + match?: string | string[]; + /** The directory under the target the output paths, and a page's `root`, are relative to. */ + subDir?: string; + /** A directory of static text files, relative to the project, copied under `subDir`. */ + assets?: TemplateAssets; + /** Fail the run when a relative link in this entry's HTML pages lands on nothing. */ + linkCheck?: boolean; } export interface TemplateSpecFile { generators: TemplateSpecEntry[]; } @@ -55,6 +66,35 @@ export function parseTemplateSpec(json: unknown): TemplateSpecFile { entry.format = raw.format as RenderFormat; } if (typeof raw.target === "string") entry.target = raw.target; + const at = `template-spec generators[${i}]`; + if (raw.data !== undefined) { + if (!DATA.includes(raw.data as TemplateData)) { + throw new Error(`${at}: data must be one of ${DATA.join(" | ")}, got '${String(raw.data)}'`); + } + entry.data = raw.data as TemplateData; + } + if (raw.match !== undefined) { + const list = Array.isArray(raw.match) ? raw.match : [raw.match]; + if (list.length === 0 || !list.every((m): m is string => typeof m === "string" && m !== "")) { + throw new Error(`${at}: match must be a non-empty string or a non-empty list of them`); + } + entry.match = Array.isArray(raw.match) ? list : list[0]!; + } + if (raw.subDir !== undefined) { + if (typeof raw.subDir !== "string") throw new Error(`${at}: subDir must be a string`); + entry.subDir = raw.subDir; + } + if (raw.assets !== undefined) { + const a = raw.assets; + if (!isRecord(a) || typeof a.from !== "string" || a.from === "" || Object.keys(a).some((k) => k !== "from")) { + throw new Error(`${at}: assets must be { "from": "" }`); + } + entry.assets = { from: a.from }; + } + if (raw.linkCheck !== undefined) { + if (typeof raw.linkCheck !== "boolean") throw new Error(`${at}: linkCheck must be a boolean`); + entry.linkCheck = raw.linkCheck; + } return entry; }); return { generators }; @@ -70,6 +110,11 @@ export function templateSpecToGenerators(spec: TemplateSpecFile): Generator[] { outputPattern: e.outputPattern, ...(e.format !== undefined ? { format: e.format } : {}), ...(e.target !== undefined ? { target: e.target } : {}), + ...(e.data !== undefined && { data: e.data }), + ...(e.match !== undefined && { match: e.match }), + ...(e.subDir !== undefined && { subDir: e.subDir }), + ...(e.assets !== undefined && { assets: e.assets }), + ...(e.linkCheck !== undefined && { linkCheck: e.linkCheck }), }), ); } diff --git a/server/typescript/packages/codegen-ts/test/authoring-surface.snapshot.json b/server/typescript/packages/codegen-ts/test/authoring-surface.snapshot.json index 8e72122e74..685f01aa0b 100644 --- a/server/typescript/packages/codegen-ts/test/authoring-surface.snapshot.json +++ b/server/typescript/packages/codegen-ts/test/authoring-surface.snapshot.json @@ -6,6 +6,7 @@ "GeneratorFactory", "GeneratorProvides", "GeneratorRoutes", + "RunOutputCheck", "RunOutputFile", "oncePerRun", "perEntity", diff --git a/server/typescript/packages/codegen-ts/test/generators/template-generator-docs-view.test.ts b/server/typescript/packages/codegen-ts/test/generators/template-generator-docs-view.test.ts new file mode 100644 index 0000000000..20924ee1ea --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/generators/template-generator-docs-view.test.ts @@ -0,0 +1,209 @@ +// The template generator over the docs view (docs/features/docs-view.md): the perNode and +// perRequirement scopes, `data: "docsView"` on perModel and perPackage, `{path}` and `root`, +// `subDir`, the asset copy and the link check. The cross-port bytes are pinned by +// fixtures/template-codegen-conformance/docs-view/; this file covers the refusals and the +// behaviour a corpus cannot show (a failed check writes nothing). + +import { describe, test, expect, afterEach } from "bun:test"; +import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { InMemoryProvider } from "@metaobjectsdev/render"; +import { MetaDataLoader, InMemoryStringSource, type MetaRoot } from "@metaobjectsdev/metadata"; +import { runGen, defineConfig } from "../../src/index.js"; +import { templateGenerator } from "../../src/generators/template-generator.js"; +import { parseTemplateSpec } from "../../src/template-codegen/template-spec.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; + +const MODEL = JSON.stringify({ + "metadata.root": { + package: "acme", + children: [ + { "object.entity": { name: "Customer", children: [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + ] } }, + { "object.value": { name: "Address", children: [{ "field.string": { name: "line1" } }] } }, + { "requirement.functional": { + name: "Buy", "@level": 4, "@status": "live", + "@statement": "A customer can buy.", "@counterexample": "One who cannot.", + "@implementedBy": ["Customer"], + } }, + ], + }, +}); + +async function load(): Promise { + const res = await new MetaDataLoader().load([new InMemoryStringSource(MODEL)]); + expect(res.errors).toEqual([]); + return res.root as MetaRoot; +} + +const scratch: string[] = []; +afterEach(() => { for (const d of scratch.splice(0)) removeTree(d); }); + +async function gen(generators: ReturnType[], setup?: (project: string) => void): Promise<{ out: string }> { + const project = makeScratchDir("tmpl-view-"); + scratch.push(project); + setup?.(project); + const out = join(project, "out"); + await runGen({ + config: defineConfig({ outDir: out, extStyle: "none", dbImport: "~/db", dialect: "sqlite", generators }), + metadata: await load(), + projectRoot: project, + }); + return { out }; +} + +describe("templateGenerator() over the docs view", () => { + test("perNode renders one page per matching node at {path}, with root leading back", async () => { + const provider = new InMemoryProvider({ node: "{{#node}}{{id}} {{type}}.{{subType}}{{/node}} root={{root}} nodes={{counts.nodes}}" }); + const { out } = await gen([templateGenerator({ name: "n", template: "node", scope: "perNode", match: "object.entity", outputPattern: "{path}", provider })]); + expect(readFileSync(join(out, "model/acme/Customer.html"), "utf8")).toBe("acme::Customer object.entity root=../../ nodes=3"); + expect(existsSync(join(out, "model/acme/Address.html"))).toBe(false); + }); + + test("match takes a list, and * matches every node type except requirements", async () => { + const provider = new InMemoryProvider({ node: "{{#node}}{{name}}{{/node}}" }); + const { out } = await gen([ + templateGenerator({ name: "a", template: "node", scope: "perNode", match: ["object.value", "requirement.*"], outputPattern: "a/{name}.txt", provider }), + templateGenerator({ name: "b", template: "node", scope: "perNode", outputPattern: "b/{name}.txt", provider }), + templateGenerator({ name: "c", template: "node", scope: "perNode", match: ["*", "requirement.functional"], outputPattern: "c/{name}.txt", provider }), + ]); + expect(existsSync(join(out, "a/Address.txt")) && existsSync(join(out, "a/Buy.txt"))).toBe(true); + expect(existsSync(join(out, "a/Customer.txt"))).toBe(false); + for (const n of ["Address", "Customer"]) expect(existsSync(join(out, `b/${n}.txt`))).toBe(true); + expect(existsSync(join(out, "b/Buy.txt"))).toBe(false); + for (const n of ["Address", "Buy", "Customer"]) expect(existsSync(join(out, `c/${n}.txt`))).toBe(true); + }); + + test("a full site, perNode at the default match beside perRequirement, writes each page once", async () => { + const provider = new InMemoryProvider({ + node: "{{#node}}node {{name}}{{/node}}", + req: "{{#requirement}}requirement {{name}}{{/requirement}}", + }); + const { out } = await gen([ + templateGenerator({ name: "n", template: "node", scope: "perNode", subDir: "site", outputPattern: "{path}", provider }), + templateGenerator({ name: "r", template: "req", scope: "perRequirement", subDir: "site", outputPattern: "{path}", provider }), + ]); + expect(readFileSync(join(out, "site/model/acme/Customer.html"), "utf8")).toBe("node Customer"); + expect(readFileSync(join(out, "site/requirements/acme/Buy.html"), "utf8")).toBe("requirement Buy"); + }); + + test("perRequirement renders each requirement; perModel and perPackage read the view on request", async () => { + const provider = new InMemoryProvider({ + req: "{{#requirement}}{{address}} {{status}}{{/requirement}}", + all: "{{#nodes}}{{name}} {{/nodes}}", + pkg: "{{#package}}{{name}}={{count}}{{/package}}", + }); + const { out } = await gen([ + templateGenerator({ name: "r", template: "req", scope: "perRequirement", outputPattern: "{path}", provider }), + templateGenerator({ name: "m", template: "all", scope: "perModel", data: "docsView", subDir: "site", outputPattern: "all.txt", provider }), + templateGenerator({ name: "p", template: "pkg", scope: "perPackage", data: "docsView", outputPattern: "{package}.txt", provider }), + ]); + expect(readFileSync(join(out, "requirements/acme/Buy.html"), "utf8")).toBe("Buy live"); + expect(readFileSync(join(out, "site/all.txt"), "utf8")).toBe("Address Buy Customer "); + expect(readFileSync(join(out, "acme.txt"), "utf8")).toBe("acme=3"); + }); + + test("a link that lands on nothing fails the run and writes nothing", async () => { + const provider = new InMemoryProvider({ + node: `{{#node}}x i{{/node}}`, + }); + let err: unknown; + let project = ""; + try { + await gen([templateGenerator({ name: "n", template: "node", scope: "perNode", match: "object.entity", outputPattern: "{path}", format: "html", linkCheck: true, provider })], (p) => { project = p; }); + } catch (e) { + err = e; + } + expect(String(err)).toContain("[n] link check failed, 2 link(s) land on nothing:"); + expect(String(err)).toContain("model/acme/Customer.html -> ../../model/acme/Customer.html#nope"); + expect(String(err)).toContain("model/acme/Customer.html -> ../../index.html"); + expect(existsSync(join(project, "out"))).toBe(false); + }); + + test("a full run does not let a link land on a generated file it no longer produces", async () => { + const project = makeScratchDir("tmpl-view-"); + scratch.push(project); + const out = join(project, "out"); + const provider = new InMemoryProvider({ node: "{{#node}}{{name}}{{/node}}", index: `a` }); + const run = async (match: string[], generatorNames?: string[]) => runGen({ + config: defineConfig({ outDir: out, extStyle: "none", dbImport: "~/db", dialect: "sqlite", generators: [ + templateGenerator({ name: "n", template: "node", scope: "perNode", match, outputPattern: "{path}", format: "html", provider }), + templateGenerator({ name: "i", template: "index", scope: "perModel", data: "docsView", outputPattern: "index.html", format: "html", linkCheck: true, provider }), + ] }), + metadata: await load(), + projectRoot: project, + ...(generatorNames !== undefined && { generatorNames }), + }); + await run(["object.*"]); + expect(existsSync(join(out, "model/acme/Address.html"))).toBe(true); + await expect(run(["object.entity"])).rejects.toThrow(/index\.html -> model\/acme\/Address\.html/); + expect(existsSync(join(out, "model/acme/Address.html"))).toBe(true); + await run(["object.entity"], ["i"]); + }); + + test("the link check sees pages a later generator renders, and the copied assets", async () => { + const provider = new InMemoryProvider({ + node: `{{#node}}i{{/node}}`, + index: `

x

`, + }); + const { out } = await gen([ + templateGenerator({ name: "n", template: "node", scope: "perNode", match: "object.entity", outputPattern: "{path}", format: "html", linkCheck: true, assets: { from: "static" }, provider }), + templateGenerator({ name: "i", template: "index", scope: "perModel", data: "docsView", outputPattern: "index.html", format: "html", provider }), + ], (project) => { + mkdirSync(join(project, "static", "css"), { recursive: true }); + writeFileSync(join(project, "static", "css", "a.css"), "a {}\n"); + }); + expect(readFileSync(join(out, "css/a.css"), "utf8")).toBe("a {}\n"); + }); + + test("an asset that is not UTF-8 text is refused, and a missing assets directory too", async () => { + const provider = new InMemoryProvider({ m: "x" }); + const bin = (project: string) => { + mkdirSync(join(project, "static")); + writeFileSync(join(project, "static", "logo.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0xff, 0xfe])); + }; + await expect(gen([templateGenerator({ name: "m", template: "m", scope: "perModel", outputPattern: "m.txt", assets: { from: "static" }, provider })], bin)) + .rejects.toThrow(/logo\.png is not a UTF-8 text file/); + await expect(gen([templateGenerator({ name: "m", template: "m", scope: "perModel", outputPattern: "m.txt", assets: { from: "missing" }, provider })])) + .rejects.toThrow(/assets directory does not exist: missing/); + }); + + test("refuses a configuration that cannot mean anything", () => { + const base = { name: "x", template: "t", outputPattern: "{path}" } as const; + expect(() => templateGenerator({ ...base, scope: "perNode", data: "entities" })).toThrow(/reads the docs view/); + expect(() => templateGenerator({ ...base, scope: "perEntity", data: "docsView" })).toThrow(/use perNode/); + expect(() => templateGenerator({ ...base, scope: "perModel", match: "object.*" })).toThrow(/`match` applies/); + expect(() => templateGenerator({ ...base, scope: "perNode", match: "object" })).toThrow(/`match` takes/); + expect(() => templateGenerator({ ...base, scope: "perNode", linkCheck: true })).toThrow(/format "html"/); + }); + + test("{path} outside perNode and perRequirement is an error naming the scopes that have it", async () => { + const provider = new InMemoryProvider({ m: "x" }); + await expect(gen([templateGenerator({ name: "m", template: "m", scope: "perModel", data: "docsView", outputPattern: "{path}", provider })])) + .rejects.toThrow(/uses \{path\} but no page path is in scope/); + }); +}); + +describe("template-spec: the docs view keys", () => { + test("parses data, match, subDir, assets and linkCheck", () => { + const spec = parseTemplateSpec({ generators: [{ + name: "n", template: "t", scope: "perNode", outputPattern: "{path}", format: "html", + data: "docsView", match: ["object.*"], subDir: "site", assets: { from: "a" }, linkCheck: true, + }] }); + expect(spec.generators[0]).toEqual({ + name: "n", template: "t", scope: "perNode", outputPattern: "{path}", format: "html", + data: "docsView", match: ["object.*"], subDir: "site", assets: { from: "a" }, linkCheck: true, + }); + }); + test("refuses malformed values", () => { + const at = (extra: Record) => () => parseTemplateSpec({ generators: [{ name: "n", template: "t", scope: "perNode", outputPattern: "{path}", ...extra }] }); + expect(at({ data: "view" })).toThrow(/data must be one of entities \| docsView/); + expect(at({ match: [] })).toThrow(/match must be/); + expect(at({ assets: { to: "x" } })).toThrow(/assets must be/); + expect(at({ assets: { from: "a", to: "b" } })).toThrow(/assets must be \{ "from": "" \}/); + expect(at({ linkCheck: "yes" })).toThrow(/linkCheck must be a boolean/); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/template-codegen/conformance.test.ts b/server/typescript/packages/codegen-ts/test/template-codegen/conformance.test.ts index 41d5ed0b68..342a013d38 100644 --- a/server/typescript/packages/codegen-ts/test/template-codegen/conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/template-codegen/conformance.test.ts @@ -1,5 +1,5 @@ import { describe, test, expect } from "bun:test"; -import { readdirSync, readFileSync, statSync, cpSync } from "node:fs"; +import { readdirSync, readFileSync, statSync, cpSync, rmSync } from "node:fs"; import { join, resolve, relative } from "node:path"; import { runGen, defineConfig, parseTemplateSpec, templateSpecToGenerators } from "../../src/index.js"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; @@ -7,6 +7,8 @@ import { FileSource } from "@metaobjectsdev/metadata/core"; import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; const CORPUS = resolve(import.meta.dir, "../../../../../../fixtures/template-codegen-conformance"); +/** Set to rewrite each case's `expected/` from this port's output (an intentional change). */ +const UPDATE = process.env.UPDATE_TEMPLATE_CONFORMANCE === "1"; function walkFiles(dir: string, base = dir): string[] { return readdirSync(dir).flatMap((n) => { @@ -15,37 +17,53 @@ function walkFiles(dir: string, base = dir): string[] { }); } -describe("template-codegen conformance (TS)", () => { - test("spec.json over metadata/ matches expected/ byte-for-byte", async () => { - const spec = parseTemplateSpec(JSON.parse(readFileSync(join(CORPUS, "spec.json"), "utf8"))); - const loader = new MetaDataLoader(); - const res = await loader.load([new FileSource(join(CORPUS, "metadata", "meta.shop.json"))]); - expect(res.errors).toEqual([]); +/** Run a case's spec.json over its metadata/ (every file, sorted by name) and compare with its + * expected/. The case's templates/ and each entry's assets directory are copied into a scratch + * project, so runGen writes its .gen-state merge base there, never into the corpus. */ +async function runCase(caseDir: string): Promise { + const spec = parseTemplateSpec(JSON.parse(readFileSync(join(caseDir, "spec.json"), "utf8"))); + const metaDir = join(caseDir, "metadata"); + const sources = readdirSync(metaDir).filter((f) => f.endsWith(".json")).sort().map((f) => new FileSource(join(metaDir, f))); + const res = await new MetaDataLoader().load(sources); + expect(res.errors).toEqual([]); - // Hermetic: copy the corpus templates into a tmp projectRoot so runGen writes - // its .gen-state merge base into the tmp tree, never into the committed corpus. - const projectRoot = makeScratchDir("tmpl-conf-"); - const out = join(projectRoot, "out"); - cpSync(join(CORPUS, "templates"), join(projectRoot, "templates"), { recursive: true }); - try { - await runGen({ - config: defineConfig({ - outDir: out, extStyle: "none", dbImport: "~/db", dialect: "sqlite", - generators: templateSpecToGenerators(spec), - }), - metadata: res.root, - projectRoot, - }); - const expectedDir = join(CORPUS, "expected"); - const got = walkFiles(out).sort(); - const want = walkFiles(expectedDir).sort(); - expect(got).toEqual(want); - for (const rel of want) { - expect(`${rel}:\n${readFileSync(join(out, rel), "utf8")}`) - .toBe(`${rel}:\n${readFileSync(join(expectedDir, rel), "utf8")}`); - } - } finally { - removeTree(projectRoot); + const projectRoot = makeScratchDir("tmpl-conf-"); + const out = join(projectRoot, "out"); + cpSync(join(caseDir, "templates"), join(projectRoot, "templates"), { recursive: true }); + for (const { assets } of spec.generators) { + if (assets !== undefined) cpSync(join(caseDir, assets.from), join(projectRoot, assets.from), { recursive: true }); + } + try { + await runGen({ + config: defineConfig({ + outDir: out, extStyle: "none", dbImport: "~/db", dialect: "sqlite", + generators: templateSpecToGenerators(spec), + }), + metadata: res.root, + projectRoot, + }); + const expectedDir = join(caseDir, "expected"); + if (UPDATE) { + rmSync(expectedDir, { recursive: true, force: true }); + cpSync(out, expectedDir, { recursive: true }); } + const got = walkFiles(out).sort(); + const want = walkFiles(expectedDir).sort(); + expect(got).toEqual(want); + for (const rel of want) { + expect(`${rel}:\n${readFileSync(join(out, rel), "utf8")}`) + .toBe(`${rel}:\n${readFileSync(join(expectedDir, rel), "utf8")}`); + } + } finally { + removeTree(projectRoot); + } +} + +describe("template-codegen conformance (TS)", () => { + test("spec.json over metadata/ matches expected/ byte-for-byte", async () => { + await runCase(CORPUS); + }); + test("docs-view/: the docs view scopes, {path}, subDir, assets and the link check", async () => { + await runCase(join(CORPUS, "docs-view")); }); }); diff --git a/server/typescript/packages/codegen-ts/test/template-codegen/template-spec.test.ts b/server/typescript/packages/codegen-ts/test/template-codegen/template-spec.test.ts index 50390be2b1..088541c5bc 100644 --- a/server/typescript/packages/codegen-ts/test/template-codegen/template-spec.test.ts +++ b/server/typescript/packages/codegen-ts/test/template-codegen/template-spec.test.ts @@ -53,7 +53,7 @@ describe("schema ↔ parser drift", () => { test("schema enumerates the same scopes the parser accepts", () => { const scopeEnum = (schema as { properties: { generators: { items: { properties: { scope: { enum: string[] } } } } } }) .properties.generators.items.properties.scope.enum; - expect(scopeEnum).toEqual(["perEntity", "perPackage", "perModel"]); + expect(scopeEnum).toEqual(["perEntity", "perPackage", "perModel", "perNode", "perRequirement"]); }); test("schema enumerates the same formats the parser accepts", () => { const formatEnum = (schema as { properties: { generators: { items: { properties: { format: { enum: string[] } } } } } }) diff --git a/server/typescript/packages/docs-site/src/index.ts b/server/typescript/packages/docs-site/src/index.ts index 87a1cc6635..50df34d613 100644 --- a/server/typescript/packages/docs-site/src/index.ts +++ b/server/typescript/packages/docs-site/src/index.ts @@ -2,6 +2,7 @@ export { generateSite, DEFAULT_ASSET_BASE } from "./site.js"; export type { SiteOptions, SiteResult } from "./site.js"; export { SITE_TEMPLATE_NAMES, SITE_ASSET_NAMES, CLASSIC_TEMPLATE_NAMES, CLASSIC_ASSET_NAMES, readSiteFile } from "./scaffold.js"; export type { MetaDataTypeProvider } from "@metaobjectsdev/metadata"; +export { findDanglingLinks } from "./link-check.js"; // The explorer reads the docs view, which `@metaobjectsdev/metadata` builds from the loaded model // (`buildDocsView`, `docs/features/docs-view.md`). export { generateExplorerSite, readPromptTexts, EXPLORER_TEMPLATE_NAMES, EXPLORER_ASSET_NAMES, CYTOSCAPE_PATH } from "./explorer/site.js"; diff --git a/server/typescript/packages/docs-site/src/link-check.ts b/server/typescript/packages/docs-site/src/link-check.ts index f71405e812..dce483505e 100644 --- a/server/typescript/packages/docs-site/src/link-check.ts +++ b/server/typescript/packages/docs-site/src/link-check.ts @@ -1,28 +1,46 @@ -import { existsSync, readFileSync } from "node:fs"; -import { dirname, join, normalize } from "node:path"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { posix } from "node:path"; -export function checkLinks(outDir: string, pages: string[]): string[] { +/** + * The relative links in `pages` that do not land: every `href` that names a file `read` cannot + * return, or an anchor no `id="…"` in that file carries. One ` -> ` line each. + * + * Paths are `/`-separated and resolved against each other, so the caller picks the space (a + * site-relative path, or an absolute one with its separators turned to `/`). Absolute URLs, + * `mailto:`, a bare `#` and root-relative hrefs (served from outside the site, an `assetBase` + * mirror) are skipped; a query string selects a view on a page and does not name a file. + */ +export function findDanglingLinks(pages: readonly string[], read: (path: string) => string | undefined): string[] { const errs: string[] = []; const idCache = new Map>(); - const idsOf = (p: string) => { - if (!idCache.has(p)) idCache.set(p, new Set([...readFileSync(p, "utf8").matchAll(/id="([^"]+)"/g)].map((m) => m[1]!))); + const idsOf = (p: string, html: string) => { + if (!idCache.has(p)) idCache.set(p, new Set([...html.matchAll(/id="([^"]+)"/g)].map((m) => m[1]!))); return idCache.get(p)!; }; for (const page of pages) { - const html = readFileSync(join(outDir, page), "utf8"); + const html = read(page) ?? ""; for (const m of html.matchAll(/href="([^"]+)"/g)) { const href = m[1]!; - // A root-relative href is served from outside the site (an `assetBase` mirror); the site's - // own links are all relative. if (/^(https?:|mailto:|#$|\/)/.test(href)) continue; const [target0 = "", anchor] = href.split("#"); - // A query string selects a view on the page (`map.html?slice=…`); the file is what must exist. const file = target0.split("?")[0] ?? ""; - const target = file === "" ? page : normalize(join(dirname(page), file)); - const abs = join(outDir, target); - if (!existsSync(abs)) { errs.push(`${page} -> ${href}`); continue; } - if (anchor && !idsOf(abs).has(anchor)) errs.push(`${page} -> ${href}`); + const target = file === "" ? page : posix.normalize(posix.join(posix.dirname(page), file)); + const body = read(target); + if (body === undefined) { errs.push(`${page} -> ${href}`); continue; } + if (anchor && !idsOf(target, body).has(anchor)) errs.push(`${page} -> ${href}`); } } return errs; } + +/** {@link findDanglingLinks} over a site written to `outDir`, `pages` relative to it. */ +export function checkLinks(outDir: string, pages: string[]): string[] { + return findDanglingLinks(pages, (p) => { + try { + return readFileSync(join(outDir, p), "utf8"); + } catch { + return undefined; + } + }); +}